Coverage Report

Created: 2026-10-13 06:57

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