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