#include <sys/cdefs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fnmatch.h>
#include <fts.h>
#include <libgen.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>
#include "grep.h"
static bool first_match = true;
struct mprintc {
long long tail;
int last_outed;
bool doctx;
bool printmatch;
bool same_file;
};
static void procmatch_match(struct mprintc *mc, struct parsec *pc);
static void procmatch_nomatch(struct mprintc *mc, struct parsec *pc);
static bool procmatches(struct mprintc *mc, struct parsec *pc, bool matched);
#ifdef WITH_INTERNAL_NOSPEC
static int litexec(const struct pat *pat, const char *string,
size_t nmatch, regmatch_t pmatch[]);
#endif
static bool procline(struct parsec *pc);
static bool printline(struct parsec *pc, int sep, size_t *last_out);
static void printline_metadata(struct str *line, int sep);
bool
file_matching(const char *fname)
{
char *fname_base, *fname_buf;
bool ret;
ret = finclude ? false : true;
fname_buf = strdup(fname);
if (fname_buf == NULL)
err(2, "strdup");
fname_base = basename(fname_buf);
for (unsigned int i = 0; i < fpatterns; ++i) {
if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
fnmatch(fpattern[i].pat, fname_base, 0) == 0)
ret = (fpattern[i].mode != EXCL_PAT);
}
free(fname_buf);
return (ret);
}
static inline bool
dir_matching(const char *dname)
{
bool ret;
ret = dinclude ? false : true;
for (unsigned int i = 0; i < dpatterns; ++i) {
if (dname != NULL && fnmatch(dpattern[i].pat, dname, 0) == 0)
ret = (dpattern[i].mode != EXCL_PAT);
}
return (ret);
}
bool
grep_tree(char **argv)
{
FTS *fts;
FTSENT *p;
int fts_flags;
bool matched, ok;
const char *wd[] = { ".", NULL };
matched = false;
switch(linkbehave) {
case LINK_EXPLICIT:
fts_flags = FTS_COMFOLLOW | FTS_PHYSICAL;
break;
case LINK_SKIP:
fts_flags = FTS_PHYSICAL;
break;
default:
fts_flags = FTS_LOGICAL | FTS_NOSTAT;
}
fts_flags |= FTS_NOCHDIR;
fts = fts_open((argv[0] == NULL) ?
__DECONST(char * const *, wd) : argv, fts_flags, NULL);
if (fts == NULL)
err(2, "fts_open");
while (errno = 0, (p = fts_read(fts)) != NULL) {
switch (p->fts_info) {
case FTS_DNR:
case FTS_ERR:
case FTS_NS:
file_err = true;
if(!sflag)
warnc(p->fts_errno, "%s", p->fts_path);
break;
case FTS_D:
if (dexclude || dinclude)
if (!dir_matching(p->fts_name) ||
!dir_matching(p->fts_path))
fts_set(fts, p, FTS_SKIP);
break;
case FTS_DC:
warnx("warning: %s: recursive directory loop",
p->fts_path);
break;
case FTS_DP:
break;
case FTS_SL:
break;
default:
ok = true;
if (fexclude || finclude)
ok &= file_matching(p->fts_path);
if (ok && procfile(p->fts_path))
matched = true;
break;
}
}
if (errno != 0)
err(2, "fts_read");
fts_close(fts);
return (matched);
}
static void
procmatch_match(struct mprintc *mc, struct parsec *pc)
{
if (mc->doctx) {
if (!first_match && (!mc->same_file || mc->last_outed > 0))
printf("--\n");
if (Bflag > 0)
printqueue();
mc->tail = Aflag;
}
if (mc->printmatch) {
size_t last_out;
bool terminated;
last_out = 0;
terminated = printline(pc, ':', &last_out);
while (pc->matchidx >= MAX_MATCHES) {
pc->matchidx = 0;
if (procline(pc) == !vflag)
terminated = printline(pc, ':', &last_out);
else
break;
}
if (!terminated)
printline(pc, ':', &last_out);
first_match = false;
mc->same_file = true;
mc->last_outed = 0;
}
}
static void
procmatch_nomatch(struct mprintc *mc, struct parsec *pc)
{
if (mc->tail > 0) {
grep_printline(&pc->ln, '-');
mc->tail--;
if (Bflag > 0)
clearqueue();
} else if (Bflag == 0 || (Bflag > 0 && enqueue(&pc->ln)))
++mc->last_outed;
}
static bool
procmatches(struct mprintc *mc, struct parsec *pc, bool matched)
{
if (mflag && mcount <= 0) {
grep_printline(&pc->ln, '-');
mc->tail--;
return (mc->tail != 0);
}
if (matched) {
procmatch_match(mc, pc);
if (mflag) {
mcount -= 1;
if (mcount <= 0)
return (mc->tail != 0);
}
} else if (mc->doctx)
procmatch_nomatch(mc, pc);
return (true);
}
bool
procfile(const char *fn)
{
struct parsec pc;
struct mprintc mc;
struct file *f;
struct stat sb;
mode_t s;
int lines;
bool line_matched;
if (strcmp(fn, "-") == 0) {
fn = label != NULL ? label : errstr[1];
f = grep_open(NULL);
} else {
if (stat(fn, &sb) == 0) {
s = sb.st_mode & S_IFMT;
if (dirbehave == DIR_SKIP && s == S_IFDIR)
return (false);
if (devbehave == DEV_SKIP && (s == S_IFIFO ||
s == S_IFCHR || s == S_IFBLK || s == S_IFSOCK))
return (false);
}
f = grep_open(fn);
}
if (f == NULL) {
file_err = true;
if (!sflag)
warn("%s", fn);
return (false);
}
pc.ln.file = grep_strdup(fn);
pc.ln.line_no = 0;
pc.ln.len = 0;
pc.ln.boff = 0;
pc.ln.off = -1;
pc.binary = f->binary;
pc.cntlines = false;
memset(&mc, 0, sizeof(mc));
mc.printmatch = true;
if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
lflag || Lflag)
mc.printmatch = false;
if (mc.printmatch && (Aflag != 0 || Bflag != 0))
mc.doctx = true;
if (mc.printmatch && (Aflag != 0 || Bflag != 0 || mflag || nflag))
pc.cntlines = true;
mcount = mlimit;
for (lines = 0; lines == 0 || !(lflag || qflag); ) {
pc.printed = 0;
pc.matchidx = 0;
pc.lnstart = 0;
pc.ln.boff = 0;
pc.ln.off += pc.ln.len + 1;
if ((pc.ln.dat = grep_fgetln(f, &pc)) == NULL ||
pc.ln.len == 0)
break;
if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
--pc.ln.len;
pc.ln.line_no++;
if (pc.binary && binbehave == BINFILE_SKIP) {
grep_close(f);
free(pc.ln.file);
free(f);
return (0);
}
if (mflag && mcount <= 0) {
if (!procmatches(&mc, &pc, false))
break;
continue;
}
line_matched = procline(&pc) == !vflag;
if (line_matched)
++lines;
if (!procmatches(&mc, &pc, line_matched))
break;
}
if (Bflag > 0)
clearqueue();
grep_close(f);
if (cflag && !qflag) {
if (!hflag)
printf("%s:", pc.ln.file);
printf("%u\n", lines);
}
if (lflag && !qflag && lines != 0)
printf("%s%c", fn, nullflag ? 0 : '\n');
if (Lflag && !qflag && lines == 0)
printf("%s%c", fn, nullflag ? 0 : '\n');
if (lines != 0 && !cflag && !lflag && !Lflag &&
binbehave == BINFILE_BIN && f->binary && !qflag)
printf(errstr[7], fn);
free(pc.ln.file);
free(f);
return (lines != 0);
}
#ifdef WITH_INTERNAL_NOSPEC
static int
litexec(const struct pat *pat, const char *string, size_t nmatch,
regmatch_t pmatch[])
{
char *(*strstr_fn)(const char *, const char *);
char *sub, *subject;
const char *search;
size_t idx, n, ofs, stringlen;
if (cflags & REG_ICASE)
strstr_fn = strcasestr;
else
strstr_fn = strstr;
idx = 0;
ofs = pmatch[0].rm_so;
stringlen = pmatch[0].rm_eo;
if (ofs >= stringlen)
return (REG_NOMATCH);
subject = strndup(string, stringlen);
if (subject == NULL)
return (REG_ESPACE);
for (n = 0; ofs < stringlen;) {
search = (subject + ofs);
if ((unsigned long)pat->len > strlen(search))
break;
sub = strstr_fn(search, pat->pat);
if (sub == NULL)
break;
++n;
if (nmatch > 0) {
pmatch[idx].rm_so = ofs + (sub - search);
pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
if (++idx == nmatch)
break;
ofs = pmatch[idx].rm_so + 1;
} else
break;
}
free(subject);
if (n > 0 && nmatch > 0)
for (n = idx; n < nmatch; ++n)
pmatch[n].rm_so = pmatch[n].rm_eo = -1;
return (n > 0 ? 0 : REG_NOMATCH);
}
#endif
#define iswword(x) (iswalnum((x)) || (x) == L'_')
static bool
procline(struct parsec *pc)
{
regmatch_t pmatch, lastmatch, chkmatch;
wchar_t wbegin, wend;
size_t st, nst;
unsigned int i;
int r = 0, leflags = eflags;
size_t startm = 0, matchidx;
unsigned int retry;
bool lastmatched, matched;
matchidx = pc->matchidx;
if (matchall) {
if (xflag && pc->ln.len == 0) {
return (true);
} else if (!wflag && !xflag) {
return (true);
}
if (patterns == 0) {
return (!(wflag || xflag));
}
} else if (patterns == 0) {
return (false);
}
matched = false;
st = pc->lnstart;
nst = 0;
lastmatch.rm_so = lastmatch.rm_eo = 0;
while (st <= pc->ln.len) {
lastmatched = false;
startm = matchidx;
retry = 0;
if (st > 0 && pc->ln.dat[st - 1] != fileeol)
leflags |= REG_NOTBOL;
for (i = 0; i < patterns; i++) {
pmatch.rm_so = st;
pmatch.rm_eo = pc->ln.len;
#ifdef WITH_INTERNAL_NOSPEC
if (grepbehave == GREP_FIXED)
r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
else
#endif
r = regexec(&r_pattern[i], pc->ln.dat, 1, &pmatch,
leflags);
if (r != 0)
continue;
if (xflag && (pmatch.rm_so != 0 ||
(size_t)pmatch.rm_eo != pc->ln.len))
continue;
if (wflag) {
wbegin = wend = L' ';
if (pmatch.rm_so != 0 &&
sscanf(&pc->ln.dat[pmatch.rm_so - 1],
"%lc", &wbegin) != 1)
r = REG_NOMATCH;
else if ((size_t)pmatch.rm_eo !=
pc->ln.len &&
sscanf(&pc->ln.dat[pmatch.rm_eo],
"%lc", &wend) != 1)
r = REG_NOMATCH;
else if (iswword(wbegin) ||
iswword(wend))
r = REG_NOMATCH;
if (r == REG_NOMATCH &&
(retry == pc->lnstart ||
(unsigned int)pmatch.rm_so + 1 < retry))
retry = pmatch.rm_so + 1;
if (r == REG_NOMATCH)
continue;
}
lastmatched = true;
lastmatch = pmatch;
if (matchidx == 0)
matched = true;
if (matchidx > startm) {
chkmatch = pc->matches[matchidx - 1];
if (pmatch.rm_so < chkmatch.rm_so ||
(pmatch.rm_so == chkmatch.rm_so &&
(pmatch.rm_eo - pmatch.rm_so) >
(chkmatch.rm_eo - chkmatch.rm_so))) {
pc->matches[matchidx - 1] = pmatch;
nst = pmatch.rm_eo;
}
} else {
pc->matches[matchidx++] = pmatch;
nst = pmatch.rm_eo;
}
if ((color == NULL && !oflag) || qflag || lflag ||
matchidx >= MAX_MATCHES) {
pc->lnstart = nst;
lastmatched = false;
break;
}
}
if (!lastmatched && retry > pc->lnstart) {
st = retry;
continue;
}
if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
break;
if (!lastmatched || (cflags & REG_NOSUB))
nst = pc->ln.len;
if (!lastmatched)
break;
else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
nst++;
st = nst;
pc->lnstart = st;
}
pc->matchidx = matchidx;
return matched;
}
void *
grep_malloc(size_t size)
{
void *ptr;
if (size == 0)
return (NULL);
if ((ptr = malloc(size)) == NULL)
err(2, "malloc");
return (ptr);
}
void *
grep_calloc(size_t nmemb, size_t size)
{
void *ptr;
if (nmemb == 0 || size == 0)
return (NULL);
if ((ptr = calloc(nmemb, size)) == NULL)
err(2, "calloc");
return (ptr);
}
void *
grep_realloc(void *ptr, size_t size)
{
if ((ptr = realloc(ptr, size)) == NULL)
err(2, "realloc");
return (ptr);
}
char *
grep_strdup(const char *str)
{
char *ret;
if ((ret = strdup(str)) == NULL)
err(2, "strdup");
return (ret);
}
void grep_printline(struct str *line, int sep) {
printline_metadata(line, sep);
fwrite(line->dat, line->len, 1, stdout);
putchar(fileeol);
fflush(stdout);
}
static void
printline_metadata(struct str *line, int sep)
{
bool printsep;
printsep = false;
if (!hflag) {
if (!nullflag) {
fputs(line->file, stdout);
printsep = true;
} else {
printf("%s", line->file);
putchar(0);
}
}
if (nflag) {
if (printsep)
putchar(sep);
printf("%d", line->line_no);
printsep = true;
}
if (bflag) {
if (printsep)
putchar(sep);
printf("%lld", (long long)(line->off + line->boff));
printsep = true;
}
if (printsep)
putchar(sep);
}
static bool
printline(struct parsec *pc, int sep, size_t *last_out)
{
size_t a = *last_out;
size_t i, matchidx;
regmatch_t match;
bool terminated;
terminated = true;
if (oflag && matchall)
return (terminated);
matchidx = pc->matchidx;
if ((oflag || color) && (pc->printed > 0 || matchidx > 0)) {
if (!oflag && pc->printed == 0) {
printline_metadata(&pc->ln, sep);
}
for (i = 0; i < matchidx; i++) {
match = pc->matches[i];
if (match.rm_so == match.rm_eo)
continue;
if (oflag) {
pc->ln.boff = match.rm_so;
printline_metadata(&pc->ln, sep);
} else {
fwrite(pc->ln.dat + a, match.rm_so - a, 1,
stdout);
}
if (color)
fprintf(stdout, "\33[%sm\33[K", color);
fwrite(pc->ln.dat + match.rm_so,
match.rm_eo - match.rm_so, 1, stdout);
if (color)
fprintf(stdout, "\33[m\33[K");
a = match.rm_eo;
if (oflag)
putchar('\n');
}
*last_out = a;
if (!oflag && matchidx != MAX_MATCHES) {
if (pc->ln.len - a > 0) {
fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
stdout);
*last_out = pc->ln.len;
}
putchar('\n');
fflush(stdout);
} else if (!oflag) {
terminated = false;
} else {
fflush(stdout);
}
} else
grep_printline(&pc->ln, sep);
pc->printed++;
return (terminated);
}