This repository has been archived by the owner on Feb 29, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
cfm.c
2180 lines (1973 loc) · 60.9 KB
/
cfm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim: set ai ts=4 et sw=4 tw=80 cino=ws,l1: */
/* Copyright (c) Will Eccles <will@eccles.dev>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef __APPLE__
# define _DARWIN_C_SOURCE
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
# define __BSD_VISIBLE 1
#endif
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <ftw.h>
#include <limits.h>
#include <signal.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
// include user config
#include "config.h"
#ifdef __GNUC__
# define UNUSED(x) UNUSED_##x __attribute__((unused))
#else
# define UNUSED(x) UNUSED_##x
#endif
#define K_ESC '\033'
#define ESC_UP 'A'
#define ESC_DOWN 'B'
#define ESC_LEFT 'D'
#define ESC_RIGHT 'C'
#define K_ALT(k) ((int)(k) | (int)0xFFFFFF00)
// arbitrary values for keys
#define KEY_PGUP 'K'
#define KEY_PGDN 'J'
#define LIST_ALLOC_SIZE 64
#ifndef POINTER
# define POINTER "->"
#endif /* POINTER */
#ifndef BOLD_POINTER
# define BOLD_POINTER 1
#endif
#ifndef INVERT_SELECTION
# define INVERT_SELECTION 1
#endif
#ifndef INVERT_FULL_SELECTION
# define INVERT_FULL_SELECTION 1
#endif
#ifndef INDENT_SELECTION
# define INDENT_SELECTION 1
#endif
#ifdef OPENER
# if defined ENTER_OPENS && ENTER_OPENS
# define ENTER_OPEN
# else
# undef ENTER_OPEN
# endif
#else
# undef ENTER_OPENS
# undef ENTER_OPEN
#endif
#ifndef MARK_SYMBOL
# define MARK_SYMBOL '^'
#endif
#ifndef ALLOW_SPACES
# define ALLOW_SPACES 1
#endif
#ifndef ABBREVIATE_HOME
# define ABBREVIATE_HOME 1
#endif
#ifdef VIEW_COUNT
# if VIEW_COUNT > 10
# undef VIEW_COUNT
# define VIEW_COUNT 10
# elif VIEW_COUNT <= 0
# undef VIEW_COUNT
# define VIEW_COUNT 1
# endif
#else
# define VIEW_COUNT 2
#endif
#define COPYFLAGS (COPYFILE_ALL | COPYFILE_EXCL | COPYFILE_NOFOLLOW | COPYFILE_RECURSIVE)
enum elemtype {
ELEM_DIR,
ELEM_LINK,
ELEM_DIRLINK,
ELEM_EXEC,
ELEM_FILE,
};
static const char* elemtypestrings[] = {
"dir",
"@file",
"@dir",
"exec",
"file",
};
struct listelem {
enum elemtype type;
char name[NAME_MAX+1];
bool marked;
};
#define E_DIR(t) ((t)==ELEM_DIR || (t)==ELEM_DIRLINK)
static int del_id = 0;
static int mdel_id = 0;
struct deletedfile {
char* original;
int id;
bool mass;
int massid;
struct deletedfile* prev;
};
struct savedpos {
size_t pos, sel;
struct savedpos* prev;
};
static struct termios old_term;
static atomic_bool redraw = false;
static atomic_bool resize = false;
static int rows, cols;
static int pointerwidth = 2;
static char editor[PATH_MAX+1];
static char opener[PATH_MAX+1];
static char shell[PATH_MAX+1];
static char tmpdir[PATH_MAX+1];
static char cdonclosefile[PATH_MAX+1];
static atomic_bool interactive = true;
/*
* Hash table for files created by the copy function.
* The source for this was heavily inspired by libbb since I am too
* lazy to make my own entirely from scratch.
*/
#define HASH_SIZE 311U // prime number
#define hashfn(ino) ((unsigned)(ino) % HASH_SIZE)
struct hashed_file {
ino_t ino;
dev_t dev;
struct hashed_file* next;
bool isdir;
};
static struct hashed_file** file_table;
/*
* Returns whether or not a file is in the hash table.
*/
static bool is_file_hashed(const struct stat* st) {
if (!file_table) {
return false;
}
struct hashed_file* elem = file_table[hashfn(st->st_ino)];
while (elem != NULL) {
if (elem->ino == st->st_ino
&& elem->dev == st->st_dev
&& elem->isdir == !!S_ISDIR(st->st_mode)) {
return true;
}
elem = elem->next;
}
return false;
}
/*
* Hashes a file and adds it to the hash table.
*/
static void add_file_hash(const struct stat* st) {
struct hashed_file* elem = malloc(sizeof(struct hashed_file));
elem->ino = st->st_ino;
elem->dev = st->st_dev;
elem->isdir = !!S_ISDIR(st->st_mode);
if (!file_table) {
file_table = calloc(HASH_SIZE, sizeof(*file_table));
}
int i = hashfn(st->st_ino);
elem->next = file_table[i];
file_table[i] = elem;
}
/*
* Cleans up the file table.
*/
static void reset_file_table(void) {
if (!file_table) {
return;
}
struct hashed_file* elem;
struct hashed_file* next;
for (size_t i = 0; i < HASH_SIZE; i++) {
elem = file_table[i];
while (elem != NULL) {
next = elem->next;
free(elem);
elem = next;
}
}
free(file_table);
file_table = NULL;
}
/*
* Unlinks a file. Used for deldir.
*/
static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb) {
(void)sbuf; (void)type; (void)ftwb;
return remove(pathname);
}
/*
* Deletes a directory, even if it contains files.
*/
static int deldir(const char* dir) {
return nftw(dir, rmFiles, 512, FTW_DEPTH | FTW_MOUNT | FTW_PHYS);
}
/*
* If the path pointed to by f is a file, unlinks the file.
* Else, deletes the directory.
*
* Returns 0 on success.
*/
static int del(const char* f) {
struct stat fst;
if (0 != lstat(f, &fst)) {
return -1;
}
if (S_ISDIR(fst.st_mode)) {
return deldir(f);
} else {
return unlink(f);
}
}
/*
* Stats a file and returns 1 if it exists or 0 if
* it doesn't exist. It returns -1 if there was an error.
*/
static int exists(const char* path) {
struct stat fst;
if (0 != lstat(path, &fst)) {
if (errno == ENOENT) {
return 0;
} else {
return -1;
}
} else {
return 1;
}
}
/*
* Get the base name of a file.
* This is the same thing as running `basename x/y/z` at
* the command line.
*/
static char* basename(const char* path) {
char* r = strrchr(path, '/');
if (r) {
r++;
}
return r;
}
/*
* Gets the working directory the same way as getcwd,
* but checks $PWD first. If it is valid, then it will be
* stored in buf, else getcwd will be called. This fixes
* paths with one or more symlinks in them.
*
* This is a *little bit* identical to the GNU extension,
* get_current_dir_name().
*/
static void getrealcwd(char* buf, size_t size) {
char* pwd;
pwd = getenv("PWD");
struct stat dotstat, pwdstat;
if (pwd != NULL
&& stat(".", &dotstat) == 0
&& stat(pwd, &pwdstat) == 0
&& pwdstat.st_dev == dotstat.st_dev
&& pwdstat.st_ino == dotstat.st_ino) {
strncpy(buf, pwd, size);
} else {
(void)getcwd(buf, size);
}
}
/*
* This is the internal portion. Use the cpfile function instead.
* Copy file or directory recursively.
* Returns 0 on success, -1 on error.
*/
static int cpfile_inner(const char* src, const char* dst) {
char* b = basename(src);
if (b && (0 == strcmp(b, ".") || 0 == strcmp(b, ".."))) {
return 0;
}
struct stat srcstat, dststat;
bool dstexist = false;
int s = 0;
if (lstat(src, &srcstat) < 0) {
// couldn't stat source
return -1;
}
// if we already created this file we don't want to create it again
if (is_file_hashed(&srcstat)) {
return 0;
}
if (lstat(dst, &dststat) < 0) {
// couldn't stat target
if (errno != ENOENT) {
return -1;
}
} else {
if (srcstat.st_dev == dststat.st_dev && srcstat.st_ino == dststat.st_ino) {
// same file
return -1;
}
dstexist = true;
}
if (dstexist) {
return -1;
}
if (S_ISDIR(srcstat.st_mode)) {
mode_t smask = umask(0);
mode_t mode = srcstat.st_mode & ~smask;
mode |= S_IRWXU;
if (mkdir(dst, mode) < 0) {
umask(smask);
return -1;
}
umask(smask);
struct stat newst;
if (lstat(dst, &newst) < 0) {
return -1;
}
add_file_hash(&newst);
DIR* d = opendir(src);
if (d == NULL) {
s = -1;
goto preserve;
}
struct dirent* de;
while ((de = readdir(d)) != NULL) {
char *ns = malloc(PATH_MAX);
if (ns == NULL) {
s = -1;
}
char *nd = malloc(PATH_MAX);
if (nd == NULL) {
free(ns);
s = -1;
}
snprintf(ns, PATH_MAX, "%s/%s", src, de->d_name);
snprintf(nd, PATH_MAX, "%s/%s", dst, de->d_name);
if (cpfile_inner(ns, nd) != 0) {
s = -1;
}
if (ns) free(ns);
if (nd) free(nd);
}
closedir(d);
chmod(dst, srcstat.st_mode & ~smask);
goto preserve;
}
if (S_ISREG(srcstat.st_mode)) {
int sfd, dfd;
mode_t nmode;
if (S_ISLNK(srcstat.st_mode)) {
goto notreg;
}
sfd = open(src, O_RDONLY);
if (sfd == -1) {
return -1;
}
nmode = srcstat.st_mode;
if (!S_ISREG(srcstat.st_mode)) {
nmode = 0666;
}
dfd = open(dst, O_WRONLY|O_CREAT|O_EXCL, nmode);
if (dfd == -1) {
close(sfd);
return -1;
}
struct stat newst;
if (fstat(dfd, &newst) < 0) {
close(dfd);
return -1;
}
add_file_hash(&newst);
// copy the file
char cbuf[4096] = {0};
while (1) {
ssize_t r, w;
r = read(sfd, cbuf, 4096);
if (!r) {
break;
}
if (r < 0) {
s = -1;
break;
}
w = write(dfd, cbuf, r);
if (w < r) {
s = -1;
break;
}
}
if (close(dfd) < 0) {
return -1;
}
close(sfd);
if (!S_ISREG(srcstat.st_mode)) {
return s;
}
goto preserve;
}
notreg:
{
// source is not a regular file (it's a symlink or special)
if (S_ISLNK(srcstat.st_mode)) {
char lbuf[PATH_MAX+1] = {0};
ssize_t ls = readlink(src, lbuf, PATH_MAX);
if (ls == -1) {
return -1;
}
lbuf[ls] = '\0';
int r = symlink(lbuf, dst);
if (r != 0) {
return -1;
}
// can't preserve stuff for symlinks
return 0;
} else if (S_ISBLK(srcstat.st_mode) || S_ISCHR(srcstat.st_mode)
|| S_ISSOCK(srcstat.st_mode) || S_ISFIFO(srcstat.st_mode)) {
if (mknod(dst, srcstat.st_mode, srcstat.st_rdev) < 0) {
return -1;
}
} else {
return -1;
}
}
preserve:
{
// preserve mode, owner, attributes, etc. here
struct timeval t[2];
t[1].tv_sec = t[0].tv_sec = srcstat.st_mtime;
t[1].tv_usec = t[0].tv_usec = 0;
// we will fail silently if any of these don't work
utimes(dst, t);
(void)chown(dst, srcstat.st_uid, srcstat.st_gid);
chmod(dst, srcstat.st_mode);
return s;
}
}
/*
* Copies a file or directory. Returns 0 on success and -1 on failure.
*/
static int cpfile(const char* src, const char* dst) {
int s = cpfile_inner(src, dst);
reset_file_table();
return s;
}
static struct deletedfile* newdeleted(bool mass) {
struct deletedfile* d = malloc(sizeof(struct deletedfile));
if (!d) {
return NULL;
}
d->original = malloc(NAME_MAX);
if (!d->original) {
free(d);
return NULL;
}
d->id = del_id++;
d->mass = mass;
if (d->mass) {
d->massid = mdel_id;
}
d->prev = NULL;
return d;
}
static struct deletedfile* freedeleted(struct deletedfile* f) {
struct deletedfile* d = f->prev;
free(f->original);
free(f);
return d;
}
static int strnatcmp(const char *s1, const char *s2) {
for (;;) {
if (*s2 == '\0') {
return *s1 != '\0';
}
if (*s1 == '\0') {
return 1;
}
if (!(isdigit(*s1) && isdigit(*s2))) {
if (toupper(*s1) != toupper(*s2)) {
return toupper(*s1) - toupper(*s2);
}
++s1;
++s2;
} else {
char *lim1;
char *lim2;
unsigned long n1 = strtoul(s1, &lim1, 10);
unsigned long n2 = strtoul(s2, &lim2, 10);
if (n1 > n2) {
return 1;
} else if (n1 < n2) {
return -1;
}
s1 = lim1;
s2 = lim2;
}
}
}
/*
* Comparison function for list elements for qsort.
*/
static int elemcmp(const void* a, const void* b) {
const struct listelem* x = a;
const struct listelem* y = b;
if ((x->type == ELEM_DIR || x->type == ELEM_DIRLINK) &&
(y->type != ELEM_DIR && y->type != ELEM_DIRLINK)) {
return -1;
}
if ((y->type == ELEM_DIR || y->type == ELEM_DIRLINK) &&
(x->type != ELEM_DIR && x->type != ELEM_DIRLINK)) {
return 1;
}
return strnatcmp(x->name, y->name);
}
/*
* Get editor.
*/
static void geteditor(void) {
#ifdef EDITOR
strncpy(editor, EDITOR, PATH_MAX);
#else
const char* res = getenv("CFM_EDITOR");
if (!res) {
res = getenv("EDITOR");
if (!res) {
editor[0] = '\0';
} else {
strncpy(editor, res, PATH_MAX);
}
} else {
strncpy(editor, res, PATH_MAX);
}
#endif /* EDITOR */
}
/*
* Get shell.
*/
static void getshell(void) {
#ifdef SHELL
strncpy(shell, SHELL, PATH_MAX);
#else
const char* res = getenv("CFM_SHELL");
if (!res) {
res = getenv("SHELL");
if (!res) {
shell[0] = '\0';
} else {
strncpy(shell, res, PATH_MAX);
}
} else {
strncpy(shell, res, PATH_MAX);
}
#endif /* SHELL */
}
/*
* Get the opener program.
*/
static void getopener(void) {
#ifdef OPENER
strncpy(opener, OPENER, PATH_MAX);
#else
const char* res = getenv("CFM_OPENER");
if (!res) {
res = getenv("OPENER");
if (!res) {
opener[0] = '\0';
} else {
strncpy(opener, res, PATH_MAX);
}
} else {
strncpy(opener, res, PATH_MAX);
}
#endif
}
/*
* Get the tmp directory.
*/
static void maketmpdir(void) {
#ifdef TMP_DIR
strncpy(tmpdir, TMP_DIR, PATH_MAX);
#else
const char* res = getenv("CFM_TMP");
if (res) {
strncpy(tmpdir, res, PATH_MAX);
} else {
strncpy(tmpdir, "/tmp/cfmtmp", PATH_MAX);
}
#endif
if (mkdir(tmpdir, 0751)) {
if (errno == EEXIST) {
return;
} else {
tmpdir[0] = '\0';
}
}
}
static void rmtmp(void) {
if (tmpdir[0]) {
if (0 != deldir(tmpdir)) {
perror("rmtmp: deldir");
}
}
}
/*
* Write current working directory to CD_ON_CLOSE file.
* Creates the file if it doesn't exist; does not report errors.
*/
static void cdonclose(const char* wd) {
// since we assume that rmpwdfile() has already been called before this,
// cdonclosefile should have a valid path already if it's set
if (*cdonclosefile) {
FILE* outfile = fopen(cdonclosefile, "w");
if (outfile) {
fprintf(outfile, "%s\n", wd);
fclose(outfile);
}
}
}
/*
* Remove existing pwd file (CD_ON_CLOSE).
* Does not report errors.
*/
static void rmpwdfile(void) {
#ifdef CD_ON_CLOSE
if (NULL == realpath(CD_ON_CLOSE, cdonclosefile)) {
*cdonclosefile = 0;
}
#else
const char* cdocf = getenv("CFM_CD_ON_CLOSE");
if (cdocf) {
strncpy(cdonclosefile, cdocf, PATH_MAX);
}
#endif
if (*cdonclosefile) {
del(cdonclosefile);
}
}
/*
* Save the default terminal settings.
* Returns 0 on success.
*/
static int backupterm(void) {
if (!interactive) return 0;
if (tcgetattr(STDIN_FILENO, &old_term) < 0) {
perror("tcgetattr");
return 1;
}
return 0;
}
/*
* Get the size of the terminal.
* Returns 0 on success.
*/
static int termsize(void) {
if (!interactive) return 0;
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
perror("ioctl");
return 1;
}
rows = ws.ws_row;
cols = ws.ws_col;
return 0;
}
/*
* Sets up the terminal for TUI.
* Return 0 on success.
*/
static int setupterm(void) {
if (!interactive) return 0;
setvbuf(stdout, NULL, _IOFBF, 0);
struct termios new_term = old_term;
new_term.c_oflag &= ~OPOST;
new_term.c_lflag &= ~(ECHO | ICANON);
if (tcsetattr(STDIN_FILENO, TCSANOW, &new_term) < 0) {
perror("tcsetattr");
return 1;
}
printf(
"\033[?1049h" // use alternative screen buffer
"\033[?7l" // disable line wrapping
"\033[?25l" // hide cursor
"\033[2J" // clear screen
"\033[2;%dr", // limit scrolling to our rows
rows-1);
return 0;
}
/*
* Resets the terminal to how it was before we ruined it.
*/
static void resetterm(void) {
if (!interactive) return;
setvbuf(stdout, NULL, _IOLBF, 0);
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_term) < 0) {
perror("tcsetattr");
return;
}
printf(
"\033[?7h" // enable line wrapping
"\033[?25h" // unhide cursor
"\033[r" // reset scroll region
"\033[?1049l" // restore main screen
);
fflush(stdout);
}
/*
* Creates a child process.
*/
static void execcmd(const char* path, const char* cmd, const char* arg) {
pid_t pid = fork();
if (pid < 0) {
return;
}
resetterm();
if (pid == 0) {
if (chdir(path) < 0) {
_exit(EXIT_FAILURE);
}
execlp(cmd, cmd, arg, NULL);
_exit(EXIT_FAILURE);
} else {
int s;
do {
waitpid(pid, &s, WUNTRACED);
} while (!WIFEXITED(s) && !WIFSIGNALED(s));
}
setupterm();
fflush(stdout);
}
/*
* Reads a directory into the list, returning the number of items in the dir.
* This will return 0 on success.
* On failure, 'opendir' will have set 'errno'.
*/
static int listdir(const char* path, struct listelem** list, size_t* listsize, size_t* rcount, bool hidden) {
DIR* d;
struct dirent* dir;
d = opendir(path);
size_t count = 0;
struct stat st;
if (d) {
int dfd = dirfd(d);
while ((dir = readdir(d)) != NULL) {
if (dir->d_name[0] == '.' && (dir->d_name[1] == '\0' || (dir->d_name[1] == '.' && dir->d_name[2] == '\0'))) {
continue;
}
if (!hidden && dir->d_name[0] == '.') {
continue;
}
if (count == *listsize) {
*listsize += LIST_ALLOC_SIZE;
*list = realloc(*list, *listsize * sizeof(**list));
if (*list == NULL) {
perror("realloc");
exit(EXIT_FAILURE);
}
}
strncpy((*list)[count].name, dir->d_name, NAME_MAX);
(*list)[count].marked = false;
if (0 != fstatat(dfd, dir->d_name, &st, AT_SYMLINK_NOFOLLOW)) {
continue;
}
if (S_ISDIR(st.st_mode)) {
(*list)[count].type = ELEM_DIR;
} else if (S_ISLNK(st.st_mode)) {
if (0 == fstatat(dfd, dir->d_name, &st, 0)) {
if (S_ISDIR(st.st_mode)) {
(*list)[count].type = ELEM_DIRLINK;
} else {
(*list)[count].type = ELEM_LINK;
}
} else {
(*list)[count].type = ELEM_LINK;
}
} else {
if (st.st_mode & S_IXUSR) {
(*list)[count].type = ELEM_EXEC;
} else {
(*list)[count].type = ELEM_FILE;
}
}
count++;
}
closedir(d);
qsort(*list, count, sizeof(**list), elemcmp);
} else {
return -1;
}
*rcount = count;
return 0;
}
/*
* Get a filename from the user and store it in 'out'.
* out must point to a buffer capable of containing
* at least NAME_MAX bytes.
*
* initialstr is the text to write into the file before
* the user edits it.
*
* Returns 0 on success, else:
* -1 = no editor
* -2 = other error (check errno)
* -3 = invalid filename entered
*
* If an error occurs but the data in 'out'
* is still usable, it will be there. Else, out will
* be empty.
*/
static int readfname(char* out, const char* initialstr) {
if (editor[0]) {
char template[] = "/tmp/cfmtmp.XXXXXXXXXX";
int fd;
if (-1 == (fd = mkstemp(template))) {
return -2;
}
int rval = 0;
if (initialstr) {
if (-1 == write(fd, initialstr, strlen(initialstr))) {
rval = -2;
} else {
if (-1 == lseek(fd, 0, SEEK_SET)) {
rval = -2;
}
}
}
if (rval == 0) {
execcmd("/tmp/", editor, template);
ssize_t c;
memset(out, 0, NAME_MAX);
if (-1 == (c = read(fd, out, NAME_MAX - 1))) {
rval = -2;
out[0] = '\0';
} else {
if (out[0] == '\0') {
rval = -3;
}
char* nl = strchr(out, '\n');
if (nl != NULL) {
*nl = '\0';
}
rval = 0;
// validate the string
// only allow POSIX portable paths and spaces if enabled
// which is to say A-Za-z0-9._-
for (char* x = out; *x; x++) {
if (!(isalnum(*x) || *x == '.' || *x == '_' || *x == '-'
#if ALLOW_SPACES
|| *x == ' '
#endif
)) {
rval = -3;