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