-
Notifications
You must be signed in to change notification settings - Fork 2
/
list-r.c
1529 lines (1408 loc) · 39.2 KB
/
list-r.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
#define _LARGEFILE_SOURCE 1
#define _GNU_SOURCE 1
#define _FILE_OFFSET_BITS 64
#define INTERNAL_STRINGIFY(VALUE) #VALUE
#define STRINGIFY(VALUE) INTERNAL_STRINGIFY(VALUE)
#include "lib/windoze.h"
#include "lib/getopt.h"
#if WINDOWS_NATIVE
#include <windows.h>
#include <io.h>
#include <wtypes.h>
#else
#include <dirent.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "dump.h"
#include "lib/buffer.h"
#include "lib/dir.h"
#include "lib/fmt.h"
#include "lib/fnmatch.h"
#include "lib/io.h"
#include "lib/iarray.h"
#include "lib/open.h"
#include "lib/str.h"
#include "lib/stralloc.h"
#include "lib/uint64.h"
#include "lib/ioctlcmd.h"
#include "lib/byte.h"
#include "lib/array.h"
#include "lib/unix.h"
#include "lib/path.h"
#include "lib/scan.h"
#include "lib/mmap.h"
#include "lib/strlist.h"
#include "lib/strarray.h"
#include "lib/array.h"
#include "lib/errmsg.h"
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
#ifdef HAVE_STDBOOL_H
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <errno.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#if WINDOWS
#include <io.h>
#ifndef IO_REPARSE_TAG_SYMLINK
#define IO_REPARSE_TAG_SYMLINK 0xa000000c
#endif
#ifndef FILE_ATTRIBUTE_REPARSE_POINT
#define FILE_ATTRIBUTE_REPARSE_POINT 0x400
#endif
#ifndef SE_FILE_OBJECT
#define SE_FILE_OBJECT 1
#endif
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef S_IFMT
#define S_IFMT 0170000
#endif
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
static void print_strarray(buffer* b, array* a);
static int fnmatch_strarray(buffer* b, array* a, const char* string, int flags);
static strlist extensions, exclude_masks, include_masks;
static char opt_separator = DIRSEP_C;
static int opt_list = 0, opt_numeric = 0, opt_relative = 0, opt_deref = 0, opt_samedev = 1, opt_crc = 0, opt_human = 0;
static int64 opt_minsize = -1;
static long opt_depth = -1, opt_force = 0, opt_quiet = 0;
static uint32 opt_types = (uint32)(int32)-1;
static const char *opt_relative_to = 0, *opt_chdir = 0;
static const char* opt_timestyle = "%b %2e %H:%M";
static strarray etc_users, etc_groups;
#if(defined(_WIN32) || defined(MINGW)) && !defined(__MSYS__)
static uint64 filetime_to_unix(const FILETIME* ft);
typedef struct column_s {
int offsets[16];
int lengths[16];
} column_t;
static const char*
last_error() {
DWORD errCode = GetLastError();
static char tmpbuf[1024];
char* err;
tmpbuf[0] = '\0';
if(errCode == 0)
return tmpbuf;
SetLastError(0);
if(!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
0,
errCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* default
language
*/
(LPTSTR)&err,
0,
0))
return 0;
str_copy(tmpbuf, "ERROR: ");
str_cat(tmpbuf, err);
str_cat(tmpbuf, "\n");
/* or otherwise log it */
// OutputDebugString(tmpbuf);
LocalFree(err);
return tmpbuf;
}
int64
get_file_size(char* path) {
LARGE_INTEGER size;
typedef LONG(WINAPI getfilesizeex_fn)(HANDLE, PLARGE_INTEGER);
static getfilesizeex_fn* api_fn;
HANDLE hFile =
CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if(hFile == INVALID_HANDLE_VALUE)
return -1; /* error condition, could
call GetLastError to
find out more */
if(!api_fn) {
HANDLE kernel;
if((kernel = LoadLibraryA("kernel32.dll")) != INVALID_HANDLE_VALUE)
api_fn = (getfilesizeex_fn*)(void*)GetProcAddress(kernel, "GetFileSizeEx");
}
if(!api_fn)
return -1;
if(!(*api_fn)(hFile, &size)) {
CloseHandle(hFile);
return -1; /* error condition, could
call GetLastError to
find out more */
}
CloseHandle(hFile);
/* fprintf(stderr, "get_file_size: %s
* = %"PRIi64" [%s]\n", path,
* (int64)size.QuadPart,
* last_error()); */
return size.QuadPart;
}
uint64
get_file_time(const char* path) {
FILETIME c, la, lw;
int64 t;
HANDLE hFile =
CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if(hFile == INVALID_HANDLE_VALUE)
return -1; /* error condition, could
call GetLastError to
find out more */
if(!GetFileTime(hFile, &c, &la, &lw)) {
CloseHandle(hFile);
return -1; /* error condition, could
call GetLastError to
find out more */
}
CloseHandle(hFile);
if((t = filetime_to_unix(&lw)) <= 0)
if((t = filetime_to_unix(&c)) <= 0)
t = filetime_to_unix(&la);
/* fprintf(stderr, "get_file_size: %s
* = %"PRIi64" [%s]\n", path,
* (int64)size.QuadPart,
* last_error()); */
return t;
}
int
get_win_api(void* ptr, const char* dll, const char* func) {
if(*(void**)ptr == 0) {
HANDLE h;
void* fn;
if((h = LoadLibraryA(dll)) != 0) {
if((fn = (void*)GetProcAddress(h, func))) {
*(void**)ptr = fn;
return 0;
}
}
}
return -1;
}
const char*
get_file_owner(const char* path) {
static char tmpbuf[1024];
DWORD dwRtnCode = 0;
PSID pSidOwner = 0;
BOOL bRtnBool = TRUE;
LPTSTR AcctName = 0;
LPTSTR DomainName = 0;
DWORD dwAcctName = 1, dwDomainName = 1;
SID_NAME_USE eUse = SidTypeUnknown;
HANDLE hFile;
PSECURITY_DESCRIPTOR pSD = 0;
LPSTR strsid = 0;
DWORD dwErrorCode = 0;
static DWORD(
WINAPI *
get_security_info)(HANDLE, DWORD, SECURITY_INFORMATION, PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
static BOOL(WINAPI * convert_sid_to_string_sid_a)(PSID, LPSTR*);
tmpbuf[0] = '\0';
/* Get the handle of the file object.
*/
hFile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
/* Check GetLastError for CreateFile
* error code. */
if(hFile == INVALID_HANDLE_VALUE) {
dwErrorCode = GetLastError();
/* snprintf(tmpbuf,
* sizeof(tmpbuf), "CreateFile error
* = %d\n", dwErrorCode); */
return 0;
}
if(get_win_api(&get_security_info, "advapi32", "GetSecurityInfo") == -1)
return 0;
if(get_win_api(&convert_sid_to_string_sid_a, "advapi32", "ConvertSidToStringSidA") == -1)
return 0;
/* Get the owner SID of the file. */
dwRtnCode = get_security_info(hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, &pSidOwner, 0, 0, 0, &pSD);
/* Check GetLastError for
* GetSecurityInfo error condition. */
if(dwRtnCode != ERROR_SUCCESS) {
dwErrorCode = GetLastError();
/* snprintf(tmpbuf,
* sizeof(tmpbuf), "GetSecurityInfo
* error = %d\n", dwErrorCode); */
return 0;
}
if(convert_sid_to_string_sid_a(pSidOwner, &strsid)) {
str_copy(tmpbuf, strsid);
LocalFree(strsid);
}
/* First call to LookupAccountSid to
* get the tmpbuf sizes. */
bRtnBool = LookupAccountSid(0, /* local computer */
pSidOwner,
AcctName,
(LPDWORD)&dwAcctName,
DomainName,
(LPDWORD)&dwDomainName,
&eUse);
/* Reallocate memory for the buffers.
*/
AcctName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwAcctName);
/* Check GetLastError for GlobalAlloc
* error condition. */
if(AcctName == 0) {
dwErrorCode = GetLastError();
/* snprintf(tmpbuf, sizeof(tmpbuf),
* "GlobalAlloc error = %d\n",
* dwErrorCode); */
return tmpbuf;
}
DomainName = (LPTSTR)GlobalAlloc(GMEM_FIXED, dwDomainName);
/* Check GetLastError for GlobalAlloc
* error condition. */
if(DomainName == 0) {
dwErrorCode = GetLastError();
/* snprintf(tmpbuf, sizeof(tmpbuf),
* "GlobalAlloc error = %d\n",
* dwErrorCode); */
return tmpbuf;
}
/* Second call to LookupAccountSid to
* get the account name. */
bRtnBool = LookupAccountSid(0, /* name of local or remote
computer */
pSidOwner, /* security identifier
*/
AcctName, /* account name tmpbuf
*/
(LPDWORD)&dwAcctName, /* size of
account
name
tmpbuf */
DomainName, /* domain name */
(LPDWORD)&dwDomainName, /* size of
domain
name
tmpbuf
*/
&eUse); /* SID type */
/* Check GetLastError for
* LookupAccountSid error condition.
*/
if(bRtnBool == FALSE) {
dwErrorCode = GetLastError();
if(dwErrorCode == ERROR_NONE_MAPPED)
str_copy(tmpbuf, "Account owner not found for specified SID.\n");
else
str_copy(tmpbuf, "Error in LookupAccountSid.\n");
return tmpbuf;
} else if(bRtnBool == TRUE)
/* Print the account name. */
str_copy(tmpbuf, AcctName);
return tmpbuf;
}
#endif
#if WINDOWS_NATIVE
//#warning PLAIN_WINDOWS
#define WINDOWS_TICK 10000000
#define SEC_TO_UNIX_EPOCH (int64)11644473600
static uint64
filetime_to_unix(const FILETIME* ft) {
uint64 windowsTicks = ((uint64)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
return (uint64)(windowsTicks / 10000000 - SEC_TO_UNIX_EPOCH);
}
int
is_junction_point(const char* fn) {
int status = 0;
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
hFind = FindFirstFile(fn, &FindFileData);
if(INVALID_HANDLE_VALUE != hFind) {
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
/* We're probably going to skip
* this reparse point, */
/* but not always. (See the logic
* below.) */
status = 1;
/* Tag values come from */
/* http://msdn.microsoft.com/en-us/library/dd541667(prot.20).aspx
*/
switch(FindFileData.dwReserved0) {
case IO_REPARSE_TAG_MOUNT_POINT: /* ocb.error_filename(fn, "Junction
point, skipping"); */
break;
case IO_REPARSE_TAG_SYMLINK:
/* TODO: Maybe have the option
* to follow symbolic links?
*/
/* ocb.error_filename(fn,
* "Symbolic link, skipping");
*/
break;
/* TODO: Use label for
* deduplication reparse point
*/
/* when the compiler
* supports it */
/* case
* IO_REPARSE_TAG_DEDUP: */
case 0x80000013:
/* This is the reparse point
* for Data Deduplication */
/* See */
/* http://blogs.technet.com/b/filecab/archive/2012/05/21/introduction-to-data-deduplication-in-windows-server-2012.aspx
*/
/* Unfortunately the compiler
* doesn't have this value
* defined yet. */
status = 0;
break;
case IO_REPARSE_TAG_SIS:
/* Single Instance Storage */
/* "is a system's ability to
* keep one copy of content
* that multiple users or
* computers share" */
/* http://blogs.technet.com/b/filecab/archive/2006/02/03/single-instance-store-sis-in-windows-storage-server-r2.aspx
*/
status = 0;
break;
default: break;
}
}
/* We don't error check this call as
* there's nothing to do differently
*/
/* if it fails. */
FindClose(hFind);
}
return status;
}
#endif
static int list_dir_internal(stralloc* dir, int type, long depth);
static uint32
type_mask(const char* arg) {
size_t i;
uint32 mask = 0;
int inv = 0;
for(i = 0; arg[i]; i++) {
uint32 bit = 0;
switch(arg[i]) {
case 'f': bit = D_FILE; break;
case 'd': bit = D_DIRECTORY; break;
case 'l': bit = D_SYMLINK; break;
case 'b': bit = D_BLKDEV; break;
case 'c': bit = D_CHARDEV; break;
case 'p': bit = D_PIPE; break;
case 's': bit = D_SOCKET; break;
case '!':
case '~':
case '^':
inv = !inv;
mask = ~mask;
continue;
default: break;
}
if(inv)
mask &= ~bit;
else
mask |= bit;
}
return mask;
}
static size_t
read_etc(strarray* out, const char* path) {
size_t count = 0, n;
const char* x;
strarray_init(out);
if((x = mmap_read(path, &n))) {
while(n > 0) {
const char* name = x;
size_t len, namelen = byte_chr(x, n, ':');
uint32 uid = 0;
if(namelen == n)
break;
x += namelen + 1;
n -= namelen - 1;
len = byte_chr(x, n, ':');
if(len == n)
break;
x += len + 1;
n -= len - 1;
len = scan_uint(x, &uid);
if(len == n)
break;
if(len > 0) {
strarray_setb(out, uid, name, namelen);
count++;
}
len = byte_chr(x, n, '\n');
if(len == n)
break;
x += len + 1;
n -= len - 1;
}
mmap_unmap(x, n);
}
return count;
}
static char*
resolve_etc(const strarray* arr, uint32 id) {
uint64 len = strarray_size(arr);
if(id < len)
return strarray_at(arr, id);
return 0;
}
static void
make_num(stralloc* out, uint64 num, uint32 width, size_t (*fmt)(char*, uint64)) {
char buf[FMT_ULONG + 1];
if(!fmt)
fmt = &fmt_ulonglong;
size_t sz = fmt(buf, num);
ssize_t n = width - sz;
while(n-- > 0)
stralloc_catb(out, " ", 1);
stralloc_catb(out, buf, sz);
}
static void
make_time(stralloc* out, uint64 t, uint32 width) {
char fmt[21];
size_t i, sz = fmt_iso8601(fmt, t);
for(i = 0; i + sz < width; i++)
stralloc_catc(out, ' ');
if(sz > 0 && fmt[sz - 1] == 'Z')
sz--;
if(sz > 10 && fmt[10] == 'T')
fmt[10] = ' ';
stralloc_catb(out, fmt, sz);
}
#define TIMESTAMP 25
static char hex[16] = "0123456789abcdef";
void
make_taia(stralloc* out, const uint64* epoch) {
struct taia t = {0};
char *s, tpack[TAIA_PACK];
size_t i;
if(epoch)
taia_uint(&t, *epoch);
else
taia_now(&t);
taia_pack(tpack, &t);
stralloc_readyplus(out, 25);
s = &out->s[out->len];
s[0] = '@';
for(i = 0; i < 12; ++i) {
s[i * 2 + 1] = hex[(tpack[i] >> 4) & 15];
s[i * 2 + 2] = hex[tpack[i] & 15];
}
out->len += 25;
}
static void
make_str(stralloc* out, const char* s, uint32 width) {
size_t i, sz = str_len(s);
stralloc_catb(out, s, sz);
for(i = 0; i + sz < width; i++)
stralloc_catc(out, ' ');
}
static void
print_strarray(buffer* b, array* a) {
size_t i, n = array_length(a, sizeof(char*));
char** x = array_start(a);
for(i = 0; i < n; ++i) {
char* s = x[i];
if(s == 0)
break;
buffer_puts(b, x[i]);
buffer_putc(b, '\n');
}
buffer_flush(b);
}
static int
fnmatch_strarray(buffer* b, array* a, const char* string, int flags) {
size_t i, n = array_length(a, sizeof(char*));
char** x = array_start(a);
int ret = FNM_NOMATCH;
size_t string_len = str_len(string);
for(i = 0; i < n; ++i) {
char* s = x[i];
if(s == 0)
break;
if((ret = path_fnmatch(s, str_len(s), string, string_len, flags)) != FNM_NOMATCH)
break;
}
return ret;
}
/*
void
make_time(stralloc* out, time_t t,
size_t width) { if(opt_numeric) {
make_num(out, (size_t)t, width);
} else {
struct tm ltime;
char buf[1024];
size_t sz;
ssize_t n;
#ifdef HAVE_LOCALTIME_R_FUNC
localtime_r(&t, <ime);
#else
ltime = *localtime(&t);
#endif
sz = strftime(buf, sizeof(buf),
opt_timestyle, <ime); n = width - sz;
while(n-- > 0) {
stralloc_catb(out, " ", 1);
}
stralloc_catb(out, buf, sz);
}
}*/
static void
mode_octal(stralloc* out, int mode) {
char buf[6];
size_t i, n = fmt_8long(buf, mode & 07777);
if(mode)
for(i = 0; i + n < 4; i++)
stralloc_catc(out, '0');
stralloc_catb(out, buf, n);
}
static void
mode_flags(stralloc* out, int mode) {
char mchars[10];
byte_fill(mchars, sizeof(mchars), '-');
switch(mode & S_IFMT) {
#ifdef S_IFLNK
case S_IFLNK: mchars[0] = 'l'; break;
#endif
case S_IFDIR: mchars[0] = 'd'; break;
case S_IFCHR: mchars[0] = 'c'; break;
#ifdef S_IFBLK
case S_IFBLK: mchars[0] = 'b'; break;
#endif
#ifdef S_IFIFO
case S_IFIFO: mchars[0] = 'i'; break;
#endif
#ifdef S_IFSOCK
case S_IFSOCK: mchars[0] = 's'; break;
#endif
case S_IFREG: break;
}
#ifdef S_IRUSR
if(mode & S_IRUSR)
mchars[1] = 'r';
#endif
#ifdef S_IWUSR
if(mode & S_IWUSR)
mchars[2] = 'w';
#endif
#ifdef S_IXUSR
if(mode & S_IXUSR)
mchars[3] = 'x';
#endif
#ifdef S_IRGRP
if(mode & S_IRGRP)
mchars[4] = 'r';
#endif
#ifdef S_IWGRP
if(mode & S_IWGRP)
mchars[5] = 'w';
#endif
#ifdef S_IXGRP
if(mode & S_IXGRP)
mchars[6] = 'x';
#endif
#ifdef S_IROTH
if(mode & S_IROTH)
mchars[7] = 'r';
#endif
#ifdef S_IWOTH
if(mode & S_IWOTH)
mchars[8] = 'w';
#endif
#ifdef S_IXOTH
if(mode & S_IXOTH)
mchars[9] = 'x';
#endif
if(mode & 04000)
mchars[3] = 's';
stralloc_catb(out, mchars, sizeof(mchars));
}
uint32
crc32(uint32 crc, const char* data, size_t size) {
uint32 i, r = ~0;
const char* end = data + size;
while(data < end) {
r ^= *data++;
for(i = 0; i < 8; i++) {
uint32 t = ~((r & 1) - 1);
r = (r >> 1) ^ (0xedb88320 & t);
}
}
return ~r;
}
static inline dir_type_t
stat_type(const char* path, int mode) {
dir_type_t dtype = S_ISREG(mode) ? D_FILE : 0;
#ifdef S_ISLNK
dtype |= S_ISLNK(mode) ? D_SYMLINK : 0;
#else
if(is_symlink(path))
dtype |= D_SYMLINK;
#endif
dtype |= S_ISBLK(mode) ? D_BLKDEV : 0;
dtype |= S_ISCHR(mode) ? D_CHARDEV : 0;
#ifdef S_ISSOCK
dtype |= S_ISSOCK(mode) ? D_SOCKET : 0;
#endif
dtype |= S_ISFIFO(mode) ? D_PIPE : 0;
return dtype;
}
static const char* type_strs[] = {
"D_PIPE", "D_CHARDEV", "D_BLKDEV", "D_SYMLINK", "D_DIRECTORY", "D_FILE", "D_SOCKET", 0};
static const char*
type_str(dir_type_t type) {
int shift = 0;
type &= 0x7f;
for(shift = 0; type_strs[shift]; shift++) {
if((type >> shift) & 1)
break;
}
if(!type_strs[shift])
return "";
return type_strs[shift];
}
/*static inline mode_t
stat_perm(int mode) {
mode_t mask = S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO;
return mode & mask;
}*/
static int
match_extensions(const stralloc* path) {
const char *pattern, *ext, *str;
size_t elen, plen, slen, pos;
int match = 0, ret = 0;
if(extensions.sa.len == 0)
return 1;
pos = 1 + byte_rchr(path->s, path->len, '.');
elen = path->len - pos;
strlist_foreach(&extensions, pattern, plen) {
int invert = *pattern == '!' || *pattern == '^';
str = pattern + invert;
slen = plen - invert;
pos = path->len - slen;
if(elen == slen) {
match = byte_equal(path->s + pos, slen, str);
if(match ^ invert) {
#ifdef DEBUG_OUTPUT
dump_key("match");
dump_ulong(match);
dump_sep();
dump_key("pattern");
dump_bytes(pattern, plen);
dump_sep();
dump_key("str");
dump_bytes(str, slen);
dump_sep();
dump_key("slen");
dump_ulong(slen);
dump_sep();
dump_key("pos");
dump_ulong(pos);
dump_sep();
dump_key("invert");
dump_ulong(invert);
dump_sep();
dump_key("file");
dump_str(path->s);
dump_newline();
#endif
ret = !invert;
break;
}
}
}
#ifdef DEBUG_OUTPUT_
if(match) {
dump_key("match");
dump_ulong(match);
dump_sep();
dump_key("file");
dump_str(file);
dump_newline();
}
#endif
return ret;
}
/*static inline mode_t
type_mode(dir_type_t dtype) {
mode_t mode;
switch(dtype) {
case D_DIRECTORY: mode |= S_IFDIR; break;
case D_SYMLINK: mode |= S_IFLNK; break;
case D_BLKDEV: mode |= S_IFBLK; break;
case D_CHARDEV: mode |= S_IFCHR; break;
case D_SOCKET: mode |= S_IFSOCK; break;
case D_FILE: mode |= S_IFREG; break;
case D_PIPE: mode |= S_IFIFO; break;
}
return mode;
}*/
static int
file_crc32(const char* path, size_t size, uint32* crc) {
size_t n;
const char* x;
if(size == 0) {
*crc = 0;
return 0;
}
if((x = mmap_read(path, &n))) {
*crc = crc32(0, x, n);
mmap_unmap(x, n);
return 0;
}
return -1;
}
int
list_file(stralloc* path, const char* name, mode_t mode, long depth, dev_t root_dev) {
size_t l;
struct stat st;
static stralloc pre;
int is_dir, is_symlink;
size_t len;
uint32 crc;
const char *s, *pattern;
dir_type_t dtype;
int match, show = 1;
uint64 mtime = 0, size = 0, nlink = 0;
uint32 uid = 0, gid = 0;
struct dir_s d;
match = match_extensions(path);
#ifdef DEBUG_OUTPUT_
if(match) {
dump_key("match");
dump_ulong(match);
dump_sep();
dump_key("path");
dump_str(path->s);
dump_newline();
}
#endif
if(!match)
return 0;
#if !WINDOWS_NATIVE
byte_zero(&st, sizeof(st));
#endif
dtype = stat_type(path->s, mode);
if(dtype) {
is_dir = !!(dtype & D_DIRECTORY);
is_symlink = !!(dtype & D_SYMLINK);
}
#if !WINDOWS_NATIVE
if((opt_deref ? stat : lstat)(path->s, &st) == -1) {
if(!opt_quiet)
errmsg_warnsys(opt_force ? "warning: " : "error: ", path->s, 0);
if(opt_force < 1)
exit(1);
if(opt_force < 2)
return 0;
}
nlink = is_dir ? st.st_nlink : 1;
#ifdef DEBUG_OUTPUT_
dump_key("st.st_mode");
dump_int(st.st_mode);
#endif
mode = st.st_mode;
uid = st.st_uid;
gid = st.st_gid;
size = st.st_size;
mtime = st.st_mtime;
if(opt_samedev && root_dev && st.st_dev) {
if(st.st_dev != root_dev)
return 0;
}
is_dir = S_ISDIR(mode);
is_symlink = S_ISLNK(mode);
if(opt_deref && is_symlink) {
is_symlink = 0;
is_dir = S_ISDIR(st.st_mode);
}
dtype = stat_type(path->s, mode);
#else
if(dtype & D_SYMLINK)
is_symlink = 1;
#if USE_READDIR
if(!is_dir) {
size = dir_size(&d);
mtime = dir_time(&d, D_TIME_MODIFICATION);
} else {
mtime = 0;
size = 0;
}
#else
size = dir_size(&d);
mtime = dir_time(&d, D_TIME_MODIFICATION);
#endif
#endif
if(dtype) {
is_dir = !!(dtype & D_DIRECTORY);
} else {
#if WINDOWS_NATIVE
is_dir = 0;
#else
is_dir = !!S_ISDIR(mode);
#endif
}
if(is_dir)
stralloc_catc(path, opt_separator);
if(path->len > PATH_MAX) {
buffer_puts(buffer_2, "ERROR: Directory ");
buffer_putsa(buffer_2, path);
buffer_puts(buffer_2, " longer than PATH_MAX (" STRINGIFY(PATH_MAX) ")!\n");
buffer_flush(buffer_2);
return 1;
}
stralloc_nul(path);
s = path->s;
len = path->len;
if(len > 2 && s[0] == '.' && IS_DIRSEP(s[1])) {
len -= 2;
s += 2;
}
if(strlist_count(&include_masks) > 0) {
match = 0;
strlist_foreach_s(&include_masks, pattern) {
int has_slash = !!pattern[str_chr(pattern, '/')];
const char* mask = has_slash ? s : name;
if(path_fnmatch(pattern, str_len(pattern), mask, str_len(mask), FNM_PATHNAME) == 0) {
match = 1;
break;
}
}
if(!match)
return 0;
}
match = 0;
strlist_foreach_s(&exclude_masks, pattern) {
int has_slash = !!pattern[str_chr(pattern, '/')];
const char* mask = has_slash ? s : name;
if(path_fnmatch(pattern, str_len(pattern), mask, str_len(mask), FNM_PATHNAME) == 0) {
match = 1;
break;
}
}
if(match)
return 0;
if(/*!is_dir && */ (opt_minsize != -1 && size < (uint64)opt_minsize))
show = 0;
if(dtype && (dtype & opt_types) == 0)
show = 0;
if(show) {
stralloc_zero(&pre);
if(opt_crc) {
if(dtype != D_FILE || file_crc32(path->s, size, &crc)) {
stralloc_cats(&pre, "\t");
} else {
stralloc_catxlong(&pre, crc);
if(pre.len < 8)
stralloc_insertb(&pre, "00000000", 0, 8 - pre.len);
}
stralloc_catc(&pre, ' ');
}
if(opt_list) {