bsd_glob.c revision 7c478bd95313f5f23a4c958a745db2134aa03244
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Guido van Rossum.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/* most changes between the version above and the one below have been ported:
static char sscsid[]= "$OpenBSD: glob.c,v 1.8.10.1 2001/04/10 jason Exp $";
*/
#endif /* LIBC_SCCS and not lint */
/*
* glob(3) -- a superset of the one defined in POSIX 1003.2.
*
* The [!...] convention to negate a range is supported (SysV, Posix, ksh).
*
* Optional extra services, controlled by flags not defined by POSIX:
*
* GLOB_QUOTE:
* Escaping convention: \ inhibits any special meaning the following
* character might have (except \ at end of string is retained).
* GLOB_MAGCHAR:
* Set in gl_flags if pattern contained a globbing character.
* GLOB_NOMAGIC:
* Same as GLOB_NOCHECK, but it will only append pattern if it did
* not contain any magic characters. [Used in csh style globbing]
* GLOB_ALTDIRFUNC:
* Use alternately specified directory access functions.
* GLOB_TILDE:
* GLOB_BRACE:
* expand {1,2}{a,b} to 1a 1b 2a 2b
* gl_matchc:
* Number of matches in the current invocation of glob.
* GLOB_ALPHASORT:
* sort alphabetically like csh (case doesn't matter) instead of in ASCII
* order
*/
#include <EXTERN.h>
#include <perl.h>
#include <XSUB.h>
#include "bsd_glob.h"
#ifdef I_PWD
# include <pwd.h>
#else
#if defined(HAS_PASSWD) && !defined(VMS)
#endif
#endif
#ifndef MAXPATHLEN
# ifdef PATH_MAX
# define MAXPATHLEN PATH_MAX
# ifdef MACOS_TRADITIONAL
# define MAXPATHLEN 255
# else
# define MAXPATHLEN 1024
# endif
# endif
#endif
#ifdef I_LIMITS
#include <limits.h>
#endif
#ifndef ARG_MAX
# ifdef MACOS_TRADITIONAL
# else
# ifdef _SC_ARG_MAX
# else
# ifdef _POSIX_ARG_MAX
# define ARG_MAX _POSIX_ARG_MAX
# else
# ifdef WIN32
# else
# endif
# endif
# endif
# endif
#endif
#define BG_DOLLAR '$'
#define BG_DOT '.'
#define BG_EOS '\0'
#define BG_LBRACKET '['
#define BG_NOT '!'
#define BG_QUESTION '?'
#define BG_QUOTE '\\'
#define BG_RANGE '-'
#define BG_RBRACKET ']'
#ifdef MACOS_TRADITIONAL
# define BG_SEP ':'
#else
# define BG_SEP '/'
#endif
#ifdef DOSISH
#define BG_SEP2 '\\'
#endif
#define BG_STAR '*'
#define BG_TILDE '~'
#define BG_UNDERSCORE '_'
#define BG_LBRACE '{'
#define BG_RBRACE '}'
#define BG_SLASH '/'
#define BG_COMMA ','
#ifndef GLOB_DEBUG
#define M_QUOTE 0x8000
#define M_PROTECT 0x4000
#define M_MASK 0xffff
#define M_ASCII 0x00ff
#else
#define M_QUOTE 0x80
#define M_PROTECT 0x40
#define M_MASK 0xff
#define M_ASCII 0x7f
#endif /* !GLOB_DEBUG */
static int compare(const void *, const void *);
static int ci_compare(const void *, const void *);
static const Char *
#ifdef GLOB_DEBUG
#endif /* GLOB_DEBUG */
#ifdef PERL_IMPLICIT_CONTEXT
static Direntry_t *
my_readdir(DIR *d)
{
#ifndef NETWARE
return PerlDir_read(d);
#else
return (DIR *)PerlDir_read(d);
#endif
}
#else
/* ReliantUNIX (OS formerly known as SINIX) defines readdir
* in LFS-mode to be a 64-bit version of readdir. */
# ifdef sinix
static Direntry_t *
my_readdir(DIR *d)
{
return readdir(d);
}
# else
# define my_readdir readdir
# endif
#endif
#ifdef MACOS_TRADITIONAL
#include <Files.h>
#include <Types.h>
#include <string.h>
static short resolve_updirs(char *new_pattern);
static void remove_trColon(char *path);
#endif
int
{
int c;
#ifdef MACOS_TRADITIONAL
int err;
#endif
#ifndef MACOS_TRADITIONAL
#endif
/* TODO: GLOB_APPEND / GLOB_DOOFFS aren't supported yet */
#if 0
if (!(flags & GLOB_APPEND)) {
if (!(flags & GLOB_DOOFFS))
}
#else
#endif
#ifdef DOSISH
/* Nasty hack to treat patterns like "C:*" correctly. In this
* case, the * should match any file in the current directory
* on the C: drive. However, the glob code does not treat the
* colon specially, so it looks for files beginning "C:" in
* the current directory. To fix this, change the pattern to
* add an explicit "./" at the start (just after the drive
* letter and colon - ie change to "C:./").
*/
*bufnext++ = ':';
*bufnext++ = '.';
patnext += 2;
}
#endif
#ifdef MACOS_TRADITIONAL
/* Check if we need to match a volume name (e.g. '*HD:*') */
g_matchVol = false;
p = (char *) pattern;
if (*p != BG_SEP) {
p++;
while (*p != BG_EOS) {
if (*p == BG_SEP) {
g_matchVol = true;
break;
}
p++;
}
}
/* Transform the pattern:
* (a) Resolve updirs, e.g.
* '*:t*p::' -> '*:'
* ':a*:tmp::::' -> '::'
* ':base::t*p:::' -> '::'
* '*HD::' -> return 0 (error, quit silently)
*
* (b) Remove a single trailing ':', unless it's a "match volume only"
* pattern like '*HD:'; e.g.
* '*:tmp:' -> '*:tmp' but
* '*HD:' -> '*HD:'
* (If we don't do that, even filenames will have a trailing ':' in
* the result.)
*/
/* We operate on a copy of the pattern */
return (GLOB_NOSPACE);
p = (char *) pattern;
while (*np++ = *p++) ;
/* Resolve updirs ... */
if (err) {
/* The pattern is incorrect: tried to move
up above the volume root, see above.
We quit silently. */
return 0;
}
/* remove trailing colon ... */
#endif /* MACOS_TRADITIONAL */
if (flags & GLOB_QUOTE) {
/* Protect the quoted characters. */
if (c == BG_QUOTE) {
#ifdef DOSISH
/* To avoid backslashitis on Win32,
* we only treat \ as a quoting character
* if it precedes one of the
* metacharacters []-{}~\
*/
c != '-' && c != '{' && c != '}' &&
c != '~' && c != '\\') {
#else
#endif
c = BG_QUOTE;
--patnext;
}
} else
*bufnext++ = c;
} else
*bufnext++ = c;
#ifdef MACOS_TRADITIONAL
if (flags & GLOB_BRACE)
else
return err;
#else
if (flags & GLOB_BRACE)
else
#endif
}
/*
* Expand recursively a glob {} pattern. When there is no more expansion
* invoke the standard globbing routine to glob the rest of the magic
* characters
*/
static int
{
int rv;
/* Protect a single {}, for find(1), like csh */
return rv;
}
/*
* Recursive brace globbing helper. Tries to expand a single brace.
* If it succeeds then it invokes globexp1 with the new pattern.
* If it fails then it tries to glob the rest of the pattern and returns.
*/
static int
{
int i;
/* copy part up to the brace */
;
/* Find the balanced brace */
if (*pe == BG_LBRACKET) {
/* Ignore everything between [] */
;
/*
* We could not find a matching BG_RBRACKET.
* Ignore and just look for BG_RBRACE
*/
}
i++;
if (i == 0)
break;
i--;
}
/* Non matching braces; just glob the pattern */
return 0;
}
switch (*pm) {
case BG_LBRACKET:
/* Ignore everything between [] */
;
/*
* We could not find a matching BG_RBRACKET.
* Ignore and just look for BG_RBRACE
*/
}
break;
case BG_LBRACE:
i++;
break;
case BG_RBRACE:
if (i) {
i--;
break;
}
/* FALLTHROUGH */
case BG_COMMA:
break;
else {
/* Append the current string */
;
/*
* Append the rest of the pattern after the
* closing brace
*/
;
/* Expand the current pattern */
#ifdef GLOB_DEBUG
#endif /* GLOB_DEBUG */
/* move after the comma, to the next string */
}
break;
default:
break;
}
}
*rv = 0;
return 0;
}
/*
* expand tilde from the passwd file.
*/
static const Char *
{
char *h;
const Char *p;
return pattern;
/* Copy up to the end of the string or / */
;
*h = BG_EOS;
#if 0
if (h == (char *)eb)
return what;
#endif
/*
* handle a plain ~ or ~/ by expanding $HOME
* first and then trying the password file
*/
#ifdef HAS_PASSWD
return pattern;
else
#else
return pattern;
#endif
}
} else {
/*
* Expand a ~user
*/
#ifdef HAS_PASSWD
return pattern;
else
#else
return pattern;
#endif
}
/* Copy the home directory */
;
/* Append the rest of the pattern */
;
*b = BG_EOS;
return patbuf;
}
/*
* The main glob() routine: compiles the pattern (optionally processing
* quotes), calls glob1() to do the real pattern matching, and finally
* sorts the list (unless unsorted operation is requested). Returns 0
* if things went well, nonzero if errors occurred. It is not an error
* to find no matches.
*/
static int
{
#ifdef MACOS_TRADITIONAL
}
#endif
/* We don't need to check for buffer overflow any more. */
switch (c) {
case BG_LBRACKET:
c = *qpatnext;
if (c == BG_NOT)
++qpatnext;
*bufnext++ = BG_LBRACKET;
if (c == BG_NOT)
--qpatnext;
break;
}
if (c == BG_NOT)
c = *qpatnext++;
do {
qpatnext += 2;
}
} while ((c = *qpatnext++) != BG_RBRACKET);
break;
case BG_QUESTION:
break;
case BG_STAR:
/* collapse adjacent stars to one,
* to avoid exponential behavior
*/
break;
default:
break;
}
}
#ifdef GLOB_DEBUG
#endif /* GLOB_DEBUG */
return(err);
}
/*
* If there was no match we are going to append the pattern
* if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified
* and the pattern did not contain any magic characters
* GLOB_NOMAGIC is there just for compatibility with csh.
*/
{
#ifdef GLOB_DEBUG
printf("calling globextend from glob0\n");
#endif /* GLOB_DEBUG */
}
? ci_compare : compare);
return(0);
}
static int
ci_compare(const void *p, const void *q)
{
const char *pp = *(const char **)p;
const char *qq = *(const char **)q;
int ci;
break;
++pp;
++qq;
}
if (ci == 0)
return compare(p, q);
return ci;
}
static int
compare(const void *p, const void *q)
{
return(strcmp(*(char **)p, *(char **)q));
}
static int
{
/* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */
return(0);
}
/*
* The functions glob2 and glob3 are mutually recursive; there is one level
* of recursion for each segment in the pattern that contains one or more
* meta characters.
*/
static int
{
Char *p, *q;
int anymeta;
/*
* Loop over pattern segments until end of pattern or until
* segment with meta character found.
*/
for (anymeta = 0;;) {
return(0);
#ifdef DOSISH
#endif
#ifdef MACOS_TRADITIONAL
short err;
if (err)
return (err);
#else
return (1);
#endif
}
#ifdef GLOB_DEBUG
printf("calling globextend from glob2\n");
#endif /* GLOB_DEBUG */
}
/* Find end of next segment, copy tentatively to pathend. */
q = pathend;
p = pattern;
#ifdef DOSISH
&& *p != BG_SEP2
#endif
) {
if (ismeta(*p))
anymeta = 1;
if (q+1 > pathend_last)
return (1);
*q++ = *p++;
}
if (!anymeta) { /* No expansion, do next segment. */
pathend = q;
pattern = p;
#ifdef DOSISH
#endif
) {
return (1);
}
} else
/* Need expansion, recurse. */
}
/* NOTREACHED */
}
static int
{
register Direntry_t *dp;
int err;
int nocase;
char buf[MAXPATHLEN];
/*
* The readdirfunc declaration can't be prototyped, because it is
* assigned, below, to two functions which are prototyped in glob.h
* and dirent.h as taking pointers to differently typed opaque
* structures.
*/
if (pathend > pathend_last)
return (1);
errno = 0;
#ifdef VMS
{
if (q - pathbuf > 5) {
q -= 5;
if (q[0] == '.' &&
{
q[0] = '/';
q[1] = BG_EOS;
pathend = q+1;
}
}
}
#endif
#ifdef MACOS_TRADITIONAL
if ((!*pathbuf) && (g_matchVol)) {
short index;
err = 0;
/* Get and match a list of volume names */
/* Initial BG_DOT must be matched literally. */
continue;
;
if (dc >= pathend_last) {
err = 1;
break;
}
continue;
}
if (err)
break;
}
return(err);
} else { /* open dir */
#endif /* MACOS_TRADITIONAL */
/* TODO: don't call for ENOENT or ENOTDIR? */
if (pglob->gl_errfunc) {
return (GLOB_ABEND);
return (GLOB_ABEND);
}
return(0);
}
err = 0;
/* Search directory for matching names. */
else
/* Initial BG_DOT must be matched literally. */
continue;
;
if (dc >= pathend_last) {
err = 1;
break;
}
continue;
}
if (err)
break;
}
else
return(err);
#ifdef MACOS_TRADITIONAL
}
#endif
}
/*
* Extend the gl_pathv member of a glob_t structure to accomodate a new item,
* add the new item, and update gl_pathc.
*
* This assumes the BSD realloc, which only copies the block when its size
* crosses a power-of-two boundary; for v7 realloc, this would cause quadratic
* behavior.
*
* Return 0 if new item added, error code if memory couldn't be allocated.
*
* Invariant of the glob_t structure:
* Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and
* gl_pathv points to (gl_offs + gl_pathc + 1) items.
*/
static int
{
register char **pathv;
register int i;
char *copy;
const Char *p;
#ifdef GLOB_DEBUG
printf("Adding ");
for (p = path; *p; p++)
printf("\n");
#endif /* GLOB_DEBUG */
else
}
return(GLOB_NOSPACE);
}
/* first time around -- clear initial gl_offs items */
}
for (p = path; *p++;)
;
return(GLOB_NOSPACE);
}
}
errno = 0;
return(GLOB_NOSPACE);
}
}
/*
* pattern matching function for filenames. Each occurrence of the *
* pattern causes a recursion level.
*/
static int
{
int ok, negate_range;
Char c, k;
c = *pat++;
switch (c & M_MASK) {
case M_ALL:
return(1);
do
return(1);
;
return(0);
case M_ONE:
return(0);
break;
case M_SET:
ok = 0;
return(0);
++pat;
if (nocase) {
ok = 1;
} else {
if (c <= k && k <= pat[1])
ok = 1;
}
pat += 2;
ok = 1;
if (ok == negate_range)
return(0);
break;
default:
k = *name++;
return(0);
break;
}
}
}
/* Free allocated data belonging to a glob_t structure. */
void
{
register int i;
register char **pp;
if (*pp)
}
}
static DIR *
{
char buf[MAXPATHLEN];
if (!*str) {
#ifdef MACOS_TRADITIONAL
#else
#endif
} else {
return(NULL);
}
return(PerlDir_open(buf));
}
static int
{
char buf[MAXPATHLEN];
return(-1);
#ifdef HAS_LSTAT
#else
#endif /* HAS_LSTAT */
}
static int
{
char buf[MAXPATHLEN];
return(-1);
}
static Char *
{
do {
return (str);
} while (*str++);
return (NULL);
}
static int
{
while (len--) {
return (0);
}
return (1);
}
#ifdef GLOB_DEBUG
static void
{
register Char *p;
for (p = s; *p; p++)
(void)printf("\n");
for (p = s; *p; p++)
(void)printf("\n");
for (p = s; *p; p++)
(void)printf("\n");
}
#endif /* GLOB_DEBUG */
#ifdef MACOS_TRADITIONAL
/* Replace the last occurrence of the pattern ":[^:]+::", e.g. ":lib::",
with a single ':', if possible. It is not an error, if the pattern
doesn't match (we return -1), but if there are two consecutive colons
'::', there must be a preceding ':[^:]+'. Hence, a volume path like
"HD::" is considered to be an error (we return 1), that is, it can't
be resolved. We return 0 on success.
*/
static short
{
char *f, *m, *b; /* front, middle, back */
b = lastchar;
m = lastchar-1;
f = lastchar-2;
/* find a '[^:]::' (e.g. b::) pattern ... */
&& (f >= path)) {
f--;
m--;
b--;
}
if (f < path) { /* no (more) match */
return -1;
}
end_mark = b;
/* ... and now find its preceding colon ':' */
f--;
}
if (f < path) {
/* No preceding colon found, must be a
volume path. We can't move up the
tree and that's an error */
return 1;
}
bgn_mark = f;
/* Shrink path, i.e. exclude all characters between
bgn_mark and end_mark */
return 0;
}
/* Resolve all updirs in pattern. */
static short
resolve_updirs(char *new_pattern)
{
short err;
do {
} while (!err);
if (err == 1) {
return NO_UPDIR_ERR;
}
return 0;
}
/* Remove a trailing colon from the path, but only if it's
not a volume path (e.g. HD:) and not a path consisting
solely of colons. */
static void
remove_trColon(char *path)
{
/* if path matches the pattern /:[^:]+:$/, we can
remove the trailing ':' */
/* there's a trailing ':', there must be at least
one preceding char != ':' and a preceding ':' */
lc--;
lc--;
} else {
return;
}
lc--;
}
/* ... there's a preceding ':', we remove
the trailing colon */
}
}
}
/* With the GLOB_MARK flag on, we append a colon, if pathbuf
is a directory. If the directory name contains no colons,
e.g. 'lib', we can't simply append a ':', since this (e.g.
'lib:') is not a valid (relative) path on Mac OS. Instead,
we add a leading _and_ trailing ':'. */
static short
{
/* check if pathbuf contains a ':',
i.e. is not a file name */
p = pathbuf;
while (*p != BG_EOS) {
if (*p == BG_SEP) {
is_file = false;
break;
}
p++;
}
if (is_file) {
return (1);
}
/* right shift one char */
p--;
pathend++;
while (p >= pathbuf) {
*pe-- = *p--;
}
/* first char becomes a colon */
/* append a colon */
} else {
return (1);
}
}
return 0;
}
/* Return a FSSpec record for the specified volume
(borrowed from MacPerl.xs). */
static OSErr
{
return err;
return noErr; /* 0 */
}
/* Extract a C name from a FSSpec. Note that there are
no leading or trailing colons. */
static void
{
unsigned char *nc;
short i;
/* FSSpec.name is a Pascal string,
convert it to C ... */
for (i=1; i<=len; i++) {
}
}
#endif /* MACOS_TRADITIONAL */