glob.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. /* $OpenBSD: glob.c,v 1.49 2020/04/21 08:25:22 dtucker Exp $ */
  2. /*
  3. * Copyright (c) 1989, 1993
  4. * The Regents of the University of California. All rights reserved.
  5. *
  6. * This code is derived from software contributed to Berkeley by
  7. * Guido van Rossum.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in the
  16. * documentation and/or other materials provided with the distribution.
  17. * 3. Neither the name of the University nor the names of its contributors
  18. * may be used to endorse or promote products derived from this software
  19. * without specific prior written permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. */
  33. /* OPENBSD ORIGINAL: lib/libc/gen/glob.c */
  34. /*
  35. * glob(3) -- a superset of the one defined in POSIX 1003.2.
  36. *
  37. * The [!...] convention to negate a range is supported (SysV, Posix, ksh).
  38. *
  39. * Optional extra services, controlled by flags not defined by POSIX:
  40. *
  41. * GLOB_QUOTE:
  42. * Escaping convention: \ inhibits any special meaning the following
  43. * character might have (except \ at end of string is retained).
  44. * GLOB_MAGCHAR:
  45. * Set in gl_flags if pattern contained a globbing character.
  46. * GLOB_NOMAGIC:
  47. * Same as GLOB_NOCHECK, but it will only append pattern if it did
  48. * not contain any magic characters. [Used in csh style globbing]
  49. * GLOB_ALTDIRFUNC:
  50. * Use alternately specified directory access functions.
  51. * GLOB_TILDE:
  52. * expand ~user/foo to the /home/dir/of/user/foo
  53. * GLOB_BRACE:
  54. * expand {1,2}{a,b} to 1a 1b 2a 2b
  55. * gl_matchc:
  56. * Number of matches in the current invocation of glob.
  57. */
  58. #include "includes.h"
  59. #include "glob.h"
  60. #include <sys/types.h>
  61. #include <sys/stat.h>
  62. #include <dirent.h>
  63. #include <ctype.h>
  64. #include <errno.h>
  65. #include <limits.h>
  66. #include <pwd.h>
  67. #include <stdlib.h>
  68. #ifdef HAVE_STDINT_H
  69. #include <stdint.h>
  70. #endif
  71. #include <string.h>
  72. #include <unistd.h>
  73. #if !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) || \
  74. !defined(GLOB_HAS_GL_MATCHC) || !defined(GLOB_HAS_GL_STATV) || \
  75. !defined(HAVE_DECL_GLOB_NOMATCH) || HAVE_DECL_GLOB_NOMATCH == 0 || \
  76. defined(BROKEN_GLOB)
  77. #include "charclass.h"
  78. #ifdef TILDE
  79. # undef TILDE
  80. #endif
  81. #define DOLLAR '$'
  82. #define DOT '.'
  83. #define EOS '\0'
  84. #define LBRACKET '['
  85. #define NOT '!'
  86. #define QUESTION '?'
  87. #define QUOTE '\\'
  88. #define RANGE '-'
  89. #define RBRACKET ']'
  90. #define SEP '/'
  91. #define STAR '*'
  92. #define TILDE '~'
  93. #define UNDERSCORE '_'
  94. #define LBRACE '{'
  95. #define RBRACE '}'
  96. #define SLASH '/'
  97. #define COMMA ','
  98. #ifndef DEBUG
  99. #define M_QUOTE 0x8000
  100. #define M_PROTECT 0x4000
  101. #define M_MASK 0xffff
  102. #define M_ASCII 0x00ff
  103. typedef u_short Char;
  104. #else
  105. #define M_QUOTE 0x80
  106. #define M_PROTECT 0x40
  107. #define M_MASK 0xff
  108. #define M_ASCII 0x7f
  109. typedef char Char;
  110. #endif
  111. #define CHAR(c) ((Char)((c)&M_ASCII))
  112. #define META(c) ((Char)((c)|M_QUOTE))
  113. #define M_ALL META('*')
  114. #define M_END META(']')
  115. #define M_NOT META('!')
  116. #define M_ONE META('?')
  117. #define M_RNG META('-')
  118. #define M_SET META('[')
  119. #define M_CLASS META(':')
  120. #define ismeta(c) (((c)&M_QUOTE) != 0)
  121. #define GLOB_LIMIT_MALLOC 65536
  122. #define GLOB_LIMIT_STAT 2048
  123. #define GLOB_LIMIT_READDIR 16384
  124. struct glob_lim {
  125. size_t glim_malloc;
  126. size_t glim_stat;
  127. size_t glim_readdir;
  128. };
  129. struct glob_path_stat {
  130. char *gps_path;
  131. struct stat *gps_stat;
  132. };
  133. static int compare(const void *, const void *);
  134. static int compare_gps(const void *, const void *);
  135. static int g_Ctoc(const Char *, char *, size_t);
  136. static int g_lstat(Char *, struct stat *, glob_t *);
  137. static DIR *g_opendir(Char *, glob_t *);
  138. static Char *g_strchr(const Char *, int);
  139. static int g_strncmp(const Char *, const char *, size_t);
  140. static int g_stat(Char *, struct stat *, glob_t *);
  141. static int glob0(const Char *, glob_t *, struct glob_lim *);
  142. static int glob1(Char *, Char *, glob_t *, struct glob_lim *);
  143. static int glob2(Char *, Char *, Char *, Char *, Char *, Char *,
  144. glob_t *, struct glob_lim *);
  145. static int glob3(Char *, Char *, Char *, Char *, Char *,
  146. Char *, Char *, glob_t *, struct glob_lim *);
  147. static int globextend(const Char *, glob_t *, struct glob_lim *,
  148. struct stat *);
  149. static const Char *
  150. globtilde(const Char *, Char *, size_t, glob_t *);
  151. static int globexp1(const Char *, glob_t *, struct glob_lim *);
  152. static int globexp2(const Char *, const Char *, glob_t *,
  153. struct glob_lim *);
  154. static int match(Char *, Char *, Char *);
  155. #ifdef DEBUG
  156. static void qprintf(const char *, Char *);
  157. #endif
  158. int
  159. glob(const char *pattern, int flags, int (*errfunc)(const char *, int),
  160. glob_t *pglob)
  161. {
  162. const u_char *patnext;
  163. int c;
  164. Char *bufnext, *bufend, patbuf[PATH_MAX];
  165. struct glob_lim limit = { 0, 0, 0 };
  166. patnext = (u_char *) pattern;
  167. if (!(flags & GLOB_APPEND)) {
  168. pglob->gl_pathc = 0;
  169. pglob->gl_pathv = NULL;
  170. pglob->gl_statv = NULL;
  171. if (!(flags & GLOB_DOOFFS))
  172. pglob->gl_offs = 0;
  173. }
  174. pglob->gl_flags = flags & ~GLOB_MAGCHAR;
  175. pglob->gl_errfunc = errfunc;
  176. pglob->gl_matchc = 0;
  177. if (strnlen(pattern, PATH_MAX) == PATH_MAX)
  178. return(GLOB_NOMATCH);
  179. if (pglob->gl_offs >= SSIZE_MAX || pglob->gl_pathc >= SSIZE_MAX ||
  180. pglob->gl_pathc >= SSIZE_MAX - pglob->gl_offs - 1)
  181. return GLOB_NOSPACE;
  182. bufnext = patbuf;
  183. bufend = bufnext + PATH_MAX - 1;
  184. if (flags & GLOB_NOESCAPE)
  185. while (bufnext < bufend && (c = *patnext++) != EOS)
  186. *bufnext++ = c;
  187. else {
  188. /* Protect the quoted characters. */
  189. while (bufnext < bufend && (c = *patnext++) != EOS)
  190. if (c == QUOTE) {
  191. if ((c = *patnext++) == EOS) {
  192. c = QUOTE;
  193. --patnext;
  194. }
  195. *bufnext++ = c | M_PROTECT;
  196. } else
  197. *bufnext++ = c;
  198. }
  199. *bufnext = EOS;
  200. if (flags & GLOB_BRACE)
  201. return globexp1(patbuf, pglob, &limit);
  202. else
  203. return glob0(patbuf, pglob, &limit);
  204. }
  205. /*
  206. * Expand recursively a glob {} pattern. When there is no more expansion
  207. * invoke the standard globbing routine to glob the rest of the magic
  208. * characters
  209. */
  210. static int
  211. globexp1(const Char *pattern, glob_t *pglob, struct glob_lim *limitp)
  212. {
  213. const Char* ptr = pattern;
  214. /* Protect a single {}, for find(1), like csh */
  215. if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS)
  216. return glob0(pattern, pglob, limitp);
  217. if ((ptr = (const Char *) g_strchr(ptr, LBRACE)) != NULL)
  218. return globexp2(ptr, pattern, pglob, limitp);
  219. return glob0(pattern, pglob, limitp);
  220. }
  221. /*
  222. * Recursive brace globbing helper. Tries to expand a single brace.
  223. * If it succeeds then it invokes globexp1 with the new pattern.
  224. * If it fails then it tries to glob the rest of the pattern and returns.
  225. */
  226. static int
  227. globexp2(const Char *ptr, const Char *pattern, glob_t *pglob,
  228. struct glob_lim *limitp)
  229. {
  230. int i, rv;
  231. Char *lm, *ls;
  232. const Char *pe, *pm, *pl;
  233. Char patbuf[PATH_MAX];
  234. /* copy part up to the brace */
  235. for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++)
  236. ;
  237. *lm = EOS;
  238. ls = lm;
  239. /* Find the balanced brace */
  240. for (i = 0, pe = ++ptr; *pe; pe++)
  241. if (*pe == LBRACKET) {
  242. /* Ignore everything between [] */
  243. for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++)
  244. ;
  245. if (*pe == EOS) {
  246. /*
  247. * We could not find a matching RBRACKET.
  248. * Ignore and just look for RBRACE
  249. */
  250. pe = pm;
  251. }
  252. } else if (*pe == LBRACE)
  253. i++;
  254. else if (*pe == RBRACE) {
  255. if (i == 0)
  256. break;
  257. i--;
  258. }
  259. /* Non matching braces; just glob the pattern */
  260. if (i != 0 || *pe == EOS)
  261. return glob0(patbuf, pglob, limitp);
  262. for (i = 0, pl = pm = ptr; pm <= pe; pm++) {
  263. switch (*pm) {
  264. case LBRACKET:
  265. /* Ignore everything between [] */
  266. for (pl = pm++; *pm != RBRACKET && *pm != EOS; pm++)
  267. ;
  268. if (*pm == EOS) {
  269. /*
  270. * We could not find a matching RBRACKET.
  271. * Ignore and just look for RBRACE
  272. */
  273. pm = pl;
  274. }
  275. break;
  276. case LBRACE:
  277. i++;
  278. break;
  279. case RBRACE:
  280. if (i) {
  281. i--;
  282. break;
  283. }
  284. /* FALLTHROUGH */
  285. case COMMA:
  286. if (i && *pm == COMMA)
  287. break;
  288. else {
  289. /* Append the current string */
  290. for (lm = ls; (pl < pm); *lm++ = *pl++)
  291. ;
  292. /*
  293. * Append the rest of the pattern after the
  294. * closing brace
  295. */
  296. for (pl = pe + 1; (*lm++ = *pl++) != EOS; )
  297. ;
  298. /* Expand the current pattern */
  299. #ifdef DEBUG
  300. qprintf("globexp2:", patbuf);
  301. #endif
  302. rv = globexp1(patbuf, pglob, limitp);
  303. if (rv && rv != GLOB_NOMATCH)
  304. return rv;
  305. /* move after the comma, to the next string */
  306. pl = pm + 1;
  307. }
  308. break;
  309. default:
  310. break;
  311. }
  312. }
  313. return 0;
  314. }
  315. /*
  316. * expand tilde from the passwd file.
  317. */
  318. static const Char *
  319. globtilde(const Char *pattern, Char *patbuf, size_t patbuf_len, glob_t *pglob)
  320. {
  321. struct passwd *pwd;
  322. char *h;
  323. const Char *p;
  324. Char *b, *eb;
  325. if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE))
  326. return pattern;
  327. /* Copy up to the end of the string or / */
  328. eb = &patbuf[patbuf_len - 1];
  329. for (p = pattern + 1, h = (char *) patbuf;
  330. h < (char *)eb && *p && *p != SLASH; *h++ = *p++)
  331. ;
  332. *h = EOS;
  333. #if 0
  334. if (h == (char *)eb)
  335. return what;
  336. #endif
  337. if (((char *) patbuf)[0] == EOS) {
  338. /*
  339. * handle a plain ~ or ~/ by expanding $HOME
  340. * first and then trying the password file
  341. */
  342. #if 0
  343. if (issetugid() != 0 || (h = getenv("HOME")) == NULL) {
  344. #endif
  345. if ((getuid() != geteuid()) || (h = getenv("HOME")) == NULL) {
  346. if ((pwd = getpwuid(getuid())) == NULL)
  347. return pattern;
  348. else
  349. h = pwd->pw_dir;
  350. }
  351. } else {
  352. /*
  353. * Expand a ~user
  354. */
  355. if ((pwd = getpwnam((char*) patbuf)) == NULL)
  356. return pattern;
  357. else
  358. h = pwd->pw_dir;
  359. }
  360. /* Copy the home directory */
  361. for (b = patbuf; b < eb && *h; *b++ = *h++)
  362. ;
  363. /* Append the rest of the pattern */
  364. while (b < eb && (*b++ = *p++) != EOS)
  365. ;
  366. *b = EOS;
  367. return patbuf;
  368. }
  369. static int
  370. g_strncmp(const Char *s1, const char *s2, size_t n)
  371. {
  372. int rv = 0;
  373. while (n--) {
  374. rv = *(Char *)s1 - *(const unsigned char *)s2++;
  375. if (rv)
  376. break;
  377. if (*s1++ == '\0')
  378. break;
  379. }
  380. return rv;
  381. }
  382. static int
  383. g_charclass(const Char **patternp, Char **bufnextp)
  384. {
  385. const Char *pattern = *patternp + 1;
  386. Char *bufnext = *bufnextp;
  387. const Char *colon;
  388. struct cclass *cc;
  389. size_t len;
  390. if ((colon = g_strchr(pattern, ':')) == NULL || colon[1] != ']')
  391. return 1; /* not a character class */
  392. len = (size_t)(colon - pattern);
  393. for (cc = cclasses; cc->name != NULL; cc++) {
  394. if (!g_strncmp(pattern, cc->name, len) && cc->name[len] == '\0')
  395. break;
  396. }
  397. if (cc->name == NULL)
  398. return -1; /* invalid character class */
  399. *bufnext++ = M_CLASS;
  400. *bufnext++ = (Char)(cc - &cclasses[0]);
  401. *bufnextp = bufnext;
  402. *patternp += len + 3;
  403. return 0;
  404. }
  405. /*
  406. * The main glob() routine: compiles the pattern (optionally processing
  407. * quotes), calls glob1() to do the real pattern matching, and finally
  408. * sorts the list (unless unsorted operation is requested). Returns 0
  409. * if things went well, nonzero if errors occurred. It is not an error
  410. * to find no matches.
  411. */
  412. static int
  413. glob0(const Char *pattern, glob_t *pglob, struct glob_lim *limitp)
  414. {
  415. const Char *qpatnext;
  416. int c, err;
  417. size_t oldpathc;
  418. Char *bufnext, patbuf[PATH_MAX];
  419. qpatnext = globtilde(pattern, patbuf, PATH_MAX, pglob);
  420. oldpathc = pglob->gl_pathc;
  421. bufnext = patbuf;
  422. /* We don't need to check for buffer overflow any more. */
  423. while ((c = *qpatnext++) != EOS) {
  424. switch (c) {
  425. case LBRACKET:
  426. c = *qpatnext;
  427. if (c == NOT)
  428. ++qpatnext;
  429. if (*qpatnext == EOS ||
  430. g_strchr(qpatnext+1, RBRACKET) == NULL) {
  431. *bufnext++ = LBRACKET;
  432. if (c == NOT)
  433. --qpatnext;
  434. break;
  435. }
  436. *bufnext++ = M_SET;
  437. if (c == NOT)
  438. *bufnext++ = M_NOT;
  439. c = *qpatnext++;
  440. do {
  441. if (c == LBRACKET && *qpatnext == ':') {
  442. do {
  443. err = g_charclass(&qpatnext,
  444. &bufnext);
  445. if (err)
  446. break;
  447. c = *qpatnext++;
  448. } while (c == LBRACKET && *qpatnext == ':');
  449. if (err == -1 &&
  450. !(pglob->gl_flags & GLOB_NOCHECK))
  451. return GLOB_NOMATCH;
  452. if (c == RBRACKET)
  453. break;
  454. }
  455. *bufnext++ = CHAR(c);
  456. if (*qpatnext == RANGE &&
  457. (c = qpatnext[1]) != RBRACKET) {
  458. *bufnext++ = M_RNG;
  459. *bufnext++ = CHAR(c);
  460. qpatnext += 2;
  461. }
  462. } while ((c = *qpatnext++) != RBRACKET);
  463. pglob->gl_flags |= GLOB_MAGCHAR;
  464. *bufnext++ = M_END;
  465. break;
  466. case QUESTION:
  467. pglob->gl_flags |= GLOB_MAGCHAR;
  468. *bufnext++ = M_ONE;
  469. break;
  470. case STAR:
  471. pglob->gl_flags |= GLOB_MAGCHAR;
  472. /* collapse adjacent stars to one,
  473. * to avoid exponential behavior
  474. */
  475. if (bufnext == patbuf || bufnext[-1] != M_ALL)
  476. *bufnext++ = M_ALL;
  477. break;
  478. default:
  479. *bufnext++ = CHAR(c);
  480. break;
  481. }
  482. }
  483. *bufnext = EOS;
  484. #ifdef DEBUG
  485. qprintf("glob0:", patbuf);
  486. #endif
  487. if ((err = glob1(patbuf, patbuf+PATH_MAX-1, pglob, limitp)) != 0)
  488. return(err);
  489. /*
  490. * If there was no match we are going to append the pattern
  491. * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
  492. * and the pattern did not contain any magic characters
  493. * GLOB_NOMAGIC is there just for compatibility with csh.
  494. */
  495. if (pglob->gl_pathc == oldpathc) {
  496. if ((pglob->gl_flags & GLOB_NOCHECK) ||
  497. ((pglob->gl_flags & GLOB_NOMAGIC) &&
  498. !(pglob->gl_flags & GLOB_MAGCHAR)))
  499. return(globextend(pattern, pglob, limitp, NULL));
  500. else
  501. return(GLOB_NOMATCH);
  502. }
  503. if (!(pglob->gl_flags & GLOB_NOSORT)) {
  504. if ((pglob->gl_flags & GLOB_KEEPSTAT)) {
  505. /* Keep the paths and stat info synced during sort */
  506. struct glob_path_stat *path_stat;
  507. size_t i;
  508. size_t n = pglob->gl_pathc - oldpathc;
  509. size_t o = pglob->gl_offs + oldpathc;
  510. if ((path_stat = calloc(n, sizeof(*path_stat))) == NULL)
  511. return GLOB_NOSPACE;
  512. for (i = 0; i < n; i++) {
  513. path_stat[i].gps_path = pglob->gl_pathv[o + i];
  514. path_stat[i].gps_stat = pglob->gl_statv[o + i];
  515. }
  516. qsort(path_stat, n, sizeof(*path_stat), compare_gps);
  517. for (i = 0; i < n; i++) {
  518. pglob->gl_pathv[o + i] = path_stat[i].gps_path;
  519. pglob->gl_statv[o + i] = path_stat[i].gps_stat;
  520. }
  521. free(path_stat);
  522. } else {
  523. qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc,
  524. pglob->gl_pathc - oldpathc, sizeof(char *),
  525. compare);
  526. }
  527. }
  528. return(0);
  529. }
  530. static int
  531. compare(const void *p, const void *q)
  532. {
  533. return(strcmp(*(char **)p, *(char **)q));
  534. }
  535. static int
  536. compare_gps(const void *_p, const void *_q)
  537. {
  538. const struct glob_path_stat *p = (const struct glob_path_stat *)_p;
  539. const struct glob_path_stat *q = (const struct glob_path_stat *)_q;
  540. return(strcmp(p->gps_path, q->gps_path));
  541. }
  542. static int
  543. glob1(Char *pattern, Char *pattern_last, glob_t *pglob, struct glob_lim *limitp)
  544. {
  545. Char pathbuf[PATH_MAX];
  546. /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
  547. if (*pattern == EOS)
  548. return(0);
  549. return(glob2(pathbuf, pathbuf+PATH_MAX-1,
  550. pathbuf, pathbuf+PATH_MAX-1,
  551. pattern, pattern_last, pglob, limitp));
  552. }
  553. /*
  554. * The functions glob2 and glob3 are mutually recursive; there is one level
  555. * of recursion for each segment in the pattern that contains one or more
  556. * meta characters.
  557. */
  558. static int
  559. glob2(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
  560. Char *pattern, Char *pattern_last, glob_t *pglob, struct glob_lim *limitp)
  561. {
  562. struct stat sb;
  563. Char *p, *q;
  564. int anymeta;
  565. /*
  566. * Loop over pattern segments until end of pattern or until
  567. * segment with meta character found.
  568. */
  569. for (anymeta = 0;;) {
  570. if (*pattern == EOS) { /* End of pattern? */
  571. *pathend = EOS;
  572. if ((pglob->gl_flags & GLOB_LIMIT) &&
  573. limitp->glim_stat++ >= GLOB_LIMIT_STAT) {
  574. errno = 0;
  575. *pathend++ = SEP;
  576. *pathend = EOS;
  577. return(GLOB_NOSPACE);
  578. }
  579. if (g_lstat(pathbuf, &sb, pglob))
  580. return(0);
  581. if (((pglob->gl_flags & GLOB_MARK) &&
  582. pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) ||
  583. (S_ISLNK(sb.st_mode) &&
  584. (g_stat(pathbuf, &sb, pglob) == 0) &&
  585. S_ISDIR(sb.st_mode)))) {
  586. if (pathend+1 > pathend_last)
  587. return (1);
  588. *pathend++ = SEP;
  589. *pathend = EOS;
  590. }
  591. ++pglob->gl_matchc;
  592. return(globextend(pathbuf, pglob, limitp, &sb));
  593. }
  594. /* Find end of next segment, copy tentatively to pathend. */
  595. q = pathend;
  596. p = pattern;
  597. while (*p != EOS && *p != SEP) {
  598. if (ismeta(*p))
  599. anymeta = 1;
  600. if (q+1 > pathend_last)
  601. return (1);
  602. *q++ = *p++;
  603. }
  604. if (!anymeta) { /* No expansion, do next segment. */
  605. pathend = q;
  606. pattern = p;
  607. while (*pattern == SEP) {
  608. if (pathend+1 > pathend_last)
  609. return (1);
  610. *pathend++ = *pattern++;
  611. }
  612. } else
  613. /* Need expansion, recurse. */
  614. return(glob3(pathbuf, pathbuf_last, pathend,
  615. pathend_last, pattern, p, pattern_last,
  616. pglob, limitp));
  617. }
  618. /* NOTREACHED */
  619. }
  620. static int
  621. glob3(Char *pathbuf, Char *pathbuf_last, Char *pathend, Char *pathend_last,
  622. Char *pattern, Char *restpattern, Char *restpattern_last, glob_t *pglob,
  623. struct glob_lim *limitp)
  624. {
  625. struct dirent *dp;
  626. DIR *dirp;
  627. int err;
  628. char buf[PATH_MAX];
  629. /*
  630. * The readdirfunc declaration can't be prototyped, because it is
  631. * assigned, below, to two functions which are prototyped in glob.h
  632. * and dirent.h as taking pointers to differently typed opaque
  633. * structures.
  634. */
  635. struct dirent *(*readdirfunc)(void *);
  636. if (pathend > pathend_last)
  637. return (1);
  638. *pathend = EOS;
  639. errno = 0;
  640. if ((dirp = g_opendir(pathbuf, pglob)) == NULL) {
  641. /* TODO: don't call for ENOENT or ENOTDIR? */
  642. if (pglob->gl_errfunc) {
  643. if (g_Ctoc(pathbuf, buf, sizeof(buf)))
  644. return(GLOB_ABORTED);
  645. if (pglob->gl_errfunc(buf, errno) ||
  646. pglob->gl_flags & GLOB_ERR)
  647. return(GLOB_ABORTED);
  648. }
  649. return(0);
  650. }
  651. err = 0;
  652. /* Search directory for matching names. */
  653. if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  654. readdirfunc = pglob->gl_readdir;
  655. else
  656. readdirfunc = (struct dirent *(*)(void *))readdir;
  657. while ((dp = (*readdirfunc)(dirp))) {
  658. u_char *sc;
  659. Char *dc;
  660. if ((pglob->gl_flags & GLOB_LIMIT) &&
  661. limitp->glim_readdir++ >= GLOB_LIMIT_READDIR) {
  662. errno = 0;
  663. *pathend++ = SEP;
  664. *pathend = EOS;
  665. err = GLOB_NOSPACE;
  666. break;
  667. }
  668. /* Initial DOT must be matched literally. */
  669. if (dp->d_name[0] == DOT && *pattern != DOT)
  670. continue;
  671. dc = pathend;
  672. sc = (u_char *) dp->d_name;
  673. while (dc < pathend_last && (*dc++ = *sc++) != EOS)
  674. ;
  675. if (dc >= pathend_last) {
  676. *dc = EOS;
  677. err = 1;
  678. break;
  679. }
  680. if (!match(pathend, pattern, restpattern)) {
  681. *pathend = EOS;
  682. continue;
  683. }
  684. err = glob2(pathbuf, pathbuf_last, --dc, pathend_last,
  685. restpattern, restpattern_last, pglob, limitp);
  686. if (err)
  687. break;
  688. }
  689. if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  690. (*pglob->gl_closedir)(dirp);
  691. else
  692. closedir(dirp);
  693. return(err);
  694. }
  695. /*
  696. * Extend the gl_pathv member of a glob_t structure to accommodate a new item,
  697. * add the new item, and update gl_pathc.
  698. *
  699. * This assumes the BSD realloc, which only copies the block when its size
  700. * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
  701. * behavior.
  702. *
  703. * Return 0 if new item added, error code if memory couldn't be allocated.
  704. *
  705. * Invariant of the glob_t structure:
  706. * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
  707. * gl_pathv points to (gl_offs + gl_pathc + 1) items.
  708. */
  709. static int
  710. globextend(const Char *path, glob_t *pglob, struct glob_lim *limitp,
  711. struct stat *sb)
  712. {
  713. char **pathv;
  714. size_t i, newn, len;
  715. char *copy = NULL;
  716. const Char *p;
  717. struct stat **statv;
  718. newn = 2 + pglob->gl_pathc + pglob->gl_offs;
  719. if (pglob->gl_offs >= SSIZE_MAX ||
  720. pglob->gl_pathc >= SSIZE_MAX ||
  721. newn >= SSIZE_MAX ||
  722. SIZE_MAX / sizeof(*pathv) <= newn ||
  723. SIZE_MAX / sizeof(*statv) <= newn) {
  724. nospace:
  725. for (i = pglob->gl_offs; i < newn - 2; i++) {
  726. if (pglob->gl_pathv && pglob->gl_pathv[i])
  727. free(pglob->gl_pathv[i]);
  728. if ((pglob->gl_flags & GLOB_KEEPSTAT) != 0 &&
  729. pglob->gl_pathv && pglob->gl_pathv[i])
  730. free(pglob->gl_statv[i]);
  731. }
  732. free(pglob->gl_pathv);
  733. pglob->gl_pathv = NULL;
  734. free(pglob->gl_statv);
  735. pglob->gl_statv = NULL;
  736. return(GLOB_NOSPACE);
  737. }
  738. pathv = reallocarray(pglob->gl_pathv, newn, sizeof(*pathv));
  739. if (pathv == NULL)
  740. goto nospace;
  741. if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) {
  742. /* first time around -- clear initial gl_offs items */
  743. pathv += pglob->gl_offs;
  744. for (i = pglob->gl_offs; i > 0; i--)
  745. *--pathv = NULL;
  746. }
  747. pglob->gl_pathv = pathv;
  748. if ((pglob->gl_flags & GLOB_KEEPSTAT) != 0) {
  749. statv = reallocarray(pglob->gl_statv, newn, sizeof(*statv));
  750. if (statv == NULL)
  751. goto nospace;
  752. if (pglob->gl_statv == NULL && pglob->gl_offs > 0) {
  753. /* first time around -- clear initial gl_offs items */
  754. statv += pglob->gl_offs;
  755. for (i = pglob->gl_offs; i > 0; i--)
  756. *--statv = NULL;
  757. }
  758. pglob->gl_statv = statv;
  759. if (sb == NULL)
  760. statv[pglob->gl_offs + pglob->gl_pathc] = NULL;
  761. else {
  762. limitp->glim_malloc += sizeof(**statv);
  763. if ((pglob->gl_flags & GLOB_LIMIT) &&
  764. limitp->glim_malloc >= GLOB_LIMIT_MALLOC) {
  765. errno = 0;
  766. return(GLOB_NOSPACE);
  767. }
  768. if ((statv[pglob->gl_offs + pglob->gl_pathc] =
  769. malloc(sizeof(**statv))) == NULL)
  770. goto copy_error;
  771. memcpy(statv[pglob->gl_offs + pglob->gl_pathc], sb,
  772. sizeof(*sb));
  773. }
  774. statv[pglob->gl_offs + pglob->gl_pathc + 1] = NULL;
  775. }
  776. for (p = path; *p++;)
  777. ;
  778. len = (size_t)(p - path);
  779. limitp->glim_malloc += len;
  780. if ((copy = malloc(len)) != NULL) {
  781. if (g_Ctoc(path, copy, len)) {
  782. free(copy);
  783. return(GLOB_NOSPACE);
  784. }
  785. pathv[pglob->gl_offs + pglob->gl_pathc++] = copy;
  786. }
  787. pathv[pglob->gl_offs + pglob->gl_pathc] = NULL;
  788. if ((pglob->gl_flags & GLOB_LIMIT) &&
  789. (newn * sizeof(*pathv)) + limitp->glim_malloc >
  790. GLOB_LIMIT_MALLOC) {
  791. errno = 0;
  792. return(GLOB_NOSPACE);
  793. }
  794. copy_error:
  795. return(copy == NULL ? GLOB_NOSPACE : 0);
  796. }
  797. /*
  798. * pattern matching function for filenames. Each occurrence of the *
  799. * pattern causes an iteration.
  800. *
  801. * Note, this function differs from the original as per the discussion
  802. * here: https://research.swtch.com/glob
  803. *
  804. * Basically we removed the recursion and made it use the algorithm
  805. * from Russ Cox to not go quadratic on cases like a file called
  806. * ("a" x 100) . "x" matched against a pattern like "a*a*a*a*a*a*a*y".
  807. */
  808. static int
  809. match(Char *name, Char *pat, Char *patend)
  810. {
  811. int ok, negate_range;
  812. Char c, k;
  813. Char *nextp = NULL;
  814. Char *nextn = NULL;
  815. loop:
  816. while (pat < patend) {
  817. c = *pat++;
  818. switch (c & M_MASK) {
  819. case M_ALL:
  820. while (pat < patend && (*pat & M_MASK) == M_ALL)
  821. pat++; /* eat consecutive '*' */
  822. if (pat == patend)
  823. return(1);
  824. if (*name == EOS)
  825. return(0);
  826. nextn = name + 1;
  827. nextp = pat - 1;
  828. break;
  829. case M_ONE:
  830. if (*name++ == EOS)
  831. goto fail;
  832. break;
  833. case M_SET:
  834. ok = 0;
  835. if ((k = *name++) == EOS)
  836. goto fail;
  837. if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS)
  838. ++pat;
  839. while (((c = *pat++) & M_MASK) != M_END) {
  840. if ((c & M_MASK) == M_CLASS) {
  841. Char idx = *pat & M_MASK;
  842. if (idx < NCCLASSES &&
  843. cclasses[idx].isctype(k))
  844. ok = 1;
  845. ++pat;
  846. }
  847. if ((*pat & M_MASK) == M_RNG) {
  848. if (c <= k && k <= pat[1])
  849. ok = 1;
  850. pat += 2;
  851. } else if (c == k)
  852. ok = 1;
  853. }
  854. if (ok == negate_range)
  855. goto fail;
  856. break;
  857. default:
  858. if (*name++ != c)
  859. goto fail;
  860. break;
  861. }
  862. }
  863. if (*name == EOS)
  864. return(1);
  865. fail:
  866. if (nextn) {
  867. pat = nextp;
  868. name = nextn;
  869. goto loop;
  870. }
  871. return(0);
  872. }
  873. /* Free allocated data belonging to a glob_t structure. */
  874. void
  875. globfree(glob_t *pglob)
  876. {
  877. size_t i;
  878. char **pp;
  879. if (pglob->gl_pathv != NULL) {
  880. pp = pglob->gl_pathv + pglob->gl_offs;
  881. for (i = pglob->gl_pathc; i--; ++pp)
  882. free(*pp);
  883. free(pglob->gl_pathv);
  884. pglob->gl_pathv = NULL;
  885. }
  886. if (pglob->gl_statv != NULL) {
  887. for (i = 0; i < pglob->gl_pathc; i++) {
  888. free(pglob->gl_statv[i]);
  889. }
  890. free(pglob->gl_statv);
  891. pglob->gl_statv = NULL;
  892. }
  893. }
  894. static DIR *
  895. g_opendir(Char *str, glob_t *pglob)
  896. {
  897. char buf[PATH_MAX];
  898. if (!*str)
  899. strlcpy(buf, ".", sizeof buf);
  900. else {
  901. if (g_Ctoc(str, buf, sizeof(buf)))
  902. return(NULL);
  903. }
  904. if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  905. return((*pglob->gl_opendir)(buf));
  906. return(opendir(buf));
  907. }
  908. static int
  909. g_lstat(Char *fn, struct stat *sb, glob_t *pglob)
  910. {
  911. char buf[PATH_MAX];
  912. if (g_Ctoc(fn, buf, sizeof(buf)))
  913. return(-1);
  914. if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  915. return((*pglob->gl_lstat)(buf, sb));
  916. return(lstat(buf, sb));
  917. }
  918. static int
  919. g_stat(Char *fn, struct stat *sb, glob_t *pglob)
  920. {
  921. char buf[PATH_MAX];
  922. if (g_Ctoc(fn, buf, sizeof(buf)))
  923. return(-1);
  924. if (pglob->gl_flags & GLOB_ALTDIRFUNC)
  925. return((*pglob->gl_stat)(buf, sb));
  926. return(stat(buf, sb));
  927. }
  928. static Char *
  929. g_strchr(const Char *str, int ch)
  930. {
  931. do {
  932. if (*str == ch)
  933. return ((Char *)str);
  934. } while (*str++);
  935. return (NULL);
  936. }
  937. static int
  938. g_Ctoc(const Char *str, char *buf, size_t len)
  939. {
  940. while (len--) {
  941. if ((*buf++ = *str++) == EOS)
  942. return (0);
  943. }
  944. return (1);
  945. }
  946. #ifdef DEBUG
  947. static void
  948. qprintf(const char *str, Char *s)
  949. {
  950. Char *p;
  951. (void)printf("%s:\n", str);
  952. for (p = s; *p; p++)
  953. (void)printf("%c", CHAR(*p));
  954. (void)printf("\n");
  955. for (p = s; *p; p++)
  956. (void)printf("%c", *p & M_PROTECT ? '"' : ' ');
  957. (void)printf("\n");
  958. for (p = s; *p; p++)
  959. (void)printf("%c", ismeta(*p) ? '_' : ' ');
  960. (void)printf("\n");
  961. }
  962. #endif
  963. #endif /* !defined(HAVE_GLOB) || !defined(GLOB_HAS_ALTDIRFUNC) ||
  964. !defined(GLOB_HAS_GL_MATCHC) || !defined(GLOB_HAS_GL_STATV) */