#include <ctype.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "config.h"
#include "pcre.h"
#define FALSE 0
#define TRUE 1
typedef int BOOL;
#define VERSION "4.4 29-Nov-2006"
#define MAX_PATTERN_COUNT 100
#if BUFSIZ > 8192
#define MBUFTHIRD BUFSIZ
#else
#define MBUFTHIRD 8192
#endif
enum { FN_NONE, FN_DEFAULT, FN_ONLY, FN_NOMATCH_ONLY, FN_FORCE };
enum { dee_READ, dee_SKIP, dee_RECURSE };
enum { DEE_READ, DEE_SKIP };
#define PO_WORD_MATCH 0x0001
#define PO_LINE_MATCH 0x0002
#define PO_FIXED_STRINGS 0x0004
enum { EL_LF, EL_CR, EL_CRLF, EL_ANY };
#ifdef JFRIEDL_DEBUG
static int S_arg = -1;
static unsigned int jfriedl_XR = 0;
static unsigned int jfriedl_XT = 0;
static const char *jfriedl_prefix = "";
static const char *jfriedl_postfix = "";
#endif
static int endlinetype;
static char *colour_string = (char *)"1;31";
static char *colour_option = NULL;
static char *dee_option = NULL;
static char *DEE_option = NULL;
static char *newline = NULL;
static char *pattern_filename = NULL;
static char *stdin_name = (char *)"(standard input)";
static char *locale = NULL;
static const unsigned char *pcretables = NULL;
static int pattern_count = 0;
static pcre **pattern_list;
static pcre_extra **hints_list;
static char *include_pattern = NULL;
static char *exclude_pattern = NULL;
static pcre *include_compiled = NULL;
static pcre *exclude_compiled = NULL;
static int after_context = 0;
static int before_context = 0;
static int both_context = 0;
static int dee_action = dee_READ;
static int DEE_action = DEE_READ;
static int error_count = 0;
static int filenames = FN_DEFAULT;
static int process_options = 0;
static BOOL count_only = FALSE;
static BOOL do_colour = FALSE;
static BOOL hyphenpending = FALSE;
static BOOL invert = FALSE;
static BOOL multiline = FALSE;
static BOOL number = FALSE;
static BOOL only_matching = FALSE;
static BOOL quiet = FALSE;
static BOOL silent = FALSE;
static BOOL utf8 = FALSE;
enum { OP_NODATA, OP_STRING, OP_OP_STRING, OP_NUMBER, OP_OP_NUMBER,
OP_PATLIST };
typedef struct option_item {
int type;
int one_char;
void *dataptr;
const char *long_name;
const char *help_text;
} option_item;
#define N_COLOUR (-1)
#define N_EXCLUDE (-2)
#define N_HELP (-3)
#define N_INCLUDE (-4)
#define N_LABEL (-5)
#define N_LOCALE (-6)
#define N_NULL (-7)
static option_item optionlist[] = {
{ OP_NODATA, N_NULL, NULL, "", " terminate options" },
{ OP_NODATA, N_HELP, NULL, "help", "display this help and exit" },
{ OP_NUMBER, 'A', &after_context, "after-context=number", "set number of following context lines" },
{ OP_NUMBER, 'B', &before_context, "before-context=number", "set number of prior context lines" },
{ OP_OP_STRING, N_COLOUR, &colour_option, "color=option", "matched text color option" },
{ OP_NUMBER, 'C', &both_context, "context=number", "set number of context lines, before & after" },
{ OP_NODATA, 'c', NULL, "count", "print only a count of matching lines per FILE" },
{ OP_OP_STRING, N_COLOUR, &colour_option, "colour=option", "matched text colour option" },
{ OP_STRING, 'D', &DEE_option, "devices=action","how to handle devices, FIFOs, and sockets" },
{ OP_STRING, 'd', &dee_option, "directories=action", "how to handle directories" },
{ OP_PATLIST, 'e', NULL, "regex(p)", "specify pattern (may be used more than once)" },
{ OP_NODATA, 'F', NULL, "fixed_strings", "patterns are sets of newline-separated strings" },
{ OP_STRING, 'f', &pattern_filename, "file=path", "read patterns from file" },
{ OP_NODATA, 'H', NULL, "with-filename", "force the prefixing filename on output" },
{ OP_NODATA, 'h', NULL, "no-filename", "suppress the prefixing filename on output" },
{ OP_NODATA, 'i', NULL, "ignore-case", "ignore case distinctions" },
{ OP_NODATA, 'l', NULL, "files-with-matches", "print only FILE names containing matches" },
{ OP_NODATA, 'L', NULL, "files-without-match","print only FILE names not containing matches" },
{ OP_STRING, N_LABEL, &stdin_name, "label=name", "set name for standard input" },
{ OP_STRING, N_LOCALE, &locale, "locale=locale", "use the named locale" },
{ OP_NODATA, 'M', NULL, "multiline", "run in multiline mode" },
{ OP_STRING, 'N', &newline, "newline=type", "specify newline type (CR, LR, CRLF)" },
{ OP_NODATA, 'n', NULL, "line-number", "print line number with output lines" },
{ OP_NODATA, 'o', NULL, "only-matching", "show only the part of the line that matched" },
{ OP_NODATA, 'q', NULL, "quiet", "suppress output, just set return code" },
{ OP_NODATA, 'r', NULL, "recursive", "recursively scan sub-directories" },
{ OP_STRING, N_EXCLUDE,&exclude_pattern, "exclude=pattern","exclude matching files when recursing" },
{ OP_STRING, N_INCLUDE,&include_pattern, "include=pattern","include matching files when recursing" },
#ifdef JFRIEDL_DEBUG
{ OP_OP_NUMBER, 'S', &S_arg, "jeffS", "replace matched (sub)string with X" },
#endif
{ OP_NODATA, 's', NULL, "no-messages", "suppress error messages" },
{ OP_NODATA, 'u', NULL, "utf-8", "use UTF-8 mode" },
{ OP_NODATA, 'V', NULL, "version", "print version information and exit" },
{ OP_NODATA, 'v', NULL, "invert-match", "select non-matching lines" },
{ OP_NODATA, 'w', NULL, "word-regex(p)", "force patterns to match only as words" },
{ OP_NODATA, 'x', NULL, "line-regex(p)", "force patterns to match only whole lines" },
{ OP_NODATA, 0, NULL, NULL, NULL }
};
static const char *prefix[] = {
"", "\\b", "^(?:", "^(?:", "\\Q", "\\b\\Q", "^(?:\\Q", "^(?:\\Q" };
static const char *suffix[] = {
"", "\\b", ")$", ")$", "\\E", "\\E\\b", "\\E)$", "\\E)$" };
const int utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01};
const char utf8_table4[] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 };
#if IS_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
typedef DIR directory_type;
static int
isdirectory(char *filename)
{
struct stat statbuf;
if (stat(filename, &statbuf) < 0)
return 0;
return ((statbuf.st_mode & S_IFMT) == S_IFDIR)? '/' : 0;
}
static directory_type *
opendirectory(char *filename)
{
return opendir(filename);
}
static char *
readdirectory(directory_type *dir)
{
for (;;)
{
struct dirent *dent = readdir(dir);
if (dent == NULL) return NULL;
if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0)
return dent->d_name;
}
return NULL;
}
static void
closedirectory(directory_type *dir)
{
closedir(dir);
}
static int
isregfile(char *filename)
{
struct stat statbuf;
if (stat(filename, &statbuf) < 0)
return 1;
return (statbuf.st_mode & S_IFMT) == S_IFREG;
}
static BOOL
is_stdout_tty(void)
{
return isatty(fileno(stdout));
}
#elif HAVE_WIN32API
#ifndef STRICT
# define STRICT
#endif
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES 0xFFFFFFFF
#endif
#include <windows.h>
typedef struct directory_type
{
HANDLE handle;
BOOL first;
WIN32_FIND_DATA data;
} directory_type;
int
isdirectory(char *filename)
{
DWORD attr = GetFileAttributes(filename);
if (attr == INVALID_FILE_ATTRIBUTES)
return 0;
return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) ? '/' : 0;
}
directory_type *
opendirectory(char *filename)
{
size_t len;
char *pattern;
directory_type *dir;
DWORD err;
len = strlen(filename);
pattern = (char *) malloc(len + 3);
dir = (directory_type *) malloc(sizeof(*dir));
if ((pattern == NULL) || (dir == NULL))
{
fprintf(stderr, "pcregrep: malloc failed\n");
exit(2);
}
memcpy(pattern, filename, len);
memcpy(&(pattern[len]), "\\*", 3);
dir->handle = FindFirstFile(pattern, &(dir->data));
if (dir->handle != INVALID_HANDLE_VALUE)
{
free(pattern);
dir->first = TRUE;
return dir;
}
err = GetLastError();
free(pattern);
free(dir);
errno = (err == ERROR_ACCESS_DENIED) ? EACCES : ENOENT;
return NULL;
}
char *
readdirectory(directory_type *dir)
{
for (;;)
{
if (!dir->first)
{
if (!FindNextFile(dir->handle, &(dir->data)))
return NULL;
}
else
{
dir->first = FALSE;
}
if (strcmp(dir->data.cFileName, ".") != 0 && strcmp(dir->data.cFileName, "..") != 0)
return dir->data.cFileName;
}
#ifndef _MSC_VER
return NULL;
#endif
}
void
closedirectory(directory_type *dir)
{
FindClose(dir->handle);
free(dir);
}
int isregfile(char *filename)
{
return !isdirectory(filename)
}
static BOOL
is_stdout_tty(void)
{
FALSE;
}
#else
typedef void directory_type;
int isdirectory(char *filename) { return 0; }
directory_type * opendirectory(char *filename) {}
char *readdirectory(directory_type *dir) {}
void closedirectory(directory_type *dir) {}
int isregfile(char *filename) { return 1; }
static BOOL
is_stdout_tty(void)
{
return FALSE;
}
#endif
#if ! HAVE_STRERROR
extern int sys_nerr;
extern char *sys_errlist[];
char *
strerror(int n)
{
if (n < 0 || n >= sys_nerr) return "unknown error number";
return sys_errlist[n];
}
#endif
static char *
end_of_line(char *p, char *endptr, int *lenptr)
{
switch(endlinetype)
{
default:
case EL_LF:
while (p < endptr && *p != '\n') p++;
if (p < endptr)
{
*lenptr = 1;
return p + 1;
}
*lenptr = 0;
return endptr;
case EL_CR:
while (p < endptr && *p != '\r') p++;
if (p < endptr)
{
*lenptr = 1;
return p + 1;
}
*lenptr = 0;
return endptr;
case EL_CRLF:
for (;;)
{
while (p < endptr && *p != '\r') p++;
if (++p >= endptr)
{
*lenptr = 0;
return endptr;
}
if (*p == '\n')
{
*lenptr = 2;
return p + 1;
}
}
break;
case EL_ANY:
while (p < endptr)
{
int extra = 0;
register int c = *((unsigned char *)p);
if (utf8 && c >= 0xc0)
{
int gcii, gcss;
extra = utf8_table4[c & 0x3f];
gcss = 6*extra;
c = (c & utf8_table3[extra]) << gcss;
for (gcii = 1; gcii <= extra; gcii++)
{
gcss -= 6;
c |= (p[gcii] & 0x3f) << gcss;
}
}
p += 1 + extra;
switch (c)
{
case 0x0a:
case 0x0b:
case 0x0c:
*lenptr = 1;
return p;
case 0x0d:
if (p < endptr && *p == 0x0a)
{
*lenptr = 2;
p++;
}
else *lenptr = 1;
return p;
case 0x85:
*lenptr = utf8? 2 : 1;
return p;
case 0x2028:
case 0x2029:
*lenptr = 3;
return p;
default:
break;
}
}
*lenptr = 0;
return endptr;
}
}
static char *
previous_line(char *p, char *startptr)
{
switch(endlinetype)
{
default:
case EL_LF:
p--;
while (p > startptr && p[-1] != '\n') p--;
return p;
case EL_CR:
p--;
while (p > startptr && p[-1] != '\n') p--;
return p;
case EL_CRLF:
for (;;)
{
p -= 2;
while (p > startptr && p[-1] != '\n') p--;
if (p <= startptr + 1 || p[-2] == '\r') return p;
}
return p;
case EL_ANY:
if (*(--p) == '\n' && p > startptr && p[-1] == '\r') p--;
if (utf8) while ((*p & 0xc0) == 0x80) p--;
while (p > startptr)
{
register int c;
char *pp = p - 1;
if (utf8)
{
int extra = 0;
while ((*pp & 0xc0) == 0x80) pp--;
c = *((unsigned char *)pp);
if (c >= 0xc0)
{
int gcii, gcss;
extra = utf8_table4[c & 0x3f];
gcss = 6*extra;
c = (c & utf8_table3[extra]) << gcss;
for (gcii = 1; gcii <= extra; gcii++)
{
gcss -= 6;
c |= (pp[gcii] & 0x3f) << gcss;
}
}
}
else c = *((unsigned char *)pp);
switch (c)
{
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x85:
case 0x2028:
case 0x2029:
return p;
default:
break;
}
p = pp;
}
return startptr;
}
}
static void do_after_lines(int lastmatchnumber, char *lastmatchrestart,
char *endptr, char *printname)
{
if (after_context > 0 && lastmatchnumber > 0)
{
int count = 0;
while (lastmatchrestart < endptr && count++ < after_context)
{
int ellength;
char *pp = lastmatchrestart;
if (printname != NULL) fprintf(stdout, "%s-", printname);
if (number) fprintf(stdout, "%d-", lastmatchnumber++);
pp = end_of_line(pp, endptr, &ellength);
fwrite(lastmatchrestart, 1, pp - lastmatchrestart, stdout);
lastmatchrestart = pp;
}
hyphenpending = TRUE;
}
}
static int
pcregrep(FILE *in, char *printname)
{
int rc = 1;
int linenumber = 1;
int lastmatchnumber = 0;
int count = 0;
int offsets[99];
char *lastmatchrestart = NULL;
char buffer[3*MBUFTHIRD];
char *ptr = buffer;
char *endptr;
size_t bufflength;
BOOL endhyphenpending = FALSE;
bufflength = fread(buffer, 1, 3*MBUFTHIRD, in);
endptr = buffer + bufflength;
while (ptr < endptr)
{
int i, endlinelength;
int mrc = 0;
BOOL match = FALSE;
char *t = ptr;
size_t length, linelength;
t = end_of_line(t, endptr, &endlinelength);
linelength = t - ptr - endlinelength;
length = multiline? endptr - ptr : linelength;
#ifdef JFRIEDL_DEBUG
if (jfriedl_XT || jfriedl_XR)
{
#include <sys/time.h>
#include <time.h>
struct timeval start_time, end_time;
struct timezone dummy;
if (jfriedl_XT)
{
unsigned long newlen = length * jfriedl_XT + strlen(jfriedl_prefix) + strlen(jfriedl_postfix);
const char *orig = ptr;
ptr = malloc(newlen + 1);
if (!ptr) {
printf("out of memory");
exit(2);
}
endptr = ptr;
strcpy(endptr, jfriedl_prefix); endptr += strlen(jfriedl_prefix);
for (i = 0; i < jfriedl_XT; i++) {
strncpy(endptr, orig, length);
endptr += length;
}
strcpy(endptr, jfriedl_postfix); endptr += strlen(jfriedl_postfix);
length = newlen;
}
if (gettimeofday(&start_time, &dummy) != 0)
perror("bad gettimeofday");
for (i = 0; i < jfriedl_XR; i++)
match = (pcre_exec(pattern_list[0], hints_list[0], ptr, length, 0, 0, offsets, 99) >= 0);
if (gettimeofday(&end_time, &dummy) != 0)
perror("bad gettimeofday");
double delta = ((end_time.tv_sec + (end_time.tv_usec / 1000000.0))
-
(start_time.tv_sec + (start_time.tv_usec / 1000000.0)));
printf("%s TIMER[%.4f]\n", match ? "MATCH" : "FAIL", delta);
return 0;
}
#endif
for (i = 0; i < pattern_count; i++)
{
mrc = pcre_exec(pattern_list[i], hints_list[i], ptr, length, 0, 0,
offsets, 99);
if (mrc >= 0) { match = TRUE; break; }
if (mrc != PCRE_ERROR_NOMATCH)
{
fprintf(stderr, "pcregrep: pcre_exec() error %d while matching ", mrc);
if (pattern_count > 1) fprintf(stderr, "pattern number %d to ", i+1);
fprintf(stderr, "this line:\n");
fwrite(ptr, 1, linelength, stderr);
fprintf(stderr, "\n");
if (error_count == 0 &&
(mrc == PCRE_ERROR_MATCHLIMIT || mrc == PCRE_ERROR_RECURSIONLIMIT))
{
fprintf(stderr, "pcregrep: error %d means that a resource limit "
"was exceeded\n", mrc);
fprintf(stderr, "pcregrep: check your regex for nested unlimited loops\n");
}
if (error_count++ > 20)
{
fprintf(stderr, "pcregrep: too many errors - abandoned\n");
exit(2);
}
match = invert;
break;
}
}
if (match != invert)
{
BOOL hyphenprinted = FALSE;
if (filenames == FN_NOMATCH_ONLY) return 1;
if (count_only) count++;
else if (filenames == FN_ONLY)
{
fprintf(stdout, "%s\n", printname);
return 0;
}
else if (quiet) return 0;
else if (only_matching)
{
if (printname != NULL) fprintf(stdout, "%s:", printname);
if (number) fprintf(stdout, "%d:", linenumber);
fwrite(ptr + offsets[0], 1, offsets[1] - offsets[0], stdout);
fprintf(stdout, "\n");
}
else
{
if (after_context > 0 && lastmatchnumber > 0)
{
int ellength;
int linecount = 0;
char *p = lastmatchrestart;
while (p < ptr && linecount < after_context)
{
p = end_of_line(p, ptr, &ellength);
linecount++;
}
while (lastmatchrestart < p)
{
char *pp = lastmatchrestart;
if (printname != NULL) fprintf(stdout, "%s-", printname);
if (number) fprintf(stdout, "%d-", lastmatchnumber++);
pp = end_of_line(pp, endptr, &ellength);
fwrite(lastmatchrestart, 1, pp - lastmatchrestart, stdout);
lastmatchrestart = pp;
}
if (lastmatchrestart != ptr) hyphenpending = TRUE;
}
if (hyphenpending)
{
fprintf(stdout, "--\n");
hyphenpending = FALSE;
hyphenprinted = TRUE;
}
if (before_context > 0)
{
int linecount = 0;
char *p = ptr;
while (p > buffer && (lastmatchnumber == 0 || p > lastmatchrestart) &&
linecount < before_context)
{
linecount++;
p = previous_line(p, buffer);
}
if (lastmatchnumber > 0 && p > lastmatchrestart && !hyphenprinted)
fprintf(stdout, "--\n");
while (p < ptr)
{
int ellength;
char *pp = p;
if (printname != NULL) fprintf(stdout, "%s-", printname);
if (number) fprintf(stdout, "%d-", linenumber - linecount--);
pp = end_of_line(pp, endptr, &ellength);
fwrite(p, 1, pp - p, stdout);
p = pp;
}
}
if (after_context > 0 || before_context > 0)
endhyphenpending = TRUE;
if (printname != NULL) fprintf(stdout, "%s:", printname);
if (number) fprintf(stdout, "%d:", linenumber);
if (multiline)
{
int ellength;
char *endmatch = ptr + offsets[1];
t = ptr;
while (t < endmatch)
{
t = end_of_line(t, endptr, &ellength);
if (t <= endmatch) linenumber++; else break;
}
endmatch = end_of_line(endmatch, endptr, &ellength);
linelength = endmatch - ptr - ellength;
}
#ifdef JFRIEDL_DEBUG
if (S_arg >= 0 && S_arg < mrc)
{
int first = S_arg * 2;
int last = first + 1;
fwrite(ptr, 1, offsets[first], stdout);
fprintf(stdout, "X");
fwrite(ptr + offsets[last], 1, linelength - offsets[last], stdout);
}
else
#endif
if (do_colour)
{
fwrite(ptr, 1, offsets[0], stdout);
fprintf(stdout, "%c[%sm", 0x1b, colour_string);
fwrite(ptr + offsets[0], 1, offsets[1] - offsets[0], stdout);
fprintf(stdout, "%c[00m", 0x1b);
fwrite(ptr + offsets[1], 1, linelength - offsets[1], stdout);
}
else fwrite(ptr, 1, linelength + endlinelength, stdout);
}
rc = 0;
lastmatchrestart = ptr + linelength + endlinelength;
lastmatchnumber = linenumber + 1;
}
ptr += linelength + endlinelength;
linenumber++;
if (bufflength >= sizeof(buffer) && ptr > buffer + 2*MBUFTHIRD)
{
if (after_context > 0 &&
lastmatchnumber > 0 &&
lastmatchrestart < buffer + MBUFTHIRD)
{
do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);
lastmatchnumber = 0;
}
memmove(buffer, buffer + MBUFTHIRD, 2*MBUFTHIRD);
ptr -= MBUFTHIRD;
bufflength = 2*MBUFTHIRD + fread(buffer + 2*MBUFTHIRD, 1, MBUFTHIRD, in);
endptr = buffer + bufflength;
if (lastmatchnumber > 0) lastmatchrestart -= MBUFTHIRD;
}
}
if (!only_matching && !count_only)
{
do_after_lines(lastmatchnumber, lastmatchrestart, endptr, printname);
hyphenpending |= endhyphenpending;
}
if (filenames == FN_NOMATCH_ONLY)
{
fprintf(stdout, "%s\n", printname);
return 0;
}
if (count_only)
{
if (printname != NULL) fprintf(stdout, "%s:", printname);
fprintf(stdout, "%d\n", count);
}
return rc;
}
static int
grep_or_recurse(char *pathname, BOOL dir_recurse, BOOL only_one_at_top)
{
int rc = 1;
int sep;
FILE *in;
if (strcmp(pathname, "-") == 0)
{
return pcregrep(stdin,
(filenames > FN_DEFAULT || (filenames == FN_DEFAULT && !only_one_at_top))?
stdin_name : NULL);
}
if ((sep = isdirectory(pathname)) != 0)
{
if (dee_action == dee_SKIP) return 1;
if (dee_action == dee_RECURSE)
{
char buffer[1024];
char *nextfile;
directory_type *dir = opendirectory(pathname);
if (dir == NULL)
{
if (!silent)
fprintf(stderr, "pcregrep: Failed to open directory %s: %s\n", pathname,
strerror(errno));
return 2;
}
while ((nextfile = readdirectory(dir)) != NULL)
{
int frc, blen;
sprintf(buffer, "%.512s%c%.128s", pathname, sep, nextfile);
blen = strlen(buffer);
if (exclude_compiled != NULL &&
pcre_exec(exclude_compiled, NULL, buffer, blen, 0, 0, NULL, 0) >= 0)
continue;
if (include_compiled != NULL &&
pcre_exec(include_compiled, NULL, buffer, blen, 0, 0, NULL, 0) < 0)
continue;
frc = grep_or_recurse(buffer, dir_recurse, FALSE);
if (frc > 1) rc = frc;
else if (frc == 0 && rc == 1) rc = 0;
}
closedirectory(dir);
return rc;
}
}
else if (!isregfile(pathname) && DEE_action == DEE_SKIP) return 1;
in = fopen(pathname, "r");
if (in == NULL)
{
if (!silent)
fprintf(stderr, "pcregrep: Failed to open %s: %s\n", pathname,
strerror(errno));
return 2;
}
rc = pcregrep(in, (filenames > FN_DEFAULT ||
(filenames == FN_DEFAULT && !only_one_at_top))? pathname : NULL);
fclose(in);
return rc;
}
static int
usage(int rc)
{
option_item *op;
fprintf(stderr, "Usage: pcregrep [-");
for (op = optionlist; op->one_char != 0; op++)
{
if (op->one_char > 0) fprintf(stderr, "%c", op->one_char);
}
fprintf(stderr, "] [long options] [pattern] [files]\n");
fprintf(stderr, "Type `pcregrep --help' for more information.\n");
return rc;
}
static void
help(void)
{
option_item *op;
printf("Usage: pcregrep [OPTION]... [PATTERN] [FILE1 FILE2 ...]\n");
printf("Search for PATTERN in each FILE or standard input.\n");
printf("PATTERN must be present if neither -e nor -f is used.\n");
printf("\"-\" can be used as a file name to mean STDIN.\n\n");
printf("Example: pcregrep -i 'hello.*world' menu.h main.c\n\n");
printf("Options:\n");
for (op = optionlist; op->one_char != 0; op++)
{
int n;
char s[4];
if (op->one_char > 0) sprintf(s, "-%c,", op->one_char); else strcpy(s, " ");
printf(" %s --%s%n", s, op->long_name, &n);
n = 30 - n;
if (n < 1) n = 1;
printf("%.*s%s\n", n, " ", op->help_text);
}
printf("\nWhen reading patterns from a file instead of using a command line option,\n");
printf("trailing white space is removed and blank lines are ignored.\n");
printf("There is a maximum of %d patterns.\n", MAX_PATTERN_COUNT);
printf("\nWith no FILEs, read standard input. If fewer than two FILEs given, assume -h.\n");
printf("Exit status is 0 if any matches, 1 if no matches, and 2 if trouble.\n");
}
static int
handle_option(int letter, int options)
{
switch(letter)
{
case N_HELP: help(); exit(0);
case 'c': count_only = TRUE; break;
case 'F': process_options |= PO_FIXED_STRINGS; break;
case 'H': filenames = FN_FORCE; break;
case 'h': filenames = FN_NONE; break;
case 'i': options |= PCRE_CASELESS; break;
case 'l': filenames = FN_ONLY; break;
case 'L': filenames = FN_NOMATCH_ONLY; break;
case 'M': multiline = TRUE; options |= PCRE_MULTILINE|PCRE_FIRSTLINE; break;
case 'n': number = TRUE; break;
case 'o': only_matching = TRUE; break;
case 'q': quiet = TRUE; break;
case 'r': dee_action = dee_RECURSE; break;
case 's': silent = TRUE; break;
case 'u': options |= PCRE_UTF8; utf8 = TRUE; break;
case 'v': invert = TRUE; break;
case 'w': process_options |= PO_WORD_MATCH; break;
case 'x': process_options |= PO_LINE_MATCH; break;
case 'V':
fprintf(stderr, "pcregrep version %s using ", VERSION);
fprintf(stderr, "PCRE version %s\n", pcre_version());
exit(0);
break;
default:
fprintf(stderr, "pcregrep: Unknown option -%c\n", letter);
exit(usage(2));
}
return options;
}
static char *
ordin(int n)
{
static char buffer[8];
char *p = buffer;
sprintf(p, "%d", n);
while (*p != 0) p++;
switch (n%10)
{
case 1: strcpy(p, "st"); break;
case 2: strcpy(p, "nd"); break;
case 3: strcpy(p, "rd"); break;
default: strcpy(p, "th"); break;
}
return buffer;
}
static BOOL
compile_single_pattern(char *pattern, int options, char *filename, int count)
{
char buffer[MBUFTHIRD + 16];
const char *error;
int errptr;
if (pattern_count >= MAX_PATTERN_COUNT)
{
fprintf(stderr, "pcregrep: Too many %spatterns (max %d)\n",
(filename == NULL)? "command-line " : "", MAX_PATTERN_COUNT);
return FALSE;
}
sprintf(buffer, "%s%.*s%s", prefix[process_options], MBUFTHIRD, pattern,
suffix[process_options]);
pattern_list[pattern_count] =
pcre_compile(buffer, options, &error, &errptr, pcretables);
if (pattern_list[pattern_count++] != NULL) return TRUE;
errptr -= (int)strlen(prefix[process_options]);
if (errptr > (int)strlen(pattern)) errptr = (int)strlen(pattern);
if (filename == NULL)
{
if (count == 0)
fprintf(stderr, "pcregrep: Error in command-line regex "
"at offset %d: %s\n", errptr, error);
else
fprintf(stderr, "pcregrep: Error in %s command-line regex "
"at offset %d: %s\n", ordin(count), errptr, error);
}
else
{
fprintf(stderr, "pcregrep: Error in regex in line %d of %s "
"at offset %d: %s\n", count, filename, errptr, error);
}
return FALSE;
}
static BOOL
compile_pattern(char *pattern, int options, char *filename, int count)
{
if ((process_options & PO_FIXED_STRINGS) != 0)
{
char *eop = pattern + strlen(pattern);
char buffer[MBUFTHIRD];
for(;;)
{
int ellength;
char *p = end_of_line(pattern, eop, &ellength);
if (ellength == 0)
return compile_single_pattern(pattern, options, filename, count);
sprintf(buffer, "%.*s", p - pattern - ellength, pattern);
pattern = p;
if (!compile_single_pattern(buffer, options, filename, count))
return FALSE;
}
}
else return compile_single_pattern(pattern, options, filename, count);
}
int
main(int argc, char **argv)
{
int i, j;
int rc = 1;
int pcre_options = 0;
int cmd_pattern_count = 0;
int errptr;
BOOL only_one_at_top;
char *patterns[MAX_PATTERN_COUNT];
const char *locale_from = "--locale";
const char *error;
(void)pcre_config(PCRE_CONFIG_NEWLINE, &i);
switch(i)
{
default: newline = (char *)"lf"; break;
case '\r': newline = (char *)"cr"; break;
case ('\r' << 8) | '\n': newline = (char *)"crlf"; break;
case -1: newline = (char *)"any"; break;
}
for (i = 1; i < argc; i++)
{
option_item *op = NULL;
char *option_data = (char *)"";
BOOL longop;
BOOL longopwasequals = FALSE;
if (argv[i][0] != '-') break;
if (argv[i][1] == 0)
{
if (pattern_filename != NULL || pattern_count > 0) break;
else exit(usage(2));
}
if (argv[i][1] == '-')
{
char *arg = argv[i] + 2;
char *argequals = strchr(arg, '=');
if (*arg == 0)
{
i++;
break;
}
longop = TRUE;
for (op = optionlist; op->one_char != 0; op++)
{
char *opbra = strchr(op->long_name, '(');
char *equals = strchr(op->long_name, '=');
if (opbra == NULL)
{
if (equals == NULL)
{
if (strcmp(arg, op->long_name) == 0) break;
}
else
{
int oplen = equals - op->long_name;
int arglen = (argequals == NULL)? strlen(arg) : argequals - arg;
if (oplen == arglen && strncmp(arg, op->long_name, oplen) == 0)
{
option_data = arg + arglen;
if (*option_data == '=')
{
option_data++;
longopwasequals = TRUE;
}
break;
}
}
}
else
{
char buff1[24];
char buff2[24];
int baselen = opbra - op->long_name;
sprintf(buff1, "%.*s", baselen, op->long_name);
sprintf(buff2, "%s%.*s", buff1, strlen(op->long_name) - baselen - 2,
opbra + 1);
if (strcmp(arg, buff1) == 0 || strcmp(arg, buff2) == 0)
break;
}
}
if (op->one_char == 0)
{
fprintf(stderr, "pcregrep: Unknown option %s\n", argv[i]);
exit(usage(2));
}
}
#ifdef JFRIEDL_DEBUG
else if (strcmp(argv[i], "-pre") == 0) {
jfriedl_prefix = argv[++i];
continue;
} else if (strcmp(argv[i], "-post") == 0) {
jfriedl_postfix = argv[++i];
continue;
} else if (strcmp(argv[i], "-XT") == 0) {
sscanf(argv[++i], "%d", &jfriedl_XT);
continue;
} else if (strcmp(argv[i], "-XR") == 0) {
sscanf(argv[++i], "%d", &jfriedl_XR);
continue;
}
#endif
else
{
char *s = argv[i] + 1;
longop = FALSE;
while (*s != 0)
{
for (op = optionlist; op->one_char != 0; op++)
{ if (*s == op->one_char) break; }
if (op->one_char == 0)
{
fprintf(stderr, "pcregrep: Unknown option letter '%c' in \"%s\"\n",
*s, argv[i]);
exit(usage(2));
}
if (op->type != OP_NODATA || s[1] == 0)
{
option_data = s+1;
break;
}
pcre_options = handle_option(*s++, pcre_options);
}
}
if (op->type == OP_NODATA)
{
pcre_options = handle_option(op->one_char, pcre_options);
continue;
}
if (*option_data == 0 &&
(op->type == OP_OP_STRING || op->type == OP_OP_NUMBER))
{
switch (op->one_char)
{
case N_COLOUR:
colour_option = (char *)"auto";
break;
#ifdef JFRIEDL_DEBUG
case 'S':
S_arg = 0;
break;
#endif
}
continue;
}
if (*option_data == 0)
{
if (i >= argc - 1 || longopwasequals)
{
fprintf(stderr, "pcregrep: Data missing after %s\n", argv[i]);
exit(usage(2));
}
option_data = argv[++i];
}
if (op->type == OP_PATLIST)
{
if (cmd_pattern_count >= MAX_PATTERN_COUNT)
{
fprintf(stderr, "pcregrep: Too many command-line patterns (max %d)\n",
MAX_PATTERN_COUNT);
return 2;
}
patterns[cmd_pattern_count++] = option_data;
}
else if (op->type != OP_NUMBER && op->type != OP_OP_NUMBER)
{
*((char **)op->dataptr) = option_data;
}
else
{
char *endptr;
int n = strtoul(option_data, &endptr, 10);
if (*endptr != 0)
{
if (longop)
{
char *equals = strchr(op->long_name, '=');
int nlen = (equals == NULL)? (int)strlen(op->long_name) :
equals - op->long_name;
fprintf(stderr, "pcregrep: Malformed number \"%s\" after --%.*s\n",
option_data, nlen, op->long_name);
}
else
fprintf(stderr, "pcregrep: Malformed number \"%s\" after -%c\n",
option_data, op->one_char);
exit(usage(2));
}
*((int *)op->dataptr) = n;
}
}
if (both_context > 0)
{
if (after_context == 0) after_context = both_context;
if (before_context == 0) before_context = both_context;
}
if (locale == NULL)
{
locale = getenv("LC_ALL");
locale_from = "LCC_ALL";
}
if (locale == NULL)
{
locale = getenv("LC_CTYPE");
locale_from = "LC_CTYPE";
}
if (locale != NULL)
{
if (setlocale(LC_CTYPE, locale) == NULL)
{
fprintf(stderr, "pcregrep: Failed to set locale %s (obtained from %s)\n",
locale, locale_from);
return 2;
}
pcretables = pcre_maketables();
}
if (colour_option != NULL && strcmp(colour_option, "never") != 0)
{
if (strcmp(colour_option, "always") == 0) do_colour = TRUE;
else if (strcmp(colour_option, "auto") == 0) do_colour = is_stdout_tty();
else
{
fprintf(stderr, "pcregrep: Unknown colour setting \"%s\"\n",
colour_option);
return 2;
}
if (do_colour)
{
char *cs = getenv("PCREGREP_COLOUR");
if (cs == NULL) cs = getenv("PCREGREP_COLOR");
if (cs != NULL) colour_string = cs;
}
}
if (strcmp(newline, "cr") == 0 || strcmp(newline, "CR") == 0)
{
pcre_options |= PCRE_NEWLINE_CR;
endlinetype = EL_CR;
}
else if (strcmp(newline, "lf") == 0 || strcmp(newline, "LF") == 0)
{
pcre_options |= PCRE_NEWLINE_LF;
endlinetype = EL_LF;
}
else if (strcmp(newline, "crlf") == 0 || strcmp(newline, "CRLF") == 0)
{
pcre_options |= PCRE_NEWLINE_CRLF;
endlinetype = EL_CRLF;
}
else if (strcmp(newline, "any") == 0 || strcmp(newline, "ANY") == 0)
{
pcre_options |= PCRE_NEWLINE_ANY;
endlinetype = EL_ANY;
}
else
{
fprintf(stderr, "pcregrep: Invalid newline specifier \"%s\"\n", newline);
return 2;
}
if (dee_option != NULL)
{
if (strcmp(dee_option, "read") == 0) dee_action = dee_READ;
else if (strcmp(dee_option, "recurse") == 0) dee_action = dee_RECURSE;
else if (strcmp(dee_option, "skip") == 0) dee_action = dee_SKIP;
else
{
fprintf(stderr, "pcregrep: Invalid value \"%s\" for -d\n", dee_option);
return 2;
}
}
if (DEE_option != NULL)
{
if (strcmp(DEE_option, "read") == 0) DEE_action = DEE_READ;
else if (strcmp(DEE_option, "skip") == 0) DEE_action = DEE_SKIP;
else
{
fprintf(stderr, "pcregrep: Invalid value \"%s\" for -D\n", DEE_option);
return 2;
}
}
#ifdef JFRIEDL_DEBUG
if (S_arg > 9)
{
fprintf(stderr, "pcregrep: bad value for -S option\n");
return 2;
}
if (jfriedl_XT != 0 || jfriedl_XR != 0)
{
if (jfriedl_XT == 0) jfriedl_XT = 1;
if (jfriedl_XR == 0) jfriedl_XR = 1;
}
#endif
pattern_list = (pcre **)malloc(MAX_PATTERN_COUNT * sizeof(pcre *));
hints_list = (pcre_extra **)malloc(MAX_PATTERN_COUNT * sizeof(pcre_extra *));
if (pattern_list == NULL || hints_list == NULL)
{
fprintf(stderr, "pcregrep: malloc failed\n");
return 2;
}
if (cmd_pattern_count == 0 && pattern_filename == NULL)
{
if (i >= argc) return usage(2);
patterns[cmd_pattern_count++] = argv[i++];
}
for (j = 0; j < cmd_pattern_count; j++)
{
if (!compile_pattern(patterns[j], pcre_options, NULL,
(j == 0 && cmd_pattern_count == 1)? 0 : j + 1))
return 2;
}
if (pattern_filename != NULL)
{
int linenumber = 0;
FILE *f;
char *filename;
char buffer[MBUFTHIRD];
if (strcmp(pattern_filename, "-") == 0)
{
f = stdin;
filename = stdin_name;
}
else
{
f = fopen(pattern_filename, "r");
if (f == NULL)
{
fprintf(stderr, "pcregrep: Failed to open %s: %s\n", pattern_filename,
strerror(errno));
return 2;
}
filename = pattern_filename;
}
while (fgets(buffer, MBUFTHIRD, f) != NULL)
{
char *s = buffer + (int)strlen(buffer);
while (s > buffer && isspace((unsigned char)(s[-1]))) s--;
*s = 0;
linenumber++;
if (buffer[0] == 0) continue;
if (!compile_pattern(buffer, pcre_options, filename, linenumber))
return 2;
}
if (f != stdin) fclose(f);
}
for (j = 0; j < pattern_count; j++)
{
hints_list[j] = pcre_study(pattern_list[j], 0, &error);
if (error != NULL)
{
char s[16];
if (pattern_count == 1) s[0] = 0; else sprintf(s, " number %d", j);
fprintf(stderr, "pcregrep: Error while studying regex%s: %s\n", s, error);
return 2;
}
}
if (exclude_pattern != NULL)
{
exclude_compiled = pcre_compile(exclude_pattern, 0, &error, &errptr,
pcretables);
if (exclude_compiled == NULL)
{
fprintf(stderr, "pcregrep: Error in 'exclude' regex at offset %d: %s\n",
errptr, error);
return 2;
}
}
if (include_pattern != NULL)
{
include_compiled = pcre_compile(include_pattern, 0, &error, &errptr,
pcretables);
if (include_compiled == NULL)
{
fprintf(stderr, "pcregrep: Error in 'include' regex at offset %d: %s\n",
errptr, error);
return 2;
}
}
if (i >= argc)
return pcregrep(stdin, (filenames > FN_DEFAULT)? stdin_name : NULL);
only_one_at_top = i == argc - 1;
for (; i < argc; i++)
{
int frc = grep_or_recurse(argv[i], dee_action == dee_RECURSE,
only_one_at_top);
if (frc > 1) rc = frc;
else if (frc == 0 && rc == 1) rc = 0;
}
return rc;
}