-
Notifications
You must be signed in to change notification settings - Fork 30
/
path.c
1919 lines (1710 loc) · 59.6 KB
/
path.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
/* Yash: yet another shell */
/* path.c: filename-related utilities */
/* (C) 2007-2020 magicant */
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "common.h"
#include "path.h"
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#if HAVE_GETTEXT
# include <libintl.h>
#endif
#include <limits.h>
#if HAVE_PATHS_H
# include <paths.h>
#endif
#include <pwd.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#include "builtin.h"
#include "exec.h"
#include "expand.h"
#include "hashtable.h"
#include "option.h"
#include "plist.h"
#include "redir.h"
#include "sig.h"
#include "strbuf.h"
#include "util.h"
#include "variable.h"
#include "xfnmatch.h"
#include "yash.h"
#if HAVE_FACCESSAT
# ifndef faccessat
extern int faccessat(int fd, const char *path, int amode, int flags)
__attribute__((nonnull));
# endif
#elif HAVE_EACCESS
# ifndef eaccess
extern int eaccess(const char *path, int amode)
__attribute__((nonnull));
# endif
#endif
static bool check_access(const char *path, mode_t mode, int amode)
__attribute__((nonnull));
/* Checks if `path' is an existing file. */
bool is_file(const char *path)
{
return access(path, F_OK) == 0;
// struct stat st;
// return (stat(path, &st) == 0);
}
/* Checks if `path' is a regular file. */
bool is_regular_file(const char *path)
{
struct stat st;
return (stat(path, &st) == 0) && S_ISREG(st.st_mode);
}
/* Checks if `path' is a non-regular file. */
bool is_irregular_file(const char *path)
{
struct stat st;
return (stat(path, &st) == 0) && !S_ISREG(st.st_mode);
}
/* Checks if `path' is a readable file. */
bool is_readable(const char *path)
{
return check_access(path, S_IRUSR | S_IRGRP | S_IROTH, R_OK);
}
/* Checks if `path' is a writable file. */
bool is_writable(const char *path)
{
return check_access(path, S_IWUSR | S_IWGRP | S_IWOTH, W_OK);
}
/* Checks if `path' is an executable file (or a searchable directory). */
bool is_executable(const char *path)
{
return check_access(path, S_IXUSR | S_IXGRP | S_IXOTH, X_OK);
}
/* Checks if this process has a proper permission to access the specified file.
* Returns false if the file does not exist. */
bool check_access(const char *path, mode_t mode, int amode)
{
/* Even if the faccessat/eaccess function was considered available by
* `configure', the OS kernel may not support it. We fall back on our own
* checking function if faccessat/eaccess was rejected. */
#if HAVE_FACCESSAT
if (faccessat(AT_FDCWD, path, amode, AT_EACCESS) == 0)
return true;
if (errno != ENOSYS && errno != EINVAL)
return false;
#elif HAVE_EACCESS
if (eaccess(path, amode) == 0)
return true;
if (errno != ENOSYS && errno != EINVAL)
return false;
#else
(void) amode;
#endif
/* The algorithm below is not 100% valid for all POSIX systems. */
struct stat st;
uid_t uid;
gid_t gid;
if (stat(path, &st) < 0)
return false;
uid = geteuid();
#if !YASH_DISABLE_SUPERUSER
if (uid == 0) {
/* the "root" user has special permissions */
return (mode & (S_IRUSR | S_IRGRP | S_IROTH
| S_IWUSR | S_IWGRP | S_IWOTH))
|| S_ISDIR(st.st_mode)
|| (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH));
}
#endif
st.st_mode &= mode;
if (uid == st.st_uid)
return st.st_mode & S_IRWXU;
gid = getegid();
if (gid == st.st_gid)
return st.st_mode & S_IRWXG;
int gcount = getgroups(0, &gid); /* the second argument is a dummy */
if (gcount > 0) {
gid_t groups[gcount];
gcount = getgroups(gcount, groups);
if (gcount > 0) {
for (int i = 0; i < gcount; i++)
if (gid == groups[i])
return st.st_mode & S_IRWXG;
}
}
return st.st_mode & S_IRWXO;
}
/* Checks if `path' is a readable regular file. */
bool is_readable_regular(const char *path)
{
return is_regular_file(path) && is_readable(path);
}
/* Checks if `path' is an executable regular file. */
bool is_executable_regular(const char *path)
{
return is_regular_file(path) && is_executable(path);
}
/* Checks if `path' is a directory. */
bool is_directory(const char *path)
{
struct stat st;
return (stat(path, &st) == 0) && S_ISDIR(st.st_mode);
}
/* Checks if two stat results name the same file. */
inline bool stat_result_same_file(
const struct stat *stat1, const struct stat *stat2)
{
return stat1->st_dev == stat2->st_dev
&& stat1->st_ino == stat2->st_ino;
}
/* Checks if two files are the same file. */
bool is_same_file(const char *path1, const char *path2)
{
struct stat stat1, stat2;
return stat(path1, &stat1) == 0 && stat(path2, &stat2) == 0
&& stat_result_same_file(&stat1, &stat2);
}
/* Checks if the specified `path' is normalized, that is, containing no "."
* or ".." in it. */
/* Note that a normalized path may contain redundant slashes. */
bool is_normalized_path(const wchar_t *path)
{
while (path[0] != L'\0') {
if (path[0] == L'.' &&
(path[1] == L'\0' || path[1] == L'/' ||
(path[1] == L'.' && (path[2] == L'\0' || path[2] == L'/'))))
return false;
path = wcschr(path, L'/');
if (path == NULL)
break;
path++;
}
return true;
}
/* Returns the result of `getcwd' as a newly malloced string.
* On error, `errno' is set and NULL is returned. */
char *xgetcwd(void)
{
#if GETCWD_AUTO_MALLOC
char *pwd = getcwd(NULL, 0);
return (pwd != NULL) ? xrealloc(pwd, add(strlen(pwd), 1)) : NULL;
#else
size_t pwdlen = 40;
char *pwd = xmalloc(pwdlen);
while (getcwd(pwd, pwdlen) == NULL) {
if (errno == ERANGE) {
pwdlen = mul(pwdlen, 2);
pwd = xrealloc(pwd, pwdlen);
} else {
int saveerrno = errno;
free(pwd);
pwd = NULL;
errno = saveerrno;
break;
}
}
return pwd;
#endif
}
/* Searches directories `dirs' for a file named `name' that satisfies predicate
* `cond'.
* name: the pathname of the file to be searched for.
* If `name' is an absolute path, a copy of it is simply returned.
* dirs: a NULL-terminated array of strings that are the names of
* directories to search. An empty string is treated as the current
* directory. If `dirs' is NULL, no directory is searched.
* cond: the function that determines the specified pathname satisfies a
* certain condition.
* For each directory in `dirs', in order, the directory name and "/" and
* `name' are concatenated to produce a pathname and `cond' is called with
* the pathname. If `cond' returns true, search is complete and the pathname
* is returned as a newly malloced string. If `cond' returns false to all the
* produced pathnames, NULL is returned.
* If `name' starts with a slash, a copy of `name' is simply returned. If `name'
* is an empty string or `dirs' is NULL, NULL is returned.
* `name' and all the directory names in `dirs' must start and end in the
* initial shift state. */
char *which(
const char *restrict name,
char *const *restrict dirs,
bool cond(const char *path))
{
if (name[0] == L'\0')
return NULL;
if (name[0] == '/')
return xstrdup(name);
if (dirs == NULL)
return NULL;
size_t namelen = strlen(name);
for (const char *dir; (dir = *dirs) != NULL; dirs++) {
size_t dirlen = strlen(dir);
char path[dirlen + namelen + 3];
if (dirlen > 0) {
/* concatenate `dir' and `name' to produce a pathname `path' */
strcpy(path, dir);
if (path[dirlen - 1] != '/')
path[dirlen++] = '/';
strcpy(path + dirlen, name);
} else {
/* if `dir' is empty, it's considered to be the current directory */
strcpy(path, name);
}
if (cond(path))
return xstrdup(path);
}
return NULL;
}
/* Creates a new temporary file under "/tmp".
* `mode' is the access permission bits of the file.
* The name of the temporary file ends with `suffix`, which should be as short
* as possible and must not exceed 8 bytes.
* On successful completion, a file descriptor is returned, which is both
* readable and writeable regardless of `mode', and a pointer to a string
* containing the filename is assigned to `*filename', which should be freed by
* the caller. The filename consists only of portable filename characters.
* On failure, -1 is returned with `**filename' left unchanged and `errno' is
* set to the error value. */
int create_temporary_file(
char **restrict filename, const char *restrict suffix, mode_t mode)
{
static uintmax_t num = 0;
uintmax_t n;
int fd;
xstrbuf_T buf;
n = (uintmax_t) shell_pid * 272229637312669;
if (num == 0)
num = (uintmax_t) time(NULL) * 5131212142718371 << 1 | 1;
sb_initwithmax(&buf, 31);
for (int i = 0; i < 100; i++) {
num = (num ^ n) * 16777619;
sb_printf(&buf, "/tmp/yash-%" PRIXMAX, num);
size_t maxlen = _POSIX_NAME_MAX + 5 - strlen(suffix);
if (buf.length > maxlen)
sb_truncate(&buf, maxlen);
sb_cat(&buf, suffix);
fd = open(buf.contents, O_RDWR | O_CREAT | O_EXCL, mode);
if (fd >= 0) {
*filename = sb_tostr(&buf);
return fd;
} else if (errno != EEXIST && errno != EINTR) {
int saveerrno = errno;
sb_destroy(&buf);
errno = saveerrno;
return -1;
}
sb_clear(&buf);
}
sb_destroy(&buf);
errno = EAGAIN;
return -1;
}
/********** Command Hashtable **********/
static inline void forget_command_path(const char *command)
__attribute__((nonnull));
static wchar_t *get_default_path(void)
__attribute__((malloc,warn_unused_result));
/* A hashtable from command names to their full path.
* Keys are pointers to a multibyte string containing a command name and
* values are pointers to a multibyte string containing the commands' full path.
* For each entry, the key string is part of the value, that is, the last
* pathname component of the value.
* Full paths may be relative, in which case the paths are unreliable because
* the working directory may have been changed since the paths had been
* entered. */
static hashtable_T cmdhash;
/* Initializes the command hashtable. */
void init_cmdhash(void)
{
assert(cmdhash.capacity == 0);
ht_init(&cmdhash, hashstr, htstrcmp);
}
/* Empties the command hashtable. */
void clear_cmdhash(void)
{
ht_clear(&cmdhash, vfree);
}
/* Searches PATH for the specified command and returns its full pathname.
* If `forcelookup' is false and the command is already entered in the command
* hashtable, the value in the hashtable is returned. Otherwise, `which' is
* called to search for the command, the result is entered into the hashtable,
* and then it is returned. If no command is found, NULL is returned. */
const char *get_command_path(const char *name, bool forcelookup)
{
const char *path;
if (!forcelookup) {
path = ht_get(&cmdhash, name).value;
if (path != NULL && path[0] == '/' && is_executable_regular(path))
return path;
}
path = which(name, get_path_array(PA_PATH), is_executable_regular);
if (path != NULL) {
size_t namelen = strlen(name), pathlen = strlen(path);
const char *nameinpath = path + pathlen - namelen;
assert(strcmp(name, nameinpath) == 0);
vfree(ht_set(&cmdhash, nameinpath, path));
} else {
forget_command_path(name);
}
return path;
}
/* Removes the specified command from the command hashtable. */
void forget_command_path(const char *command)
{
vfree(ht_remove(&cmdhash, command));
}
/* Last result of `get_command_path_default'. */
static char *gcpd_value = NULL;
/* Paths for `get_command_path_default'. */
static char **default_path = NULL;
/* Searches for the specified command using the system's default PATH.
* The full path of the command is returned if found, NULL otherwise.
* The return value is valid until the next call to this function. */
const char *get_command_path_default(const char *name)
{
assert(name != gcpd_value);
free(gcpd_value);
if (default_path == NULL) {
wchar_t *defpath = get_default_path();
if (defpath == NULL) {
gcpd_value = NULL;
return gcpd_value;
}
default_path = decompose_paths(defpath);
free(defpath);
}
gcpd_value = which(name, default_path, is_executable_regular);
return gcpd_value;
}
/* Returns the system's default PATH as a newly malloced string.
* The default PATH is (assumed to be) guaranteed to contain all the standard
* utilities. */
wchar_t *get_default_path(void)
{
#if HAVE_PATHS_H && defined _PATH_STDPATH
return malloc_mbstowcs(_PATH_STDPATH);
#else
size_t size = 100;
char *buf = xmalloc(size);
size_t s = confstr(_CS_PATH, buf, size);
if (s > size) {
size = s;
buf = xrealloc(buf, size);
s = confstr(_CS_PATH, buf, size);
}
if (s == 0 || s > size) {
free(buf);
return NULL;
}
return realloc_mbstowcs(buf);
#endif
}
/********** Home Directory Cache **********/
static struct passwd *xgetpwnam(const char *name)
__attribute__((nonnull));
static void clear_homedirhash(void);
static inline void forget_home_directory(const wchar_t *username);
/* Calls `getpwnam' until it doesn't return EINTR. */
struct passwd *xgetpwnam(const char *name)
{
struct passwd *pw;
do {
errno = 0;
pw = getpwnam(name);
} while (pw == NULL && errno == EINTR);
return pw;
}
/* A hashtable from users' names to their home directory paths.
* Keys are pointers to a wide string containing a user's login name and
* values are pointers to a wide string containing their home directory name.
* A memory block for the key/value string must be allocated at once so that,
* when the value is `free'd, the key is `free'd as well. */
static hashtable_T homedirhash;
/* Initializes the home directory hashtable. */
void init_homedirhash(void)
{
assert(homedirhash.capacity == 0);
ht_init(&homedirhash, hashwcs, htwcscmp);
}
/* Empties the home directory hashtable. */
void clear_homedirhash(void)
{
ht_clear(&homedirhash, vfree);
}
/* Returns the full pathname of the specified user's home directory.
* If `forcelookup' is false and the path is already entered in the home
* directory hashtable, the value in the hashtable is returned. Otherwise,
* `getpwnam' is called, the result is entered into the hashtable and then
* it is returned. If no entry is returned by `getpwnam', NULL is returned. */
const wchar_t *get_home_directory(const wchar_t *username, bool forcelookup)
{
const wchar_t *path;
if (!forcelookup) {
path = ht_get(&homedirhash, username).value;
if (path != NULL)
return path;
}
char *mbsusername = malloc_wcstombs(username);
if (mbsusername == NULL)
return NULL;
struct passwd *pw = xgetpwnam(mbsusername);
free(mbsusername);
if (pw == NULL)
return NULL;
xwcsbuf_T dir;
wb_init(&dir);
if (wb_mbscat(&dir, pw->pw_dir) != NULL) {
wb_destroy(&dir);
return NULL;
}
wb_wccat(&dir, L'\0');
size_t usernameindex = dir.length;
wb_cat(&dir, username);
wchar_t *dirname = wb_towcs(&dir);
vfree(ht_set(&homedirhash, dirname + usernameindex, dirname));
return dirname;
}
/* Forget the specified user's home directory. */
void forget_home_directory(const wchar_t *username)
{
vfree(ht_remove(&homedirhash, username));
}
/********** wglob **********/
/* Parsed glob pattern component */
struct wglob_pattern {
enum {
WGLOB_LITERAL, WGLOB_MATCH, WGLOB_RECSEARCH,
} type;
union {
struct {
char *name;
wchar_t *wname;
} literal;
struct {
xfnmatch_T *pattern;
} match;
struct {
bool followlink, allowperiod;
} recsearch;
} value;
};
/* Data used in search */
struct wglob_search {
plist_T pattern;
enum wglobflags_T flags;
xstrbuf_T path;
xwcsbuf_T wpath;
plist_T *results;
};
/* `pattern' is an array of pointers to struct wglob_pattern objects. Each
* wglob_pattern object is called a "component", which corresponds to one
* segment of the entire pattern that is split at slashes.
* `path' and `wpath' are intermediate pathnames, denoting the currently
* searched directory. They are the multi-byte and wide string versions of the
* same pathname. The multi-byte version is mainly used for calling OS APIs and
* the wide version for producing the final results. */
/* Data used in search for one level of directory */
struct wglob_stack {
const struct wglob_stack *prev;
struct stat st;
unsigned char active_components[];
};
/* `st' is mainly used to detect recursion into the same directory and prevent
* infinite search.
* The length of `active_components' is the same as that of `pattern' in `struct
* wglob_search'. When an item of `active_components' is zero, the component is
* not active. When non-zero, it is active. For a recursive search component,
* the value is the depth of the current recursion. */
/* The wglob search algorithm used to perform naive search, but it was slow when
* the pattern contained more than one recursive search component */
// (e.g. foo/**/bar/**/baz)
/* We now implement a state-machine-based algorithm that tries to avoid
* searching the same directory more than once. During search, we keep track of
* "active components" in the pattern, which are the components that correspond
* to the currently searched intermediate path. In a recursive search, a single
* directory may match more than one component, so there may be more than one
* active component at a time. We scan all the active components for each
* intermediate path and produce a set of active components for the next path.
*/
static plist_T wglob_parse_pattern(
const wchar_t *pattern, enum wglobflags_T flags)
__attribute__((nonnull,warn_unused_result));
static struct wglob_pattern *wglob_parse_component(
const wchar_t *pattern, enum wglobflags_T flags, bool has_next)
__attribute__((nonnull,malloc,warn_unused_result));
static struct wglob_pattern *wglob_create_recsearch_component(
bool followlink, bool allowperiod)
__attribute__((malloc,warn_unused_result));
static void wglob_free_pattern(struct wglob_pattern *c);
static void wglob_free_pattern_vp(void *c);
static inline struct wglob_stack *wglob_stack_new(
const struct wglob_search *s, const struct wglob_stack *prev)
__attribute__((nonnull(1)));
static void wglob_search(
struct wglob_search *restrict s, struct wglob_stack *restrict t)
__attribute__((nonnull));
static void wglob_search_literal_each(
struct wglob_search *restrict s, const struct wglob_stack *restrict t)
__attribute__((nonnull));
static void wglob_add_result(
struct wglob_search *s, bool only_if_existing, bool markdir)
__attribute__((nonnull));
static void wglob_search_literal_uniq(
struct wglob_search *restrict s, struct wglob_stack *restrict t)
__attribute__((nonnull));
static bool wglob_scandir(
struct wglob_search *restrict s, const struct wglob_stack *restrict t)
__attribute__((nonnull));
static void wglob_scandir_entry(
const char *name, struct wglob_search *restrict s,
const struct wglob_stack *restrict t, struct wglob_stack *restrict t2,
bool only_if_existing)
__attribute__((nonnull));
static bool wglob_should_recurse(
const char *restrict name, const char *restrict path,
const struct wglob_pattern *restrict c, struct wglob_stack *restrict t,
size_t count)
__attribute__((nonnull));
static bool wglob_is_reentry(const struct wglob_stack *const t, size_t count)
__attribute__((nonnull,pure));
static int wglob_sortcmp(const void *v1, const void *v2)
__attribute__((pure,nonnull));
/* A wide string version of `glob'.
* Adds all pathnames that matches the specified pattern to the specified list.
* pattern: the pattern to match
* flags: a bitwise OR of the following flags:
* WGLB_MARK: directory items have '/' appended to their name
* WGLB_CASEFOLD: do matching case-insensitively
* WGLB_PERIOD: L'*' and L'?' match L'.' at the beginning
* WGLB_NOSORT: don't sort resulting items
* WGLB_RECDIR: allow recursive search with L"**"
* list: a list of pointers to wide strings to which resulting items are
* added.
* Returns true iff successful. However, some result items may be added to the
* list even if unsuccessful.
* If the pattern is invalid, immediately returns false.
* If the shell is interactive and SIGINT is not blocked, this function can be
* interrupted, in which case false is returned.
* Minor errors such as permission errors are ignored. */
bool wglob(const wchar_t *restrict pattern, enum wglobflags_T flags,
plist_T *restrict list)
{
struct wglob_search s;
size_t listbase = list->length;
s.pattern = wglob_parse_pattern(pattern, flags);
if (s.pattern.length == 0) {
pl_destroy(&s.pattern);
return false;
}
s.flags = flags;
sb_init(&s.path);
wb_init(&s.wpath);
s.results = list;
struct wglob_stack *t = wglob_stack_new(&s, NULL);
t->active_components[0] = 1;
wglob_search(&s, t);
free(t);
sb_destroy(&s.path);
wb_destroy(&s.wpath);
plfree(pl_toary(&s.pattern), wglob_free_pattern_vp);
if (!(flags & WGLB_NOSORT)) {
size_t count = list->length - listbase; /* # of resulting items */
qsort(list->contents + listbase, count, sizeof (void *), wglob_sortcmp);
}
return !is_interrupted();
}
/* Parses the specified pattern.
* The result is a pointer list of newly malloced `struct wglob_pattern's.
* WGLB_CASEFOLD, WGLB_PERIOD and WGLB_RECDIR in `flags' affect the results. */
plist_T wglob_parse_pattern(const wchar_t *pattern, enum wglobflags_T flags)
{
plist_T components;
pl_init(&components);
for (;;) {
const wchar_t *slash = wcschr(pattern, L'/');
size_t componentlength =
(slash != NULL) ? (size_t) (slash - pattern) : wcslen(pattern);
wchar_t component[componentlength + 1];
wcsncpy(component, pattern, componentlength);
component[componentlength] = L'\0';
struct wglob_pattern *c =
wglob_parse_component(component, flags, slash != NULL);
if (c == NULL) {
pl_clear(&components, wglob_free_pattern_vp);
break;
}
pl_add(&components, c);
if (slash == NULL)
break;
pattern = &slash[1];
}
return components;
}
/* Parses one pattern component.
* `has_next' must be true if the component is not the last one. */
struct wglob_pattern *wglob_parse_component(
const wchar_t *pattern, enum wglobflags_T flags, bool has_next)
{
assert(!wcschr(pattern, L'/'));
if (has_next && (flags & WGLB_RECDIR)) {
if (wcscmp(pattern, L"**") == 0)
return wglob_create_recsearch_component(false, false);
if (wcscmp(pattern, L"***") == 0)
return wglob_create_recsearch_component(true, false);
if (wcscmp(pattern, L".**") == 0)
return wglob_create_recsearch_component(false, true);
if (wcscmp(pattern, L".***") == 0)
return wglob_create_recsearch_component(true, true);
}
struct wglob_pattern *result = xmalloc(sizeof *result);
if (is_matching_pattern(pattern)) {
xfnmflags_T xflags = XFNM_HEADONLY | XFNM_TAILONLY;
if (flags & WGLB_CASEFOLD)
xflags |= XFNM_CASEFOLD;
if (!(flags & WGLB_PERIOD))
xflags |= XFNM_PERIOD;
result->type = WGLOB_MATCH;
result->value.match.pattern = xfnm_compile(pattern, xflags);
if (result->value.match.pattern == NULL)
goto fail;
} else {
wchar_t *value = unescape(pattern);
result->type = WGLOB_LITERAL;
result->value.literal.wname = value;
result->value.literal.name = malloc_wcstombs(value);
if (result->value.literal.name == NULL)
goto fail;
}
return result;
fail:
wglob_free_pattern(result);
return NULL;
}
struct wglob_pattern *wglob_create_recsearch_component(
bool followlink, bool allowperiod)
{
struct wglob_pattern *result = xmalloc(sizeof *result);
result->type = WGLOB_RECSEARCH;
result->value.recsearch.followlink = followlink;
result->value.recsearch.allowperiod = allowperiod;
return result;
}
void wglob_free_pattern(struct wglob_pattern *c)
{
if (c == NULL)
return;
switch (c->type) {
case WGLOB_LITERAL:
free(c->value.literal.name);
free(c->value.literal.wname);
break;
case WGLOB_MATCH:
xfnm_free(c->value.match.pattern);
break;
case WGLOB_RECSEARCH:
break;
}
free(c);
}
void wglob_free_pattern_vp(void *c)
{
wglob_free_pattern(c);
}
/* Allocates a new wglob_stack entry with no active components.
* Note that `st' is uninitialized. */
struct wglob_stack *wglob_stack_new(
const struct wglob_search *s, const struct wglob_stack *prev)
{
struct wglob_stack *t =
xmallocs(sizeof *t, sizeof *t->active_components, s->pattern.length);
t->prev = prev;
memset(t->active_components, 0, s->pattern.length);
return t;
}
/* Searches the directory `s->path' and adds matching pathnames to `s->results'.
* `s->path' and `s->wpath' must contain the same pathname, which must be empty
* or end with a slash. The contents of `s->path' and `s->wpath' may be changed
* during the search, but when the function returns the contents are restored to
* the original value.
* Only the WGLB_MARK flag in `s->flags' affects the results. */
void wglob_search(
struct wglob_search *restrict s, struct wglob_stack *restrict t)
{
assert(s->path.length == 0 ||
s->path.contents[s->path.length - 1] == '/');
assert(s->wpath.length == 0 ||
s->wpath.contents[s->wpath.length - 1] == L'/');
if (is_interrupted())
return;
/* find active WGLOB_RECSEARCH components and activate their next component
* to allow the WGLOB_RECSEARCH component to match nothing. */
for (size_t i = 0; i < s->pattern.length; i++) {
if (!t->active_components[i])
continue;
const struct wglob_pattern *c = s->pattern.contents[i];
if (c->type == WGLOB_RECSEARCH) {
assert(i + 1 < s->pattern.length);
t->active_components[i + 1] = t->active_components[i];
}
}
/* count active components */
size_t active_literals = 0, active_matchers = 0;
for (size_t i = 0; i < s->pattern.length; i++) {
if (!t->active_components[i])
continue;
const struct wglob_pattern *c = s->pattern.contents[i];
if (c->type == WGLOB_LITERAL)
active_literals++;
else
active_matchers++;
}
/* perform search depending on the type of active components */
if (active_matchers > 0)
if (wglob_scandir(s, t))
return;
if (active_literals == 1)
wglob_search_literal_each(s, t);
else if (active_literals > 0)
wglob_search_literal_uniq(s, t);
}
/* Applies active components to the current directory path and continues
* searching subdirectories.
* This function ignores active components that are not literal.
* This function must be used only when there is only one literal active
* component. If more than one component are active, duplicate results may be
* produced for the same pathname. */
void wglob_search_literal_each(
struct wglob_search *restrict s, const struct wglob_stack *restrict t)
{
size_t savepathlen = s->path.length, savewpathlen = s->wpath.length;
for (size_t i = 0; i < s->pattern.length; i++) {
if (!t->active_components[i])
continue;
const struct wglob_pattern *c = s->pattern.contents[i];
if (c->type != WGLOB_LITERAL)
continue;
sb_cat(&s->path, c->value.literal.name);
wb_cat(&s->wpath, c->value.literal.wname);
if (i + 1 < s->pattern.length) {
/* There is a next component. */
struct wglob_stack *t2 = wglob_stack_new(s, t);
t2->active_components[i + 1] = 1;
sb_ccat(&s->path, '/');
wb_wccat(&s->wpath, L'/');
wglob_search(s, t2);
free(t2);
} else {
/* This is the last component. */
wglob_add_result(s, true, false);
}
sb_truncate(&s->path, savepathlen);
wb_truncate(&s->wpath, savewpathlen);
}
}
/* Adds `s->path' to `s->results'. */
void wglob_add_result(
struct wglob_search *s, bool only_if_existing, bool markdir)
{
if (!only_if_existing && !markdir) {
pl_add(s->results, xwcsdup(s->wpath.contents));
return;
}
struct stat st;
bool existing = stat(s->path.contents, &st) >= 0;
if (only_if_existing && !existing)
return;
if (!markdir || !existing || !S_ISDIR(st.st_mode)) {
pl_add(s->results, xwcsdup(s->wpath.contents));
return;
}
size_t length = add(wcslen(s->wpath.contents), 1);
xwcsbuf_T result;
wb_initwithmax(&result, length);
wb_cat(&result, s->wpath.contents);
wb_wccat(&result, L'/');
pl_add(s->results, wb_towcs(&result));
}
/* Applies active components to the current directory path and continues
* searching subdirectories.
* This function ignores active components that are not literal. */
void wglob_search_literal_uniq(
struct wglob_search *restrict s, struct wglob_stack *restrict t)
{
/* collect names of active literal components */
hashtable_T ac;
ht_initwithcapacity(&ac, hashwcs, htwcscmp, s->pattern.length);
for (size_t i = 0; i < s->pattern.length; i++) {
if (!t->active_components[i])
continue;
const struct wglob_pattern *c = s->pattern.contents[i];
if (c->type != WGLOB_LITERAL)
continue;
ht_set(&ac, c->value.literal.wname, c);
}
kvpair_T *names = ht_tokvarray(&ac);
ht_destroy(&ac);
/* descend down for each name */
struct wglob_stack *t2 = wglob_stack_new(s, t);
for (const kvpair_T *n = names; n->key != NULL; n++) {
const struct wglob_pattern *c = n->value;
memset(t2->active_components, 0, s->pattern.length);
wglob_scandir_entry(c->value.literal.name, s, t, t2, true);
}
free(t2);
free(names);
}
/* Applies active components to the current directory path and continues
* searching subdirectories.
* Returns true if the directory could be searched. */
bool wglob_scandir(
struct wglob_search *restrict s, const struct wglob_stack *restrict t)
{
DIR* dir = opendir((s->path.length == 0) ? "." : s->path.contents);
if (dir == NULL)
return false;