xref: /openbsd-src/usr.bin/sed/main.c (revision 850e275390052b330d93020bf619a739a3c277ac)
1 /*	$OpenBSD: main.c,v 1.12 2007/10/16 20:19:27 sobrado 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 #ifndef lint
37 static const char copyright[] =
38 "@(#) Copyright (c) 1992, 1993\n\
39 	The Regents of the University of California.  All rights reserved.\n";
40 /* from: static char sccsid[] = "@(#)main.c	8.2 (Berkeley) 1/3/94"; */
41 static const char rcsid[] = "$OpenBSD: main.c,v 1.12 2007/10/16 20:19:27 sobrado Exp $";
42 #endif /* not lint */
43 
44 #include <sys/types.h>
45 
46 #include <ctype.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <regex.h>
50 #include <stddef.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 /*
60  * Linked list of units (strings and files) to be compiled
61  */
62 struct s_compunit {
63 	struct s_compunit *next;
64 	enum e_cut {CU_FILE, CU_STRING} type;
65 	char *s;			/* Pointer to string or fname */
66 };
67 
68 /*
69  * Linked list pointer to compilation units and pointer to current
70  * next pointer.
71  */
72 static struct s_compunit *script, **cu_nextp = &script;
73 
74 /*
75  * Linked list of files to be processed
76  */
77 struct s_flist {
78 	char *fname;
79 	struct s_flist *next;
80 };
81 
82 /*
83  * Linked list pointer to files and pointer to current
84  * next pointer.
85  */
86 static struct s_flist *files, **fl_nextp = &files;
87 
88 int aflag, eflag, nflag;
89 
90 /*
91  * Current file and line number; line numbers restart across compilation
92  * units, but span across input files.
93  */
94 char *fname;			/* File name. */
95 u_long linenum;
96 int lastline;			/* TRUE on the last line of the last file */
97 
98 static void add_compunit(enum e_cut, char *);
99 static void add_file(char *);
100 
101 int
102 main(int argc, char *argv[])
103 {
104 	int c, fflag;
105 
106 	fflag = 0;
107 	while ((c = getopt(argc, argv, "ae:f:nu")) != -1)
108 		switch (c) {
109 		case 'a':
110 			aflag = 1;
111 			break;
112 		case 'e':
113 			eflag = 1;
114 			add_compunit(CU_STRING, optarg);
115 			break;
116 		case 'f':
117 			fflag = 1;
118 			add_compunit(CU_FILE, optarg);
119 			break;
120 		case 'n':
121 			nflag = 1;
122 			break;
123 		case 'u':
124 			setlinebuf(stdout);
125 			break;
126 		default:
127 		case '?':
128 			(void)fprintf(stderr,
129 			    "usage: sed [-anu] command [file ...]\n"
130 			    "       sed [-anu] [-e command] [-f command_file] [file ...]\n");
131 			exit(1);
132 		}
133 	argc -= optind;
134 	argv += optind;
135 
136 	/* First usage case; script is the first arg */
137 	if (!eflag && !fflag && *argv) {
138 		add_compunit(CU_STRING, *argv);
139 		argv++;
140 	}
141 
142 	compile();
143 
144 	/* Continue with first and start second usage */
145 	if (*argv)
146 		for (; *argv; argv++)
147 			add_file(*argv);
148 	else
149 		add_file(NULL);
150 	process();
151 	cfclose(prog, NULL);
152 	if (fclose(stdout))
153 		err(FATAL, "stdout: %s", strerror(errno));
154 	exit (0);
155 }
156 
157 /*
158  * Like fgets, but go through the chain of compilation units chaining them
159  * together.  Empty strings and files are ignored.
160  */
161 char *
162 cu_fgets(char *buf, int n)
163 {
164 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
165 	static FILE *f;		/* Current open file */
166 	static char *s;		/* Current pointer inside string */
167 	static char string_ident[30];
168 	char *p;
169 
170 again:
171 	switch (state) {
172 	case ST_EOF:
173 		if (script == NULL)
174 			return (NULL);
175 		linenum = 0;
176 		switch (script->type) {
177 		case CU_FILE:
178 			if ((f = fopen(script->s, "r")) == NULL)
179 				err(FATAL,
180 				    "%s: %s", script->s, strerror(errno));
181 			fname = script->s;
182 			state = ST_FILE;
183 			goto again;
184 		case CU_STRING:
185 			if ((snprintf(string_ident,
186 			    sizeof(string_ident), "\"%s\"", script->s)) >=
187 			    sizeof(string_ident))
188 				strlcpy(string_ident +
189 				    sizeof(string_ident) - 6, " ...\"", 5);
190 			fname = string_ident;
191 			s = script->s;
192 			state = ST_STRING;
193 			goto again;
194 		}
195 	case ST_FILE:
196 		if ((p = fgets(buf, n, f)) != NULL) {
197 			linenum++;
198 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
199 				nflag = 1;
200 			return (p);
201 		}
202 		script = script->next;
203 		(void)fclose(f);
204 		state = ST_EOF;
205 		goto again;
206 	case ST_STRING:
207 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
208 			nflag = 1;
209 		p = buf;
210 		for (;;) {
211 			if (n-- <= 1) {
212 				*p = '\0';
213 				linenum++;
214 				return (buf);
215 			}
216 			switch (*s) {
217 			case '\0':
218 				state = ST_EOF;
219 				if (s == script->s) {
220 					script = script->next;
221 					goto again;
222 				} else {
223 					script = script->next;
224 					*p = '\0';
225 					linenum++;
226 					return (buf);
227 				}
228 			case '\n':
229 				*p++ = '\n';
230 				*p = '\0';
231 				s++;
232 				linenum++;
233 				return (buf);
234 			default:
235 				*p++ = *s++;
236 			}
237 		}
238 	}
239 	/* NOTREACHED */
240 }
241 
242 /*
243  * Like fgets, but go through the list of files chaining them together.
244  * Set len to the length of the line.
245  */
246 int
247 mf_fgets(SPACE *sp, enum e_spflag spflag)
248 {
249 	static FILE *f;		/* Current open file */
250 	size_t len;
251 	char *p;
252 	int c;
253 
254 	if (f == NULL)
255 		/* Advance to first non-empty file */
256 		for (;;) {
257 			if (files == NULL) {
258 				lastline = 1;
259 				return (0);
260 			}
261 			if (files->fname == NULL) {
262 				f = stdin;
263 				fname = "stdin";
264 			} else {
265 				fname = files->fname;
266 				if ((f = fopen(fname, "r")) == NULL)
267 					err(FATAL, "%s: %s",
268 					    fname, strerror(errno));
269 			}
270 			if ((c = getc(f)) != EOF) {
271 				(void)ungetc(c, f);
272 				break;
273 			}
274 			(void)fclose(f);
275 			files = files->next;
276 		}
277 
278 	if (lastline) {
279 		sp->len = 0;
280 		return (0);
281 	}
282 
283 	/*
284 	 * Use fgetln so that we can handle essentially infinite input data.
285 	 * Can't use the pointer into the stdio buffer as the process space
286 	 * because the ungetc() can cause it to move.
287 	 */
288 	p = fgetln(f, &len);
289 	if (ferror(f))
290 		err(FATAL, "%s: %s", fname, strerror(errno ? errno : EIO));
291 	cspace(sp, p, len, spflag);
292 
293 	linenum++;
294 	/* Advance to next non-empty file */
295 	while ((c = getc(f)) == EOF) {
296 		(void)fclose(f);
297 		files = files->next;
298 		if (files == NULL) {
299 			lastline = 1;
300 			return (1);
301 		}
302 		if (files->fname == NULL) {
303 			f = stdin;
304 			fname = "stdin";
305 		} else {
306 			fname = files->fname;
307 			if ((f = fopen(fname, "r")) == NULL)
308 				err(FATAL, "%s: %s", fname, strerror(errno));
309 		}
310 	}
311 	(void)ungetc(c, f);
312 	return (1);
313 }
314 
315 /*
316  * Add a compilation unit to the linked list
317  */
318 static void
319 add_compunit(enum e_cut type, char *s)
320 {
321 	struct s_compunit *cu;
322 
323 	cu = xmalloc(sizeof(struct s_compunit));
324 	cu->type = type;
325 	cu->s = s;
326 	cu->next = NULL;
327 	*cu_nextp = cu;
328 	cu_nextp = &cu->next;
329 }
330 
331 /*
332  * Add a file to the linked list
333  */
334 static void
335 add_file(char *s)
336 {
337 	struct s_flist *fp;
338 
339 	fp = xmalloc(sizeof(struct s_flist));
340 	fp->next = NULL;
341 	*fl_nextp = fp;
342 	fp->fname = s;
343 	fl_nextp = &fp->next;
344 }
345