Annotation of src/usr.bin/grep/util.c, Revision 1.8
1.8 ! tedu 1: /* $OpenBSD: util.c,v 1.7 2003/06/24 17:32:10 tedu 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.6 tedu 51: static int grep_search(fastgrep_t *, unsigned char *, int);
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: {
58: FTS *fts;
59: FTSENT *p;
60: int c, fts_flags;
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:
73: if (!(fts = fts_open(argv, fts_flags, (int (*) ()) NULL)))
74: err(1, NULL);
75: while ((p = fts_read(fts)) != NULL) {
76: switch (p->fts_info) {
77: case FTS_DNR:
78: break;
79: case FTS_ERR:
80: errx(1, "%s: %s", p->fts_path, strerror(p->fts_errno));
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;
120: linesqueued = 0;
121: ln.off = -1;
122:
123: if (Bflag > 0)
124: initqueue();
125: for (c = 0; !(lflag && c);) {
126: ln.off += ln.len + 1;
127: if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL)
128: break;
129: if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
130: --ln.len;
131: ln.line_no++;
132:
133: z = tail;
1.2 deraadt 134:
1.4 tedu 135: if ((t = procline(&ln, nottext)) == 0 && Bflag > 0 && z == 0) {
1.1 deraadt 136: enqueue(&ln);
137: linesqueued++;
138: }
139: c += t;
140: }
141: if (Bflag > 0)
142: clearqueue();
143: grep_close(f);
144:
145: if (cflag) {
146: if (!hflag)
147: printf("%s:", ln.file);
148: printf("%u\n", c);
149: }
150: if (lflag && c != 0)
151: printf("%s\n", fn);
152: if (Lflag && c == 0)
153: printf("%s\n", fn);
1.4 tedu 154: if (c && !cflag && !lflag && !Lflag &&
1.7 tedu 155: binbehave == BIN_FILE_BIN && nottext && !qflag)
1.4 tedu 156: printf("Binary file %s matches\n", fn);
157:
1.1 deraadt 158: return c;
159: }
160:
161:
162: /*
163: * Process an individual line in a file. Return non-zero if it matches.
164: */
165:
166: #define isword(x) (isalnum(x) || (x) == '_')
167:
168: static int
1.4 tedu 169: procline(str_t *l, int nottext)
1.1 deraadt 170: {
171: regmatch_t pmatch;
172: int c, i, r, t;
173:
174: if (matchall) {
175: c = !vflag;
176: goto print;
177: }
1.2 deraadt 178:
1.1 deraadt 179: t = vflag ? REG_NOMATCH : 0;
180: pmatch.rm_so = 0;
181: pmatch.rm_eo = l->len;
182: for (c = i = 0; i < patterns; i++) {
1.6 tedu 183: if (fg_pattern[i].pattern)
184: r = grep_search(&fg_pattern[i], (unsigned char *)l->dat,
185: l->len);
186: else
187: r = regexec(&r_pattern[i], l->dat, 0, &pmatch, eflags);
1.1 deraadt 188: if (r == REG_NOMATCH && t == 0)
189: continue;
190: if (r == 0) {
191: if (wflag) {
1.5 deraadt 192: if ((pmatch.rm_so != 0 &&
193: isword(l->dat[pmatch.rm_so - 1])) ||
194: (pmatch.rm_eo != l->len &&
195: isword(l->dat[pmatch.rm_eo])))
1.1 deraadt 196: r = REG_NOMATCH;
197: }
198: if (xflag) {
199: if (pmatch.rm_so != 0 || pmatch.rm_eo != l->len)
200: r = REG_NOMATCH;
201: }
202: }
203: if (r == t) {
204: c++;
205: break;
206: }
207: }
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: /*
233: * Returns: -1 on failure
234: * 0 on success
235: */
236: int
237: fastcomp(fastgrep_t *fg, const char *pattern)
238: {
239: int i;
240: int bol = 0;
241: int eol = 0;
242: int origPatternLen;
243: int shiftPatternLen;
244: int hasDot = 0;
245: int firstHalfDot = -1;
246: int firstLastHalfDot = -1;
247: int lastHalfDot = 0;
248:
1.8 ! tedu 249: if (Fflag) {
! 250: fg->pattern = NULL;
! 251: return (-1);
! 252: }
! 253:
1.6 tedu 254: /* Initialize. */
255: origPatternLen = fg->patternLen = strlen(pattern);
256: fg->bol = 0;
257: fg->eol = 0;
258: fg->reversedSearch = 0;
259:
260: /* Remove end-of-line character ('$'). */
261: if (pattern[fg->patternLen - 1] == '$') {
262: eol++;
263: fg->eol = 1;
264: fg->patternLen--;
265: boleol = 1;
266: }
267:
268: /* Remove beginning-of-line character ('^'). */
269: if (pattern[0] == '^') {
270: bol++;
271: fg->bol = 1;
272: fg->patternLen--;
273: boleol = 1;
274: }
275:
276: /*
1.8 ! tedu 277: * Copy pattern minus '^' and '$' characters at the beginning and
! 278: * ending of the string respectively.
1.6 tedu 279: */
280: fg->pattern = grep_strdup(pattern + bol);
281:
282: /* Look for ways to cheat...er...avoid the full regex engine. */
283: for (i = 0; i < fg->patternLen; i++)
284: {
285: /* Can still cheat? */
286: if ((isalnum(fg->pattern[i])) || isspace(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: (fg->pattern[i] == ':') || (fg->pattern[i] == '/')) {
291: /* As long as it is good, upper case it for later. */
292: if (iflag)
293: fg->pattern[i] = toupper(fg->pattern[i]);
294: } else if (fg->pattern[i] == '.') {
295: hasDot = i;
296: if (i < fg->patternLen / 2) {
297: if (firstHalfDot < -1)
298: /* Closest dot to the beginning */
299: firstHalfDot = i;
300: } else {
301: /* Closest dot to the end of the pattern. */
302: lastHalfDot = i;
303: if (firstLastHalfDot < 0)
304: firstLastHalfDot = i;
305: }
306: } else {
307: /* Free memory and let others know this is empty. */
308: free(fg->pattern);
309: fg->pattern = NULL;
310: return (-1);
311: }
312: }
313:
314: /*
315: * Determine if a reverse search would be faster based on the placement
316: * of the dots.
317: */
318: if ((!(lflag || cflag)) && ((!(bol || eol)) &&
319: ((lastHalfDot) && ((firstHalfDot < 0) ||
320: ((fg->patternLen - (lastHalfDot + 1)) < firstHalfDot))))) {
321: fg->reversedSearch = 1;
322: hasDot = fg->patternLen - (firstHalfDot < 0 ?
323: firstLastHalfDot : firstHalfDot) - 1;
324: grep_revstr(fg->pattern, fg->patternLen);
325: }
326:
327: /*
328: * Normal Quick Search would require a shift based on the position the
329: * next character after the comparison is within the pattern. With
330: * wildcards, the position of the last dot effects the maximum shift
331: * distance.
332: * The closer to the end the wild card is the slower the search. A
333: * reverse version of this algorithm would be useful for wildcards near
334: * the end of the string.
335: *
336: * Examples:
337: * Pattern Max shift
338: * ------- ---------
339: * this 5
340: * .his 4
341: * t.is 3
342: * th.s 2
343: * thi. 1
344: */
345:
346: /* Adjust the shift based on location of the last dot ('.'). */
347: shiftPatternLen = fg->patternLen - hasDot;
348:
349: /* Preprocess pattern. */
350: for (i = 0; i <= UCHAR_MAX; i++)
351: fg->qsBc[i] = shiftPatternLen;
352: for (i = hasDot + 1; i < fg->patternLen; i++) {
353: fg->qsBc[fg->pattern[i]] = fg->patternLen - i;
354: /*
355: * If case is ignored, make the jump apply to both upper and
356: * lower cased characters. As the pattern is stored in upper
357: * case, apply the same to the lower case equivalents.
358: */
359: if (iflag)
360: fg->qsBc[tolower(fg->pattern[i])] = fg->patternLen - i;
361: }
362:
363: /*
364: * Put pattern back to normal after pre-processing to allow for easy
365: * comparisons later.
366: */
367: if (fg->reversedSearch)
368: grep_revstr(fg->pattern, fg->patternLen);
369:
370: return (0);
371: }
372:
373: static int grep_search(fastgrep_t *fg, unsigned char *data, int dataLen)
374: {
375: int j;
376: int rtrnVal = REG_NOMATCH;
377:
378: /* No point in going farther if we do not have enough data. */
379: if (dataLen < fg->patternLen)
380: return (rtrnVal);
381:
382: /* Only try once at the beginning or ending of the line. */
383: if (fg->bol || fg->eol) {
384: /* Simple text comparison. */
385: /* Verify data is >= pattern length before searching on it. */
386: if (dataLen >= fg->patternLen) {
387: /* Determine where in data to start search at. */
388: if (fg->eol)
389: j = dataLen - fg->patternLen;
390: else
391: j = 0;
392: if (!((fg->bol && fg->eol) && (dataLen != fg->patternLen)))
393: if (grep_cmp(fg->pattern, data + j, fg->patternLen) == -1)
394: rtrnVal = 0;
395: }
396: } else if (fg->reversedSearch) {
397: /* Quick Search algorithm. */
398: j = dataLen;
399: do {
400: if (grep_cmp(fg->pattern, data + j - fg->patternLen,
401: fg->patternLen) == -1) {
402: rtrnVal = 0;
403: break;
404: }
405:
406: /* Shift if within bounds, otherwise, we are done. */
407: if (j == 0)
408: break;
409: else
410: j -= fg->qsBc[data[j - fg->patternLen - 1]];
411: } while (j >= 0);
412: } else {
413: /* Quick Search algorithm. */
414: j = 0;
415: do {
416: if (grep_cmp(fg->pattern, data + j, fg->patternLen) == -1) {
417: rtrnVal = 0;
418: break;
419: }
420:
421: /* Shift if within bounds, otherwise, we are done. */
422: if (j + fg->patternLen == dataLen)
423: break;
424: else
425: j += fg->qsBc[data[j + fg->patternLen]];
426: } while (j <= (dataLen - fg->patternLen));
427: }
428:
429: return (rtrnVal);
430: }
431:
432:
1.1 deraadt 433: void *
434: grep_malloc(size_t size)
435: {
436: void *ptr;
437:
438: if ((ptr = malloc(size)) == NULL)
439: err(1, "malloc");
440: return ptr;
441: }
442:
443: void *
444: grep_realloc(void *ptr, size_t size)
445: {
446: if ((ptr = realloc(ptr, size)) == NULL)
447: err(1, "realloc");
448: return ptr;
1.6 tedu 449: }
450:
451: unsigned char *
452: grep_strdup(const char *str)
453: {
454: unsigned char *ptr;
455:
456: if ((ptr = (unsigned char *)strdup(str)) == NULL)
457: err(1, "strdup");
458: return ptr;
459: }
460:
461: /*
462: * Returns: i >= 0 on failure (position that it failed)
463: * -1 on success
464: */
465: int
466: grep_cmp(const unsigned char *pattern, const unsigned char *data,
467: size_t len)
468: {
469: int i;
470:
471: for (i = 0; i < len; i++) {
472: if (((pattern[i] == data[i]) || (pattern[i] == '.')) ||
473: (iflag && pattern[i] == toupper(data[i])))
474: continue;
475: return (i);
476: }
477:
478: return (-1);
479: }
480:
481: static void
482: grep_revstr(unsigned char *str, int len)
483: {
484: int i;
485: char c;
486:
487: for (i = 0; i < len / 2; i++) {
488: c = str[i];
489: str[i] = str[len - i - 1];
490: str[len - i - 1] = c;
491: }
1.1 deraadt 492: }
493:
494: void
495: printline(str_t *line, int sep)
496: {
497: int n;
1.2 deraadt 498:
1.1 deraadt 499: n = 0;
500: if (!hflag) {
501: fputs(line->file, stdout);
502: ++n;
503: }
504: if (nflag) {
505: if (n)
506: putchar(sep);
507: printf("%d", line->line_no);
508: ++n;
509: }
510: if (bflag) {
511: if (n)
512: putchar(sep);
513: printf("%lu", (unsigned long)line->off);
514: }
515: if (n)
516: putchar(sep);
517: fwrite(line->dat, line->len, 1, stdout);
518: putchar('\n');
1.7 tedu 519: }
520:
521: size_t
522: strlcpy(char *dst, const char *src, size_t siz)
523: {
524: register char *d = dst;
525: register const char *s = src;
526: register size_t n = siz;
527:
528: /* Copy as many bytes as will fit */
529: if (n != 0 && --n != 0) {
530: do {
531: if ((*d++ = *s++) == 0)
532: break;
533: } while (--n != 0);
534: }
535:
536: /* Not enough room in dst, add NUL and traverse rest of src */
537: if (n == 0) {
538: if (siz != 0)
539: *d = '\0'; /* NUL-terminate dst */
540: while (*s++)
541: ;
542: }
543:
544: return(s - src - 1); /* count does not include NUL */
1.1 deraadt 545: }