Annotation of src/usr.bin/sed/process.c, Revision 1.11
1.11 ! deraadt 1: /* $OpenBSD: process.c,v 1.10 2003/06/03 02:56:16 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: #ifndef lint
37: /* from: static char sccsid[] = "@(#)process.c 8.1 (Berkeley) 6/6/93"; */
1.11 ! deraadt 38: static char *rcsid = "$OpenBSD: process.c,v 1.10 2003/06/03 02:56:16 millert Exp $";
1.1 deraadt 39: #endif /* not lint */
40:
41: #include <sys/types.h>
42: #include <sys/stat.h>
43: #include <sys/ioctl.h>
44: #include <sys/uio.h>
45:
46: #include <ctype.h>
47: #include <errno.h>
48: #include <fcntl.h>
49: #include <limits.h>
50: #include <regex.h>
51: #include <stdio.h>
52: #include <stdlib.h>
53: #include <string.h>
54: #include <unistd.h>
55:
56: #include "defs.h"
57: #include "extern.h"
58:
59: static SPACE HS, PS, SS;
60: #define pd PS.deleted
61: #define ps PS.space
62: #define psl PS.len
63: #define hs HS.space
64: #define hsl HS.len
65:
1.7 millert 66: static inline int applies(struct s_command *);
67: static void flush_appends(void);
68: static void lputs(char *);
69: static inline int regexec_e(regex_t *, const char *, int, int, size_t);
70: static void regsub(SPACE *, char *, char *);
71: static int substitute(struct s_command *);
1.1 deraadt 72:
73: struct s_appends *appends; /* Array of pointers to strings to append. */
74: static int appendx; /* Index into appends array. */
75: int appendnum; /* Size of appends array. */
76:
77: static int lastaddr; /* Set by applies if last address of a range. */
78: static int sdone; /* If any substitutes since last line input. */
79: /* Iov structure for 'w' commands. */
80: static regex_t *defpreg;
81: size_t maxnsub;
82: regmatch_t *match;
83:
84: #define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
85:
86: void
1.11 ! deraadt 87: process(void)
1.1 deraadt 88: {
89: struct s_command *cp;
90: SPACE tspace;
91: size_t len, oldpsl;
92: char *p;
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':
109: if (appendx >= appendnum)
110: appends = xrealloc(appends,
111: sizeof(struct s_appends) *
112: (appendnum *= 2));
113: appends[appendx].type = AP_STRING;
114: appends[appendx].s = cp->t;
115: appends[appendx].len = strlen(cp->t);
116: appendx++;
117: break;
118: case 'b':
119: cp = cp->u.c;
120: goto redirect;
121: case 'c':
122: pd = 1;
123: psl = 0;
124: if (cp->a2 == NULL || lastaddr)
125: (void)printf("%s", cp->t);
126: break;
127: case 'd':
128: pd = 1;
129: goto new;
130: case 'D':
131: if (pd)
132: goto new;
1.8 millert 133: if (psl == 0 ||
134: (p = memchr(ps, '\n', psl - 1)) == NULL) {
1.1 deraadt 135: pd = 1;
136: goto new;
137: } else {
138: psl -= (p + 1) - ps;
139: memmove(ps, p + 1, psl);
140: goto top;
141: }
142: case 'g':
143: cspace(&PS, hs, hsl, REPLACE);
144: break;
145: case 'G':
1.5 deraadt 146: if (hs == NULL)
147: cspace(&HS, "\n", 1, REPLACE);
1.1 deraadt 148: cspace(&PS, hs, hsl, 0);
149: break;
150: case 'h':
151: cspace(&HS, ps, psl, REPLACE);
152: break;
153: case 'H':
154: cspace(&HS, ps, psl, 0);
155: break;
156: case 'i':
157: (void)printf("%s", cp->t);
158: break;
159: case 'l':
160: lputs(ps);
161: break;
162: case 'n':
163: if (!nflag && !pd)
164: OUT(ps)
165: flush_appends();
166: if (!mf_fgets(&PS, REPLACE))
167: exit(0);
168: pd = 0;
169: break;
170: case 'N':
171: flush_appends();
172: if (!mf_fgets(&PS, 0)) {
173: if (!nflag && !pd)
174: OUT(ps)
175: exit(0);
176: }
177: break;
178: case 'p':
179: if (pd)
180: break;
181: OUT(ps)
182: break;
183: case 'P':
184: if (pd)
185: break;
1.8 millert 186: if (psl != 0 &&
187: (p = memchr(ps, '\n', psl - 1)) != NULL) {
1.1 deraadt 188: oldpsl = psl;
189: psl = (p + 1) - ps;
190: }
191: OUT(ps)
192: if (p != NULL)
193: psl = oldpsl;
194: break;
195: case 'q':
196: if (!nflag && !pd)
197: OUT(ps)
198: flush_appends();
199: exit(0);
200: case 'r':
201: if (appendx >= appendnum)
202: appends = xrealloc(appends,
203: sizeof(struct s_appends) *
204: (appendnum *= 2));
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)
255: OUT(ps)
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);
304: return (cp->nonsel ? ! r : r);
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;
318: size_t re_off, slen;
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:
339: switch (n) {
340: case 0: /* Global */
341: do {
342: if (lastempty || match[0].rm_so != match[0].rm_eo) {
343: /* Locate start of replaced string. */
344: re_off = match[0].rm_so;
345: /* Copy leading retained string. */
346: cspace(&SS, s, re_off, APPEND);
347: /* Add in regular expression. */
348: regsub(&SS, s, cp->u.s->new);
349: }
350:
351: /* Move past this match. */
352: if (match[0].rm_so != match[0].rm_eo) {
353: s += match[0].rm_eo;
354: slen -= match[0].rm_eo;
355: lastempty = 0;
356: } else {
357: if (match[0].rm_so == 0)
358: cspace(&SS, s, match[0].rm_so + 1,
359: APPEND);
360: else
361: cspace(&SS, s + match[0].rm_so, 1,
362: APPEND);
363: s += match[0].rm_so + 1;
364: slen -= match[0].rm_so + 1;
365: lastempty = 1;
366: }
367: } while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
368: /* Copy trailing retained string. */
369: if (slen > 0)
370: cspace(&SS, s, slen, APPEND);
371: break;
372: default: /* Nth occurrence */
373: while (--n) {
374: s += match[0].rm_eo;
375: slen -= match[0].rm_eo;
376: if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
377: return (0);
378: }
379: /* FALLTHROUGH */
380: case 1: /* 1st occurrence */
381: /* Locate start of replaced string. */
382: re_off = match[0].rm_so + (s - ps);
383: /* Copy leading retained string. */
384: cspace(&SS, ps, re_off, APPEND);
385: /* Add in regular expression. */
386: regsub(&SS, s, cp->u.s->new);
387: /* Copy trailing retained string. */
388: s += match[0].rm_eo;
389: slen -= match[0].rm_eo;
390: cspace(&SS, s, slen, APPEND);
391: break;
392: }
393:
394: /*
395: * Swap the substitute space and the pattern space, and make sure
396: * that any leftover pointers into stdio memory get lost.
397: */
398: tspace = PS;
399: PS = SS;
400: SS = tspace;
401: SS.space = SS.back;
402:
403: /* Handle the 'p' flag. */
404: if (cp->u.s->p)
405: OUT(ps)
406:
407: /* Handle the 'w' flag. */
408: if (cp->u.s->wfile && !pd) {
409: if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
410: O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
1.9 jsyn 411: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 412: if (write(cp->u.s->wfd, ps, psl) != psl)
1.9 jsyn 413: err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
1.1 deraadt 414: }
415: return (1);
416: }
417:
418: /*
419: * Flush append requests. Always called before reading a line,
420: * therefore it also resets the substitution done (sdone) flag.
421: */
422: static void
1.11 ! deraadt 423: flush_appends(void)
1.1 deraadt 424: {
425: FILE *f;
426: int count, i;
427: char buf[8 * 1024];
428:
429: for (i = 0; i < appendx; i++)
430: switch (appends[i].type) {
431: case AP_STRING:
432: fwrite(appends[i].s, sizeof(char), appends[i].len,
433: stdout);
434: break;
435: case AP_FILE:
436: /*
437: * Read files probably shouldn't be cached. Since
438: * it's not an error to read a non-existent file,
439: * it's possible that another program is interacting
440: * with the sed script through the file system. It
441: * would be truly bizarre, but possible. It's probably
442: * not that big a performance win, anyhow.
443: */
444: if ((f = fopen(appends[i].s, "r")) == NULL)
445: break;
1.3 deraadt 446: while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
1.1 deraadt 447: (void)fwrite(buf, sizeof(char), count, stdout);
448: (void)fclose(f);
449: break;
450: }
451: if (ferror(stdout))
452: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
453: appendx = sdone = 0;
454: }
455:
456: static void
1.11 ! deraadt 457: lputs(char *s)
1.1 deraadt 458: {
1.6 mpech 459: int count;
460: char *escapes, *p;
1.1 deraadt 461: struct winsize win;
462: static int termwidth = -1;
463:
464: if (termwidth == -1)
1.3 deraadt 465: if ((p = getenv("COLUMNS")))
1.1 deraadt 466: termwidth = atoi(p);
467: else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
468: win.ws_col > 0)
469: termwidth = win.ws_col;
470: else
471: termwidth = 60;
472:
473: for (count = 0; *s; ++s) {
474: if (count >= termwidth) {
475: (void)printf("\\\n");
476: count = 0;
477: }
478: if (isascii(*s) && isprint(*s) && *s != '\\') {
479: (void)putchar(*s);
480: count++;
481: } else {
482: escapes = "\\\a\b\f\n\r\t\v";
483: (void)putchar('\\');
1.3 deraadt 484: if ((p = strchr(escapes, *s))) {
1.1 deraadt 485: (void)putchar("\\abfnrtv"[p - escapes]);
486: count += 2;
487: } else {
488: (void)printf("%03o", *(u_char *)s);
489: count += 4;
490: }
491: }
492: }
493: (void)putchar('$');
494: (void)putchar('\n');
495: if (ferror(stdout))
496: err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
497: }
498:
499: static inline int
1.11 ! deraadt 500: regexec_e(regex_t *preg, const char *string, int eflags,
! 501: int nomatch, size_t slen)
1.1 deraadt 502: {
503: int eval;
504:
505: if (preg == NULL) {
506: if (defpreg == NULL)
507: err(FATAL, "first RE may not be empty");
508: } else
509: defpreg = preg;
510:
511: /* Set anchors, discounting trailing newline (if any). */
512: if (slen > 0 && string[slen - 1] == '\n')
513: slen--;
514: match[0].rm_so = 0;
515: match[0].rm_eo = slen;
516:
517: eval = regexec(defpreg, string,
518: nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
519: switch(eval) {
520: case 0:
521: return (1);
522: case REG_NOMATCH:
523: return (0);
524: }
525: err(FATAL, "RE error: %s", strregerror(eval, defpreg));
526: /* NOTREACHED */
527: }
528:
529: /*
530: * regsub - perform substitutions after a regexp match
531: * Based on a routine by Henry Spencer
532: */
533: static void
1.11 ! deraadt 534: regsub(SPACE *sp, char *string, char *src)
1.1 deraadt 535: {
1.6 mpech 536: int len, no;
537: char c, *dst;
1.1 deraadt 538:
539: #define NEEDSP(reqlen) \
540: if (sp->len >= sp->blen - (reqlen) - 1) { \
541: sp->blen += (reqlen) + 1024; \
542: sp->space = sp->back = xrealloc(sp->back, sp->blen); \
543: dst = sp->space + sp->len; \
544: }
545:
546: dst = sp->space + sp->len;
547: while ((c = *src++) != '\0') {
548: if (c == '&')
549: no = 0;
550: else if (c == '\\' && isdigit(*src))
551: no = *src++ - '0';
552: else
553: no = -1;
554: if (no < 0) { /* Ordinary character. */
555: if (c == '\\' && (*src == '\\' || *src == '&'))
556: c = *src++;
557: NEEDSP(1);
558: *dst++ = c;
559: ++sp->len;
560: } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
561: len = match[no].rm_eo - match[no].rm_so;
562: NEEDSP(len);
563: memmove(dst, string + match[no].rm_so, len);
564: dst += len;
565: sp->len += len;
566: }
567: }
568: NEEDSP(1);
569: *dst = '\0';
570: }
571:
572: /*
573: * aspace --
574: * Append the source space to the destination space, allocating new
575: * space as necessary.
576: */
577: void
1.11 ! deraadt 578: cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
1.1 deraadt 579: {
580: size_t tlen;
581:
582: /* Make sure SPACE has enough memory and ramp up quickly. */
583: tlen = sp->len + len + 1;
584: if (tlen > sp->blen) {
585: sp->blen = tlen + 1024;
586: sp->space = sp->back = xrealloc(sp->back, sp->blen);
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)
605: switch(cp->code) {
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: }