[BACK]Return to util.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / grep

Annotation of src/usr.bin/grep/util.c, Revision 1.21

1.21    ! otto        1: /*     $OpenBSD: util.c,v 1.20 2004/01/18 19:01:55 espie Exp $ */
1.3       deraadt     2:
1.1       deraadt     3: /*-
                      4:  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
                      5:  * All rights reserved.
                      6:  *
                      7:  * Redistribution and use in source and binary forms, with or without
                      8:  * modification, are permitted provided that the following conditions
                      9:  * are met:
                     10:  * 1. Redistributions of source code must retain the above copyright
                     11:  *    notice, this list of conditions and the following disclaimer.
                     12:  * 2. Redistributions in binary form must reproduce the above copyright
                     13:  *    notice, this list of conditions and the following disclaimer in the
                     14:  *    documentation and/or other materials provided with the distribution.
                     15:  *
                     16:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
                     17:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     18:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     19:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
                     20:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     21:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     22:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     23:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     24:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     25:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     26:  * SUCH DAMAGE.
                     27:  */
                     28:
                     29: #include <sys/types.h>
                     30: #include <sys/stat.h>
                     31:
                     32: #include <ctype.h>
                     33: #include <err.h>
                     34: #include <errno.h>
                     35: #include <fts.h>
                     36: #include <regex.h>
                     37: #include <stdio.h>
                     38: #include <stdlib.h>
                     39: #include <string.h>
                     40: #include <unistd.h>
                     41: #include <zlib.h>
                     42:
                     43: #include "grep.h"
                     44:
                     45: /*
                     46:  * Process a file line by line...
                     47:  */
                     48:
                     49: static int     linesqueued;
1.4       tedu       50: static int     procline(str_t *l, int);
1.9       millert    51: static int     grep_search(fastgrep_t *, unsigned char *, int, regmatch_t *pmatch);
1.6       tedu       52: static int     grep_cmp(const unsigned char *, const unsigned char *, size_t);
                     53: static void    grep_revstr(unsigned char *, int);
1.1       deraadt    54:
1.2       deraadt    55: int
1.1       deraadt    56: grep_tree(char **argv)
                     57: {
1.10      deraadt    58:        FTS     *fts;
                     59:        FTSENT  *p;
                     60:        int     c, fts_flags;
1.1       deraadt    61:
                     62:        c = fts_flags = 0;
                     63:
                     64:        if (Hflag)
                     65:                fts_flags = FTS_COMFOLLOW;
                     66:        if (Pflag)
                     67:                fts_flags = FTS_PHYSICAL;
                     68:        if (Sflag)
                     69:                fts_flags = FTS_LOGICAL;
                     70:
                     71:        fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
                     72:
1.11      millert    73:        if (!(fts = fts_open(argv, fts_flags, NULL)))
1.14      millert    74:                err(2, NULL);
1.1       deraadt    75:        while ((p = fts_read(fts)) != NULL) {
                     76:                switch (p->fts_info) {
                     77:                case FTS_DNR:
                     78:                        break;
                     79:                case FTS_ERR:
1.14      millert    80:                        errx(2, "%s: %s", p->fts_path, strerror(p->fts_errno));
1.1       deraadt    81:                        break;
                     82:                case FTS_DP:
                     83:                        break;
                     84:                default:
                     85:                        c += procfile(p->fts_path);
                     86:                        break;
                     87:                }
                     88:        }
                     89:
                     90:        return c;
                     91: }
                     92:
                     93: int
                     94: procfile(char *fn)
                     95: {
                     96:        str_t ln;
                     97:        file_t *f;
1.4       tedu       98:        int c, t, z, nottext;
1.1       deraadt    99:
                    100:        if (fn == NULL) {
                    101:                fn = "(standard input)";
                    102:                f = grep_fdopen(STDIN_FILENO, "r");
                    103:        } else {
                    104:                f = grep_open(fn, "r");
                    105:        }
                    106:        if (f == NULL) {
                    107:                if (!sflag)
                    108:                        warn("%s", fn);
                    109:                return 0;
                    110:        }
1.4       tedu      111:
                    112:        nottext = grep_bin_file(f);
                    113:        if (nottext && binbehave == BIN_FILE_SKIP) {
1.1       deraadt   114:                grep_close(f);
                    115:                return 0;
                    116:        }
                    117:
                    118:        ln.file = fn;
                    119:        ln.line_no = 0;
1.20      espie     120:        ln.len = 0;
1.1       deraadt   121:        linesqueued = 0;
                    122:        ln.off = -1;
                    123:
                    124:        if (Bflag > 0)
                    125:                initqueue();
                    126:        for (c = 0; !(lflag && c);) {
                    127:                ln.off += ln.len + 1;
                    128:                if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL)
                    129:                        break;
                    130:                if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
                    131:                        --ln.len;
                    132:                ln.line_no++;
                    133:
                    134:                z = tail;
1.2       deraadt   135:
1.4       tedu      136:                if ((t = procline(&ln, nottext)) == 0 && Bflag > 0 && z == 0) {
1.1       deraadt   137:                        enqueue(&ln);
                    138:                        linesqueued++;
                    139:                }
                    140:                c += t;
                    141:        }
                    142:        if (Bflag > 0)
                    143:                clearqueue();
                    144:        grep_close(f);
                    145:
                    146:        if (cflag) {
                    147:                if (!hflag)
                    148:                        printf("%s:", ln.file);
                    149:                printf("%u\n", c);
                    150:        }
                    151:        if (lflag && c != 0)
                    152:                printf("%s\n", fn);
                    153:        if (Lflag && c == 0)
                    154:                printf("%s\n", fn);
1.4       tedu      155:        if (c && !cflag && !lflag && !Lflag &&
1.7       tedu      156:            binbehave == BIN_FILE_BIN && nottext && !qflag)
1.4       tedu      157:                printf("Binary file %s matches\n", fn);
                    158:
1.1       deraadt   159:        return c;
                    160: }
                    161:
                    162:
                    163: /*
                    164:  * Process an individual line in a file. Return non-zero if it matches.
                    165:  */
                    166:
                    167: #define isword(x) (isalnum(x) || (x) == '_')
                    168:
                    169: static int
1.4       tedu      170: procline(str_t *l, int nottext)
1.1       deraadt   171: {
                    172:        regmatch_t      pmatch;
1.15      dhartmei  173:        int             c, i, r;
1.1       deraadt   174:
                    175:        if (matchall) {
                    176:                c = !vflag;
                    177:                goto print;
                    178:        }
1.2       deraadt   179:
1.1       deraadt   180:        for (c = i = 0; i < patterns; i++) {
1.9       millert   181:                pmatch.rm_so = 0;
                    182:                pmatch.rm_eo = l->len;
1.6       tedu      183:                if (fg_pattern[i].pattern)
                    184:                        r = grep_search(&fg_pattern[i], (unsigned char *)l->dat,
1.9       millert   185:                            l->len, &pmatch);
1.6       tedu      186:                else
1.9       millert   187:                        r = regexec(&r_pattern[i], l->dat, 1, &pmatch, eflags);
1.1       deraadt   188:                if (r == 0) {
                    189:                        if (wflag) {
1.5       deraadt   190:                                if ((pmatch.rm_so != 0 &&
                    191:                                    isword(l->dat[pmatch.rm_so - 1])) ||
                    192:                                    (pmatch.rm_eo != l->len &&
                    193:                                    isword(l->dat[pmatch.rm_eo])))
1.1       deraadt   194:                                        r = REG_NOMATCH;
                    195:                        }
                    196:                        if (xflag) {
                    197:                                if (pmatch.rm_so != 0 || pmatch.rm_eo != l->len)
                    198:                                        r = REG_NOMATCH;
                    199:                        }
                    200:                }
1.15      dhartmei  201:                if (r == 0) {
1.1       deraadt   202:                        c++;
                    203:                        break;
                    204:                }
                    205:        }
1.15      dhartmei  206:        if (vflag)
                    207:                c = !c;
1.2       deraadt   208:
1.1       deraadt   209: print:
1.4       tedu      210:        if (c && binbehave == BIN_FILE_BIN && nottext)
                    211:                return c; /* Binary file */
                    212:
1.1       deraadt   213:        if ((tail > 0 || c) && !cflag && !qflag) {
                    214:                if (c) {
1.5       deraadt   215:                        if (first > 0 && tail == 0 && (Bflag < linesqueued) &&
                    216:                            (Aflag || Bflag))
1.1       deraadt   217:                                printf("--\n");
                    218:                        first = 1;
                    219:                        tail = Aflag;
                    220:                        if (Bflag > 0)
                    221:                                printqueue();
                    222:                        linesqueued = 0;
                    223:                        printline(l, ':');
                    224:                } else {
                    225:                        printline(l, '-');
                    226:                        tail--;
                    227:                }
                    228:        }
                    229:        return c;
                    230: }
                    231:
1.6       tedu      232: /*
1.10      deraadt   233:  * Returns: -1 on failure, 0 on success
1.6       tedu      234:  */
                    235: int
                    236: fastcomp(fastgrep_t *fg, const char *pattern)
                    237: {
                    238:        int i;
                    239:        int bol = 0;
                    240:        int eol = 0;
                    241:        int origPatternLen;
                    242:        int shiftPatternLen;
                    243:        int hasDot = 0;
                    244:        int firstHalfDot = -1;
                    245:        int firstLastHalfDot = -1;
                    246:        int lastHalfDot = 0;
                    247:
1.8       tedu      248:        if (Fflag) {
                    249:                fg->pattern = NULL;
                    250:                return (-1);
                    251:        }
                    252:
1.6       tedu      253:        /* Initialize. */
                    254:        origPatternLen = fg->patternLen = strlen(pattern);
                    255:        fg->bol = 0;
                    256:        fg->eol = 0;
                    257:        fg->reversedSearch = 0;
                    258:
                    259:        /* Remove end-of-line character ('$'). */
                    260:        if (pattern[fg->patternLen - 1] == '$') {
                    261:                eol++;
                    262:                fg->eol = 1;
                    263:                fg->patternLen--;
                    264:                boleol = 1;
                    265:        }
                    266:
                    267:        /* Remove beginning-of-line character ('^'). */
                    268:        if (pattern[0] == '^') {
                    269:                bol++;
                    270:                fg->bol = 1;
                    271:                fg->patternLen--;
                    272:                boleol = 1;
                    273:        }
                    274:
                    275:        /*
1.8       tedu      276:         * Copy pattern minus '^' and '$' characters at the beginning and
                    277:         * ending of the string respectively.
1.6       tedu      278:         */
                    279:        fg->pattern = grep_strdup(pattern + bol);
                    280:
                    281:        /* Look for ways to cheat...er...avoid the full regex engine. */
                    282:        for (i = 0; i < fg->patternLen; i++)
                    283:        {
                    284:                /* Can still cheat? */
                    285:                if ((isalnum(fg->pattern[i])) || isspace(fg->pattern[i]) ||
                    286:                    (fg->pattern[i] == '_') || (fg->pattern[i] == ',') ||
                    287:                    (fg->pattern[i] == '^') || (fg->pattern[i] == '$') ||
                    288:                    (fg->pattern[i] == '=') || (fg->pattern[i] == '-') ||
                    289:                    (fg->pattern[i] == ':') || (fg->pattern[i] == '/')) {
                    290:                        /* As long as it is good, upper case it for later. */
                    291:                        if (iflag)
                    292:                                fg->pattern[i] = toupper(fg->pattern[i]);
                    293:                } else if (fg->pattern[i] == '.') {
                    294:                        hasDot = i;
                    295:                        if (i < fg->patternLen / 2) {
1.19      otto      296:                                if (firstHalfDot < 0)
1.6       tedu      297:                                        /* Closest dot to the beginning */
                    298:                                        firstHalfDot = i;
                    299:                        } else {
                    300:                                /* Closest dot to the end of the pattern. */
                    301:                                lastHalfDot = i;
                    302:                                if (firstLastHalfDot < 0)
                    303:                                        firstLastHalfDot = i;
                    304:                        }
                    305:                } else {
                    306:                        /* Free memory and let others know this is empty. */
                    307:                        free(fg->pattern);
                    308:                        fg->pattern = NULL;
                    309:                        return (-1);
                    310:                }
                    311:        }
                    312:
                    313:        /*
                    314:         * Determine if a reverse search would be faster based on the placement
                    315:         * of the dots.
                    316:         */
                    317:        if ((!(lflag || cflag)) && ((!(bol || eol)) &&
                    318:            ((lastHalfDot) && ((firstHalfDot < 0) ||
                    319:            ((fg->patternLen - (lastHalfDot + 1)) < firstHalfDot))))) {
                    320:                fg->reversedSearch = 1;
                    321:                hasDot = fg->patternLen - (firstHalfDot < 0 ?
                    322:                    firstLastHalfDot : firstHalfDot) - 1;
                    323:                grep_revstr(fg->pattern, fg->patternLen);
                    324:        }
                    325:
                    326:        /*
                    327:         * Normal Quick Search would require a shift based on the position the
                    328:         * next character after the comparison is within the pattern.  With
                    329:         * wildcards, the position of the last dot effects the maximum shift
                    330:         * distance.
                    331:         * The closer to the end the wild card is the slower the search.  A
1.10      deraadt   332:         * reverse version of this algorithm would be useful for wildcards near
1.6       tedu      333:         * the end of the string.
                    334:         *
                    335:         * Examples:
                    336:         * Pattern      Max shift
                    337:         * -------      ---------
                    338:         * this         5
                    339:         * .his         4
                    340:         * t.is         3
                    341:         * th.s         2
                    342:         * thi.         1
                    343:         */
                    344:
                    345:        /* Adjust the shift based on location of the last dot ('.'). */
                    346:        shiftPatternLen = fg->patternLen - hasDot;
                    347:
                    348:        /* Preprocess pattern. */
                    349:        for (i = 0; i <= UCHAR_MAX; i++)
                    350:                fg->qsBc[i] = shiftPatternLen;
                    351:        for (i = hasDot + 1; i < fg->patternLen; i++) {
                    352:                fg->qsBc[fg->pattern[i]] = fg->patternLen - i;
                    353:                /*
                    354:                 * If case is ignored, make the jump apply to both upper and
                    355:                 * lower cased characters.  As the pattern is stored in upper
                    356:                 * case, apply the same to the lower case equivalents.
                    357:                 */
                    358:                if (iflag)
                    359:                        fg->qsBc[tolower(fg->pattern[i])] = fg->patternLen - i;
                    360:        }
                    361:
                    362:        /*
                    363:         * Put pattern back to normal after pre-processing to allow for easy
                    364:         * comparisons later.
                    365:         */
                    366:        if (fg->reversedSearch)
                    367:                grep_revstr(fg->pattern, fg->patternLen);
                    368:
                    369:        return (0);
                    370: }
                    371:
1.9       millert   372: static int
                    373: grep_search(fastgrep_t *fg, unsigned char *data, int dataLen, regmatch_t *pmatch)
1.6       tedu      374: {
                    375:        int j;
                    376:        int rtrnVal = REG_NOMATCH;
                    377:
1.9       millert   378:        pmatch->rm_so = -1;
                    379:        pmatch->rm_eo = -1;
                    380:
1.6       tedu      381:        /* No point in going farther if we do not have enough data. */
                    382:        if (dataLen < fg->patternLen)
                    383:                return (rtrnVal);
                    384:
                    385:        /* Only try once at the beginning or ending of the line. */
                    386:        if (fg->bol || fg->eol) {
                    387:                /* Simple text comparison. */
                    388:                /* Verify data is >= pattern length before searching on it. */
                    389:                if (dataLen >= fg->patternLen) {
                    390:                        /* Determine where in data to start search at. */
                    391:                        if (fg->eol)
                    392:                                j = dataLen - fg->patternLen;
                    393:                        else
                    394:                                j = 0;
                    395:                        if (!((fg->bol && fg->eol) && (dataLen != fg->patternLen)))
1.9       millert   396:                                if (grep_cmp(fg->pattern, data + j, fg->patternLen) == -1) {
1.6       tedu      397:                                        rtrnVal = 0;
1.9       millert   398:                                        pmatch->rm_so = j;
                    399:                                        pmatch->rm_eo = j + fg->patternLen;
                    400:                                }
1.6       tedu      401:                }
                    402:        } else if (fg->reversedSearch) {
                    403:                /* Quick Search algorithm. */
1.17      millert   404:                j = dataLen;
                    405:                do {
1.6       tedu      406:                        if (grep_cmp(fg->pattern, data + j - fg->patternLen,
                    407:                            fg->patternLen) == -1) {
                    408:                                rtrnVal = 0;
1.9       millert   409:                                pmatch->rm_so = j - fg->patternLen;
                    410:                                pmatch->rm_eo = j;
1.6       tedu      411:                                break;
                    412:                        }
1.17      millert   413:                        /* Shift if within bounds, otherwise, we are done. */
                    414:                        if (j == fg->patternLen)
                    415:                                break;
                    416:                        j -= fg->qsBc[data[j - fg->patternLen - 1]];
                    417:                } while (j >= fg->patternLen);
1.6       tedu      418:        } else {
                    419:                /* Quick Search algorithm. */
                    420:                j = 0;
                    421:                do {
                    422:                        if (grep_cmp(fg->pattern, data + j, fg->patternLen) == -1) {
                    423:                                rtrnVal = 0;
1.9       millert   424:                                pmatch->rm_so = j;
                    425:                                pmatch->rm_eo = j + fg->patternLen;
1.6       tedu      426:                                break;
                    427:                        }
                    428:
                    429:                        /* Shift if within bounds, otherwise, we are done. */
                    430:                        if (j + fg->patternLen == dataLen)
                    431:                                break;
                    432:                        else
                    433:                                j += fg->qsBc[data[j + fg->patternLen]];
                    434:                } while (j <= (dataLen - fg->patternLen));
                    435:        }
                    436:
                    437:        return (rtrnVal);
                    438: }
                    439:
                    440:
1.1       deraadt   441: void *
                    442: grep_malloc(size_t size)
                    443: {
1.10      deraadt   444:        void    *ptr;
1.1       deraadt   445:
                    446:        if ((ptr = malloc(size)) == NULL)
1.14      millert   447:                err(2, "malloc");
1.1       deraadt   448:        return ptr;
                    449: }
                    450:
                    451: void *
                    452: grep_realloc(void *ptr, size_t size)
                    453: {
                    454:        if ((ptr = realloc(ptr, size)) == NULL)
1.14      millert   455:                err(2, "realloc");
1.1       deraadt   456:        return ptr;
1.6       tedu      457: }
                    458:
                    459: unsigned char *
                    460: grep_strdup(const char *str)
                    461: {
                    462:        unsigned char *ptr;
                    463:
                    464:        if ((ptr = (unsigned char *)strdup(str)) == NULL)
1.14      millert   465:                err(2, "strdup");
1.6       tedu      466:        return ptr;
                    467: }
                    468:
                    469: /*
                    470:  * Returns:    i >= 0 on failure (position that it failed)
                    471:  *             -1 on success
                    472:  */
1.18      avsm      473: static int
1.9       millert   474: grep_cmp(const unsigned char *pattern, const unsigned char *data, size_t len)
1.6       tedu      475: {
                    476:        int i;
                    477:
                    478:        for (i = 0; i < len; i++) {
                    479:                if (((pattern[i] == data[i]) || (pattern[i] == '.')) ||
                    480:                    (iflag && pattern[i] == toupper(data[i])))
                    481:                        continue;
                    482:                return (i);
                    483:        }
                    484:
                    485:        return (-1);
                    486: }
                    487:
                    488: static void
                    489: grep_revstr(unsigned char *str, int len)
                    490: {
                    491:        int i;
                    492:        char c;
                    493:
                    494:        for (i = 0; i < len / 2; i++) {
                    495:                c = str[i];
                    496:                str[i] = str[len - i - 1];
                    497:                str[len - i - 1] = c;
                    498:        }
1.1       deraadt   499: }
                    500:
                    501: void
                    502: printline(str_t *line, int sep)
                    503: {
                    504:        int n;
1.2       deraadt   505:
1.1       deraadt   506:        n = 0;
                    507:        if (!hflag) {
                    508:                fputs(line->file, stdout);
                    509:                ++n;
                    510:        }
                    511:        if (nflag) {
                    512:                if (n)
                    513:                        putchar(sep);
                    514:                printf("%d", line->line_no);
                    515:                ++n;
                    516:        }
                    517:        if (bflag) {
                    518:                if (n)
                    519:                        putchar(sep);
1.21    ! otto      520:                printf("%lld", (long long)line->off);
        !           521:                ++n;
1.1       deraadt   522:        }
                    523:        if (n)
                    524:                putchar(sep);
                    525:        fwrite(line->dat, line->len, 1, stdout);
                    526:        putchar('\n');
                    527: }