My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

nnn.c 71 KiB

7 år sedan
7 år sedan
7 år sedan
9 år sedan
10 år sedan
9 år sedan
9 år sedan
7 år sedan
8 år sedan
8 år sedan
8 år sedan
7 år sedan
7 år sedan
8 år sedan
8 år sedan
10 år sedan
10 år sedan
8 år sedan
8 år sedan
8 år sedan
8 år sedan
8 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
8 år sedan
7 år sedan
7 år sedan
8 år sedan
7 år sedan
8 år sedan
8 år sedan
7 år sedan
8 år sedan
7 år sedan
8 år sedan
8 år sedan
8 år sedan
9 år sedan
7 år sedan
9 år sedan
7 år sedan
9 år sedan
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394
  1. /* See LICENSE file for copyright and license details. */
  2. /*
  3. * Visual layout:
  4. * .---------
  5. * | DIR: /mnt/path
  6. * |
  7. * | file0
  8. * | file1
  9. * | > file2
  10. * | file3
  11. * | file4
  12. * ...
  13. * | filen
  14. * |
  15. * | Permission denied
  16. * '------
  17. */
  18. #ifdef __linux__
  19. #ifdef __i386__
  20. #define _FILE_OFFSET_BITS 64 /* Support large files on 32-bit Linux */
  21. #endif
  22. #include <sys/inotify.h>
  23. #define LINUX_INOTIFY
  24. #if !defined(__GLIBC__)
  25. #include <sys/types.h>
  26. #endif
  27. #endif
  28. #include <sys/resource.h>
  29. #include <sys/stat.h>
  30. #include <sys/statvfs.h>
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  32. #include <sys/types.h>
  33. #include <sys/event.h>
  34. #include <sys/time.h>
  35. #define BSD_KQUEUE
  36. #else
  37. #include <sys/sysmacros.h>
  38. #endif
  39. #include <sys/wait.h>
  40. #include <ctype.h>
  41. #ifdef __linux__ /* Fix failure due to mvaddnwstr() */
  42. #ifndef NCURSES_WIDECHAR
  43. #define NCURSES_WIDECHAR 1
  44. #endif
  45. #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  46. #ifndef _XOPEN_SOURCE_EXTENDED
  47. #define _XOPEN_SOURCE_EXTENDED
  48. #endif
  49. #endif
  50. #ifndef __USE_XOPEN /* Fix failure due to wcswidth(), ncursesw/curses.h includes whcar.h on Ubuntu 14.04 */
  51. #define __USE_XOPEN
  52. #endif
  53. #include <curses.h>
  54. #include <dirent.h>
  55. #include <errno.h>
  56. #include <fcntl.h>
  57. #include <grp.h>
  58. #include <libgen.h>
  59. #include <limits.h>
  60. #ifdef __gnu_hurd__
  61. #define PATH_MAX 4096
  62. #endif
  63. #include <locale.h>
  64. #include <pwd.h>
  65. #include <regex.h>
  66. #include <signal.h>
  67. #include <stdarg.h>
  68. #include <stdio.h>
  69. #include <stdlib.h>
  70. #include <string.h>
  71. #include <time.h>
  72. #include <unistd.h>
  73. #include <readline/history.h>
  74. #include <readline/readline.h>
  75. #ifndef __USE_XOPEN_EXTENDED
  76. #define __USE_XOPEN_EXTENDED 1
  77. #endif
  78. #include <ftw.h>
  79. #include <wchar.h>
  80. #include "nnn.h"
  81. #ifdef DEBUGMODE
  82. static int DEBUG_FD;
  83. static int
  84. xprintf(int fd, const char *fmt, ...)
  85. {
  86. char buf[BUFSIZ];
  87. int r;
  88. va_list ap;
  89. va_start(ap, fmt);
  90. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  91. if (r > 0)
  92. r = write(fd, buf, r);
  93. va_end(ap);
  94. return r;
  95. }
  96. static int
  97. enabledbg()
  98. {
  99. FILE *fp = fopen("/tmp/nnn_debug", "w");
  100. if (!fp) {
  101. fprintf(stderr, "Cannot open debug file\n");
  102. return -1;
  103. }
  104. DEBUG_FD = fileno(fp);
  105. if (DEBUG_FD == -1) {
  106. fprintf(stderr, "Cannot open debug file descriptor\n");
  107. return -1;
  108. }
  109. return 0;
  110. }
  111. static void
  112. disabledbg()
  113. {
  114. close(DEBUG_FD);
  115. }
  116. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  117. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  118. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  119. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=%p\n", x)
  120. #else
  121. #define DPRINTF_D(x)
  122. #define DPRINTF_U(x)
  123. #define DPRINTF_S(x)
  124. #define DPRINTF_P(x)
  125. #endif /* DEBUGMODE */
  126. /* Macro definitions */
  127. #define VERSION "1.7"
  128. #define GENERAL_INFO "License: BSD 2-Clause\nWebpage: https://github.com/jarun/nnn"
  129. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  130. #undef MIN
  131. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  132. #define ISODD(x) ((x) & 1)
  133. #define TOUPPER(ch) \
  134. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  135. #define MAX_CMD_LEN 5120
  136. #define CWD "DIR: "
  137. #define CURSR " > "
  138. #define EMPTY " "
  139. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  140. #define FILTER '/'
  141. #define REGEX_MAX 128
  142. #define BM_MAX 10
  143. #define ENTRY_INCR 64 /* Number of dir 'entry' structures to allocate per shot */
  144. #define NAMEBUF_INCR 0x1000 /* 64 dir entries at a time, avg. 64 chars per filename = 64*64B = 4KB */
  145. #define DESCRIPTOR_LEN 32
  146. #define _ALIGNMENT 0x10
  147. #define _ALIGNMENT_MASK 0xF
  148. /* Macros to define process spawn behaviour as flags */
  149. #define F_NONE 0x00 /* no flag set */
  150. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  151. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  152. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  153. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  154. #define F_NORMAL 0x80 /* spawn child process in non-curses regular CLI mode */
  155. /* CRC8 macros */
  156. #define WIDTH (8 * sizeof(unsigned char))
  157. #define TOPBIT (1 << (WIDTH - 1))
  158. #define POLYNOMIAL 0xD8 /* 11011 followed by 0's */
  159. #define CRC8_TABLE_LEN 256
  160. /* Function macros */
  161. #define exitcurses() endwin()
  162. #define clearprompt() printmsg("")
  163. #define printwarn() printmsg(strerror(errno))
  164. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  165. #define copyfilter() xstrlcpy(fltr, ifilter, NAME_MAX)
  166. #define copycurname() xstrlcpy(oldname, dents[cur].name, NAME_MAX + 1)
  167. #define settimeout() timeout(1000)
  168. #define cleartimeout() timeout(-1)
  169. #define errexit() printerr(__LINE__)
  170. #ifdef LINUX_INOTIFY
  171. #define EVENT_SIZE (sizeof(struct inotify_event))
  172. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  173. #elif defined(BSD_KQUEUE)
  174. #define NUM_EVENT_SLOTS 1
  175. #define NUM_EVENT_FDS 1
  176. #endif
  177. /* TYPE DEFINITIONS */
  178. typedef unsigned long ulong;
  179. typedef unsigned int uint;
  180. typedef unsigned char uchar;
  181. /* STRUCTURES */
  182. /* Directory entry */
  183. typedef struct entry {
  184. char *name;
  185. time_t t;
  186. off_t size;
  187. blkcnt_t blocks; /* number of 512B blocks allocated */
  188. mode_t mode;
  189. uint nlen; /* Length of file name; can be uchar (< NAME_MAX + 1) */
  190. }__attribute__ ((packed, aligned(_ALIGNMENT))) *pEntry;
  191. /* Bookmark */
  192. typedef struct {
  193. char *key;
  194. char *loc;
  195. } bm;
  196. /* Settings */
  197. typedef struct {
  198. ushort filtermode : 1; /* Set to enter filter mode */
  199. ushort mtimeorder : 1; /* Set to sort by time modified */
  200. ushort sizeorder : 1; /* Set to sort by file size */
  201. ushort blkorder : 1; /* Set to sort by blocks used (disk usage) */
  202. ushort showhidden : 1; /* Set to show hidden files */
  203. ushort copymode : 1; /* Set when copying files */
  204. ushort showdetail : 1; /* Clear to show fewer file info */
  205. ushort showcolor : 1; /* Set to show dirs in blue */
  206. ushort dircolor : 1; /* Current status of dir color */
  207. ushort metaviewer : 1; /* Index of metadata viewer in utils[] */
  208. ushort quote : 1; /* Copy paths within quotes */
  209. ushort noxdisplay : 1; /* X11 is not available */
  210. ushort color : 3; /* Color code for directories */
  211. } settings;
  212. /* GLOBALS */
  213. /* Configuration */
  214. static settings cfg = {0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 4};
  215. static struct entry *dents;
  216. static char *pnamebuf, *pcopybuf;
  217. static int ndents, cur, total_dents = ENTRY_INCR;
  218. static uint idle;
  219. static uint idletimeout, copybufpos, copybuflen;
  220. static char *player;
  221. static char *copier;
  222. static char *editor;
  223. static char *desktop_manager;
  224. static char nowait = F_NOTRACE;
  225. static blkcnt_t ent_blocks;
  226. static blkcnt_t dir_blocks;
  227. static ulong num_files;
  228. static uint open_max;
  229. static bm bookmark[BM_MAX];
  230. static uchar crc8table[CRC8_TABLE_LEN];
  231. static uchar g_crc;
  232. #ifdef LINUX_INOTIFY
  233. static int inotify_fd, inotify_wd = -1;
  234. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  235. #elif defined(BSD_KQUEUE)
  236. static int kq, event_fd = -1;
  237. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  238. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  239. static struct timespec gtimeout;
  240. #endif
  241. /* Macros for utilities */
  242. #define MEDIAINFO 0
  243. #define EXIFTOOL 1
  244. #define OPENER 2
  245. #define NLAY 3
  246. #define ATOOL 4
  247. #define VIDIR 5
  248. /* Utilities to open files, run actions */
  249. static char * const utils[] = {
  250. "mediainfo",
  251. "exiftool",
  252. #ifdef __APPLE__
  253. "/usr/bin/open",
  254. #else
  255. "xdg-open",
  256. #endif
  257. "nlay",
  258. "atool",
  259. "vidir"
  260. };
  261. /* Common strings */
  262. #define STR_NFTWFAIL_ID 0
  263. #define STR_ATROOT_ID 1
  264. #define STR_NOHOME_ID 2
  265. #define STR_INPUT_ID 3
  266. #define STR_INVBM_ID 4
  267. #define STR_COPY_ID 5
  268. #define STR_DATE_ID 6
  269. static const char messages[][16] =
  270. {
  271. "nftw(3) failed",
  272. "already at /",
  273. "HOME not set",
  274. "no traversal",
  275. "invalid key",
  276. "set NNN_COPIER",
  277. "%F %T %z",
  278. };
  279. /* For use in functions which are isolated and don't return the buffer */
  280. static char g_buf[MAX_CMD_LEN] __attribute__ ((aligned));
  281. /* Buffer for file path copy file */
  282. static char g_cppath[48] __attribute__ ((aligned));
  283. /* Forward declarations */
  284. static void redraw(char *path);
  285. /* Functions */
  286. /*
  287. * CRC8 source:
  288. * https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
  289. */
  290. static void
  291. crc8init()
  292. {
  293. uchar remainder, bit;
  294. uint dividend;
  295. /* Compute the remainder of each possible dividend */
  296. for (dividend = 0; dividend < CRC8_TABLE_LEN; ++dividend)
  297. {
  298. /* Start with the dividend followed by zeros */
  299. remainder = dividend << (WIDTH - 8);
  300. /* Perform modulo-2 division, a bit at a time */
  301. for (bit = 8; bit > 0; --bit)
  302. {
  303. /* Try to divide the current data bit */
  304. if (remainder & TOPBIT)
  305. remainder = (remainder << 1) ^ POLYNOMIAL;
  306. else
  307. remainder = (remainder << 1);
  308. }
  309. /* Store the result into the table */
  310. crc8table[dividend] = remainder;
  311. }
  312. }
  313. static uchar
  314. crc8fast(uchar const message[], size_t n)
  315. {
  316. uchar data;
  317. uchar remainder = 0;
  318. size_t byte;
  319. /* Divide the message by the polynomial, a byte at a time */
  320. for (byte = 0; byte < n; ++byte)
  321. {
  322. data = message[byte] ^ (remainder >> (WIDTH - 8));
  323. remainder = crc8table[data] ^ (remainder << 8);
  324. }
  325. /* The final remainder is the CRC */
  326. return remainder;
  327. }
  328. /* Messages show up at the bottom */
  329. static void
  330. printmsg(const char *msg)
  331. {
  332. mvprintw(LINES - 1, 0, "%s\n", msg);
  333. }
  334. /* Kill curses and display error before exiting */
  335. static void
  336. printerr(int linenum)
  337. {
  338. exitcurses();
  339. fprintf(stderr, "line %d: (%d) %s\n", linenum, errno, strerror(errno));
  340. exit(1);
  341. }
  342. /* Print prompt on the last line */
  343. static void
  344. printprompt(char *str)
  345. {
  346. clearprompt();
  347. printw(str);
  348. }
  349. /* Increase the limit on open file descriptors, if possible */
  350. static rlim_t
  351. max_openfds()
  352. {
  353. struct rlimit rl;
  354. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  355. if (limit != 0)
  356. return 32;
  357. limit = rl.rlim_cur;
  358. rl.rlim_cur = rl.rlim_max;
  359. /* Return ~75% of max possible */
  360. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  361. limit = rl.rlim_max - (rl.rlim_max >> 2);
  362. /*
  363. * 20K is arbitrary. If the limit is set to max possible
  364. * value, the memory usage increases to more than double.
  365. */
  366. return limit > 20480 ? 20480 : limit;
  367. }
  368. return limit;
  369. }
  370. /*
  371. * Wrapper to realloc()
  372. * Frees current memory if realloc() fails and returns NULL.
  373. *
  374. * As per the docs, the *alloc() family is supposed to be memory aligned:
  375. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  376. * OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  377. */
  378. static void *
  379. xrealloc(void *pcur, size_t len)
  380. {
  381. static void *pmem;
  382. pmem = realloc(pcur, len);
  383. if (!pmem && pcur)
  384. free(pcur);
  385. return pmem;
  386. }
  387. /*
  388. * Custom xstrlen()
  389. */
  390. static size_t
  391. xstrlen(const char *s)
  392. {
  393. static size_t len;
  394. if (!s)
  395. return 0;
  396. len = 0;
  397. while (*s)
  398. ++len, ++s;
  399. return len;
  400. }
  401. /*
  402. * Just a safe strncpy(3)
  403. * Always null ('\0') terminates if both src and dest are valid pointers.
  404. * Returns the number of bytes copied including terminating null byte.
  405. */
  406. static size_t
  407. xstrlcpy(char *dest, const char *src, size_t n)
  408. {
  409. static ulong *s, *d;
  410. static size_t len, blocks;
  411. static const uint lsize = sizeof(ulong);
  412. static const uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  413. if (!src || !dest || !n)
  414. return 0;
  415. len = xstrlen(src) + 1;
  416. if (n > len)
  417. n = len;
  418. else if (len > n)
  419. /* Save total number of bytes to copy in len */
  420. len = n;
  421. /*
  422. * To enable -O3 ensure src and dest are 16-byte aligned
  423. * More info: http://www.felixcloutier.com/x86/MOVDQA.html
  424. */
  425. if ((n >= lsize) && (((ulong)src & _ALIGNMENT_MASK) == 0 && ((ulong)dest & _ALIGNMENT_MASK) == 0)) {
  426. s = (ulong *)src;
  427. d = (ulong *)dest;
  428. blocks = n >> _WSHIFT;
  429. n &= lsize - 1;
  430. while (blocks) {
  431. *d = *s;
  432. ++d, ++s;
  433. --blocks;
  434. }
  435. if (!n) {
  436. dest = (char *)d;
  437. *--dest = '\0';
  438. return len;
  439. }
  440. src = (char *)s;
  441. dest = (char *)d;
  442. }
  443. while (--n && (*dest = *src))
  444. ++dest, ++src;
  445. if (!n)
  446. *dest = '\0';
  447. return len;
  448. }
  449. /*
  450. * Custom strcmp(), just what we need.
  451. * Returns 0 if same, -ve if s1 < s2, +ve if s1 > s2.
  452. */
  453. static int
  454. xstrcmp(const char *s1, const char *s2)
  455. {
  456. if (!s1 || !s2)
  457. return -1;
  458. while (*s1 && *s1 == *s2)
  459. ++s1, ++s2;
  460. return *s1 - *s2;
  461. }
  462. /*
  463. * The poor man's implementation of memrchr(3).
  464. * We are only looking for '/' in this program.
  465. * And we are NOT expecting a '/' at the end.
  466. * Ideally 0 < n <= strlen(s).
  467. */
  468. static void *
  469. xmemrchr(uchar *s, uchar ch, size_t n)
  470. {
  471. static uchar *ptr;
  472. if (!s || !n)
  473. return NULL;
  474. ptr = s + n;
  475. do {
  476. --ptr;
  477. if (*ptr == ch)
  478. return ptr;
  479. } while (s != ptr);
  480. return NULL;
  481. }
  482. /*
  483. * The following dirname(3) implementation does not
  484. * modify the input. We use a copy of the original.
  485. *
  486. * Modified from the glibc (GNU LGPL) version.
  487. */
  488. static char *
  489. xdirname(const char *path)
  490. {
  491. static char * const buf = g_buf, *last_slash, *runp;
  492. xstrlcpy(buf, path, PATH_MAX);
  493. /* Find last '/'. */
  494. last_slash = xmemrchr((uchar *)buf, '/', xstrlen(buf));
  495. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  496. /* Determine whether all remaining characters are slashes. */
  497. for (runp = last_slash; runp != buf; --runp)
  498. if (runp[-1] != '/')
  499. break;
  500. /* The '/' is the last character, we have to look further. */
  501. if (runp != buf)
  502. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  503. }
  504. if (last_slash != NULL) {
  505. /* Determine whether all remaining characters are slashes. */
  506. for (runp = last_slash; runp != buf; --runp)
  507. if (runp[-1] != '/')
  508. break;
  509. /* Terminate the buffer. */
  510. if (runp == buf) {
  511. /* The last slash is the first character in the string.
  512. * We have to return "/". As a special case we have to
  513. * return "//" if there are exactly two slashes at the
  514. * beginning of the string. See XBD 4.10 Path Name
  515. * Resolution for more information.
  516. */
  517. if (last_slash == buf + 1)
  518. ++last_slash;
  519. else
  520. last_slash = buf + 1;
  521. } else
  522. last_slash = runp;
  523. last_slash[0] = '\0';
  524. } else {
  525. /* This assignment is ill-designed but the XPG specs require to
  526. * return a string containing "." in any case no directory part
  527. * is found and so a static and constant string is required.
  528. */
  529. buf[0] = '.';
  530. buf[1] = '\0';
  531. }
  532. return buf;
  533. }
  534. static char *
  535. xbasename(char *path)
  536. {
  537. static char *base;
  538. base = xmemrchr((uchar *)path, '/', xstrlen(path));
  539. return base ? base + 1 : path;
  540. }
  541. /* Writes buflen char(s) from buf to a file */
  542. static void
  543. writecp(const char *buf, const size_t buflen)
  544. {
  545. FILE *fp = fopen(g_cppath, "w");
  546. if (fp) {
  547. fwrite(buf, 1, buflen, fp);
  548. fclose(fp);
  549. } else
  550. printwarn();
  551. }
  552. static bool
  553. appendfilepath(const char *path, const size_t len)
  554. {
  555. if ((copybufpos >= copybuflen) || (len > (copybuflen - (copybufpos + 3)))) {
  556. copybuflen += PATH_MAX;
  557. pcopybuf = xrealloc(pcopybuf, copybuflen);
  558. if (!pcopybuf) {
  559. printmsg("no memory!");
  560. return FALSE;
  561. }
  562. }
  563. if (copybufpos) {
  564. pcopybuf[copybufpos - 1] = '\n';
  565. if (cfg.quote) {
  566. pcopybuf[copybufpos] = '\'';
  567. ++copybufpos;
  568. }
  569. } else if (cfg.quote) {
  570. pcopybuf[copybufpos] = '\'';
  571. ++copybufpos;
  572. }
  573. copybufpos += xstrlcpy(pcopybuf + copybufpos, path, len);
  574. if (cfg.quote) {
  575. pcopybuf[copybufpos - 1] = '\'';
  576. pcopybuf[copybufpos] = '\0';
  577. ++copybufpos;
  578. }
  579. return TRUE;
  580. }
  581. /*
  582. * Return number of dots if all chars in a string are dots, else 0
  583. */
  584. static int
  585. all_dots(const char *path)
  586. {
  587. int count = 0;
  588. if (!path)
  589. return FALSE;
  590. while (*path == '.')
  591. ++count, ++path;
  592. if (*path)
  593. return 0;
  594. return count;
  595. }
  596. /* Initialize curses mode */
  597. static void
  598. initcurses(void)
  599. {
  600. if (initscr() == NULL) {
  601. char *term = getenv("TERM");
  602. if (term != NULL)
  603. fprintf(stderr, "error opening TERM: %s\n", term);
  604. else
  605. fprintf(stderr, "initscr() failed\n");
  606. exit(1);
  607. }
  608. cbreak();
  609. noecho();
  610. nonl();
  611. intrflush(stdscr, FALSE);
  612. keypad(stdscr, TRUE);
  613. curs_set(FALSE); /* Hide cursor */
  614. start_color();
  615. use_default_colors();
  616. if (cfg.showcolor)
  617. init_pair(1, cfg.color, -1);
  618. settimeout(); /* One second */
  619. }
  620. /*
  621. * Spawns a child process. Behaviour can be controlled using flag.
  622. * Limited to 2 arguments to a program, flag works on bit set.
  623. */
  624. static void
  625. spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
  626. {
  627. static char *shlvl;
  628. static pid_t pid;
  629. static int status;
  630. if (flag & F_NORMAL)
  631. exitcurses();
  632. pid = fork();
  633. if (pid == 0) {
  634. if (dir != NULL)
  635. status = chdir(dir);
  636. shlvl = getenv("SHLVL");
  637. /* Show a marker (to indicate nnn spawned shell) */
  638. if (flag & F_MARKER && shlvl != NULL) {
  639. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  640. printf("Spawned shell level: %d\n", atoi(shlvl) + 1);
  641. }
  642. /* Suppress stdout and stderr */
  643. if (flag & F_NOTRACE) {
  644. int fd = open("/dev/null", O_WRONLY, 0200);
  645. dup2(fd, 1);
  646. dup2(fd, 2);
  647. close(fd);
  648. }
  649. if (flag & F_SIGINT)
  650. signal(SIGINT, SIG_DFL);
  651. execlp(file, file, arg1, arg2, NULL);
  652. _exit(1);
  653. } else {
  654. if (!(flag & F_NOWAIT))
  655. /* Ignore interruptions */
  656. while (waitpid(pid, &status, 0) == -1)
  657. DPRINTF_D(status);
  658. DPRINTF_D(pid);
  659. if (flag & F_NORMAL)
  660. refresh();
  661. }
  662. }
  663. /* Get program name from env var, else return fallback program */
  664. static char *
  665. xgetenv(const char *name, char *fallback)
  666. {
  667. static char *value;
  668. if (name == NULL)
  669. return fallback;
  670. value = getenv(name);
  671. return value && value[0] ? value : fallback;
  672. }
  673. /* Check if a dir exists, IS a dir and is readable */
  674. static bool
  675. xdiraccess(const char *path)
  676. {
  677. static DIR *dirp;
  678. dirp = opendir(path);
  679. if (dirp == NULL) {
  680. printwarn();
  681. return FALSE;
  682. }
  683. closedir(dirp);
  684. return TRUE;
  685. }
  686. /*
  687. * We assume none of the strings are NULL.
  688. *
  689. * Let's have the logic to sort numeric names in numeric order.
  690. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  691. *
  692. * If the absolute numeric values are same, we fallback to alphasort.
  693. */
  694. static int
  695. xstricmp(const char * const s1, const char * const s2)
  696. {
  697. static const char *c1, *c2;
  698. c1 = s1;
  699. while (isspace(*c1))
  700. ++c1;
  701. c2 = s2;
  702. while (isspace(*c2))
  703. ++c2;
  704. if (*c1 == '-' || *c1 == '+')
  705. ++c1;
  706. if (*c2 == '-' || *c2 == '+')
  707. ++c2;
  708. if (isdigit(*c1) && isdigit(*c2)) {
  709. while (*c1 >= '0' && *c1 <= '9')
  710. ++c1;
  711. while (isspace(*c1))
  712. ++c1;
  713. while (*c2 >= '0' && *c2 <= '9')
  714. ++c2;
  715. while (isspace(*c2))
  716. ++c2;
  717. }
  718. if (!*c1 && !*c2) {
  719. static long long num1, num2;
  720. num1 = strtoll(s1, NULL, 10);
  721. num2 = strtoll(s2, NULL, 10);
  722. if (num1 != num2) {
  723. if (num1 > num2)
  724. return 1;
  725. else
  726. return -1;
  727. }
  728. }
  729. return strcoll(s1, s2);
  730. }
  731. /* Return the integer value of a char representing HEX */
  732. static char
  733. xchartohex(char c)
  734. {
  735. if (c >= '0' && c <= '9')
  736. return c - '0';
  737. c = TOUPPER(c);
  738. if (c >= 'A' && c <= 'F')
  739. return c - 'A' + 10;
  740. return c;
  741. }
  742. /* Trim all whitespace from both ends, / from end */
  743. static char *
  744. strstrip(char *s)
  745. {
  746. if (!s || !*s)
  747. return s;
  748. size_t len = xstrlen(s) - 1;
  749. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  750. --len;
  751. s[len + 1] = '\0';
  752. while (*s && isspace(*s))
  753. ++s;
  754. return s;
  755. }
  756. static char *
  757. getmime(const char *file)
  758. {
  759. static regex_t regex;
  760. static uint i;
  761. static const uint len = LEN(assocs);
  762. for (i = 0; i < len; ++i) {
  763. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  764. continue;
  765. if (regexec(&regex, file, 0, NULL, 0) == 0)
  766. return assocs[i].mime;
  767. }
  768. return NULL;
  769. }
  770. static int
  771. setfilter(regex_t *regex, char *filter)
  772. {
  773. static size_t len;
  774. static int r;
  775. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  776. if (r != 0 && filter && filter[0] != '\0') {
  777. len = COLS;
  778. if (len > NAME_MAX)
  779. len = NAME_MAX;
  780. regerror(r, regex, g_buf, len);
  781. printmsg(g_buf);
  782. }
  783. return r;
  784. }
  785. static void
  786. initfilter(int dot, char **ifilter)
  787. {
  788. *ifilter = dot ? "." : "^[^.]";
  789. }
  790. static int
  791. visible(regex_t *regex, char *file)
  792. {
  793. return regexec(regex, file, 0, NULL, 0) == 0;
  794. }
  795. static int
  796. entrycmp(const void *va, const void *vb)
  797. {
  798. static pEntry pa, pb;
  799. pa = (pEntry)va;
  800. pb = (pEntry)vb;
  801. /* Sort directories first */
  802. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  803. return 1;
  804. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  805. return -1;
  806. /* Do the actual sorting */
  807. if (cfg.mtimeorder)
  808. return pb->t - pa->t;
  809. if (cfg.sizeorder) {
  810. if (pb->size > pa->size)
  811. return 1;
  812. else if (pb->size < pa->size)
  813. return -1;
  814. }
  815. if (cfg.blkorder) {
  816. if (pb->blocks > pa->blocks)
  817. return 1;
  818. else if (pb->blocks < pa->blocks)
  819. return -1;
  820. }
  821. return xstricmp(pa->name, pb->name);
  822. }
  823. /*
  824. * Returns SEL_* if key is bound and 0 otherwise.
  825. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  826. * The next keyboard input can be simulated by presel.
  827. */
  828. static int
  829. nextsel(char **run, char **env, int *presel)
  830. {
  831. static int c;
  832. static uint i;
  833. static const uint len = LEN(bindings);
  834. #ifdef LINUX_INOTIFY
  835. static char inotify_buf[EVENT_BUF_LEN];
  836. #elif defined(BSD_KQUEUE)
  837. static struct kevent event_data[NUM_EVENT_SLOTS];
  838. #endif
  839. c = *presel;
  840. if (c == 0)
  841. c = getch();
  842. else {
  843. *presel = 0;
  844. /* Unwatch dir if we are still in a filtered view */
  845. #ifdef LINUX_INOTIFY
  846. if (inotify_wd >= 0) {
  847. inotify_rm_watch(inotify_fd, inotify_wd);
  848. inotify_wd = -1;
  849. }
  850. #elif defined(BSD_KQUEUE)
  851. if (event_fd >= 0) {
  852. close(event_fd);
  853. event_fd = -1;
  854. }
  855. #endif
  856. }
  857. if (c == -1) {
  858. ++idle;
  859. /* Do not check for directory changes in du
  860. * mode. A redraw forces du calculation.
  861. * Check for changes every odd second.
  862. */
  863. #ifdef LINUX_INOTIFY
  864. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  865. #elif defined(BSD_KQUEUE)
  866. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  867. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  868. #endif
  869. c = CONTROL('L');
  870. } else
  871. idle = 0;
  872. for (i = 0; i < len; ++i)
  873. if (c == bindings[i].sym) {
  874. *run = bindings[i].run;
  875. *env = bindings[i].env;
  876. return bindings[i].act;
  877. }
  878. return 0;
  879. }
  880. /*
  881. * Move non-matching entries to the end
  882. */
  883. static void
  884. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  885. {
  886. static int count;
  887. static struct entry _dent, *pdent1, *pdent2;
  888. for (count = 0; count < ndents; ++count) {
  889. if (filter(re, (*dents)[count].name) == 0) {
  890. if (count != --ndents) {
  891. pdent1 = &(*dents)[count];
  892. pdent2 = &(*dents)[ndents];
  893. *(&_dent) = *pdent1;
  894. *pdent1 = *pdent2;
  895. *pdent2 = *(&_dent);
  896. --count;
  897. }
  898. continue;
  899. }
  900. }
  901. }
  902. static int
  903. matches(char *fltr)
  904. {
  905. static regex_t re;
  906. /* Search filter */
  907. if (setfilter(&re, fltr) != 0)
  908. return -1;
  909. fill(&dents, visible, &re);
  910. qsort(dents, ndents, sizeof(*dents), entrycmp);
  911. return 0;
  912. }
  913. static int
  914. filterentries(char *path)
  915. {
  916. static char ln[REGEX_MAX] __attribute__ ((aligned));
  917. static wchar_t wln[REGEX_MAX] __attribute__ ((aligned));
  918. static wint_t ch[2] = {0};
  919. int r, total = ndents, oldcur = cur, len = 1;
  920. char *pln = ln + 1;
  921. ln[0] = wln[0] = FILTER;
  922. ln[1] = wln[1] = '\0';
  923. cur = 0;
  924. cleartimeout();
  925. echo();
  926. curs_set(TRUE);
  927. printprompt(ln);
  928. while ((r = get_wch(ch)) != ERR) {
  929. if (*ch == 127 /* handle DEL */ || *ch == KEY_DC || *ch == KEY_BACKSPACE) {
  930. if (len == 1) {
  931. cur = oldcur;
  932. *ch = CONTROL('L');
  933. goto end;
  934. }
  935. wln[--len] = '\0';
  936. if (len == 1)
  937. cur = oldcur;
  938. wcstombs(ln, wln, REGEX_MAX);
  939. ndents = total;
  940. if (matches(pln) == -1)
  941. continue;
  942. redraw(path);
  943. printprompt(ln);
  944. continue;
  945. }
  946. if (r == OK) {
  947. switch (*ch) {
  948. case '\r': // with nonl(), this is ENTER key value
  949. if (len == 1) {
  950. cur = oldcur;
  951. goto end;
  952. }
  953. if (matches(pln) == -1)
  954. goto end;
  955. redraw(path);
  956. goto end;
  957. case CONTROL('L'): // fallthrough
  958. case CONTROL('K'): // fallthrough
  959. case CONTROL('Y'): // fallthrough
  960. case CONTROL('_'): // fallthrough
  961. case CONTROL('R'): // fallthrough
  962. case CONTROL('O'): // fallthrough
  963. case CONTROL('B'): // fallthrough
  964. case CONTROL('V'): // fallthrough
  965. case CONTROL('J'): // fallthrough
  966. case CONTROL('G'): // fallthrough
  967. case CONTROL('X'): // fallthrough
  968. case CONTROL('F'): // fallthrough
  969. case CONTROL('I'): // fallthrough
  970. case CONTROL('T'):
  971. if (len == 1)
  972. cur = oldcur;
  973. goto end;
  974. default:
  975. /* Reset cur in case it's a repeat search */
  976. if (len == 1)
  977. cur = 0;
  978. if (len == REGEX_MAX - 1)
  979. break;
  980. wln[len] = (wchar_t)*ch;
  981. wln[++len] = '\0';
  982. wcstombs(ln, wln, REGEX_MAX);
  983. ndents = total;
  984. if (matches(pln) == -1)
  985. continue;
  986. redraw(path);
  987. printprompt(ln);
  988. }
  989. } else {
  990. if (len == 1)
  991. cur = oldcur;
  992. goto end;
  993. }
  994. }
  995. end:
  996. noecho();
  997. curs_set(FALSE);
  998. settimeout();
  999. /* Return keys for navigation etc. */
  1000. return *ch;
  1001. }
  1002. /* Show a prompt with input string and return the changes */
  1003. static char *
  1004. xreadline(char *fname)
  1005. {
  1006. int old_curs = curs_set(1);
  1007. size_t len, pos;
  1008. int x, y, r;
  1009. wint_t ch[2] = {0};
  1010. static wchar_t * const buf = (wchar_t *)g_buf;
  1011. if (fname) {
  1012. DPRINTF_S(fname);
  1013. len = pos = mbstowcs(buf, fname, NAME_MAX);
  1014. } else
  1015. len = (size_t)-1;
  1016. if (len == (size_t)-1) {
  1017. buf[0] = '\0';
  1018. len = pos = 0;
  1019. }
  1020. getyx(stdscr, y, x);
  1021. cleartimeout();
  1022. while (1) {
  1023. buf[len] = ' ';
  1024. mvaddnwstr(y, x, buf, len + 1);
  1025. move(y, x + wcswidth(buf, pos));
  1026. if ((r = get_wch(ch)) != ERR) {
  1027. if (r == OK) {
  1028. if (*ch == KEY_ENTER || *ch == '\n' || *ch == '\r')
  1029. break;
  1030. if (*ch == CONTROL('L')) {
  1031. clearprompt();
  1032. len = pos = 0;
  1033. continue;
  1034. }
  1035. /* TAB breaks cursor position, ignore it */
  1036. if (*ch == '\t')
  1037. continue;
  1038. if (pos < NAME_MAX - 1) {
  1039. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  1040. buf[pos] = *ch;
  1041. ++len, ++pos;
  1042. continue;
  1043. }
  1044. } else {
  1045. switch (*ch) {
  1046. case KEY_LEFT:
  1047. if (pos > 0)
  1048. --pos;
  1049. break;
  1050. case KEY_RIGHT:
  1051. if (pos < len)
  1052. ++pos;
  1053. break;
  1054. case KEY_BACKSPACE:
  1055. if (pos > 0) {
  1056. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  1057. --len, --pos;
  1058. }
  1059. break;
  1060. case KEY_DC:
  1061. if (pos < len) {
  1062. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  1063. --len;
  1064. }
  1065. break;
  1066. default:
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. buf[len] = '\0';
  1073. if (old_curs != ERR)
  1074. curs_set(old_curs);
  1075. settimeout();
  1076. DPRINTF_S(buf);
  1077. wcstombs(g_buf, buf, NAME_MAX);
  1078. return g_buf;
  1079. }
  1080. static char *
  1081. readinput(void)
  1082. {
  1083. cleartimeout();
  1084. echo();
  1085. curs_set(TRUE);
  1086. memset(g_buf, 0, NAME_MAX + 1);
  1087. wgetnstr(stdscr, g_buf, NAME_MAX);
  1088. noecho();
  1089. curs_set(FALSE);
  1090. settimeout();
  1091. return g_buf[0] ? g_buf : NULL;
  1092. }
  1093. /*
  1094. * Updates out with "dir/name or "/name"
  1095. * Returns the number of bytes copied including the terminating NULL byte
  1096. */
  1097. size_t
  1098. mkpath(char *dir, char *name, char *out, size_t n)
  1099. {
  1100. static size_t len;
  1101. /* Handle absolute path */
  1102. if (name[0] == '/')
  1103. return xstrlcpy(out, name, n);
  1104. else {
  1105. /* Handle root case */
  1106. if (istopdir(dir))
  1107. len = 1;
  1108. else
  1109. len = xstrlcpy(out, dir, n);
  1110. }
  1111. out[len - 1] = '/';
  1112. return (xstrlcpy(out + len, name, n - len) + len);
  1113. }
  1114. static void
  1115. parsebmstr(char *bms)
  1116. {
  1117. int i = 0;
  1118. while (*bms && i < BM_MAX) {
  1119. bookmark[i].key = bms;
  1120. ++bms;
  1121. while (*bms && *bms != ':')
  1122. ++bms;
  1123. if (!*bms) {
  1124. bookmark[i].key = NULL;
  1125. break;
  1126. }
  1127. *bms = '\0';
  1128. bookmark[i].loc = ++bms;
  1129. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  1130. bookmark[i].key = NULL;
  1131. break;
  1132. }
  1133. while (*bms && *bms != ';')
  1134. ++bms;
  1135. if (*bms)
  1136. *bms = '\0';
  1137. else
  1138. break;
  1139. ++bms;
  1140. ++i;
  1141. }
  1142. }
  1143. /*
  1144. * Get the real path to a bookmark
  1145. *
  1146. * NULL is returned in case of no match, path resolution failure etc.
  1147. * buf would be modified, so check return value before access
  1148. */
  1149. static char *
  1150. get_bm_loc(char *key, char *buf)
  1151. {
  1152. int r;
  1153. if (!key || !key[0])
  1154. return NULL;
  1155. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  1156. if (xstrcmp(bookmark[r].key, key) == 0) {
  1157. if (bookmark[r].loc[0] == '~') {
  1158. char *home = getenv("HOME");
  1159. if (!home) {
  1160. DPRINTF_S(messages[STR_NOHOME_ID]);
  1161. return NULL;
  1162. }
  1163. snprintf(buf, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1164. } else
  1165. xstrlcpy(buf, bookmark[r].loc, PATH_MAX);
  1166. return buf;
  1167. }
  1168. }
  1169. DPRINTF_S("Invalid key");
  1170. return NULL;
  1171. }
  1172. static void
  1173. resetdircolor(mode_t mode)
  1174. {
  1175. if (cfg.dircolor && !S_ISDIR(mode)) {
  1176. attroff(COLOR_PAIR(1) | A_BOLD);
  1177. cfg.dircolor = 0;
  1178. }
  1179. }
  1180. /*
  1181. * Replace escape characters in a string with '?'
  1182. * Adjust string length to maxcols if > 0;
  1183. *
  1184. * Interestingly, note that unescape() uses g_buf. What happens if
  1185. * str also points to g_buf? In this case we assume that the caller
  1186. * acknowledges that it's OK to lose the data in g_buf after this
  1187. * call to unescape().
  1188. * The API, on its part, first converts str to multibyte (after which
  1189. * it doesn't touch str anymore). Only after that it starts modifying
  1190. * g_buf. This is a phased operation.
  1191. */
  1192. static char *
  1193. unescape(const char *str, uint maxcols)
  1194. {
  1195. static wchar_t wbuf[PATH_MAX] __attribute__ ((aligned));
  1196. static wchar_t *buf;
  1197. static size_t len;
  1198. /* Convert multi-byte to wide char */
  1199. len = mbstowcs(wbuf, str, PATH_MAX);
  1200. g_buf[0] = '\0';
  1201. buf = wbuf;
  1202. if (maxcols && len > maxcols) {
  1203. len = wcswidth(wbuf, len);
  1204. if (len > maxcols)
  1205. wbuf[maxcols] = 0;
  1206. }
  1207. while (*buf) {
  1208. if (*buf <= '\x1f' || *buf == '\x7f')
  1209. *buf = '\?';
  1210. ++buf;
  1211. }
  1212. /* Convert wide char to multi-byte */
  1213. wcstombs(g_buf, wbuf, PATH_MAX);
  1214. return g_buf;
  1215. }
  1216. static char *
  1217. coolsize(off_t size)
  1218. {
  1219. static const char * const U = "BKMGTPEZY";
  1220. static char size_buf[12]; /* Buffer to hold human readable size */
  1221. static off_t rem;
  1222. static int i;
  1223. i = 0;
  1224. rem = 0;
  1225. while (size > 1024) {
  1226. rem = size & (0x3FF); /* 1024 - 1 = 0x3FF */
  1227. size >>= 10;
  1228. ++i;
  1229. }
  1230. if (i == 1) {
  1231. rem = (rem * 1000) >> 10;
  1232. rem /= 10;
  1233. if (rem % 10 >= 5) {
  1234. rem = (rem / 10) + 1;
  1235. if (rem == 10) {
  1236. ++size;
  1237. rem = 0;
  1238. }
  1239. } else
  1240. rem /= 10;
  1241. } else if (i == 2) {
  1242. rem = (rem * 1000) >> 10;
  1243. if (rem % 10 >= 5) {
  1244. rem = (rem / 10) + 1;
  1245. if (rem == 100) {
  1246. ++size;
  1247. rem = 0;
  1248. }
  1249. } else
  1250. rem /= 10;
  1251. } else if (i > 0) {
  1252. rem = (rem * 10000) >> 10;
  1253. if (rem % 10 >= 5) {
  1254. rem = (rem / 10) + 1;
  1255. if (rem == 1000) {
  1256. ++size;
  1257. rem = 0;
  1258. }
  1259. } else
  1260. rem /= 10;
  1261. }
  1262. if (i > 0)
  1263. snprintf(size_buf, 12, "%lu.%0*lu%c", (ulong)size, i, (ulong)rem, U[i]);
  1264. else
  1265. snprintf(size_buf, 12, "%lu%c", (ulong)size, U[i]);
  1266. return size_buf;
  1267. }
  1268. static char *
  1269. get_file_sym(mode_t mode)
  1270. {
  1271. static char ind[2] = "\0\0";
  1272. if (S_ISDIR(mode))
  1273. ind[0] = '/';
  1274. else if (S_ISLNK(mode))
  1275. ind[0] = '@';
  1276. else if (S_ISSOCK(mode))
  1277. ind[0] = '=';
  1278. else if (S_ISFIFO(mode))
  1279. ind[0] = '|';
  1280. else if (mode & 0100)
  1281. ind[0] = '*';
  1282. else
  1283. ind[0] = '\0';
  1284. return ind;
  1285. }
  1286. static void
  1287. printent(struct entry *ent, int sel, uint namecols)
  1288. {
  1289. static char *pname;
  1290. pname = unescape(ent->name, namecols);
  1291. /* Directories are always shown on top */
  1292. resetdircolor(ent->mode);
  1293. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1294. }
  1295. static void
  1296. printent_long(struct entry *ent, int sel, uint namecols)
  1297. {
  1298. static char buf[18], *pname;
  1299. strftime(buf, 18, "%F %R", localtime(&ent->t));
  1300. pname = unescape(ent->name, namecols);
  1301. /* Directories are always shown on top */
  1302. resetdircolor(ent->mode);
  1303. if (sel)
  1304. attron(A_REVERSE);
  1305. if (S_ISDIR(ent->mode)) {
  1306. if (cfg.blkorder)
  1307. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1308. else
  1309. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1310. } else if (S_ISLNK(ent->mode))
  1311. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1312. else if (S_ISSOCK(ent->mode))
  1313. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1314. else if (S_ISFIFO(ent->mode))
  1315. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1316. else if (S_ISBLK(ent->mode))
  1317. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1318. else if (S_ISCHR(ent->mode))
  1319. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1320. else if (ent->mode & 0100) {
  1321. if (cfg.blkorder)
  1322. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1323. else
  1324. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1325. } else {
  1326. if (cfg.blkorder)
  1327. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1328. else
  1329. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1330. }
  1331. if (sel)
  1332. attroff(A_REVERSE);
  1333. }
  1334. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1335. static char
  1336. get_fileind(mode_t mode, char *desc)
  1337. {
  1338. static char c;
  1339. if (S_ISREG(mode)) {
  1340. c = '-';
  1341. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1342. if (mode & 0100)
  1343. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1344. } else if (S_ISDIR(mode)) {
  1345. c = 'd';
  1346. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1347. } else if (S_ISBLK(mode)) {
  1348. c = 'b';
  1349. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1350. } else if (S_ISCHR(mode)) {
  1351. c = 'c';
  1352. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1353. #ifdef S_ISFIFO
  1354. } else if (S_ISFIFO(mode)) {
  1355. c = 'p';
  1356. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1357. #endif /* S_ISFIFO */
  1358. #ifdef S_ISLNK
  1359. } else if (S_ISLNK(mode)) {
  1360. c = 'l';
  1361. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1362. #endif /* S_ISLNK */
  1363. #ifdef S_ISSOCK
  1364. } else if (S_ISSOCK(mode)) {
  1365. c = 's';
  1366. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1367. #endif /* S_ISSOCK */
  1368. #ifdef S_ISDOOR
  1369. /* Solaris 2.6, etc. */
  1370. } else if (S_ISDOOR(mode)) {
  1371. c = 'D';
  1372. desc[0] = '\0';
  1373. #endif /* S_ISDOOR */
  1374. } else {
  1375. /* Unknown type -- possibly a regular file? */
  1376. c = '?';
  1377. desc[0] = '\0';
  1378. }
  1379. return c;
  1380. }
  1381. /* Convert a mode field into "ls -l" type perms field. */
  1382. static char *
  1383. get_lsperms(mode_t mode, char *desc)
  1384. {
  1385. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1386. static char bits[11] = {'\0'};
  1387. bits[0] = get_fileind(mode, desc);
  1388. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1389. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1390. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1391. if (mode & S_ISUID)
  1392. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1393. if (mode & S_ISGID)
  1394. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1395. if (mode & S_ISVTX)
  1396. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1397. return bits;
  1398. }
  1399. /*
  1400. * Gets only a single line (that's what we need
  1401. * for now) or shows full command output in pager.
  1402. *
  1403. * If pager is valid, returns NULL
  1404. */
  1405. static char *
  1406. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1407. {
  1408. pid_t pid;
  1409. int pipefd[2];
  1410. FILE *pf;
  1411. int tmp, flags;
  1412. char *ret = NULL;
  1413. if (pipe(pipefd) == -1)
  1414. errexit();
  1415. for (tmp = 0; tmp < 2; ++tmp) {
  1416. /* Get previous flags */
  1417. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1418. /* Set bit for non-blocking flag */
  1419. flags |= O_NONBLOCK;
  1420. /* Change flags on fd */
  1421. fcntl(pipefd[tmp], F_SETFL, flags);
  1422. }
  1423. pid = fork();
  1424. if (pid == 0) {
  1425. /* In child */
  1426. close(pipefd[0]);
  1427. dup2(pipefd[1], STDOUT_FILENO);
  1428. dup2(pipefd[1], STDERR_FILENO);
  1429. close(pipefd[1]);
  1430. execlp(file, file, arg1, arg2, NULL);
  1431. _exit(1);
  1432. }
  1433. /* In parent */
  1434. waitpid(pid, &tmp, 0);
  1435. close(pipefd[1]);
  1436. if (!pager) {
  1437. pf = fdopen(pipefd[0], "r");
  1438. if (pf) {
  1439. ret = fgets(buf, bytes, pf);
  1440. close(pipefd[0]);
  1441. }
  1442. return ret;
  1443. }
  1444. pid = fork();
  1445. if (pid == 0) {
  1446. /* Show in pager in child */
  1447. dup2(pipefd[0], STDIN_FILENO);
  1448. close(pipefd[0]);
  1449. execlp("less", "less", NULL);
  1450. _exit(1);
  1451. }
  1452. /* In parent */
  1453. waitpid(pid, &tmp, 0);
  1454. close(pipefd[0]);
  1455. return NULL;
  1456. }
  1457. /*
  1458. * Follows the stat(1) output closely
  1459. */
  1460. static int
  1461. show_stats(char *fpath, char *fname, struct stat *sb)
  1462. {
  1463. char desc[DESCRIPTOR_LEN];
  1464. char *perms = get_lsperms(sb->st_mode, desc);
  1465. char *p, *begin = g_buf;
  1466. char tmp[] = "/tmp/nnnXXXXXX";
  1467. int fd = mkstemp(tmp);
  1468. if (fd == -1)
  1469. return -1;
  1470. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1471. /* Show file name or 'symlink' -> 'target' */
  1472. if (perms[0] == 'l') {
  1473. /* Note that MAX_CMD_LEN > PATH_MAX */
  1474. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1475. if (len != -1) {
  1476. g_buf[len] = '\0';
  1477. /*
  1478. * We pass g_buf but unescape() operates on g_buf too!
  1479. * Read the API notes for information on how this works.
  1480. */
  1481. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1482. }
  1483. }
  1484. /* Show size, blocks, file type */
  1485. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1486. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1487. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1488. #else
  1489. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1490. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1491. #endif
  1492. /* Show containing device, inode, hardlink count */
  1493. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1494. snprintf(g_buf, 32, "%xh/%ud", sb->st_dev, sb->st_dev);
  1495. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1496. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1497. #else
  1498. snprintf(g_buf, 32, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1499. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1500. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1501. #endif
  1502. /* Show major, minor number for block or char device */
  1503. if (perms[0] == 'b' || perms[0] == 'c')
  1504. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1505. /* Show permissions, owner, group */
  1506. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1507. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1508. /* Show last access time */
  1509. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_atime));
  1510. dprintf(fd, "\n\n Access: %s", g_buf);
  1511. /* Show last modification time */
  1512. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_mtime));
  1513. dprintf(fd, "\n Modify: %s", g_buf);
  1514. /* Show last status change time */
  1515. strftime(g_buf, 40, messages[STR_DATE_ID], localtime(&sb->st_ctime));
  1516. dprintf(fd, "\n Change: %s", g_buf);
  1517. if (S_ISREG(sb->st_mode)) {
  1518. /* Show file(1) output */
  1519. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1520. if (p) {
  1521. dprintf(fd, "\n\n ");
  1522. while (*p) {
  1523. if (*p == ',') {
  1524. *p = '\0';
  1525. dprintf(fd, " %s\n", begin);
  1526. begin = p + 1;
  1527. }
  1528. ++p;
  1529. }
  1530. dprintf(fd, " %s", begin);
  1531. }
  1532. dprintf(fd, "\n\n");
  1533. } else
  1534. dprintf(fd, "\n\n\n");
  1535. close(fd);
  1536. exitcurses();
  1537. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1538. unlink(tmp);
  1539. refresh();
  1540. return 0;
  1541. }
  1542. static size_t
  1543. get_fs_free(const char *path)
  1544. {
  1545. static struct statvfs svb;
  1546. if (statvfs(path, &svb) == -1)
  1547. return 0;
  1548. else
  1549. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1550. }
  1551. static size_t
  1552. get_fs_capacity(const char *path)
  1553. {
  1554. struct statvfs svb;
  1555. if (statvfs(path, &svb) == -1)
  1556. return 0;
  1557. else
  1558. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1559. }
  1560. static int
  1561. show_mediainfo(char *fpath, char *arg)
  1562. {
  1563. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1564. return -1;
  1565. exitcurses();
  1566. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1567. refresh();
  1568. return 0;
  1569. }
  1570. static int
  1571. handle_archive(char *fpath, char *arg, char *dir)
  1572. {
  1573. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[ATOOL], NULL, 0))
  1574. return -1;
  1575. if (arg[1] == 'x')
  1576. spawn(utils[ATOOL], arg, fpath, dir, F_NORMAL);
  1577. else {
  1578. exitcurses();
  1579. get_output(NULL, 0, utils[ATOOL], arg, fpath, 1);
  1580. refresh();
  1581. }
  1582. return 0;
  1583. }
  1584. /*
  1585. * The help string tokens (each line) start with a HEX value
  1586. * which indicates the number of spaces to print before the
  1587. * particular token. This method was chosen instead of a flat
  1588. * string because the number of bytes in help was increasing
  1589. * the binary size by around a hundred bytes. This would only
  1590. * have increased as we keep adding new options.
  1591. */
  1592. static int
  1593. show_help(char *path)
  1594. {
  1595. char tmp[] = "/tmp/nnnXXXXXX";
  1596. int i = 0, fd = mkstemp(tmp);
  1597. char *start, *end;
  1598. static char helpstr[] = (
  1599. "cKey | Function\n"
  1600. "e- + -\n"
  1601. "7↑, k, ^P | Previous entry\n"
  1602. "7↓, j, ^N | Next entry\n"
  1603. "7PgUp, ^U | Scroll half page up\n"
  1604. "7PgDn, ^D | Scroll half page down\n"
  1605. "1Home, g, ^, ^A | First entry\n"
  1606. "2End, G, $, ^E | Last entry\n"
  1607. "4→, ↵, l, ^M | Open file or enter dir\n"
  1608. "1←, Bksp, h, ^H | Go to parent dir\n"
  1609. "d^O | Open with...\n"
  1610. "5Insert, ^I | Toggle navigate-as-you-type\n"
  1611. "e~ | Go HOME\n"
  1612. "e& | Go to initial dir\n"
  1613. "e- | Go to last visited dir\n"
  1614. "e/ | Filter dir contents\n"
  1615. "d^/ | Open desktop search tool\n"
  1616. "e. | Toggle hide . files\n"
  1617. "d^B | Bookmark prompt\n"
  1618. "eb | Pin current dir\n"
  1619. "d^V | Go to pinned dir\n"
  1620. "ec | Change dir prompt\n"
  1621. "ed | Toggle detail view\n"
  1622. "eD | File details\n"
  1623. "em | Brief media info\n"
  1624. "eM | Full media info\n"
  1625. "en | Create new\n"
  1626. "d^R | Rename entry\n"
  1627. "eR | Rename dir entries\n"
  1628. "es | Toggle sort by size\n"
  1629. "aS, ^J | Toggle du mode\n"
  1630. "et | Toggle sort by mtime\n"
  1631. "e! | Spawn SHELL in dir\n"
  1632. "ee | Edit entry in EDITOR\n"
  1633. "eo | Open dir in file manager\n"
  1634. "ep | Open entry in PAGER\n"
  1635. "eF | List archive\n"
  1636. "d^F | Extract archive\n"
  1637. "d^K | Invoke file path copier\n"
  1638. "d^Y | Toggle multi-copy mode\n"
  1639. "d^T | Toggle path quote\n"
  1640. "d^L | Redraw, clear prompt\n"
  1641. "e? | Help, settings\n"
  1642. "aQ, ^G | Quit and cd\n"
  1643. "aq, ^X | Quit\n\n");
  1644. if (fd == -1)
  1645. return -1;
  1646. start = end = helpstr;
  1647. while (*end) {
  1648. while (*end != '\n')
  1649. ++end;
  1650. if (start == end) {
  1651. ++end;
  1652. continue;
  1653. }
  1654. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1655. start = ++end;
  1656. }
  1657. dprintf(fd, "\n");
  1658. if (getenv("NNN_BMS")) {
  1659. dprintf(fd, "BOOKMARKS\n");
  1660. for (; i < BM_MAX; ++i)
  1661. if (bookmark[i].key)
  1662. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1663. else
  1664. break;
  1665. dprintf(fd, "\n");
  1666. }
  1667. if (editor)
  1668. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1669. if (desktop_manager)
  1670. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1671. if (idletimeout)
  1672. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1673. if (copier)
  1674. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1675. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1676. dprintf(fd, "%s free\n", coolsize(get_fs_capacity(path)));
  1677. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1678. close(fd);
  1679. exitcurses();
  1680. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1681. unlink(tmp);
  1682. refresh();
  1683. return 0;
  1684. }
  1685. static int
  1686. sum_bsizes(const char *fpath, const struct stat *sb,
  1687. int typeflag, struct FTW *ftwbuf)
  1688. {
  1689. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1690. ent_blocks += sb->st_blocks;
  1691. ++num_files;
  1692. return 0;
  1693. }
  1694. static int
  1695. dentfill(char *path, struct entry **dents,
  1696. int (*filter)(regex_t *, char *), regex_t *re)
  1697. {
  1698. static DIR *dirp;
  1699. static struct dirent *dp;
  1700. static char *namep, *pnb;
  1701. static struct entry *dentp;
  1702. static size_t off, namebuflen = NAMEBUF_INCR;
  1703. static ulong num_saved;
  1704. static int fd, n, count;
  1705. static struct stat sb_path, sb;
  1706. off = 0;
  1707. dirp = opendir(path);
  1708. if (dirp == NULL)
  1709. return 0;
  1710. fd = dirfd(dirp);
  1711. n = 0;
  1712. if (cfg.blkorder) {
  1713. num_files = 0;
  1714. dir_blocks = 0;
  1715. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1716. printwarn();
  1717. return 0;
  1718. }
  1719. }
  1720. while ((dp = readdir(dirp)) != NULL) {
  1721. namep = dp->d_name;
  1722. if (filter(re, namep) == 0) {
  1723. if (!cfg.blkorder)
  1724. continue;
  1725. /* Skip self and parent */
  1726. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1727. continue;
  1728. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1729. continue;
  1730. if (S_ISDIR(sb.st_mode)) {
  1731. if (sb_path.st_dev == sb.st_dev) {
  1732. ent_blocks = 0;
  1733. mkpath(path, namep, g_buf, PATH_MAX);
  1734. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1735. printmsg(messages[STR_NFTWFAIL_ID]);
  1736. dir_blocks += sb.st_blocks;
  1737. } else
  1738. dir_blocks += ent_blocks;
  1739. }
  1740. } else {
  1741. if (sb.st_blocks)
  1742. dir_blocks += sb.st_blocks;
  1743. ++num_files;
  1744. }
  1745. continue;
  1746. }
  1747. /* Skip self and parent */
  1748. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1749. (namep[1] == '.' && namep[2] == '\0'))))
  1750. continue;
  1751. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1752. DPRINTF_S(namep);
  1753. continue;
  1754. }
  1755. if (n == total_dents) {
  1756. total_dents += ENTRY_INCR;
  1757. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1758. if (*dents == NULL) {
  1759. if (pnamebuf)
  1760. free(pnamebuf);
  1761. errexit();
  1762. }
  1763. DPRINTF_P(*dents);
  1764. }
  1765. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1766. if (namebuflen - off < NAME_MAX + 1) {
  1767. namebuflen += NAMEBUF_INCR;
  1768. pnb = pnamebuf;
  1769. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1770. if (pnamebuf == NULL) {
  1771. free(*dents);
  1772. errexit();
  1773. }
  1774. DPRINTF_P(pnamebuf);
  1775. /* realloc() may result in memory move, we must re-adjust if that happens */
  1776. if (pnb != pnamebuf) {
  1777. dentp = *dents;
  1778. dentp->name = pnamebuf;
  1779. for (count = 1; count < n; ++dentp, ++count)
  1780. /* Current filename starts at last filename start + length */
  1781. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1782. }
  1783. }
  1784. dentp = *dents + n;
  1785. /* Copy file name */
  1786. dentp->name = (char *)((size_t)pnamebuf + off);
  1787. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1788. off += dentp->nlen;
  1789. /* Copy other fields */
  1790. dentp->mode = sb.st_mode;
  1791. dentp->t = sb.st_mtime;
  1792. dentp->size = sb.st_size;
  1793. if (cfg.blkorder) {
  1794. if (S_ISDIR(sb.st_mode)) {
  1795. ent_blocks = 0;
  1796. num_saved = num_files + 1;
  1797. mkpath(path, namep, g_buf, PATH_MAX);
  1798. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1799. printmsg(messages[STR_NFTWFAIL_ID]);
  1800. dentp->blocks = sb.st_blocks;
  1801. } else
  1802. dentp->blocks = ent_blocks;
  1803. if (sb_path.st_dev == sb.st_dev)
  1804. dir_blocks += dentp->blocks;
  1805. else
  1806. num_files = num_saved;
  1807. } else {
  1808. dentp->blocks = sb.st_blocks;
  1809. dir_blocks += dentp->blocks;
  1810. ++num_files;
  1811. }
  1812. }
  1813. ++n;
  1814. }
  1815. /* Should never be null */
  1816. if (closedir(dirp) == -1) {
  1817. if (*dents) {
  1818. free(pnamebuf);
  1819. free(*dents);
  1820. }
  1821. errexit();
  1822. }
  1823. return n;
  1824. }
  1825. static void
  1826. dentfree(struct entry *dents)
  1827. {
  1828. free(pnamebuf);
  1829. free(dents);
  1830. }
  1831. /* Return the position of the matching entry or 0 otherwise */
  1832. static int
  1833. dentfind(struct entry *dents, const char *fname, int n)
  1834. {
  1835. static int i;
  1836. if (!fname)
  1837. return 0;
  1838. DPRINTF_S(fname);
  1839. for (i = 0; i < n; ++i)
  1840. if (xstrcmp(fname, dents[i].name) == 0)
  1841. return i;
  1842. return 0;
  1843. }
  1844. static int
  1845. populate(char *path, char *oldname, char *fltr)
  1846. {
  1847. static regex_t re;
  1848. /* Can fail when permissions change while browsing.
  1849. * It's assumed that path IS a directory when we are here.
  1850. */
  1851. if (access(path, R_OK) == -1)
  1852. return -1;
  1853. /* Search filter */
  1854. if (setfilter(&re, fltr) != 0)
  1855. return -1;
  1856. if (cfg.blkorder) {
  1857. printmsg("calculating...");
  1858. refresh();
  1859. }
  1860. #ifdef DEBUGMODE
  1861. struct timespec ts1, ts2;
  1862. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1863. #endif
  1864. ndents = dentfill(path, &dents, visible, &re);
  1865. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1866. #ifdef DEBUGMODE
  1867. clock_gettime(CLOCK_REALTIME, &ts2);
  1868. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1869. #endif
  1870. /* Find cur from history */
  1871. cur = dentfind(dents, oldname, ndents);
  1872. regfree(&re);
  1873. return 0;
  1874. }
  1875. static void
  1876. redraw(char *path)
  1877. {
  1878. static char buf[(NAME_MAX + 1) << 1] __attribute__ ((aligned));
  1879. static size_t ncols;
  1880. static int nlines, i;
  1881. static bool mode_changed;
  1882. mode_changed = FALSE;
  1883. nlines = MIN(LINES - 4, ndents);
  1884. /* Clean screen */
  1885. erase();
  1886. if (cfg.copymode)
  1887. if (g_crc != crc8fast((uchar *)dents, ndents * sizeof(struct entry))) {
  1888. cfg.copymode = 0;
  1889. DPRINTF_S("copymode off");
  1890. }
  1891. /* Fail redraw if < than 10 columns */
  1892. if (COLS < 10) {
  1893. printmsg("too few columns!");
  1894. return;
  1895. }
  1896. /* Strip trailing slashes */
  1897. for (i = xstrlen(path) - 1; i > 0; --i)
  1898. if (path[i] == '/')
  1899. path[i] = '\0';
  1900. else
  1901. break;
  1902. DPRINTF_D(cur);
  1903. DPRINTF_S(path);
  1904. if (!realpath(path, g_buf)) {
  1905. printwarn();
  1906. return;
  1907. }
  1908. ncols = COLS;
  1909. if (ncols > PATH_MAX)
  1910. ncols = PATH_MAX;
  1911. /* No text wrapping in cwd line */
  1912. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1913. g_buf[ncols - 6] = '\0';
  1914. printw(CWD "%s\n\n", g_buf);
  1915. /* Fallback to light mode if less than 35 columns */
  1916. if (ncols < 35 && cfg.showdetail) {
  1917. cfg.showdetail ^= 1;
  1918. printptr = &printent;
  1919. mode_changed = TRUE;
  1920. }
  1921. /* Calculate the number of cols available to print entry name */
  1922. if (cfg.showdetail)
  1923. ncols -= 32;
  1924. else
  1925. ncols -= 5;
  1926. if (cfg.showcolor) {
  1927. attron(COLOR_PAIR(1) | A_BOLD);
  1928. cfg.dircolor = 1;
  1929. }
  1930. /* Print listing */
  1931. if (cur < (nlines >> 1)) {
  1932. for (i = 0; i < nlines; ++i)
  1933. printptr(&dents[i], i == cur, ncols);
  1934. } else if (cur >= ndents - (nlines >> 1)) {
  1935. for (i = ndents - nlines; i < ndents; ++i)
  1936. printptr(&dents[i], i == cur, ncols);
  1937. } else {
  1938. static int odd;
  1939. odd = ISODD(nlines);
  1940. nlines >>= 1;
  1941. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1942. printptr(&dents[i], i == cur, ncols);
  1943. }
  1944. /* Must reset e.g. no files in dir */
  1945. if (cfg.dircolor) {
  1946. attroff(COLOR_PAIR(1) | A_BOLD);
  1947. cfg.dircolor = 0;
  1948. }
  1949. if (cfg.showdetail) {
  1950. if (ndents) {
  1951. static char sort[9];
  1952. if (cfg.mtimeorder)
  1953. xstrlcpy(sort, "by time ", 9);
  1954. else if (cfg.sizeorder)
  1955. xstrlcpy(sort, "by size ", 9);
  1956. else
  1957. sort[0] = '\0';
  1958. /* We need to show filename as it may be truncated in directory listing */
  1959. if (!cfg.blkorder)
  1960. snprintf(buf, (NAME_MAX + 1) << 1, "%d/%d %s[%s%s]",
  1961. cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1962. else {
  1963. i = snprintf(buf, 128, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1964. snprintf(buf + i, ((NAME_MAX + 1) << 1) - 128, "vol: %s free [%s%s]",
  1965. coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1966. }
  1967. printmsg(buf);
  1968. } else
  1969. printmsg("0 items");
  1970. }
  1971. if (mode_changed) {
  1972. cfg.showdetail ^= 1;
  1973. printptr = &printent_long;
  1974. }
  1975. }
  1976. static void
  1977. browse(char *ipath, char *ifilter)
  1978. {
  1979. static char path[PATH_MAX] __attribute__ ((aligned));
  1980. static char newpath[PATH_MAX] __attribute__ ((aligned));
  1981. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  1982. static char mark[PATH_MAX] __attribute__ ((aligned));
  1983. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  1984. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  1985. char *dir, *tmp, *run = NULL, *env = NULL;
  1986. struct stat sb;
  1987. int r, fd, presel, copystartid = 0, copyendid = 0;
  1988. enum action sel = SEL_RUNARG + 1;
  1989. bool dir_changed = FALSE;
  1990. xstrlcpy(path, ipath, PATH_MAX);
  1991. copyfilter();
  1992. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1993. if (cfg.filtermode)
  1994. presel = FILTER;
  1995. else
  1996. presel = 0;
  1997. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  1998. if (dents == NULL)
  1999. errexit();
  2000. DPRINTF_P(dents);
  2001. /* Allocate buffer to hold names */
  2002. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  2003. if (pnamebuf == NULL) {
  2004. free(dents);
  2005. errexit();
  2006. }
  2007. DPRINTF_P(pnamebuf);
  2008. begin:
  2009. #ifdef LINUX_INOTIFY
  2010. if (dir_changed && inotify_wd >= 0) {
  2011. inotify_rm_watch(inotify_fd, inotify_wd);
  2012. inotify_wd = -1;
  2013. dir_changed = FALSE;
  2014. }
  2015. #elif defined(BSD_KQUEUE)
  2016. if (dir_changed && event_fd >= 0) {
  2017. close(event_fd);
  2018. event_fd = -1;
  2019. dir_changed = FALSE;
  2020. }
  2021. #endif
  2022. if (populate(path, oldname, fltr) == -1) {
  2023. printwarn();
  2024. goto nochange;
  2025. }
  2026. #ifdef LINUX_INOTIFY
  2027. if (inotify_wd == -1)
  2028. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  2029. #elif defined(BSD_KQUEUE)
  2030. if (event_fd == -1) {
  2031. #if defined(O_EVTONLY)
  2032. event_fd = open(path, O_EVTONLY);
  2033. #else
  2034. event_fd = open(path, O_RDONLY);
  2035. #endif
  2036. if (event_fd >= 0)
  2037. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  2038. }
  2039. #endif
  2040. for (;;) {
  2041. redraw(path);
  2042. nochange:
  2043. /* Exit if parent has exited */
  2044. if (getppid() == 1)
  2045. _exit(0);
  2046. sel = nextsel(&run, &env, &presel);
  2047. switch (sel) {
  2048. case SEL_BACK:
  2049. /* There is no going back */
  2050. if (istopdir(path)) {
  2051. printmsg(messages[STR_ATROOT_ID]);
  2052. goto nochange;
  2053. }
  2054. dir = xdirname(path);
  2055. if (access(dir, R_OK) == -1) {
  2056. printwarn();
  2057. goto nochange;
  2058. }
  2059. /* Save history */
  2060. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2061. /* Save last working directory */
  2062. xstrlcpy(lastdir, path, PATH_MAX);
  2063. dir_changed = TRUE;
  2064. xstrlcpy(path, dir, PATH_MAX);
  2065. /* Reset filter */
  2066. copyfilter();
  2067. if (cfg.filtermode)
  2068. presel = FILTER;
  2069. goto begin;
  2070. case SEL_GOIN:
  2071. /* Cannot descend in empty directories */
  2072. if (ndents == 0)
  2073. goto begin;
  2074. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2075. DPRINTF_S(newpath);
  2076. /* Get path info */
  2077. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  2078. if (fd == -1) {
  2079. printwarn();
  2080. goto nochange;
  2081. }
  2082. if (fstat(fd, &sb) == -1) {
  2083. printwarn();
  2084. close(fd);
  2085. goto nochange;
  2086. }
  2087. close(fd);
  2088. DPRINTF_U(sb.st_mode);
  2089. switch (sb.st_mode & S_IFMT) {
  2090. case S_IFDIR:
  2091. if (access(newpath, R_OK) == -1) {
  2092. printwarn();
  2093. goto nochange;
  2094. }
  2095. /* Save last working directory */
  2096. xstrlcpy(lastdir, path, PATH_MAX);
  2097. dir_changed = TRUE;
  2098. xstrlcpy(path, newpath, PATH_MAX);
  2099. oldname[0] = '\0';
  2100. /* Reset filter */
  2101. copyfilter();
  2102. if (cfg.filtermode)
  2103. presel = FILTER;
  2104. goto begin;
  2105. case S_IFREG:
  2106. {
  2107. /* If NNN_USE_EDITOR is set,
  2108. * open text in EDITOR
  2109. */
  2110. if (editor) {
  2111. if (getmime(dents[cur].name)) {
  2112. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  2113. continue;
  2114. }
  2115. /* Recognize and open plain
  2116. * text files with vi
  2117. */
  2118. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  2119. continue;
  2120. if (strstr(g_buf, "text/") == g_buf) {
  2121. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  2122. continue;
  2123. }
  2124. }
  2125. /* Invoke desktop opener as last resort */
  2126. spawn(utils[OPENER], newpath, NULL, NULL, nowait);
  2127. continue;
  2128. }
  2129. default:
  2130. printmsg("unsupported file");
  2131. goto nochange;
  2132. }
  2133. case SEL_NEXT:
  2134. if (cur < ndents - 1)
  2135. ++cur;
  2136. else if (ndents)
  2137. /* Roll over, set cursor to first entry */
  2138. cur = 0;
  2139. break;
  2140. case SEL_PREV:
  2141. if (cur > 0)
  2142. --cur;
  2143. else if (ndents)
  2144. /* Roll over, set cursor to last entry */
  2145. cur = ndents - 1;
  2146. break;
  2147. case SEL_PGDN:
  2148. if (cur < ndents - 1)
  2149. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  2150. break;
  2151. case SEL_PGUP:
  2152. if (cur > 0)
  2153. cur -= MIN((LINES - 4) / 2, cur);
  2154. break;
  2155. case SEL_HOME:
  2156. cur = 0;
  2157. break;
  2158. case SEL_END:
  2159. cur = ndents - 1;
  2160. break;
  2161. case SEL_CD:
  2162. {
  2163. char *input;
  2164. int truecd;
  2165. /* Save the program start dir */
  2166. tmp = getcwd(newpath, PATH_MAX);
  2167. if (tmp == NULL) {
  2168. printwarn();
  2169. goto nochange;
  2170. }
  2171. /* Switch to current path for readline(3) */
  2172. if (chdir(path) == -1) {
  2173. printwarn();
  2174. goto nochange;
  2175. }
  2176. exitcurses();
  2177. tmp = readline("chdir: ");
  2178. refresh();
  2179. /* Change back to program start dir */
  2180. if (chdir(newpath) == -1)
  2181. printwarn();
  2182. if (tmp[0] == '\0')
  2183. break;
  2184. /* Add to readline(3) history */
  2185. add_history(tmp);
  2186. input = tmp;
  2187. tmp = strstrip(tmp);
  2188. if (tmp[0] == '\0') {
  2189. free(input);
  2190. break;
  2191. }
  2192. truecd = 0;
  2193. if (tmp[0] == '~') {
  2194. /* Expand ~ to HOME absolute path */
  2195. char *home = getenv("HOME");
  2196. if (home)
  2197. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2198. else {
  2199. free(input);
  2200. printmsg(messages[STR_NOHOME_ID]);
  2201. goto nochange;
  2202. }
  2203. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2204. if (lastdir[0] == '\0') {
  2205. free(input);
  2206. break;
  2207. }
  2208. /* Switch to last visited dir */
  2209. xstrlcpy(newpath, lastdir, PATH_MAX);
  2210. truecd = 1;
  2211. } else if ((r = all_dots(tmp))) {
  2212. if (r == 1) {
  2213. /* Always in the current dir */
  2214. free(input);
  2215. break;
  2216. }
  2217. /* Show a message if already at / */
  2218. if (istopdir(path)) {
  2219. printmsg(messages[STR_ATROOT_ID]);
  2220. free(input);
  2221. goto nochange;
  2222. }
  2223. --r; /* One . for the current dir */
  2224. dir = path;
  2225. /* Note: fd is used as a tmp variable here */
  2226. for (fd = 0; fd < r; ++fd) {
  2227. /* Reached / ? */
  2228. if (istopdir(path)) {
  2229. /* Can't cd beyond / */
  2230. break;
  2231. }
  2232. dir = xdirname(dir);
  2233. if (access(dir, R_OK) == -1) {
  2234. printwarn();
  2235. free(input);
  2236. goto nochange;
  2237. }
  2238. }
  2239. truecd = 1;
  2240. /* Save the path in case of cd ..
  2241. * We mark the current dir in parent dir
  2242. */
  2243. if (r == 1) {
  2244. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2245. truecd = 2;
  2246. }
  2247. xstrlcpy(newpath, dir, PATH_MAX);
  2248. } else
  2249. mkpath(path, tmp, newpath, PATH_MAX);
  2250. free(input);
  2251. if (!xdiraccess(newpath))
  2252. goto nochange;
  2253. if (truecd == 0) {
  2254. /* Probable change in dir */
  2255. /* No-op if it's the same directory */
  2256. if (xstrcmp(path, newpath) == 0)
  2257. break;
  2258. oldname[0] = '\0';
  2259. } else if (truecd == 1)
  2260. /* Sure change in dir */
  2261. oldname[0] = '\0';
  2262. /* Save last working directory */
  2263. xstrlcpy(lastdir, path, PATH_MAX);
  2264. dir_changed = TRUE;
  2265. /* Save the newly opted dir in path */
  2266. xstrlcpy(path, newpath, PATH_MAX);
  2267. /* Reset filter */
  2268. copyfilter();
  2269. DPRINTF_S(path);
  2270. if (cfg.filtermode)
  2271. presel = FILTER;
  2272. goto begin;
  2273. }
  2274. case SEL_CDHOME:
  2275. dir = getenv("HOME");
  2276. if (dir == NULL) {
  2277. clearprompt();
  2278. goto nochange;
  2279. } // fallthrough
  2280. case SEL_CDBEGIN:
  2281. if (sel == SEL_CDBEGIN)
  2282. dir = ipath;
  2283. if (!xdiraccess(dir)) {
  2284. goto nochange;
  2285. }
  2286. if (xstrcmp(path, dir) == 0) {
  2287. break;
  2288. }
  2289. /* Save last working directory */
  2290. xstrlcpy(lastdir, path, PATH_MAX);
  2291. dir_changed = TRUE;
  2292. xstrlcpy(path, dir, PATH_MAX);
  2293. oldname[0] = '\0';
  2294. /* Reset filter */
  2295. copyfilter();
  2296. DPRINTF_S(path);
  2297. if (cfg.filtermode)
  2298. presel = FILTER;
  2299. goto begin;
  2300. case SEL_CDLAST: // fallthrough
  2301. case SEL_VISIT:
  2302. if (sel == SEL_VISIT) {
  2303. if (xstrcmp(mark, path) == 0)
  2304. break;
  2305. tmp = mark;
  2306. } else
  2307. tmp = lastdir;
  2308. if (tmp[0] == '\0') {
  2309. printmsg("not set...");
  2310. goto nochange;
  2311. }
  2312. if (!xdiraccess(tmp))
  2313. goto nochange;
  2314. xstrlcpy(newpath, tmp, PATH_MAX);
  2315. xstrlcpy(lastdir, path, PATH_MAX);
  2316. dir_changed = TRUE;
  2317. xstrlcpy(path, newpath, PATH_MAX);
  2318. oldname[0] = '\0';
  2319. /* Reset filter */
  2320. copyfilter();
  2321. DPRINTF_S(path);
  2322. if (cfg.filtermode)
  2323. presel = FILTER;
  2324. goto begin;
  2325. case SEL_CDBM:
  2326. printprompt("key: ");
  2327. tmp = readinput();
  2328. clearprompt();
  2329. if (tmp == NULL || tmp[0] == '\0')
  2330. break;
  2331. /* Interpret ~, - and & keys */
  2332. if ((tmp[1] == '\0') && (tmp[0] == '~' || tmp[0] == '-' || tmp[0] == '&')) {
  2333. presel = tmp[0];
  2334. goto begin;
  2335. }
  2336. if (get_bm_loc(tmp, newpath) == NULL) {
  2337. printmsg(messages[STR_INVBM_ID]);
  2338. goto nochange;
  2339. }
  2340. if (!xdiraccess(newpath))
  2341. goto nochange;
  2342. if (xstrcmp(path, newpath) == 0)
  2343. break;
  2344. oldname[0] = '\0';
  2345. /* Save last working directory */
  2346. xstrlcpy(lastdir, path, PATH_MAX);
  2347. dir_changed = TRUE;
  2348. /* Save the newly opted dir in path */
  2349. xstrlcpy(path, newpath, PATH_MAX);
  2350. /* Reset filter */
  2351. copyfilter();
  2352. DPRINTF_S(path);
  2353. if (cfg.filtermode)
  2354. presel = FILTER;
  2355. goto begin;
  2356. case SEL_PIN:
  2357. xstrlcpy(mark, path, PATH_MAX);
  2358. printmsg(mark);
  2359. goto nochange;
  2360. case SEL_FLTR:
  2361. presel = filterentries(path);
  2362. copyfilter();
  2363. DPRINTF_S(fltr);
  2364. /* Save current */
  2365. if (ndents > 0)
  2366. copycurname();
  2367. goto nochange;
  2368. case SEL_MFLTR:
  2369. cfg.filtermode ^= 1;
  2370. if (cfg.filtermode)
  2371. presel = FILTER;
  2372. else {
  2373. /* Save current */
  2374. if (ndents > 0)
  2375. copycurname();
  2376. /* Start watching the directory */
  2377. goto begin;
  2378. }
  2379. goto nochange;
  2380. case SEL_SEARCH:
  2381. spawn(player, path, "search", NULL, F_NORMAL);
  2382. break;
  2383. case SEL_TOGGLEDOT:
  2384. cfg.showhidden ^= 1;
  2385. initfilter(cfg.showhidden, &ifilter);
  2386. copyfilter();
  2387. goto begin;
  2388. case SEL_DETAIL:
  2389. cfg.showdetail ^= 1;
  2390. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2391. /* Save current */
  2392. if (ndents > 0)
  2393. copycurname();
  2394. goto begin;
  2395. case SEL_STATS:
  2396. if (ndents > 0) {
  2397. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2398. if (lstat(newpath, &sb) == -1) {
  2399. if (dents)
  2400. dentfree(dents);
  2401. errexit();
  2402. } else {
  2403. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2404. printwarn();
  2405. goto nochange;
  2406. }
  2407. }
  2408. }
  2409. break;
  2410. case SEL_LIST: // fallthrough
  2411. case SEL_EXTRACT: // fallthrough
  2412. case SEL_MEDIA: // fallthrough
  2413. case SEL_FMEDIA:
  2414. if (ndents > 0) {
  2415. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2416. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2417. r = show_mediainfo(newpath, run);
  2418. else
  2419. r = handle_archive(newpath, run, path);
  2420. if (r == -1) {
  2421. xstrlcpy(newpath, "missing ", PATH_MAX);
  2422. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2423. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2424. else
  2425. xstrlcpy(newpath + 8, utils[ATOOL], 32);
  2426. printmsg(newpath);
  2427. goto nochange;
  2428. }
  2429. }
  2430. break;
  2431. case SEL_DFB:
  2432. if (!desktop_manager) {
  2433. printmsg("set NNN_DE_FILE_MANAGER");
  2434. goto nochange;
  2435. }
  2436. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2437. break;
  2438. case SEL_FSIZE:
  2439. cfg.sizeorder ^= 1;
  2440. cfg.mtimeorder = 0;
  2441. cfg.blkorder = 0;
  2442. cfg.copymode = 0;
  2443. /* Save current */
  2444. if (ndents > 0)
  2445. copycurname();
  2446. goto begin;
  2447. case SEL_BSIZE:
  2448. cfg.blkorder ^= 1;
  2449. if (cfg.blkorder) {
  2450. cfg.showdetail = 1;
  2451. printptr = &printent_long;
  2452. }
  2453. cfg.mtimeorder = 0;
  2454. cfg.sizeorder = 0;
  2455. cfg.copymode = 0;
  2456. /* Save current */
  2457. if (ndents > 0)
  2458. copycurname();
  2459. goto begin;
  2460. case SEL_MTIME:
  2461. cfg.mtimeorder ^= 1;
  2462. cfg.sizeorder = 0;
  2463. cfg.blkorder = 0;
  2464. cfg.copymode = 0;
  2465. /* Save current */
  2466. if (ndents > 0)
  2467. copycurname();
  2468. goto begin;
  2469. case SEL_REDRAW:
  2470. /* Save current */
  2471. if (ndents > 0)
  2472. copycurname();
  2473. goto begin;
  2474. case SEL_COPY:
  2475. if (copier && ndents) {
  2476. if (cfg.copymode) {
  2477. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2478. if (!appendfilepath(newpath, r))
  2479. goto nochange;
  2480. printmsg(newpath);
  2481. } else if (cfg.quote) {
  2482. g_buf[0] = '\'';
  2483. r = mkpath(path, dents[cur].name, g_buf + 1, PATH_MAX);
  2484. g_buf[r] = '\'';
  2485. g_buf[r + 1] = '\0';
  2486. if (cfg.noxdisplay)
  2487. writecp(g_buf, r + 1); /* Truncate NULL from end */
  2488. else
  2489. spawn(copier, g_buf, NULL, NULL, F_NONE);
  2490. g_buf[r] = '\0';
  2491. printmsg(g_buf + 1);
  2492. } else {
  2493. r = mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2494. if (cfg.noxdisplay)
  2495. writecp(newpath, r - 1); /* Truncate NULL from end */
  2496. else
  2497. spawn(copier, newpath, NULL, NULL, F_NONE);
  2498. printmsg(newpath);
  2499. }
  2500. } else if (!copier)
  2501. printmsg(messages[STR_COPY_ID]);
  2502. goto nochange;
  2503. case SEL_COPYMUL:
  2504. if (!copier) {
  2505. printmsg(messages[STR_COPY_ID]);
  2506. goto nochange;
  2507. } else if (!ndents) {
  2508. goto nochange;
  2509. }
  2510. cfg.copymode ^= 1;
  2511. if (cfg.copymode) {
  2512. g_crc = crc8fast((uchar *)dents, ndents * sizeof(struct entry));
  2513. copystartid = cur;
  2514. copybufpos = 0;
  2515. printmsg("multi-copy on");
  2516. DPRINTF_S("copymode on");
  2517. } else {
  2518. static size_t len;
  2519. len = 0;
  2520. /* Handle range selection */
  2521. if (copybufpos == 0) {
  2522. if (cur < copystartid) {
  2523. copyendid = copystartid;
  2524. copystartid = cur;
  2525. } else
  2526. copyendid = cur;
  2527. if (copystartid < copyendid) {
  2528. for (r = copystartid; r <= copyendid; ++r) {
  2529. len = mkpath(path, dents[r].name, newpath, PATH_MAX);
  2530. if (!appendfilepath(newpath, len))
  2531. goto nochange;;
  2532. }
  2533. snprintf(newpath, PATH_MAX, "%d files copied", copyendid - copystartid + 1);
  2534. printmsg(newpath);
  2535. }
  2536. }
  2537. if (copybufpos) {
  2538. if (cfg.noxdisplay)
  2539. writecp(pcopybuf, copybufpos - 1); /* Truncate NULL from end */
  2540. else
  2541. spawn(copier, pcopybuf, NULL, NULL, F_NONE);
  2542. DPRINTF_S(pcopybuf);
  2543. if (!len)
  2544. printmsg("files copied");
  2545. } else
  2546. printmsg("multi-copy off");
  2547. }
  2548. goto nochange;
  2549. case SEL_QUOTE:
  2550. cfg.quote ^= 1;
  2551. DPRINTF_D(cfg.quote);
  2552. if (cfg.quote)
  2553. printmsg("quotes on");
  2554. else
  2555. printmsg("quotes off");
  2556. goto nochange;
  2557. case SEL_OPEN:
  2558. printprompt("open with: "); // fallthrough
  2559. case SEL_NEW:
  2560. if (sel == SEL_NEW)
  2561. printprompt("name: ");
  2562. tmp = xreadline(NULL);
  2563. clearprompt();
  2564. if (tmp == NULL || tmp[0] == '\0')
  2565. break;
  2566. /* Allow only relative, same dir paths */
  2567. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2568. printmsg(messages[STR_INPUT_ID]);
  2569. goto nochange;
  2570. }
  2571. if (sel == SEL_OPEN) {
  2572. printprompt("press 'c' for cli mode");
  2573. cleartimeout();
  2574. r = getch();
  2575. settimeout();
  2576. if (r == 'c')
  2577. r = F_NORMAL;
  2578. else
  2579. r = F_NOWAIT | F_NOTRACE;
  2580. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2581. spawn(tmp, newpath, NULL, path, r);
  2582. continue;
  2583. }
  2584. /* Open the descriptor to currently open directory */
  2585. fd = open(path, O_RDONLY | O_DIRECTORY);
  2586. if (fd == -1) {
  2587. printwarn();
  2588. goto nochange;
  2589. }
  2590. /* Check if another file with same name exists */
  2591. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2592. printmsg("entry exists");
  2593. goto nochange;
  2594. }
  2595. /* Check if it's a dir or file */
  2596. printprompt("press 'f'(ile) or 'd'(ir)");
  2597. cleartimeout();
  2598. r = getch();
  2599. settimeout();
  2600. if (r == 'f') {
  2601. r = openat(fd, tmp, O_CREAT, 0666);
  2602. close(r);
  2603. } else if (r == 'd')
  2604. r = mkdirat(fd, tmp, 0777);
  2605. else {
  2606. close(fd);
  2607. break;
  2608. }
  2609. if (r == -1) {
  2610. printwarn();
  2611. close(fd);
  2612. goto nochange;
  2613. }
  2614. close(fd);
  2615. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2616. goto begin;
  2617. case SEL_RENAME:
  2618. if (ndents <= 0)
  2619. break;
  2620. printprompt("");
  2621. tmp = xreadline(dents[cur].name);
  2622. clearprompt();
  2623. if (tmp == NULL || tmp[0] == '\0')
  2624. break;
  2625. /* Allow only relative, same dir paths */
  2626. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2627. printmsg(messages[STR_INPUT_ID]);
  2628. goto nochange;
  2629. }
  2630. /* Skip renaming to same name */
  2631. if (xstrcmp(tmp, dents[cur].name) == 0)
  2632. break;
  2633. /* Open the descriptor to currently open directory */
  2634. fd = open(path, O_RDONLY | O_DIRECTORY);
  2635. if (fd == -1) {
  2636. printwarn();
  2637. goto nochange;
  2638. }
  2639. /* Check if another file with same name exists */
  2640. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2641. /* File with the same name exists */
  2642. printprompt("press 'y' to overwrite");
  2643. cleartimeout();
  2644. r = getch();
  2645. settimeout();
  2646. if (r != 'y') {
  2647. close(fd);
  2648. break;
  2649. }
  2650. }
  2651. /* Rename the file */
  2652. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2653. printwarn();
  2654. close(fd);
  2655. goto nochange;
  2656. }
  2657. close(fd);
  2658. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2659. goto begin;
  2660. case SEL_RENAMEALL:
  2661. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[VIDIR], NULL, 0)) {
  2662. printmsg("vidir missing");
  2663. goto nochange;
  2664. }
  2665. /* Save the program start dir */
  2666. tmp = getcwd(newpath, PATH_MAX);
  2667. if (tmp == NULL) {
  2668. printwarn();
  2669. goto nochange;
  2670. }
  2671. /* Switch to current path for readline(3) */
  2672. if (chdir(path) == -1) {
  2673. printwarn();
  2674. goto nochange;
  2675. }
  2676. spawn(utils[VIDIR], ".", NULL, NULL, F_NORMAL);
  2677. /* Change back to program start dir */
  2678. if (chdir(newpath) == -1)
  2679. printwarn();
  2680. /* Save current */
  2681. if (ndents > 0)
  2682. copycurname();
  2683. goto begin;
  2684. case SEL_HELP:
  2685. show_help(path);
  2686. break;
  2687. case SEL_RUN:
  2688. run = xgetenv(env, run);
  2689. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2690. /* Repopulate as directory content may have changed */
  2691. /* Save current */
  2692. if (ndents > 0)
  2693. copycurname();
  2694. goto begin;
  2695. case SEL_RUNARG:
  2696. run = xgetenv(env, run);
  2697. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2698. break;
  2699. case SEL_CDQUIT:
  2700. {
  2701. char *tmpfile = "/tmp/nnn";
  2702. tmp = getenv("NNN_TMPFILE");
  2703. if (tmp)
  2704. tmpfile = tmp;
  2705. FILE *fp = fopen(tmpfile, "w");
  2706. if (fp) {
  2707. fprintf(fp, "cd \"%s\"", path);
  2708. fclose(fp);
  2709. }
  2710. /* Fall through to exit */
  2711. } // fallthrough
  2712. case SEL_QUIT:
  2713. dentfree(dents);
  2714. return;
  2715. } /* switch (sel) */
  2716. /* Screensaver */
  2717. if (idletimeout != 0 && idle == idletimeout) {
  2718. idle = 0;
  2719. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2720. }
  2721. }
  2722. }
  2723. static void
  2724. usage(void)
  2725. {
  2726. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2727. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2728. The missing terminal file browser for X.\n\n\
  2729. positional arguments:\n\
  2730. PATH start dir [default: current dir]\n\n\
  2731. optional arguments:\n\
  2732. -b key specify bookmark key to open\n\
  2733. -c N specify dir color, disables if N>7\n\
  2734. -e use exiftool instead of mediainfo\n\
  2735. -i start in navigate-as-you-type mode\n\
  2736. -l start in light mode (fewer details)\n\
  2737. -p nlay path to custom nlay\n\
  2738. -S start in disk usage analyzer mode\n\
  2739. -v show program version and exit\n\
  2740. -h show this help and exit\n\n\
  2741. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2742. exit(0);
  2743. }
  2744. int
  2745. main(int argc, char *argv[])
  2746. {
  2747. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2748. char *ipath = NULL, *ifilter, *bmstr;
  2749. int opt;
  2750. /* Confirm we are in a terminal */
  2751. if (!isatty(0) || !isatty(1)) {
  2752. fprintf(stderr, "stdin or stdout is not a tty\n");
  2753. exit(1);
  2754. }
  2755. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2756. switch (opt) {
  2757. case 'S':
  2758. cfg.blkorder = 1;
  2759. break;
  2760. case 'l':
  2761. cfg.showdetail = 0;
  2762. printptr = &printent;
  2763. break;
  2764. case 'i':
  2765. cfg.filtermode = 1;
  2766. break;
  2767. case 'b':
  2768. ipath = optarg;
  2769. break;
  2770. case 'c':
  2771. if (atoi(optarg) > 7)
  2772. cfg.showcolor = 0;
  2773. else
  2774. cfg.color = (uchar)atoi(optarg);
  2775. break;
  2776. case 'e':
  2777. cfg.metaviewer = EXIFTOOL;
  2778. break;
  2779. case 'p':
  2780. player = optarg;
  2781. break;
  2782. case 'v':
  2783. printf("%s\n", VERSION);
  2784. return 0;
  2785. case 'h': // fallthrough
  2786. default:
  2787. usage();
  2788. }
  2789. }
  2790. /* Parse bookmarks string, if available */
  2791. bmstr = getenv("NNN_BMS");
  2792. if (bmstr)
  2793. parsebmstr(bmstr);
  2794. if (ipath) { /* Open a bookmark directly */
  2795. if (get_bm_loc(ipath, cwd) == NULL) {
  2796. fprintf(stderr, "%s\n", messages[STR_INVBM_ID]);
  2797. exit(1);
  2798. }
  2799. ipath = cwd;
  2800. } else if (argc == optind) {
  2801. /* Start in the current directory */
  2802. ipath = getcwd(cwd, PATH_MAX);
  2803. if (ipath == NULL)
  2804. ipath = "/";
  2805. } else {
  2806. ipath = realpath(argv[optind], cwd);
  2807. if (!ipath) {
  2808. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2809. exit(1);
  2810. }
  2811. }
  2812. /* Increase current open file descriptor limit */
  2813. open_max = max_openfds();
  2814. if (getuid() == 0)
  2815. cfg.showhidden = 1;
  2816. initfilter(cfg.showhidden, &ifilter);
  2817. #ifdef LINUX_INOTIFY
  2818. /* Initialize inotify */
  2819. inotify_fd = inotify_init1(IN_NONBLOCK);
  2820. if (inotify_fd < 0) {
  2821. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2822. exit(1);
  2823. }
  2824. #elif defined(BSD_KQUEUE)
  2825. kq = kqueue();
  2826. if (kq < 0) {
  2827. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2828. exit(1);
  2829. }
  2830. gtimeout.tv_sec = 0;
  2831. gtimeout.tv_nsec = 0;
  2832. #endif
  2833. /* Edit text in EDITOR, if opted */
  2834. if (getenv("NNN_USE_EDITOR"))
  2835. editor = xgetenv("EDITOR", "vi");
  2836. /* Set player if not set already */
  2837. if (!player)
  2838. player = utils[NLAY];
  2839. /* Get the desktop file browser, if set */
  2840. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2841. /* Get screensaver wait time, if set; copier used as tmp var */
  2842. copier = getenv("NNN_IDLE_TIMEOUT");
  2843. if (copier)
  2844. idletimeout = abs(atoi(copier));
  2845. /* Get the default copier, if set */
  2846. copier = getenv("NNN_COPIER");
  2847. /* Get nowait flag */
  2848. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2849. /* Enable quotes if opted */
  2850. if (getenv("NNN_QUOTE_ON"))
  2851. cfg.quote = 1;
  2852. /* Check if X11 is available */
  2853. if (getenv("NNN_NO_X")) {
  2854. cfg.noxdisplay = 1;
  2855. struct passwd *pass = getpwuid(getuid());
  2856. xstrlcpy(g_cppath, "/tmp/nnncp", 11);
  2857. xstrlcpy(g_cppath + 10, pass->pw_name, 33);
  2858. }
  2859. signal(SIGINT, SIG_IGN);
  2860. /* Test initial path */
  2861. if (!xdiraccess(ipath)) {
  2862. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2863. exit(1);
  2864. }
  2865. /* Set locale */
  2866. setlocale(LC_ALL, "");
  2867. crc8init();
  2868. #ifdef DEBUGMODE
  2869. enabledbg();
  2870. #endif
  2871. initcurses();
  2872. browse(ipath, ifilter);
  2873. exitcurses();
  2874. #ifdef LINUX_INOTIFY
  2875. /* Shutdown inotify */
  2876. if (inotify_wd >= 0)
  2877. inotify_rm_watch(inotify_fd, inotify_wd);
  2878. close(inotify_fd);
  2879. #elif defined(BSD_KQUEUE)
  2880. if (event_fd >= 0)
  2881. close(event_fd);
  2882. close(kq);
  2883. #endif
  2884. #ifdef DEBUGMODE
  2885. disabledbg();
  2886. #endif
  2887. exit(0);
  2888. }