Annotation of src/usr.bin/sed/process.c, Revision 1.21
1.21 ! jsg 1: /* $OpenBSD: process.c,v 1.20 2014/12/01 06:37:25 deraadt 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.20 deraadt 105: appends = xreallocarray(appends,
106: appendnum *= 2,
107: sizeof(struct s_appends));
1.12 tedu 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;
1.21 ! jsg 187: OUT(ps);
! 188: psl = oldpsl;
! 189: } else {
! 190: OUT(ps);
1.1 deraadt 191: }
192: break;
193: case 'q':
194: if (!nflag && !pd)
1.13 tedu 195: OUT(ps);
1.1 deraadt 196: flush_appends();
197: exit(0);
198: case 'r':
199: if (appendx >= appendnum)
1.20 deraadt 200: appends = xreallocarray(appends,
201: appendnum *= 2,
202: sizeof(struct s_appends));
1.1 deraadt 203: appends[appendx].type = AP_FILE;
204: appends[appendx].s = cp->t;
205: appends[appendx].len = strlen(cp->t);
206: appendx++;
207: break;
208: case 's':
209: sdone |= substitute(cp);
210: break;
211: case 't':
212: if (sdone) {
213: sdone = 0;
214: cp = cp->u.c;
215: goto redirect;
216: }
217: break;
218: case 'w':
219: if (pd)
220: break;
221: if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
222: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
223: DEFFILEMODE)) == -1)
1.9 jsyn 224: err(FATAL, "%s: %s",
1.1 deraadt 225: cp->t, strerror(errno));
226: if (write(cp->u.fd, ps, psl) != psl)
1.9 jsyn 227: err(FATAL, "%s: %s",
1.1 deraadt 228: cp->t, strerror(errno));
229: break;
230: case 'x':
231: if (hs == NULL)
232: cspace(&HS, "\n", 1, REPLACE);
233: tspace = PS;
234: PS = HS;
235: HS = tspace;
236: break;
237: case 'y':
1.8 millert 238: if (pd || psl == 0)
1.1 deraadt 239: break;
240: for (p = ps, len = psl; --len; ++p)
1.4 deraadt 241: *p = cp->u.y[(unsigned char)*p];
1.1 deraadt 242: break;
243: case ':':
244: case '}':
245: break;
246: case '=':
247: (void)printf("%lu\n", linenum);
248: }
249: cp = cp->next;
250: } /* for all cp */
251:
252: new: if (!nflag && !pd)
1.13 tedu 253: OUT(ps);
1.1 deraadt 254: flush_appends();
255: } /* for all lines */
256: }
257:
258: /*
259: * TRUE if the address passed matches the current program state
260: * (lastline, linenumber, ps).
261: */
262: #define MATCH(a) \
263: (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
264: (a)->type == AT_LINE ? linenum == (a)->u.l : lastline
265:
266: /*
267: * Return TRUE if the command applies to the current line. Sets the inrange
268: * flag to process ranges. Interprets the non-select (``!'') flag.
269: */
270: static inline int
1.11 deraadt 271: applies(struct s_command *cp)
1.1 deraadt 272: {
273: int r;
274:
275: lastaddr = 0;
276: if (cp->a1 == NULL && cp->a2 == NULL)
277: r = 1;
278: else if (cp->a2)
279: if (cp->inrange) {
280: if (MATCH(cp->a2)) {
281: cp->inrange = 0;
282: lastaddr = 1;
283: }
284: r = 1;
285: } else if (MATCH(cp->a1)) {
286: /*
287: * If the second address is a number less than or
288: * equal to the line number first selected, only
289: * one line shall be selected.
290: * -- POSIX 1003.2
291: */
292: if (cp->a2->type == AT_LINE &&
293: linenum >= cp->a2->u.l)
294: lastaddr = 1;
295: else
296: cp->inrange = 1;
297: r = 1;
298: } else
299: r = 0;
300: else
301: r = MATCH(cp->a1);
1.13 tedu 302: return (cp->nonsel ? !r : r);
1.1 deraadt 303: }
304:
305: /*
306: * substitute --
307: * Do substitutions in the pattern space. Currently, we build a
308: * copy of the new pattern space in the substitute space structure
309: * and then swap them.
310: */
311: static int
1.11 deraadt 312: substitute(struct s_command *cp)
1.1 deraadt 313: {
314: SPACE tspace;
315: regex_t *re;
1.18 schwarze 316: regoff_t slen;
1.1 deraadt 317: int n, lastempty;
318: char *s;
319:
320: s = ps;
321: re = cp->u.s->re;
322: if (re == NULL) {
323: if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
324: linenum = cp->u.s->linenum;
325: err(COMPILE, "\\%d not defined in the RE",
326: cp->u.s->maxbref);
327: }
328: }
329: if (!regexec_e(re, s, 0, 0, psl))
330: return (0);
331:
332: SS.len = 0; /* Clean substitute space. */
333: slen = psl;
334: n = cp->u.s->n;
335: lastempty = 1;
336:
1.18 schwarze 337: do {
338: /* Copy the leading retained string. */
339: if (n <= 1 && match[0].rm_so)
340: cspace(&SS, s, match[0].rm_so, APPEND);
341:
342: /* Skip zero-length matches right after other matches. */
343: if (lastempty || match[0].rm_so ||
344: match[0].rm_so != match[0].rm_eo) {
345: if (n <= 1) {
346: /* Want this match: append replacement. */
1.1 deraadt 347: regsub(&SS, s, cp->u.s->new);
1.18 schwarze 348: if (n == 1)
349: n = -1;
1.1 deraadt 350: } else {
1.18 schwarze 351: /* Want a later match: append original. */
352: if (match[0].rm_eo)
353: cspace(&SS, s, match[0].rm_eo, APPEND);
354: n--;
1.1 deraadt 355: }
356: }
1.18 schwarze 357:
358: /* Move past this match. */
1.1 deraadt 359: s += match[0].rm_eo;
360: slen -= match[0].rm_eo;
1.18 schwarze 361:
362: /*
363: * After a zero-length match, advance one byte,
364: * and at the end of the line, terminate.
365: */
366: if (match[0].rm_so == match[0].rm_eo) {
367: if (*s == '\0' || *s == '\n')
368: slen = -1;
369: else
370: slen--;
371: if (*s != '\0')
372: cspace(&SS, s++, 1, APPEND);
373: lastempty = 1;
374: } else
375: lastempty = 0;
376:
377: } while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
378:
379: /* Did not find the requested number of matches. */
380: if (n > 1)
381: return (0);
382:
383: /* Copy the trailing retained string. */
384: if (slen > 0)
1.1 deraadt 385: cspace(&SS, s, slen, APPEND);
386:
387: /*
388: * Swap the substitute space and the pattern space, and make sure
389: * that any leftover pointers into stdio memory get lost.
390: */
391: tspace = PS;
392: PS = SS;
393: SS = tspace;
394: SS.space = SS.back;
395:
396: /* Handle the 'p' flag. */
397: if (cp->u.s->p)
1.13 tedu 398: OUT(ps);
1.1 deraadt 399:
400: /* Handle the 'w' flag. */
401: if (cp->u.s->wfile && !pd) {
402: if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
403: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
1.9 jsyn 404: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 405: if (write(cp->u.s->wfd, ps, psl) != psl)
1.9 jsyn 406: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 407: }
408: return (1);
409: }
410:
411: /*
412: * Flush append requests. Always called before reading a line,
413: * therefore it also resets the substitution done (sdone) flag.
414: */
415: static void
1.11 deraadt 416: flush_appends(void)
1.1 deraadt 417: {
418: FILE *f;
419: int count, i;
420: char buf[8 * 1024];
421:
422: for (i = 0; i < appendx; i++)
423: switch (appends[i].type) {
424: case AP_STRING:
425: fwrite(appends[i].s, sizeof(char), appends[i].len,
426: stdout);
427: break;
428: case AP_FILE:
429: /*
430: * Read files probably shouldn't be cached. Since
431: * it's not an error to read a non-existent file,
432: * it's possible that another program is interacting
433: * with the sed script through the file system. It
434: * would be truly bizarre, but possible. It's probably
435: * not that big a performance win, anyhow.
436: */
437: if ((f = fopen(appends[i].s, "r")) == NULL)
438: break;
1.3 deraadt 439: while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
1.1 deraadt 440: (void)fwrite(buf, sizeof(char), count, stdout);
441: (void)fclose(f);
442: break;
443: }
444: if (ferror(stdout))
445: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
446: appendx = sdone = 0;
447: }
448:
449: static void
1.11 deraadt 450: lputs(char *s)
1.1 deraadt 451: {
1.6 mpech 452: int count;
453: char *escapes, *p;
1.1 deraadt 454: struct winsize win;
455: static int termwidth = -1;
456:
1.13 tedu 457: if (termwidth == -1) {
1.3 deraadt 458: if ((p = getenv("COLUMNS")))
1.1 deraadt 459: termwidth = atoi(p);
460: else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
461: win.ws_col > 0)
462: termwidth = win.ws_col;
463: else
464: termwidth = 60;
1.13 tedu 465: }
1.1 deraadt 466:
467: for (count = 0; *s; ++s) {
468: if (count >= termwidth) {
469: (void)printf("\\\n");
470: count = 0;
471: }
1.19 deraadt 472: if (isascii((unsigned char)*s) && isprint((unsigned char)*s)
473: && *s != '\\') {
1.1 deraadt 474: (void)putchar(*s);
475: count++;
1.14 millert 476: } else if (*s != '\n') {
477: escapes = "\\\a\b\f\r\t\v";
1.1 deraadt 478: (void)putchar('\\');
1.3 deraadt 479: if ((p = strchr(escapes, *s))) {
1.14 millert 480: (void)putchar("\\abfrtv"[p - escapes]);
1.1 deraadt 481: count += 2;
482: } else {
483: (void)printf("%03o", *(u_char *)s);
484: count += 4;
485: }
486: }
487: }
488: (void)putchar('$');
489: (void)putchar('\n');
490: if (ferror(stdout))
491: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
492: }
493:
494: static inline int
1.11 deraadt 495: regexec_e(regex_t *preg, const char *string, int eflags,
496: int nomatch, size_t slen)
1.1 deraadt 497: {
498: int eval;
499:
500: if (preg == NULL) {
501: if (defpreg == NULL)
502: err(FATAL, "first RE may not be empty");
503: } else
504: defpreg = preg;
505:
506: /* Set anchors, discounting trailing newline (if any). */
507: if (slen > 0 && string[slen - 1] == '\n')
508: slen--;
509: match[0].rm_so = 0;
510: match[0].rm_eo = slen;
511:
512: eval = regexec(defpreg, string,
513: nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
1.13 tedu 514: switch (eval) {
1.1 deraadt 515: case 0:
516: return (1);
517: case REG_NOMATCH:
518: return (0);
519: }
520: err(FATAL, "RE error: %s", strregerror(eval, defpreg));
521: /* NOTREACHED */
522: }
523:
524: /*
525: * regsub - perform substitutions after a regexp match
526: * Based on a routine by Henry Spencer
527: */
528: static void
1.11 deraadt 529: regsub(SPACE *sp, char *string, char *src)
1.1 deraadt 530: {
1.6 mpech 531: int len, no;
532: char c, *dst;
1.1 deraadt 533:
534: #define NEEDSP(reqlen) \
1.12 tedu 535: if (sp->len + (reqlen) + 1 >= sp->blen) { \
536: size_t newlen = sp->blen + (reqlen) + 1024; \
537: sp->space = sp->back = xrealloc(sp->back, newlen); \
538: sp->blen = newlen; \
1.1 deraadt 539: dst = sp->space + sp->len; \
540: }
541:
542: dst = sp->space + sp->len;
543: while ((c = *src++) != '\0') {
544: if (c == '&')
545: no = 0;
1.19 deraadt 546: else if (c == '\\' && isdigit((unsigned char)*src))
1.1 deraadt 547: no = *src++ - '0';
548: else
549: no = -1;
550: if (no < 0) { /* Ordinary character. */
551: if (c == '\\' && (*src == '\\' || *src == '&'))
552: c = *src++;
553: NEEDSP(1);
554: *dst++ = c;
555: ++sp->len;
556: } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
557: len = match[no].rm_eo - match[no].rm_so;
558: NEEDSP(len);
559: memmove(dst, string + match[no].rm_so, len);
560: dst += len;
561: sp->len += len;
562: }
563: }
564: NEEDSP(1);
565: *dst = '\0';
566: }
567:
568: /*
569: * aspace --
570: * Append the source space to the destination space, allocating new
571: * space as necessary.
572: */
573: void
1.11 deraadt 574: cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
1.1 deraadt 575: {
576: size_t tlen;
577:
578: /* Make sure SPACE has enough memory and ramp up quickly. */
579: tlen = sp->len + len + 1;
580: if (tlen > sp->blen) {
1.12 tedu 581: size_t newlen = tlen + 1024;
582: sp->space = sp->back = xrealloc(sp->back, newlen);
583: sp->blen = newlen;
1.1 deraadt 584: }
585:
586: if (spflag == REPLACE)
587: sp->len = 0;
588:
589: memmove(sp->space + sp->len, p, len);
590:
591: sp->space[sp->len += len] = '\0';
592: }
593:
594: /*
595: * Close all cached opened files and report any errors
596: */
597: void
1.11 deraadt 598: cfclose(struct s_command *cp, struct s_command *end)
1.1 deraadt 599: {
600:
601: for (; cp != end; cp = cp->next)
1.13 tedu 602: switch (cp->code) {
1.1 deraadt 603: case 's':
604: if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
605: err(FATAL,
606: "%s: %s", cp->u.s->wfile, strerror(errno));
607: cp->u.s->wfd = -1;
608: break;
609: case 'w':
610: if (cp->u.fd != -1 && close(cp->u.fd))
611: err(FATAL, "%s: %s", cp->t, strerror(errno));
612: cp->u.fd = -1;
613: break;
614: case '{':
615: cfclose(cp->u.c, cp->next);
616: break;
617: }
618: }