process.c revision 46081
1/*-
2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993, 1994
4 *	The Regents of the University of California.  All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38#ifndef lint
39#if 0
40static char sccsid[] = "@(#)process.c	8.6 (Berkeley) 4/20/94";
41#endif
42static const char rcsid[] =
43	"$Id: process.c,v 1.8 1998/12/07 05:33:39 archie Exp $";
44#endif /* not lint */
45
46#include <sys/types.h>
47#include <sys/stat.h>
48#include <sys/ioctl.h>
49#include <sys/uio.h>
50
51#include <ctype.h>
52#include <err.h>
53#include <errno.h>
54#include <fcntl.h>
55#include <limits.h>
56#include <regex.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <string.h>
60#include <unistd.h>
61
62#include "defs.h"
63#include "extern.h"
64
65static SPACE HS, PS, SS;
66#define	pd		PS.deleted
67#define	ps		PS.space
68#define	psl		PS.len
69#define	hs		HS.space
70#define	hsl		HS.len
71
72static inline int	 applies __P((struct s_command *));
73static void		 flush_appends __P((void));
74static void		 lputs __P((char *));
75static inline int	 regexec_e __P((regex_t *, const char *, int, int, size_t));
76static void		 regsub __P((SPACE *, char *, char *));
77static int		 substitute __P((struct s_command *));
78
79struct s_appends *appends;	/* Array of pointers to strings to append. */
80static int appendx;		/* Index into appends array. */
81int appendnum;			/* Size of appends array. */
82
83static int lastaddr;		/* Set by applies if last address of a range. */
84static int sdone;		/* If any substitutes since last line input. */
85				/* Iov structure for 'w' commands. */
86static regex_t *defpreg;
87size_t maxnsub;
88regmatch_t *match;
89
90#define OUT(s) { fwrite(s, sizeof(u_char), psl, stdout); }
91
92void
93process()
94{
95	struct s_command *cp;
96	SPACE tspace;
97	size_t len, oldpsl = 0;
98	char *p;
99
100	for (linenum = 0; mf_fgets(&PS, REPLACE);) {
101		pd = 0;
102top:
103		cp = prog;
104redirect:
105		while (cp != NULL) {
106			if (!applies(cp)) {
107				cp = cp->next;
108				continue;
109			}
110			switch (cp->code) {
111			case '{':
112				cp = cp->u.c;
113				goto redirect;
114			case 'a':
115				if (appendx >= appendnum)
116					appends = xrealloc(appends,
117					    sizeof(struct s_appends) *
118					    (appendnum *= 2));
119				appends[appendx].type = AP_STRING;
120				appends[appendx].s = cp->t;
121				appends[appendx].len = strlen(cp->t);
122				appendx++;
123				break;
124			case 'b':
125				cp = cp->u.c;
126				goto redirect;
127			case 'c':
128				pd = 1;
129				psl = 0;
130				if (cp->a2 == NULL || lastaddr)
131					(void)printf("%s", cp->t);
132				break;
133			case 'd':
134				pd = 1;
135				goto new;
136			case 'D':
137				if (pd)
138					goto new;
139				if ((p = memchr(ps, '\n', psl - 1)) == NULL) {
140					pd = 1;
141					goto new;
142				} else {
143					psl -= (p + 1) - ps;
144					memmove(ps, p + 1, psl);
145					goto top;
146				}
147			case 'g':
148				cspace(&PS, hs, hsl, REPLACE);
149				break;
150			case 'G':
151				cspace(&PS, hs, hsl, 0);
152				break;
153			case 'h':
154				cspace(&HS, ps, psl, REPLACE);
155				break;
156			case 'H':
157				cspace(&HS, ps, psl, 0);
158				break;
159			case 'i':
160				(void)printf("%s", cp->t);
161				break;
162			case 'l':
163				lputs(ps);
164				break;
165			case 'n':
166				if (!nflag && !pd)
167					OUT(ps)
168				flush_appends();
169				if (!mf_fgets(&PS, REPLACE))
170					exit(0);
171				pd = 0;
172				break;
173			case 'N':
174				flush_appends();
175				if (!mf_fgets(&PS, 0)) {
176					if (!nflag && !pd)
177						OUT(ps)
178					exit(0);
179				}
180				break;
181			case 'p':
182				if (pd)
183					break;
184				OUT(ps)
185				break;
186			case 'P':
187				if (pd)
188					break;
189				if ((p = memchr(ps, '\n', psl - 1)) != NULL) {
190					oldpsl = psl;
191					psl = (p + 1) - ps;
192				}
193				OUT(ps)
194				if (p != NULL)
195					psl = oldpsl;
196				break;
197			case 'q':
198				if (!nflag && !pd)
199					OUT(ps)
200				flush_appends();
201				exit(0);
202			case 'r':
203				if (appendx >= appendnum)
204					appends = xrealloc(appends,
205					    sizeof(struct s_appends) *
206					    (appendnum *= 2));
207				appends[appendx].type = AP_FILE;
208				appends[appendx].s = cp->t;
209				appends[appendx].len = strlen(cp->t);
210				appendx++;
211				break;
212			case 's':
213				sdone |= substitute(cp);
214				break;
215			case 't':
216				if (sdone) {
217					sdone = 0;
218					cp = cp->u.c;
219					goto redirect;
220				}
221				break;
222			case 'w':
223				if (pd)
224					break;
225				if (cp->u.fd == -1 && (cp->u.fd = open(cp->t,
226				    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
227				    DEFFILEMODE)) == -1)
228					err(1, "%s", cp->t);
229				if (write(cp->u.fd, ps, psl) != psl)
230					err(1, "%s", cp->t);
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':
240				if (pd)
241					break;
242				for (p = ps, len = psl; --len; ++p)
243					*p = cp->u.y[(unsigned char)*p];
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
254new:		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 */
272static inline int
273applies(cp)
274	struct s_command *cp;
275{
276	int r;
277
278	lastaddr = 0;
279	if (cp->a1 == NULL && cp->a2 == NULL)
280		r = 1;
281	else if (cp->a2)
282		if (cp->inrange) {
283			if (MATCH(cp->a2)) {
284				cp->inrange = 0;
285				lastaddr = 1;
286			}
287			r = 1;
288		} else if (MATCH(cp->a1)) {
289			/*
290			 * If the second address is a number less than or
291			 * equal to the line number first selected, only
292			 * one line shall be selected.
293			 *	-- POSIX 1003.2
294			 */
295			if (cp->a2->type == AT_LINE &&
296			    linenum >= cp->a2->u.l)
297				lastaddr = 1;
298			else
299				cp->inrange = 1;
300			r = 1;
301		} else
302			r = 0;
303	else
304		r = MATCH(cp->a1);
305	return (cp->nonsel ? ! r : r);
306}
307
308/*
309 * substitute --
310 *	Do substitutions in the pattern space.  Currently, we build a
311 *	copy of the new pattern space in the substitute space structure
312 *	and then swap them.
313 */
314static int
315substitute(cp)
316	struct s_command *cp;
317{
318	SPACE tspace;
319	regex_t *re;
320	size_t re_off, slen;
321	int lastempty, n;
322	char *s;
323
324	s = ps;
325	re = cp->u.s->re;
326	if (re == NULL) {
327		if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) {
328			linenum = cp->u.s->linenum;
329			errx(1, "%lu: %s: \\%d not defined in the RE",
330					linenum, fname, cp->u.s->maxbref);
331		}
332	}
333	if (!regexec_e(re, s, 0, 0, psl))
334		return (0);
335
336  	SS.len = 0;				/* Clean substitute space. */
337  	slen = psl;
338  	n = cp->u.s->n;
339	lastempty = 1;
340
341  	switch (n) {
342  	case 0:					/* Global */
343  		do {
344			if (lastempty || match[0].rm_so != match[0].rm_eo) {
345				/* Locate start of replaced string. */
346				re_off = match[0].rm_so;
347				/* Copy leading retained string. */
348				cspace(&SS, s, re_off, APPEND);
349				/* Add in regular expression. */
350				regsub(&SS, s, cp->u.s->new);
351			}
352
353			/* Move past this match. */
354			if (match[0].rm_so != match[0].rm_eo) {
355				s += match[0].rm_eo;
356				slen -= match[0].rm_eo;
357				lastempty = 0;
358			} else {
359				if (match[0].rm_so == 0)
360					cspace(&SS, s, match[0].rm_so + 1,
361					    APPEND);
362				else
363					cspace(&SS, s + match[0].rm_so, 1,
364					    APPEND);
365				s += match[0].rm_so + 1;
366				slen -= match[0].rm_so + 1;
367				lastempty = 1;
368			}
369		} while (slen > 0 && regexec_e(re, s, REG_NOTBOL, 0, slen));
370		/* Copy trailing retained string. */
371		if (slen > 0)
372			cspace(&SS, s, slen, APPEND);
373  		break;
374	default:				/* Nth occurrence */
375		while (--n) {
376			s += match[0].rm_eo;
377			slen -= match[0].rm_eo;
378			if (!regexec_e(re, s, REG_NOTBOL, 0, slen))
379				return (0);
380		}
381		/* FALLTHROUGH */
382	case 1:					/* 1st occurrence */
383		/* Locate start of replaced string. */
384		re_off = match[0].rm_so + (s - ps);
385		/* Copy leading retained string. */
386		cspace(&SS, ps, re_off, APPEND);
387		/* Add in regular expression. */
388		regsub(&SS, s, cp->u.s->new);
389		/* Copy trailing retained string. */
390		s += match[0].rm_eo;
391		slen -= match[0].rm_eo;
392		cspace(&SS, s, slen, APPEND);
393		break;
394	}
395
396	/*
397	 * Swap the substitute space and the pattern space, and make sure
398	 * that any leftover pointers into stdio memory get lost.
399	 */
400	tspace = PS;
401	PS = SS;
402	SS = tspace;
403	SS.space = SS.back;
404
405	/* Handle the 'p' flag. */
406	if (cp->u.s->p)
407		OUT(ps)
408
409	/* Handle the 'w' flag. */
410	if (cp->u.s->wfile && !pd) {
411		if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile,
412		    O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1)
413			err(1, "%s", cp->u.s->wfile);
414		if (write(cp->u.s->wfd, ps, psl) != psl)
415			err(1, "%s", cp->u.s->wfile);
416	}
417	return (1);
418}
419
420/*
421 * Flush append requests.  Always called before reading a line,
422 * therefore it also resets the substitution done (sdone) flag.
423 */
424static void
425flush_appends()
426{
427	FILE *f;
428	int count, i;
429	char buf[8 * 1024];
430
431	for (i = 0; i < appendx; i++)
432		switch (appends[i].type) {
433		case AP_STRING:
434			fwrite(appends[i].s, sizeof(char), appends[i].len,
435			    stdout);
436			break;
437		case AP_FILE:
438			/*
439			 * Read files probably shouldn't be cached.  Since
440			 * it's not an error to read a non-existent file,
441			 * it's possible that another program is interacting
442			 * with the sed script through the file system.  It
443			 * would be truly bizarre, but possible.  It's probably
444			 * not that big a performance win, anyhow.
445			 */
446			if ((f = fopen(appends[i].s, "r")) == NULL)
447				break;
448			while ((count = fread(buf, sizeof(char), sizeof(buf), f)))
449				(void)fwrite(buf, sizeof(char), count, stdout);
450			(void)fclose(f);
451			break;
452		}
453	if (ferror(stdout))
454		errx(1, "stdout: %s", strerror(errno ? errno : EIO));
455	appendx = sdone = 0;
456}
457
458static void
459lputs(s)
460	register char *s;
461{
462	register int count;
463	register char *escapes, *p;
464	struct winsize win;
465	static int termwidth = -1;
466
467	if (termwidth == -1) {
468		if ((p = getenv("COLUMNS")))
469			termwidth = atoi(p);
470		else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 &&
471		    win.ws_col > 0)
472			termwidth = win.ws_col;
473		else
474			termwidth = 60;
475	}
476
477	for (count = 0; *s; ++s) {
478		if (count >= termwidth) {
479			(void)printf("\\\n");
480			count = 0;
481		}
482		if (isprint((unsigned char)*s) && *s != '\\') {
483			(void)putchar(*s);
484			count++;
485		} else {
486			escapes = "\\\a\b\f\n\r\t\v";
487			(void)putchar('\\');
488			if ((p = strchr(escapes, *s))) {
489				(void)putchar("\\abfnrtv"[p - escapes]);
490				count += 2;
491			} else {
492				(void)printf("%03o", *(u_char *)s);
493				count += 4;
494			}
495		}
496	}
497	(void)putchar('$');
498	(void)putchar('\n');
499	if (ferror(stdout))
500		errx(1, "stdout: %s", strerror(errno ? errno : EIO));
501}
502
503static inline int
504regexec_e(preg, string, eflags, nomatch, slen)
505	regex_t *preg;
506	const char *string;
507	int eflags, nomatch;
508	size_t slen;
509{
510	int eval;
511
512	if (preg == NULL) {
513		if (defpreg == NULL)
514			errx(1, "first RE may not be empty");
515	} else
516		defpreg = preg;
517
518	/* Set anchors, discounting trailing newline (if any). */
519	if (slen > 0 && string[slen - 1] == '\n')
520		slen--;
521	match[0].rm_so = 0;
522	match[0].rm_eo = slen;
523
524	eval = regexec(defpreg, string,
525	    nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND);
526	switch(eval) {
527	case 0:
528		return (1);
529	case REG_NOMATCH:
530		return (0);
531	}
532	errx(1, "RE error: %s", strregerror(eval, defpreg));
533	/* NOTREACHED */
534}
535
536/*
537 * regsub - perform substitutions after a regexp match
538 * Based on a routine by Henry Spencer
539 */
540static void
541regsub(sp, string, src)
542	SPACE *sp;
543	char *string, *src;
544{
545	register int len, no;
546	register char c, *dst;
547
548#define	NEEDSP(reqlen)							\
549	if (sp->len >= sp->blen - (reqlen) - 1) {			\
550		sp->blen += (reqlen) + 1024;				\
551		sp->space = sp->back = xrealloc(sp->back, sp->blen);	\
552		dst = sp->space + sp->len;				\
553	}
554
555	dst = sp->space + sp->len;
556	while ((c = *src++) != '\0') {
557		if (c == '&')
558			no = 0;
559		else if (c == '\\' && isdigit((unsigned char)*src))
560			no = *src++ - '0';
561		else
562			no = -1;
563		if (no < 0) {		/* Ordinary character. */
564 			if (c == '\\' && (*src == '\\' || *src == '&'))
565 				c = *src++;
566			NEEDSP(1);
567 			*dst++ = c;
568			++sp->len;
569 		} else if (match[no].rm_so != -1 && match[no].rm_eo != -1) {
570			len = match[no].rm_eo - match[no].rm_so;
571			NEEDSP(len);
572			memmove(dst, string + match[no].rm_so, len);
573			dst += len;
574			sp->len += len;
575		}
576	}
577	NEEDSP(1);
578	*dst = '\0';
579}
580
581/*
582 * aspace --
583 *	Append the source space to the destination space, allocating new
584 *	space as necessary.
585 */
586void
587cspace(sp, p, len, spflag)
588	SPACE *sp;
589	char *p;
590	size_t len;
591	enum e_spflag spflag;
592{
593	size_t tlen;
594
595	/* Make sure SPACE has enough memory and ramp up quickly. */
596	tlen = sp->len + len + 1;
597	if (tlen > sp->blen) {
598		sp->blen = tlen + 1024;
599		sp->space = sp->back = xrealloc(sp->back, sp->blen);
600	}
601
602	if (spflag == REPLACE)
603		sp->len = 0;
604
605	memmove(sp->space + sp->len, p, len);
606
607	sp->space[sp->len += len] = '\0';
608}
609
610/*
611 * Close all cached opened files and report any errors
612 */
613void
614cfclose(cp, end)
615	register struct s_command *cp, *end;
616{
617
618	for (; cp != end; cp = cp->next)
619		switch(cp->code) {
620		case 's':
621			if (cp->u.s->wfd != -1 && close(cp->u.s->wfd))
622				err(1, "%s", cp->u.s->wfile);
623			cp->u.s->wfd = -1;
624			break;
625		case 'w':
626			if (cp->u.fd != -1 && close(cp->u.fd))
627				err(1, "%s", cp->t);
628			cp->u.fd = -1;
629			break;
630		case '{':
631			cfclose(cp->u.c, cp->next);
632			break;
633		}
634}
635