Annotation of src/usr.bin/sed/process.c, Revision 1.24
1.24 ! jasper 1: /* $OpenBSD: process.c,v 1.23 2015/04/18 18:28:37 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
1.24 ! jasper 58: #define psanl PS.append_newline
1.1 deraadt 59: #define hs HS.space
60: #define hsl HS.len
61:
1.7 millert 62: static inline int applies(struct s_command *);
63: static void flush_appends(void);
64: static void lputs(char *);
65: static inline int regexec_e(regex_t *, const char *, int, int, size_t);
66: static void regsub(SPACE *, char *, char *);
67: static int substitute(struct s_command *);
1.1 deraadt 68:
69: struct s_appends *appends; /* Array of pointers to strings to append. */
70: static int appendx; /* Index into appends array. */
1.22 deraadt 71: size_t appendnum; /* Size of appends array. */
1.1 deraadt 72:
73: static int lastaddr; /* Set by applies if last address of a range. */
74: static int sdone; /* If any substitutes since last line input. */
75: /* Iov structure for 'w' commands. */
76: static regex_t *defpreg;
77: size_t maxnsub;
78: regmatch_t *match;
79:
1.24 ! jasper 80: #define OUT() do {\
! 81: fwrite(ps, 1, psl, outfile);\
! 82: if (psanl) fputc('\n', outfile);\
! 83: } while (0)
1.1 deraadt 84:
85: void
1.11 deraadt 86: process(void)
1.1 deraadt 87: {
88: struct s_command *cp;
89: SPACE tspace;
90: size_t len, oldpsl;
91: char *p;
1.24 ! jasper 92: int oldpsanl;
1.1 deraadt 93:
94: for (linenum = 0; mf_fgets(&PS, REPLACE);) {
95: pd = 0;
96: top:
97: cp = prog;
98: redirect:
99: while (cp != NULL) {
100: if (!applies(cp)) {
101: cp = cp->next;
102: continue;
103: }
104: switch (cp->code) {
105: case '{':
106: cp = cp->u.c;
107: goto redirect;
108: case 'a':
1.12 tedu 109: if (appendx >= appendnum) {
1.20 deraadt 110: appends = xreallocarray(appends,
1.22 deraadt 111: appendnum,
112: 2 * sizeof(struct s_appends));
1.12 tedu 113: appendnum *= 2;
114: }
1.1 deraadt 115: appends[appendx].type = AP_STRING;
116: appends[appendx].s = cp->t;
117: appends[appendx].len = strlen(cp->t);
118: appendx++;
119: break;
120: case 'b':
121: cp = cp->u.c;
122: goto redirect;
123: case 'c':
124: pd = 1;
125: psl = 0;
1.24 ! jasper 126: if (cp->a2 == NULL || lastaddr || lastline())
! 127: (void)fprintf(outfile, "%s", cp->t);
1.1 deraadt 128: break;
129: case 'd':
130: pd = 1;
131: goto new;
132: case 'D':
133: if (pd)
134: goto new;
1.8 millert 135: if (psl == 0 ||
1.24 ! jasper 136: (p = memchr(ps, '\n', psl)) == NULL) {
1.1 deraadt 137: pd = 1;
138: goto new;
139: } else {
140: psl -= (p + 1) - ps;
141: memmove(ps, p + 1, psl);
142: goto top;
143: }
144: case 'g':
145: cspace(&PS, hs, hsl, REPLACE);
146: break;
147: case 'G':
1.24 ! jasper 148: cspace(&PS, "\n", 1, 0);
1.1 deraadt 149: cspace(&PS, hs, hsl, 0);
150: break;
151: case 'h':
152: cspace(&HS, ps, psl, REPLACE);
153: break;
154: case 'H':
1.24 ! jasper 155: cspace(&HS, "\n", 1, 0);
1.1 deraadt 156: cspace(&HS, ps, psl, 0);
157: break;
158: case 'i':
1.24 ! jasper 159: (void)fprintf(outfile, "%s", cp->t);
1.1 deraadt 160: break;
161: case 'l':
162: lputs(ps);
163: break;
164: case 'n':
165: if (!nflag && !pd)
1.24 ! jasper 166: OUT();
1.1 deraadt 167: flush_appends();
168: if (!mf_fgets(&PS, REPLACE))
169: exit(0);
170: pd = 0;
171: break;
172: case 'N':
173: flush_appends();
1.24 ! jasper 174: cspace(&PS, "\n", 1, 0);
! 175: if (!mf_fgets(&PS, 0))
1.1 deraadt 176: exit(0);
177: break;
178: case 'p':
179: if (pd)
180: break;
1.24 ! jasper 181: OUT();
1.1 deraadt 182: break;
183: case 'P':
184: if (pd)
185: break;
1.24 ! jasper 186: if ((p = memchr(ps, '\n', psl)) != NULL) {
1.1 deraadt 187: oldpsl = psl;
1.24 ! jasper 188: oldpsanl = psanl;
! 189: psl = p - ps;
! 190: psanl = 1;
! 191: OUT();
1.21 jsg 192: psl = oldpsl;
193: } else {
1.24 ! jasper 194: OUT();
1.1 deraadt 195: }
196: break;
197: case 'q':
198: if (!nflag && !pd)
1.24 ! jasper 199: OUT();
1.1 deraadt 200: flush_appends();
201: exit(0);
202: case 'r':
1.22 deraadt 203: if (appendx >= appendnum) {
1.20 deraadt 204: appends = xreallocarray(appends,
1.22 deraadt 205: appendnum,
206: 2 * sizeof(struct s_appends));
207: appendnum *= 2;
208: }
1.1 deraadt 209: appends[appendx].type = AP_FILE;
210: appends[appendx].s = cp->t;
211: appends[appendx].len = strlen(cp->t);
212: appendx++;
213: break;
214: case 's':
215: sdone |= substitute(cp);
216: break;
217: case 't':
218: if (sdone) {
219: sdone = 0;
220: cp = cp->u.c;
221: goto redirect;
222: }
223: break;
224: case 'w':
225: if (pd)
226: break;
227: if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
228: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
229: DEFFILEMODE)) == -1)
1.9 jsyn 230: err(FATAL, "%s: %s",
1.1 deraadt 231: cp->t, strerror(errno));
1.24 ! jasper 232: if (write(cp->u.fd, ps, psl) != psl ||
! 233: write(cp->u.fd, "\n", 1) != 1)
1.9 jsyn 234: err(FATAL, "%s: %s",
1.1 deraadt 235: cp->t, strerror(errno));
236: break;
237: case 'x':
238: if (hs == NULL)
1.24 ! jasper 239: cspace(&HS, "", 0, REPLACE);
1.1 deraadt 240: tspace = PS;
241: PS = HS;
1.24 ! jasper 242: psanl = tspace.append_newline;
1.1 deraadt 243: HS = tspace;
244: break;
245: case 'y':
1.8 millert 246: if (pd || psl == 0)
1.1 deraadt 247: break;
1.24 ! jasper 248: for (p = ps, len = psl; len--; ++p)
1.4 deraadt 249: *p = cp->u.y[(unsigned char)*p];
1.1 deraadt 250: break;
251: case ':':
252: case '}':
253: break;
254: case '=':
1.24 ! jasper 255: (void)fprintf(outfile, "%lu\n", linenum);
1.1 deraadt 256: }
257: cp = cp->next;
258: } /* for all cp */
259:
260: new: if (!nflag && !pd)
1.24 ! jasper 261: OUT();
1.1 deraadt 262: flush_appends();
263: } /* for all lines */
264: }
265:
266: /*
267: * TRUE if the address passed matches the current program state
268: * (lastline, linenumber, ps).
269: */
270: #define MATCH(a) \
271: (a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \
1.24 ! jasper 272: (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()
1.1 deraadt 273:
274: /*
275: * Return TRUE if the command applies to the current line. Sets the inrange
276: * flag to process ranges. Interprets the non-select (``!'') flag.
277: */
278: static inline int
1.11 deraadt 279: applies(struct s_command *cp)
1.1 deraadt 280: {
281: int r;
282:
283: lastaddr = 0;
284: if (cp->a1 == NULL && cp->a2 == NULL)
285: r = 1;
286: else if (cp->a2)
287: if (cp->inrange) {
288: if (MATCH(cp->a2)) {
289: cp->inrange = 0;
290: lastaddr = 1;
291: }
292: r = 1;
293: } else if (MATCH(cp->a1)) {
294: /*
295: * If the second address is a number less than or
296: * equal to the line number first selected, only
297: * one line shall be selected.
298: * -- POSIX 1003.2
299: */
300: if (cp->a2->type == AT_LINE &&
301: linenum >= cp->a2->u.l)
302: lastaddr = 1;
303: else
304: cp->inrange = 1;
305: r = 1;
306: } else
307: r = 0;
308: else
309: r = MATCH(cp->a1);
1.13 tedu 310: return (cp->nonsel ? !r : r);
1.1 deraadt 311: }
312:
313: /*
1.24 ! jasper 314: * Reset all inrange markers.
! 315: */
! 316: void
! 317: resetranges(void)
! 318: {
! 319: struct s_command *cp;
! 320:
! 321: for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next)
! 322: if (cp->a2)
! 323: cp->inrange = 0;
! 324: }
! 325:
! 326: /*
1.1 deraadt 327: * substitute --
328: * Do substitutions in the pattern space. Currently, we build a
329: * copy of the new pattern space in the substitute space structure
330: * and then swap them.
331: */
332: static int
1.11 deraadt 333: substitute(struct s_command *cp)
1.1 deraadt 334: {
335: SPACE tspace;
336: regex_t *re;
1.18 schwarze 337: regoff_t slen;
1.1 deraadt 338: int n, lastempty;
339: char *s;
340:
341: s = ps;
342: re = cp->u.s->re;
343: if (re == NULL) {
344: if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
345: linenum = cp->u.s->linenum;
346: err(COMPILE, "\\%d not defined in the RE",
347: cp->u.s->maxbref);
348: }
349: }
350: if (!regexec_e(re, s, 0, 0, psl))
351: return (0);
352:
353: SS.len = 0; /* Clean substitute space. */
354: slen = psl;
355: n = cp->u.s->n;
356: lastempty = 1;
357:
1.18 schwarze 358: do {
359: /* Copy the leading retained string. */
360: if (n <= 1 && match[0].rm_so)
361: cspace(&SS, s, match[0].rm_so, APPEND);
362:
363: /* Skip zero-length matches right after other matches. */
364: if (lastempty || match[0].rm_so ||
365: match[0].rm_so != match[0].rm_eo) {
366: if (n <= 1) {
367: /* Want this match: append replacement. */
1.1 deraadt 368: regsub(&SS, s, cp->u.s->new);
1.18 schwarze 369: if (n == 1)
370: n = -1;
1.1 deraadt 371: } else {
1.18 schwarze 372: /* Want a later match: append original. */
373: if (match[0].rm_eo)
374: cspace(&SS, s, match[0].rm_eo, APPEND);
375: n--;
1.1 deraadt 376: }
377: }
1.18 schwarze 378:
379: /* Move past this match. */
1.1 deraadt 380: s += match[0].rm_eo;
381: slen -= match[0].rm_eo;
1.18 schwarze 382:
383: /*
384: * After a zero-length match, advance one byte,
385: * and at the end of the line, terminate.
386: */
387: if (match[0].rm_so == match[0].rm_eo) {
388: if (*s == '\0' || *s == '\n')
389: slen = -1;
390: else
391: slen--;
392: if (*s != '\0')
393: cspace(&SS, s++, 1, APPEND);
394: lastempty = 1;
395: } else
396: lastempty = 0;
397:
398: } while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
399:
400: /* Did not find the requested number of matches. */
401: if (n > 1)
402: return (0);
403:
404: /* Copy the trailing retained string. */
405: if (slen > 0)
1.1 deraadt 406: cspace(&SS, s, slen, APPEND);
407:
408: /*
409: * Swap the substitute space and the pattern space, and make sure
410: * that any leftover pointers into stdio memory get lost.
411: */
412: tspace = PS;
413: PS = SS;
1.24 ! jasper 414: psanl = tspace.append_newline;
1.1 deraadt 415: SS = tspace;
416: SS.space = SS.back;
417:
418: /* Handle the 'p' flag. */
419: if (cp->u.s->p)
1.24 ! jasper 420: OUT();
1.1 deraadt 421:
422: /* Handle the 'w' flag. */
423: if (cp->u.s->wfile && !pd) {
424: if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
425: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
1.9 jsyn 426: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.24 ! jasper 427: if (write(cp->u.s->wfd, ps, psl) != psl ||
! 428: write(cp->u.s->wfd, "\n", 1) != 1)
1.9 jsyn 429: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 430: }
431: return (1);
432: }
433:
434: /*
435: * Flush append requests. Always called before reading a line,
436: * therefore it also resets the substitution done (sdone) flag.
437: */
438: static void
1.11 deraadt 439: flush_appends(void)
1.1 deraadt 440: {
441: FILE *f;
442: int count, i;
443: char buf[8 * 1024];
444:
445: for (i = 0; i < appendx; i++)
446: switch (appends[i].type) {
447: case AP_STRING:
448: fwrite(appends[i].s, sizeof(char), appends[i].len,
1.24 ! jasper 449: outfile);
1.1 deraadt 450: break;
451: case AP_FILE:
452: /*
453: * Read files probably shouldn't be cached. Since
454: * it's not an error to read a non-existent file,
455: * it's possible that another program is interacting
456: * with the sed script through the file system. It
457: * would be truly bizarre, but possible. It's probably
458: * not that big a performance win, anyhow.
459: */
460: if ((f = fopen(appends[i].s, "r")) == NULL)
461: break;
1.3 deraadt 462: while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
1.24 ! jasper 463: (void)fwrite(buf, sizeof(char), count, outfile);
1.1 deraadt 464: (void)fclose(f);
465: break;
466: }
1.24 ! jasper 467: if (ferror(outfile))
! 468: err(FATAL, "%s: %s", outfname, strerror(errno ? errno : EIO));
1.1 deraadt 469: appendx = sdone = 0;
470: }
471:
472: static void
1.11 deraadt 473: lputs(char *s)
1.1 deraadt 474: {
1.6 mpech 475: int count;
1.24 ! jasper 476: const char *escapes;
! 477: char *p;
1.1 deraadt 478: struct winsize win;
479: static int termwidth = -1;
480:
1.24 ! jasper 481: if (outfile != stdout)
! 482: termwidth = 60;
! 483:
1.13 tedu 484: if (termwidth == -1) {
1.23 deraadt 485: termwidth = 0;
1.3 deraadt 486: if ((p = getenv("COLUMNS")))
1.23 deraadt 487: termwidth = strtonum(p, 0, INT_MAX, NULL);
488: if (termwidth == 0 &&
489: ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
1.1 deraadt 490: win.ws_col > 0)
491: termwidth = win.ws_col;
1.23 deraadt 492: if (termwidth == 0)
1.1 deraadt 493: termwidth = 60;
1.13 tedu 494: }
1.1 deraadt 495:
496: for (count = 0; *s; ++s) {
497: if (count >= termwidth) {
1.24 ! jasper 498: (void)fprintf(outfile, "\\\n");
1.1 deraadt 499: count = 0;
500: }
1.19 deraadt 501: if (isascii((unsigned char)*s) && isprint((unsigned char)*s)
502: && *s != '\\') {
1.24 ! jasper 503: (void)fputc(*s, outfile);
1.1 deraadt 504: count++;
1.24 ! jasper 505: } else if (*s == '\n') {
! 506: (void)fputc('$', outfile);
! 507: (void)fputc('\n', outfile);
! 508: count = 0;
! 509: } else {
1.14 millert 510: escapes = "\\\a\b\f\r\t\v";
1.24 ! jasper 511: (void)fputc('\\', outfile);
1.3 deraadt 512: if ((p = strchr(escapes, *s))) {
1.24 ! jasper 513: (void)fputc("\\abfrtv"[p - escapes], outfile);
1.1 deraadt 514: count += 2;
515: } else {
1.24 ! jasper 516: (void)fprintf(outfile, "%03o", *(u_char *)s);
1.1 deraadt 517: count += 4;
518: }
519: }
520: }
1.24 ! jasper 521: (void)fputc('$', outfile);
! 522: (void)fputc('\n', outfile);
! 523: if (ferror(outfile))
! 524: err(FATAL, "%s: %s", outfname, strerror(errno ? errno : EIO));
1.1 deraadt 525: }
526:
527: static inline int
1.11 deraadt 528: regexec_e(regex_t *preg, const char *string, int eflags,
529: int nomatch, size_t slen)
1.1 deraadt 530: {
531: int eval;
532:
533: if (preg == NULL) {
534: if (defpreg == NULL)
535: err(FATAL, "first RE may not be empty");
536: } else
537: defpreg = preg;
538:
1.24 ! jasper 539: /* Set anchors */
1.1 deraadt 540: match[0].rm_so = 0;
541: match[0].rm_eo = slen;
542:
543: eval = regexec(defpreg, string,
544: nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
1.13 tedu 545: switch (eval) {
1.1 deraadt 546: case 0:
547: return (1);
548: case REG_NOMATCH:
549: return (0);
550: }
551: err(FATAL, "RE error: %s", strregerror(eval, defpreg));
552: /* NOTREACHED */
553: }
554:
555: /*
556: * regsub - perform substitutions after a regexp match
557: * Based on a routine by Henry Spencer
558: */
559: static void
1.11 deraadt 560: regsub(SPACE *sp, char *string, char *src)
1.1 deraadt 561: {
1.6 mpech 562: int len, no;
563: char c, *dst;
1.1 deraadt 564:
565: #define NEEDSP(reqlen) \
1.12 tedu 566: if (sp->len + (reqlen) + 1 >= sp->blen) { \
567: size_t newlen = sp->blen + (reqlen) + 1024; \
568: sp->space = sp->back = xrealloc(sp->back, newlen); \
569: sp->blen = newlen; \
1.1 deraadt 570: dst = sp->space + sp->len; \
571: }
572:
573: dst = sp->space + sp->len;
574: while ((c = *src++) != '\0') {
575: if (c == '&')
576: no = 0;
1.19 deraadt 577: else if (c == '\\' && isdigit((unsigned char)*src))
1.1 deraadt 578: no = *src++ - '0';
579: else
580: no = -1;
581: if (no < 0) { /* Ordinary character. */
582: if (c == '\\' && (*src == '\\' || *src == '&'))
583: c = *src++;
584: NEEDSP(1);
585: *dst++ = c;
586: ++sp->len;
587: } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
588: len = match[no].rm_eo - match[no].rm_so;
589: NEEDSP(len);
590: memmove(dst, string + match[no].rm_so, len);
591: dst += len;
592: sp->len += len;
593: }
594: }
595: NEEDSP(1);
596: *dst = '\0';
597: }
598:
599: /*
600: * aspace --
601: * Append the source space to the destination space, allocating new
602: * space as necessary.
603: */
604: void
1.24 ! jasper 605: cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag)
1.1 deraadt 606: {
607: size_t tlen;
608:
609: /* Make sure SPACE has enough memory and ramp up quickly. */
610: tlen = sp->len + len + 1;
611: if (tlen > sp->blen) {
1.12 tedu 612: size_t newlen = tlen + 1024;
613: sp->space = sp->back = xrealloc(sp->back, newlen);
614: sp->blen = newlen;
1.1 deraadt 615: }
616:
617: if (spflag == REPLACE)
618: sp->len = 0;
619:
620: memmove(sp->space + sp->len, p, len);
621:
622: sp->space[sp->len += len] = '\0';
623: }
624:
625: /*
626: * Close all cached opened files and report any errors
627: */
628: void
1.11 deraadt 629: cfclose(struct s_command *cp, struct s_command *end)
1.1 deraadt 630: {
631:
632: for (; cp != end; cp = cp->next)
1.13 tedu 633: switch (cp->code) {
1.1 deraadt 634: case 's':
635: if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
636: err(FATAL,
637: "%s: %s", cp->u.s->wfile, strerror(errno));
638: cp->u.s->wfd = -1;
639: break;
640: case 'w':
641: if (cp->u.fd != -1 && close(cp->u.fd))
642: err(FATAL, "%s: %s", cp->t, strerror(errno));
643: cp->u.fd = -1;
644: break;
645: case '{':
646: cfclose(cp->u.c, cp->next);
647: break;
648: }
649: }