]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/grep/util.c
MFV r316083,316094:
[FreeBSD/FreeBSD.git] / usr.bin / grep / util.c
1 /*      $NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $   */
2 /*      $FreeBSD$       */
3 /*      $OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $  */
4
5 /*-
6  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
7  * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/stat.h>
36 #include <sys/types.h>
37
38 #include <ctype.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fnmatch.h>
42 #include <fts.h>
43 #include <libgen.h>
44 #include <stdbool.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <wchar.h>
50 #include <wctype.h>
51
52 #include "fastmatch.h"
53 #include "grep.h"
54
55 static int       linesqueued;
56 static int       procline(struct str *l, int);
57
58 bool
59 file_matching(const char *fname)
60 {
61         char *fname_base, *fname_buf;
62         bool ret;
63
64         ret = finclude ? false : true;
65         fname_buf = strdup(fname);
66         if (fname_buf == NULL)
67                 err(2, "strdup");
68         fname_base = basename(fname_buf);
69
70         for (unsigned int i = 0; i < fpatterns; ++i) {
71                 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
72                     fnmatch(fpattern[i].pat, fname_base, 0) == 0) {
73                         if (fpattern[i].mode == EXCL_PAT) {
74                                 ret = false;
75                                 break;
76                         } else
77                                 ret = true;
78                 }
79         }
80         free(fname_buf);
81         return (ret);
82 }
83
84 static inline bool
85 dir_matching(const char *dname)
86 {
87         bool ret;
88
89         ret = dinclude ? false : true;
90
91         for (unsigned int i = 0; i < dpatterns; ++i) {
92                 if (dname != NULL &&
93                     fnmatch(dpattern[i].pat, dname, 0) == 0) {
94                         if (dpattern[i].mode == EXCL_PAT)
95                                 return (false);
96                         else
97                                 ret = true;
98                 }
99         }
100         return (ret);
101 }
102
103 /*
104  * Processes a directory when a recursive search is performed with
105  * the -R option.  Each appropriate file is passed to procfile().
106  */
107 int
108 grep_tree(char **argv)
109 {
110         FTS *fts;
111         FTSENT *p;
112         int c, fts_flags;
113         bool ok;
114
115         c = fts_flags = 0;
116
117         switch(linkbehave) {
118         case LINK_EXPLICIT:
119                 fts_flags = FTS_COMFOLLOW;
120                 break;
121         case LINK_SKIP:
122                 fts_flags = FTS_PHYSICAL;
123                 break;
124         default:
125                 fts_flags = FTS_LOGICAL;
126                         
127         }
128
129         fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
130
131         if (!(fts = fts_open(argv, fts_flags, NULL)))
132                 err(2, "fts_open");
133         while ((p = fts_read(fts)) != NULL) {
134                 switch (p->fts_info) {
135                 case FTS_DNR:
136                         /* FALLTHROUGH */
137                 case FTS_ERR:
138                         file_err = true;
139                         if(!sflag)
140                                 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
141                         break;
142                 case FTS_D:
143                         /* FALLTHROUGH */
144                 case FTS_DP:
145                         if (dexclude || dinclude)
146                                 if (!dir_matching(p->fts_name) ||
147                                     !dir_matching(p->fts_path))
148                                         fts_set(fts, p, FTS_SKIP);
149                         break;
150                 case FTS_DC:
151                         /* Print a warning for recursive directory loop */
152                         warnx("warning: %s: recursive directory loop",
153                                 p->fts_path);
154                         break;
155                 default:
156                         /* Check for file exclusion/inclusion */
157                         ok = true;
158                         if (fexclude || finclude)
159                                 ok &= file_matching(p->fts_path);
160
161                         if (ok)
162                                 c += procfile(p->fts_path);
163                         break;
164                 }
165         }
166
167         fts_close(fts);
168         return (c);
169 }
170
171 /*
172  * Opens a file and processes it.  Each file is processed line-by-line
173  * passing the lines to procline().
174  */
175 int
176 procfile(const char *fn)
177 {
178         struct file *f;
179         struct stat sb;
180         struct str ln;
181         mode_t s;
182         int c, t;
183
184         mcount = mlimit;
185
186         if (strcmp(fn, "-") == 0) {
187                 fn = label != NULL ? label : getstr(1);
188                 f = grep_open(NULL);
189         } else {
190                 if (!stat(fn, &sb)) {
191                         /* Check if we need to process the file */
192                         s = sb.st_mode & S_IFMT;
193                         if (s == S_IFDIR && dirbehave == DIR_SKIP)
194                                 return (0);
195                         if ((s == S_IFIFO || s == S_IFCHR || s == S_IFBLK
196                                 || s == S_IFSOCK) && devbehave == DEV_SKIP)
197                                         return (0);
198                 }
199                 f = grep_open(fn);
200         }
201         if (f == NULL) {
202                 file_err = true;
203                 if (!sflag)
204                         warn("%s", fn);
205                 return (0);
206         }
207
208         ln.file = grep_malloc(strlen(fn) + 1);
209         strcpy(ln.file, fn);
210         ln.line_no = 0;
211         ln.len = 0;
212         linesqueued = 0;
213         tail = 0;
214         ln.off = -1;
215
216         for (c = 0;  c == 0 || !(lflag || qflag); ) {
217                 ln.off += ln.len + 1;
218                 if ((ln.dat = grep_fgetln(f, &ln.len)) == NULL || ln.len == 0) {
219                         if (ln.line_no == 0 && matchall)
220                                 exit(0);
221                         else
222                                 break;
223                 }
224                 if (ln.len > 0 && ln.dat[ln.len - 1] == '\n')
225                         --ln.len;
226                 ln.line_no++;
227
228                 /* Return if we need to skip a binary file */
229                 if (f->binary && binbehave == BINFILE_SKIP) {
230                         grep_close(f);
231                         free(ln.file);
232                         free(f);
233                         return (0);
234                 }
235                 /* Process the file line-by-line */
236                 if ((t = procline(&ln, f->binary)) == 0 && Bflag > 0) {
237                         enqueue(&ln);
238                         linesqueued++;
239                 }
240                 c += t;
241                 if (mflag && mcount <= 0)
242                         break;
243         }
244         if (Bflag > 0)
245                 clearqueue();
246         grep_close(f);
247
248         if (cflag) {
249                 if (!hflag)
250                         printf("%s:", ln.file);
251                 printf("%u\n", c);
252         }
253         if (lflag && !qflag && c != 0)
254                 printf("%s%c", fn, nullflag ? 0 : '\n');
255         if (Lflag && !qflag && c == 0)
256                 printf("%s%c", fn, nullflag ? 0 : '\n');
257         if (c && !cflag && !lflag && !Lflag &&
258             binbehave == BINFILE_BIN && f->binary && !qflag)
259                 printf(getstr(8), fn);
260
261         free(ln.file);
262         free(f);
263         return (c);
264 }
265
266 #define iswword(x)      (iswalnum((x)) || (x) == L'_')
267
268 /*
269  * Processes a line comparing it with the specified patterns.  Each pattern
270  * is looped to be compared along with the full string, saving each and every
271  * match, which is necessary to colorize the output and to count the
272  * matches.  The matching lines are passed to printline() to display the
273  * appropriate output.
274  */
275 static int
276 procline(struct str *l, int nottext)
277 {
278         regmatch_t matches[MAX_LINE_MATCHES];
279         regmatch_t pmatch;
280         size_t st = 0;
281         unsigned int i;
282         int c = 0, m = 0, r = 0;
283
284         /* Loop to process the whole line */
285         while (st <= l->len) {
286                 pmatch.rm_so = st;
287                 pmatch.rm_eo = l->len;
288
289                 /* Loop to compare with all the patterns */
290                 for (i = 0; i < patterns; i++) {
291                         if (fg_pattern[i].pattern)
292                                 r = fastexec(&fg_pattern[i],
293                                     l->dat, 1, &pmatch, eflags);
294                         else
295                                 r = regexec(&r_pattern[i], l->dat, 1,
296                                     &pmatch, eflags);
297                         r = (r == 0) ? 0 : REG_NOMATCH;
298                         st = (cflags & REG_NOSUB)
299                                 ? (size_t)l->len
300                                 : (size_t)pmatch.rm_eo;
301                         if (r == REG_NOMATCH)
302                                 continue;
303                         /* Check for full match */
304                         if (r == 0 && xflag)
305                                 if (pmatch.rm_so != 0 ||
306                                     (size_t)pmatch.rm_eo != l->len)
307                                         r = REG_NOMATCH;
308                         /* Check for whole word match */
309                         if (r == 0 && (wflag || fg_pattern[i].word)) {
310                                 wchar_t wbegin, wend;
311
312                                 wbegin = wend = L' ';
313                                 if (pmatch.rm_so != 0 &&
314                                     sscanf(&l->dat[pmatch.rm_so - 1],
315                                     "%lc", &wbegin) != 1)
316                                         r = REG_NOMATCH;
317                                 else if ((size_t)pmatch.rm_eo !=
318                                     l->len &&
319                                     sscanf(&l->dat[pmatch.rm_eo],
320                                     "%lc", &wend) != 1)
321                                         r = REG_NOMATCH;
322                                 else if (iswword(wbegin) ||
323                                     iswword(wend))
324                                         r = REG_NOMATCH;
325                         }
326                         if (r == 0) {
327                                 if (m == 0)
328                                         c++;
329                                 if (m < MAX_LINE_MATCHES)
330                                         matches[m++] = pmatch;
331                                 /* matches - skip further patterns */
332                                 if ((color == NULL && !oflag) ||
333                                     qflag || lflag)
334                                         break;
335                         }
336                 }
337
338                 if (vflag) {
339                         c = !c;
340                         break;
341                 }
342
343                 /* One pass if we are not recording matches */
344                 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
345                         break;
346
347                 if (st == (size_t)pmatch.rm_so)
348                         break;  /* No matches */
349         }
350
351
352         /* Count the matches if we have a match limit */
353         if (mflag)
354                 mcount -= c;
355
356         if (c && binbehave == BINFILE_BIN && nottext)
357                 return (c); /* Binary file */
358
359         /* Dealing with the context */
360         if ((tail || c) && !cflag && !qflag && !lflag && !Lflag) {
361                 if (c) {
362                         if (!first && !prev && !tail && Aflag)
363                                 printf("--\n");
364                         tail = Aflag;
365                         if (Bflag > 0) {
366                                 if (!first && !prev)
367                                         printf("--\n");
368                                 printqueue();
369                         }
370                         linesqueued = 0;
371                         printline(l, ':', matches, m);
372                 } else {
373                         printline(l, '-', matches, m);
374                         tail--;
375                 }
376         }
377
378         if (c) {
379                 prev = true;
380                 first = false;
381         } else
382                 prev = false;
383
384         return (c);
385 }
386
387 /*
388  * Safe malloc() for internal use.
389  */
390 void *
391 grep_malloc(size_t size)
392 {
393         void *ptr;
394
395         if ((ptr = malloc(size)) == NULL)
396                 err(2, "malloc");
397         return (ptr);
398 }
399
400 /*
401  * Safe calloc() for internal use.
402  */
403 void *
404 grep_calloc(size_t nmemb, size_t size)
405 {
406         void *ptr;
407
408         if ((ptr = calloc(nmemb, size)) == NULL)
409                 err(2, "calloc");
410         return (ptr);
411 }
412
413 /*
414  * Safe realloc() for internal use.
415  */
416 void *
417 grep_realloc(void *ptr, size_t size)
418 {
419
420         if ((ptr = realloc(ptr, size)) == NULL)
421                 err(2, "realloc");
422         return (ptr);
423 }
424
425 /*
426  * Safe strdup() for internal use.
427  */
428 char *
429 grep_strdup(const char *str)
430 {
431         char *ret;
432
433         if ((ret = strdup(str)) == NULL)
434                 err(2, "strdup");
435         return (ret);
436 }
437
438 /*
439  * Prints a matching line according to the command line options.
440  */
441 void
442 printline(struct str *line, int sep, regmatch_t *matches, int m)
443 {
444         size_t a = 0;
445         int i, n = 0;
446
447         if (!hflag) {
448                 if (!nullflag) {
449                         fputs(line->file, stdout);
450                         ++n;
451                 } else {
452                         printf("%s", line->file);
453                         putchar(0);
454                 }
455         }
456         if (nflag) {
457                 if (n > 0)
458                         putchar(sep);
459                 printf("%d", line->line_no);
460                 ++n;
461         }
462         if (bflag) {
463                 if (n > 0)
464                         putchar(sep);
465                 printf("%lld", (long long)line->off);
466                 ++n;
467         }
468         if (n)
469                 putchar(sep);
470         /* --color and -o */
471         if ((oflag || color) && m > 0) {
472                 for (i = 0; i < m; i++) {
473                         if (!oflag)
474                                 fwrite(line->dat + a, matches[i].rm_so - a, 1,
475                                     stdout);
476                         if (color) 
477                                 fprintf(stdout, "\33[%sm\33[K", color);
478
479                                 fwrite(line->dat + matches[i].rm_so, 
480                                     matches[i].rm_eo - matches[i].rm_so, 1,
481                                     stdout);
482                         if (color) 
483                                 fprintf(stdout, "\33[m\33[K");
484                         a = matches[i].rm_eo;
485                         if (oflag)
486                                 putchar('\n');
487                 }
488                 if (!oflag) {
489                         if (line->len - a > 0)
490                                 fwrite(line->dat + a, line->len - a, 1, stdout);
491                         putchar('\n');
492                 }
493         } else {
494                 fwrite(line->dat, line->len, 1, stdout);
495                 putchar('\n');
496         }
497 }