Annotation of src/usr.bin/sed/process.c, Revision 1.15
1.15 ! deraadt 1: /* $OpenBSD: process.c,v 1.14 2008/10/07 21:51:37 millert Exp $ */
1.2 deraadt 2:
1.1 deraadt 3: /*-
4: * Copyright (c) 1992 Diomidis Spinellis.
5: * Copyright (c) 1992, 1993
6: * The Regents of the University of California. All rights reserved.
7: *
8: * This code is derived from software contributed to Berkeley by
9: * Diomidis Spinellis of Imperial College, University of London.
10: *
11: * Redistribution and use in source and binary forms, with or without
12: * modification, are permitted provided that the following conditions
13: * are met:
14: * 1. Redistributions of source code must retain the above copyright
15: * notice, this list of conditions and the following disclaimer.
16: * 2. Redistributions in binary form must reproduce the above copyright
17: * notice, this list of conditions and the following disclaimer in the
18: * documentation and/or other materials provided with the distribution.
1.10 millert 19: * 3. Neither the name of the University nor the names of its contributors
1.1 deraadt 20: * may be used to endorse or promote products derived from this software
21: * without specific prior written permission.
22: *
23: * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33: * SUCH DAMAGE.
34: */
35:
36: #include <sys/types.h>
37: #include <sys/stat.h>
38: #include <sys/ioctl.h>
39: #include <sys/uio.h>
40:
41: #include <ctype.h>
42: #include <errno.h>
43: #include <fcntl.h>
44: #include <limits.h>
45: #include <regex.h>
46: #include <stdio.h>
47: #include <stdlib.h>
48: #include <string.h>
49: #include <unistd.h>
50:
51: #include "defs.h"
52: #include "extern.h"
53:
54: static SPACE HS, PS, SS;
55: #define pd PS.deleted
56: #define ps PS.space
57: #define psl PS.len
58: #define hs HS.space
59: #define hsl HS.len
60:
1.7 millert 61: static inline int applies(struct s_command *);
62: static void flush_appends(void);
63: static void lputs(char *);
64: static inline int regexec_e(regex_t *, const char *, int, int, size_t);
65: static void regsub(SPACE *, char *, char *);
66: static int substitute(struct s_command *);
1.1 deraadt 67:
68: struct s_appends *appends; /* Array of pointers to strings to append. */
69: static int appendx; /* Index into appends array. */
70: int appendnum; /* Size of appends array. */
71:
72: static int lastaddr; /* Set by applies if last address of a range. */
73: static int sdone; /* If any substitutes since last line input. */
74: /* Iov structure for 'w' commands. */
75: static regex_t *defpreg;
76: size_t maxnsub;
77: regmatch_t *match;
78:
1.13 tedu 79: #define OUT(s) do { fwrite(s, sizeof(u_char), psl, stdout); } while (0)
1.1 deraadt 80:
81: void
1.11 deraadt 82: process(void)
1.1 deraadt 83: {
84: struct s_command *cp;
85: SPACE tspace;
86: size_t len, oldpsl;
87: char *p;
88:
89: for (linenum = 0; mf_fgets(&PS, REPLACE);) {
90: pd = 0;
91: top:
92: cp = prog;
93: redirect:
94: while (cp != NULL) {
95: if (!applies(cp)) {
96: cp = cp->next;
97: continue;
98: }
99: switch (cp->code) {
100: case '{':
101: cp = cp->u.c;
102: goto redirect;
103: case 'a':
1.12 tedu 104: if (appendx >= appendnum) {
1.1 deraadt 105: appends = xrealloc(appends,
106: sizeof(struct s_appends) *
1.12 tedu 107: (appendnum * 2));
108: appendnum *= 2;
109: }
1.1 deraadt 110: appends[appendx].type = AP_STRING;
111: appends[appendx].s = cp->t;
112: appends[appendx].len = strlen(cp->t);
113: appendx++;
114: break;
115: case 'b':
116: cp = cp->u.c;
117: goto redirect;
118: case 'c':
119: pd = 1;
120: psl = 0;
121: if (cp->a2 == NULL || lastaddr)
122: (void)printf("%s", cp->t);
123: break;
124: case 'd':
125: pd = 1;
126: goto new;
127: case 'D':
128: if (pd)
129: goto new;
1.8 millert 130: if (psl == 0 ||
131: (p = memchr(ps, '\n', psl - 1)) == NULL) {
1.1 deraadt 132: pd = 1;
133: goto new;
134: } else {
135: psl -= (p + 1) - ps;
136: memmove(ps, p + 1, psl);
137: goto top;
138: }
139: case 'g':
140: cspace(&PS, hs, hsl, REPLACE);
141: break;
142: case 'G':
1.5 deraadt 143: if (hs == NULL)
144: cspace(&HS, "\n", 1, REPLACE);
1.1 deraadt 145: cspace(&PS, hs, hsl, 0);
146: break;
147: case 'h':
148: cspace(&HS, ps, psl, REPLACE);
149: break;
150: case 'H':
151: cspace(&HS, ps, psl, 0);
152: break;
153: case 'i':
154: (void)printf("%s", cp->t);
155: break;
156: case 'l':
157: lputs(ps);
158: break;
159: case 'n':
160: if (!nflag && !pd)
1.13 tedu 161: OUT(ps);
1.1 deraadt 162: flush_appends();
163: if (!mf_fgets(&PS, REPLACE))
164: exit(0);
165: pd = 0;
166: break;
167: case 'N':
168: flush_appends();
169: if (!mf_fgets(&PS, 0)) {
170: if (!nflag && !pd)
1.13 tedu 171: OUT(ps);
1.1 deraadt 172: exit(0);
173: }
174: break;
175: case 'p':
176: if (pd)
177: break;
1.13 tedu 178: OUT(ps);
1.1 deraadt 179: break;
180: case 'P':
181: if (pd)
182: break;
1.8 millert 183: if (psl != 0 &&
184: (p = memchr(ps, '\n', psl - 1)) != NULL) {
1.1 deraadt 185: oldpsl = psl;
186: psl = (p + 1) - ps;
187: }
1.13 tedu 188: OUT(ps);
1.1 deraadt 189: if (p != NULL)
190: psl = oldpsl;
191: break;
192: case 'q':
193: if (!nflag && !pd)
1.13 tedu 194: OUT(ps);
1.1 deraadt 195: flush_appends();
196: exit(0);
197: case 'r':
198: if (appendx >= appendnum)
199: appends = xrealloc(appends,
200: sizeof(struct s_appends) *
201: (appendnum *= 2));
202: appends[appendx].type = AP_FILE;
203: appends[appendx].s = cp->t;
204: appends[appendx].len = strlen(cp->t);
205: appendx++;
206: break;
207: case 's':
208: sdone |= substitute(cp);
209: break;
210: case 't':
211: if (sdone) {
212: sdone = 0;
213: cp = cp->u.c;
214: goto redirect;
215: }
216: break;
217: case 'w':
218: if (pd)
219: break;
220: if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
221: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
222: DEFFILEMODE)) == -1)
1.9 jsyn 223: err(FATAL, "%s: %s",
1.1 deraadt 224: cp->t, strerror(errno));
225: if (write(cp->u.fd, ps, psl) != psl)
1.9 jsyn 226: err(FATAL, "%s: %s",
1.1 deraadt 227: cp->t, strerror(errno));
228: break;
229: case 'x':
230: if (hs == NULL)
231: cspace(&HS, "\n", 1, REPLACE);
232: tspace = PS;
233: PS = HS;
234: HS = tspace;
235: break;
236: case 'y':
1.8 millert 237: if (pd || psl == 0)
1.1 deraadt 238: break;
239: for (p = ps, len = psl; --len; ++p)
1.4 deraadt 240: *p = cp->u.y[(unsigned char)*p];
1.1 deraadt 241: break;
242: case ':':
243: case '}':
244: break;
245: case '=':
246: (void)printf("%lu\n", linenum);
247: }
248: cp = cp->next;
249: } /* for all cp */
250:
251: new: if (!nflag && !pd)
1.13 tedu 252: OUT(ps);
1.1 deraadt 253: flush_appends();
254: } /* for all lines */
255: }
256:
257: /*
258: * TRUE if the address passed matches the current program state
259: * (lastline, linenumber, ps).
260: */
261: #define MATCH(a) \
262: (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
263: (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
264:
265: /*
266: * Return TRUE if the command applies to the current line. Sets the inrange
267: * flag to process ranges. Interprets the non-select (``!'') flag.
268: */
269: static inline int
1.11 deraadt 270: applies(struct s_command *cp)
1.1 deraadt 271: {
272: int r;
273:
274: lastaddr = 0;
275: if (cp->a1 == NULL && cp->a2 == NULL)
276: r = 1;
277: else if (cp->a2)
278: if (cp->inrange) {
279: if (MATCH(cp->a2)) {
280: cp->inrange = 0;
281: lastaddr = 1;
282: }
283: r = 1;
284: } else if (MATCH(cp->a1)) {
285: /*
286: * If the second address is a number less than or
287: * equal to the line number first selected, only
288: * one line shall be selected.
289: * -- POSIX 1003.2
290: */
291: if (cp->a2->type == AT_LINE &&
292: linenum >= cp->a2->u.l)
293: lastaddr = 1;
294: else
295: cp->inrange = 1;
296: r = 1;
297: } else
298: r = 0;
299: else
300: r = MATCH(cp->a1);
1.13 tedu 301: return (cp->nonsel ? !r : r);
1.1 deraadt 302: }
303:
304: /*
305: * substitute --
306: * Do substitutions in the pattern space. Currently, we build a
307: * copy of the new pattern space in the substitute space structure
308: * and then swap them.
309: */
310: static int
1.11 deraadt 311: substitute(struct s_command *cp)
1.1 deraadt 312: {
313: SPACE tspace;
314: regex_t *re;
315: size_t re_off, slen;
316: int n, lastempty;
317: char *s;
318:
319: s = ps;
320: re = cp->u.s->re;
321: if (re == NULL) {
322: if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
323: linenum = cp->u.s->linenum;
324: err(COMPILE, "\\%d not defined in the RE",
325: cp->u.s->maxbref);
326: }
327: }
328: if (!regexec_e(re, s, 0, 0, psl))
329: return (0);
330:
331: SS.len = 0; /* Clean substitute space. */
332: slen = psl;
333: n = cp->u.s->n;
334: lastempty = 1;
335:
336: switch (n) {
337: case 0: /* Global */
338: do {
339: if (lastempty || match[0].rm_so != match[0].rm_eo) {
340: /* Locate start of replaced string. */
341: re_off = match[0].rm_so;
342: /* Copy leading retained string. */
343: cspace(&SS, s, re_off, APPEND);
344: /* Add in regular expression. */
345: regsub(&SS, s, cp->u.s->new);
346: }
347:
348: /* Move past this match. */
349: if (match[0].rm_so != match[0].rm_eo) {
350: s += match[0].rm_eo;
351: slen -= match[0].rm_eo;
352: lastempty = 0;
353: } else {
354: if (match[0].rm_so == 0)
355: cspace(&SS, s, match[0].rm_so + 1,
356: APPEND);
357: else
358: cspace(&SS, s + match[0].rm_so, 1,
359: APPEND);
360: s += match[0].rm_so + 1;
361: slen -= match[0].rm_so + 1;
362: lastempty = 1;
363: }
364: } while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
365: /* Copy trailing retained string. */
366: if (slen > 0)
367: cspace(&SS, s, slen, APPEND);
368: break;
369: default: /* Nth occurrence */
370: while (--n) {
371: s += match[0].rm_eo;
372: slen -= match[0].rm_eo;
373: if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
374: return (0);
375: }
376: /* FALLTHROUGH */
377: case 1: /* 1st occurrence */
378: /* Locate start of replaced string. */
379: re_off = match[0].rm_so + (s - ps);
380: /* Copy leading retained string. */
381: cspace(&SS, ps, re_off, APPEND);
382: /* Add in regular expression. */
383: regsub(&SS, s, cp->u.s->new);
384: /* Copy trailing retained string. */
385: s += match[0].rm_eo;
386: slen -= match[0].rm_eo;
387: cspace(&SS, s, slen, APPEND);
388: break;
389: }
390:
391: /*
392: * Swap the substitute space and the pattern space, and make sure
393: * that any leftover pointers into stdio memory get lost.
394: */
395: tspace = PS;
396: PS = SS;
397: SS = tspace;
398: SS.space = SS.back;
399:
400: /* Handle the 'p' flag. */
401: if (cp->u.s->p)
1.13 tedu 402: OUT(ps);
1.1 deraadt 403:
404: /* Handle the 'w' flag. */
405: if (cp->u.s->wfile && !pd) {
406: if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
407: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
1.9 jsyn 408: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 409: if (write(cp->u.s->wfd, ps, psl) != psl)
1.9 jsyn 410: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 411: }
412: return (1);
413: }
414:
415: /*
416: * Flush append requests. Always called before reading a line,
417: * therefore it also resets the substitution done (sdone) flag.
418: */
419: static void
1.11 deraadt 420: flush_appends(void)
1.1 deraadt 421: {
422: FILE *f;
423: int count, i;
424: char buf[8 * 1024];
425:
426: for (i = 0; i < appendx; i++)
427: switch (appends[i].type) {
428: case AP_STRING:
429: fwrite(appends[i].s, sizeof(char), appends[i].len,
430: stdout);
431: break;
432: case AP_FILE:
433: /*
434: * Read files probably shouldn't be cached. Since
435: * it's not an error to read a non-existent file,
436: * it's possible that another program is interacting
437: * with the sed script through the file system. It
438: * would be truly bizarre, but possible. It's probably
439: * not that big a performance win, anyhow.
440: */
441: if ((f = fopen(appends[i].s, "r")) == NULL)
442: break;
1.3 deraadt 443: while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
1.1 deraadt 444: (void)fwrite(buf, sizeof(char), count, stdout);
445: (void)fclose(f);
446: break;
447: }
448: if (ferror(stdout))
449: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
450: appendx = sdone = 0;
451: }
452:
453: static void
1.11 deraadt 454: lputs(char *s)
1.1 deraadt 455: {
1.6 mpech 456: int count;
457: char *escapes, *p;
1.1 deraadt 458: struct winsize win;
459: static int termwidth = -1;
460:
1.13 tedu 461: if (termwidth == -1) {
1.3 deraadt 462: if ((p = getenv("COLUMNS")))
1.1 deraadt 463: termwidth = atoi(p);
464: else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
465: win.ws_col > 0)
466: termwidth = win.ws_col;
467: else
468: termwidth = 60;
1.13 tedu 469: }
1.1 deraadt 470:
471: for (count = 0; *s; ++s) {
472: if (count >= termwidth) {
473: (void)printf("\\\n");
474: count = 0;
475: }
476: if (isascii(*s) && isprint(*s) && *s != '\\') {
477: (void)putchar(*s);
478: count++;
1.14 millert 479: } else if (*s != '\n') {
480: escapes = "\\\a\b\f\r\t\v";
1.1 deraadt 481: (void)putchar('\\');
1.3 deraadt 482: if ((p = strchr(escapes, *s))) {
1.14 millert 483: (void)putchar("\\abfrtv"[p - escapes]);
1.1 deraadt 484: count += 2;
485: } else {
486: (void)printf("%03o", *(u_char *)s);
487: count += 4;
488: }
489: }
490: }
491: (void)putchar('$');
492: (void)putchar('\n');
493: if (ferror(stdout))
494: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
495: }
496:
497: static inline int
1.11 deraadt 498: regexec_e(regex_t *preg, const char *string, int eflags,
499: int nomatch, size_t slen)
1.1 deraadt 500: {
501: int eval;
502:
503: if (preg == NULL) {
504: if (defpreg == NULL)
505: err(FATAL, "first RE may not be empty");
506: } else
507: defpreg = preg;
508:
509: /* Set anchors, discounting trailing newline (if any). */
510: if (slen > 0 && string[slen - 1] == '\n')
511: slen--;
512: match[0].rm_so = 0;
513: match[0].rm_eo = slen;
514:
515: eval = regexec(defpreg, string,
516: nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
1.13 tedu 517: switch (eval) {
1.1 deraadt 518: case 0:
519: return (1);
520: case REG_NOMATCH:
521: return (0);
522: }
523: err(FATAL, "RE error: %s", strregerror(eval, defpreg));
524: /* NOTREACHED */
525: }
526:
527: /*
528: * regsub - perform substitutions after a regexp match
529: * Based on a routine by Henry Spencer
530: */
531: static void
1.11 deraadt 532: regsub(SPACE *sp, char *string, char *src)
1.1 deraadt 533: {
1.6 mpech 534: int len, no;
535: char c, *dst;
1.1 deraadt 536:
537: #define NEEDSP(reqlen) \
1.12 tedu 538: if (sp->len + (reqlen) + 1 >= sp->blen) { \
539: size_t newlen = sp->blen + (reqlen) + 1024; \
540: sp->space = sp->back = xrealloc(sp->back, newlen); \
541: sp->blen = newlen; \
1.1 deraadt 542: dst = sp->space + sp->len; \
543: }
544:
545: dst = sp->space + sp->len;
546: while ((c = *src++) != '\0') {
547: if (c == '&')
548: no = 0;
549: else if (c == '\\' && isdigit(*src))
550: no = *src++ - '0';
551: else
552: no = -1;
553: if (no < 0) { /* Ordinary character. */
554: if (c == '\\' && (*src == '\\' || *src == '&'))
555: c = *src++;
556: NEEDSP(1);
557: *dst++ = c;
558: ++sp->len;
559: } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
560: len = match[no].rm_eo - match[no].rm_so;
561: NEEDSP(len);
562: memmove(dst, string + match[no].rm_so, len);
563: dst += len;
564: sp->len += len;
565: }
566: }
567: NEEDSP(1);
568: *dst = '\0';
569: }
570:
571: /*
572: * aspace --
573: * Append the source space to the destination space, allocating new
574: * space as necessary.
575: */
576: void
1.11 deraadt 577: cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
1.1 deraadt 578: {
579: size_t tlen;
580:
581: /* Make sure SPACE has enough memory and ramp up quickly. */
582: tlen = sp->len + len + 1;
583: if (tlen > sp->blen) {
1.12 tedu 584: size_t newlen = tlen + 1024;
585: sp->space = sp->back = xrealloc(sp->back, newlen);
586: sp->blen = newlen;
1.1 deraadt 587: }
588:
589: if (spflag == REPLACE)
590: sp->len = 0;
591:
592: memmove(sp->space + sp->len, p, len);
593:
594: sp->space[sp->len += len] = '\0';
595: }
596:
597: /*
598: * Close all cached opened files and report any errors
599: */
600: void
1.11 deraadt 601: cfclose(struct s_command *cp, struct s_command *end)
1.1 deraadt 602: {
603:
604: for (; cp != end; cp = cp->next)
1.13 tedu 605: switch (cp->code) {
1.1 deraadt 606: case 's':
607: if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
608: err(FATAL,
609: "%s: %s", cp->u.s->wfile, strerror(errno));
610: cp->u.s->wfd = -1;
611: break;
612: case 'w':
613: if (cp->u.fd != -1 && close(cp->u.fd))
614: err(FATAL, "%s: %s", cp->t, strerror(errno));
615: cp->u.fd = -1;
616: break;
617: case '{':
618: cfclose(cp->u.c, cp->next);
619: break;
620: }
621: }