xref: /openbsd/usr.bin/sed/process.c (revision 91f110e0)
1 /*	$OpenBSD: process.c,v 1.19 2013/11/28 18:24:55 deraadt Exp $	*/
2 
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.
19  * 3. Neither the name of the University nor the names of its contributors
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 
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 *);
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 
79 #define OUT(s) do { fwrite(s, sizeof(u_char), psl, stdout); } while (0)
80 
81 void
82 process(void)
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':
104 				if (appendx >= appendnum) {
105 					appends = xrealloc(appends,
106 					    sizeof(struct s_appends) *
107 					    (appendnum * 2));
108 					appendnum *= 2;
109 				}
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;
130 				if (psl == 0 ||
131 				    (p = memchr(ps, '\n', psl - 1)) == NULL) {
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':
143 				if (hs == NULL)
144 					cspace(&HS, "\n", 1, REPLACE);
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)
161 					OUT(ps);
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)
171 						OUT(ps);
172 					exit(0);
173 				}
174 				break;
175 			case 'p':
176 				if (pd)
177 					break;
178 				OUT(ps);
179 				break;
180 			case 'P':
181 				if (pd)
182 					break;
183 				if (psl != 0 &&
184 				    (p = memchr(ps, '\n', psl - 1)) != NULL) {
185 					oldpsl = psl;
186 					psl = (p + 1) - ps;
187 				}
188 				OUT(ps);
189 				if (p != NULL)
190 					psl = oldpsl;
191 				break;
192 			case 'q':
193 				if (!nflag && !pd)
194 					OUT(ps);
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)
223 					err(FATAL, "%s: %s",
224 					    cp->t, strerror(errno));
225 				if (write(cp->u.fd, ps, psl) != psl)
226 					err(FATAL, "%s: %s",
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':
237 				if (pd || psl == 0)
238 					break;
239 				for (p = ps, len = psl; --len; ++p)
240 					*p = cp->u.y[(unsigned char)*p];
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)
252 			OUT(ps);
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
270 applies(struct s_command *cp)
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);
301 	return (cp->nonsel ? !r : r);
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
311 substitute(struct s_command *cp)
312 {
313 	SPACE tspace;
314 	regex_t *re;
315 	regoff_t 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 	do {
337 		/* Copy the leading retained string. */
338 		if (n <= 1 && match[0].rm_so)
339 			cspace(&SS, s, match[0].rm_so, APPEND);
340 
341 		/* Skip zero-length matches right after other matches. */
342 		if (lastempty || match[0].rm_so ||
343 		    match[0].rm_so != match[0].rm_eo) {
344 			if (n <= 1) {
345 				/* Want this match: append replacement. */
346 				regsub(&SS, s, cp->u.s->new);
347 				if (n == 1)
348 					n = -1;
349 			} else {
350 				/* Want a later match: append original. */
351 				if (match[0].rm_eo)
352 					cspace(&SS, s, match[0].rm_eo, APPEND);
353 				n--;
354 			}
355 		}
356 
357 		/* Move past this match. */
358 		s += match[0].rm_eo;
359 		slen -= match[0].rm_eo;
360 
361 		/*
362 		 * After a zero-length match, advance one byte,
363 		 * and at the end of the line, terminate.
364 		 */
365 		if (match[0].rm_so == match[0].rm_eo) {
366 			if (*s == '\0' || *s == '\n')
367 				slen = -1;
368 			else
369 				slen--;
370 			if (*s != '\0')
371 			 	cspace(&SS, s++, 1, APPEND);
372 			lastempty = 1;
373 		} else
374 			lastempty = 0;
375 
376 	} while (n >= 0 && slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
377 
378 	/* Did not find the requested number of matches. */
379 	if (n > 1)
380 		return (0);
381 
382 	/* Copy the trailing retained string. */
383 	if (slen > 0)
384 		cspace(&SS, s, slen, APPEND);
385 
386 	/*
387 	 * Swap the substitute space and the pattern space, and make sure
388 	 * that any leftover pointers into stdio memory get lost.
389 	 */
390 	tspace = PS;
391 	PS = SS;
392 	SS = tspace;
393 	SS.space = SS.back;
394 
395 	/* Handle the 'p' flag. */
396 	if (cp->u.s->p)
397 		OUT(ps);
398 
399 	/* Handle the 'w' flag. */
400 	if (cp->u.s->wfile && !pd) {
401 		if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
402 		    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
403 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
404 		if (write(cp->u.s->wfd, ps, psl) != psl)
405 			err(FATAL, "%s: %s", cp->u.s->wfile, strerror(errno));
406 	}
407 	return (1);
408 }
409 
410 /*
411  * Flush append requests.  Always called before reading a line,
412  * therefore it also resets the substitution done (sdone) flag.
413  */
414 static void
415 flush_appends(void)
416 {
417 	FILE *f;
418 	int count, i;
419 	char buf[8 * 1024];
420 
421 	for (i = 0; i < appendx; i++)
422 		switch (appends[i].type) {
423 		case AP_STRING:
424 			fwrite(appends[i].s, sizeof(char), appends[i].len,
425 			    stdout);
426 			break;
427 		case AP_FILE:
428 			/*
429 			 * Read files probably shouldn't be cached.  Since
430 			 * it's not an error to read a non-existent file,
431 			 * it's possible that another program is interacting
432 			 * with the sed script through the file system.  It
433 			 * would be truly bizarre, but possible.  It's probably
434 			 * not that big a performance win, anyhow.
435 			 */
436 			if ((f = fopen(appends[i].s, "r")) == NULL)
437 				break;
438 			while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
439 				(void)fwrite(buf, sizeof(char), count, stdout);
440 			(void)fclose(f);
441 			break;
442 		}
443 	if (ferror(stdout))
444 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
445 	appendx = sdone = 0;
446 }
447 
448 static void
449 lputs(char *s)
450 {
451 	int count;
452 	char *escapes, *p;
453 	struct winsize win;
454 	static int termwidth = -1;
455 
456 	if (termwidth == -1) {
457 		if ((p = getenv("COLUMNS")))
458 			termwidth = atoi(p);
459 		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
460 		    win.ws_col > 0)
461 			termwidth = win.ws_col;
462 		else
463 			termwidth = 60;
464 	}
465 
466 	for (count = 0; *s; ++s) {
467 		if (count >= termwidth) {
468 			(void)printf("\\\n");
469 			count = 0;
470 		}
471 		if (isascii((unsigned char)*s) && isprint((unsigned char)*s)
472 		    && *s != '\\') {
473 			(void)putchar(*s);
474 			count++;
475 		} else if (*s != '\n') {
476 			escapes = "\\\a\b\f\r\t\v";
477 			(void)putchar('\\');
478 			if ((p = strchr(escapes, *s))) {
479 				(void)putchar("\\abfrtv"[p - escapes]);
480 				count += 2;
481 			} else {
482 				(void)printf("%03o", *(u_char *)s);
483 				count += 4;
484 			}
485 		}
486 	}
487 	(void)putchar('$');
488 	(void)putchar('\n');
489 	if (ferror(stdout))
490 		err(FATAL, "stdout: %s", strerror(errno ? errno : EIO));
491 }
492 
493 static inline int
494 regexec_e(regex_t *preg, const char *string, int eflags,
495     int nomatch, size_t slen)
496 {
497 	int eval;
498 
499 	if (preg == NULL) {
500 		if (defpreg == NULL)
501 			err(FATAL, "first RE may not be empty");
502 	} else
503 		defpreg = preg;
504 
505 	/* Set anchors, discounting trailing newline (if any). */
506 	if (slen > 0 && string[slen - 1] == '\n')
507 		slen--;
508 	match[0].rm_so = 0;
509 	match[0].rm_eo = slen;
510 
511 	eval = regexec(defpreg, string,
512 	    nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
513 	switch (eval) {
514 	case 0:
515 		return (1);
516 	case REG_NOMATCH:
517 		return (0);
518 	}
519 	err(FATAL, "RE error: %s", strregerror(eval, defpreg));
520 	/* NOTREACHED */
521 }
522 
523 /*
524  * regsub - perform substitutions after a regexp match
525  * Based on a routine by Henry Spencer
526  */
527 static void
528 regsub(SPACE *sp, char *string, char *src)
529 {
530 	int len, no;
531 	char c, *dst;
532 
533 #define	NEEDSP(reqlen)							\
534 	if (sp->len + (reqlen) + 1 >= sp->blen) {			\
535 		size_t newlen = sp->blen + (reqlen) + 1024;		\
536 		sp->space = sp->back = xrealloc(sp->back, newlen);	\
537 		sp->blen = newlen;					\
538 		dst = sp->space + sp->len;				\
539 	}
540 
541 	dst = sp->space + sp->len;
542 	while ((c = *src++) != '\0') {
543 		if (c == '&')
544 			no = 0;
545 		else if (c == '\\' && isdigit((unsigned char)*src))
546 			no = *src++ - '0';
547 		else
548 			no = -1;
549 		if (no < 0) {		/* Ordinary character. */
550  			if (c == '\\' && (*src == '\\' || *src == '&'))
551  				c = *src++;
552 			NEEDSP(1);
553  			*dst++ = c;
554 			++sp->len;
555  		} else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
556 			len = match[no].rm_eo - match[no].rm_so;
557 			NEEDSP(len);
558 			memmove(dst, string + match[no].rm_so, len);
559 			dst += len;
560 			sp->len += len;
561 		}
562 	}
563 	NEEDSP(1);
564 	*dst = '\0';
565 }
566 
567 /*
568  * aspace --
569  *	Append the source space to the destination space, allocating new
570  *	space as necessary.
571  */
572 void
573 cspace(SPACE *sp, char *p, size_t len, enum e_spflag spflag)
574 {
575 	size_t tlen;
576 
577 	/* Make sure SPACE has enough memory and ramp up quickly. */
578 	tlen = sp->len + len + 1;
579 	if (tlen > sp->blen) {
580 		size_t newlen = tlen + 1024;
581 		sp->space = sp->back = xrealloc(sp->back, newlen);
582 		sp->blen = newlen;
583 	}
584 
585 	if (spflag == REPLACE)
586 		sp->len = 0;
587 
588 	memmove(sp->space + sp->len, p, len);
589 
590 	sp->space[sp->len += len] = '\0';
591 }
592 
593 /*
594  * Close all cached opened files and report any errors
595  */
596 void
597 cfclose(struct s_command *cp, struct s_command *end)
598 {
599 
600 	for (; cp != end; cp = cp->next)
601 		switch (cp->code) {
602 		case 's':
603 			if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
604 				err(FATAL,
605 				    "%s: %s", cp->u.s->wfile, strerror(errno));
606 			cp->u.s->wfd = -1;
607 			break;
608 		case 'w':
609 			if (cp->u.fd != -1 && close(cp->u.fd))
610 				err(FATAL, "%s: %s", cp->t, strerror(errno));
611 			cp->u.fd = -1;
612 			break;
613 		case '{':
614 			cfclose(cp->u.c, cp->next);
615 			break;
616 		}
617 }
618