xref: /freebsd/usr.bin/sed/main.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
1 /*-
2  * Copyright (c) 1992 Diomidis Spinellis.
3  * Copyright (c) 1992, 1993
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 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #ifndef lint
42 static const char copyright[] =
43 "@(#) Copyright (c) 1992, 1993\n\
44 	The Regents of the University of California.  All rights reserved.\n";
45 #endif
46 
47 #ifndef lint
48 static const char sccsid[] = "@(#)main.c	8.2 (Berkeley) 1/3/94";
49 #endif
50 
51 #include <sys/types.h>
52 #include <sys/mman.h>
53 #include <sys/param.h>
54 #include <sys/stat.h>
55 
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <locale.h>
60 #include <regex.h>
61 #include <stddef.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "defs.h"
68 #include "extern.h"
69 
70 /*
71  * Linked list of units (strings and files) to be compiled
72  */
73 struct s_compunit {
74 	struct s_compunit *next;
75 	enum e_cut {CU_FILE, CU_STRING} type;
76 	char *s;			/* Pointer to string or fname */
77 };
78 
79 /*
80  * Linked list pointer to compilation units and pointer to current
81  * next pointer.
82  */
83 static struct s_compunit *script, **cu_nextp = &script;
84 
85 /*
86  * Linked list of files to be processed
87  */
88 struct s_flist {
89 	char *fname;
90 	struct s_flist *next;
91 };
92 
93 /*
94  * Linked list pointer to files and pointer to current
95  * next pointer.
96  */
97 static struct s_flist *files, **fl_nextp = &files;
98 
99 static FILE *curfile;		/* Current open file */
100 
101 int aflag, eflag, nflag;
102 int rflags = 0;
103 static int rval;		/* Exit status */
104 
105 /*
106  * Current file and line number; line numbers restart across compilation
107  * units, but span across input files.
108  */
109 const char *fname;		/* File name. */
110 const char *inplace;		/* Inplace edit file extension. */
111 u_long linenum;
112 
113 static void add_compunit(enum e_cut, char *);
114 static void add_file(char *);
115 static int inplace_edit(char **);
116 static void usage(void);
117 
118 int
119 main(argc, argv)
120 	int argc;
121 	char *argv[];
122 {
123 	int c, fflag;
124 	char *temp_arg;
125 
126 	(void) setlocale(LC_ALL, "");
127 
128 	fflag = 0;
129 	inplace = NULL;
130 
131 	while ((c = getopt(argc, argv, "Eae:f:i:n")) != -1)
132 		switch (c) {
133 		case 'E':
134 			rflags = REG_EXTENDED;
135 			break;
136 		case 'a':
137 			aflag = 1;
138 			break;
139 		case 'e':
140 			eflag = 1;
141 			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
142 				err(1, "malloc");
143 			strcpy(temp_arg, optarg);
144 			strcat(temp_arg, "\n");
145 			add_compunit(CU_STRING, temp_arg);
146 			break;
147 		case 'f':
148 			fflag = 1;
149 			add_compunit(CU_FILE, optarg);
150 			break;
151 		case 'i':
152 			inplace = optarg;
153 			break;
154 		case 'n':
155 			nflag = 1;
156 			break;
157 		default:
158 		case '?':
159 			usage();
160 		}
161 	argc -= optind;
162 	argv += optind;
163 
164 	/* First usage case; script is the first arg */
165 	if (!eflag && !fflag && *argv) {
166 		add_compunit(CU_STRING, *argv);
167 		argv++;
168 	}
169 
170 	compile();
171 
172 	/* Continue with first and start second usage */
173 	if (*argv)
174 		for (; *argv; argv++)
175 			add_file(*argv);
176 	else
177 		add_file(NULL);
178 	process();
179 	cfclose(prog, NULL);
180 	if (fclose(stdout))
181 		err(1, "stdout");
182 	exit(rval);
183 }
184 
185 static void
186 usage()
187 {
188 	(void)fprintf(stderr, "%s\n%s\n",
189 		"usage: sed script [-Ean] [-i extension] [file ...]",
190 		"       sed [-an] [-i extension] [-e script] ... [-f script_file] ... [file ...]");
191 	exit(1);
192 }
193 
194 /*
195  * Like fgets, but go through the chain of compilation units chaining them
196  * together.  Empty strings and files are ignored.
197  */
198 char *
199 cu_fgets(buf, n, more)
200 	char *buf;
201 	int n;
202 	int *more;
203 {
204 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
205 	static FILE *f;		/* Current open file */
206 	static char *s;		/* Current pointer inside string */
207 	static char string_ident[30];
208 	char *p;
209 
210 again:
211 	switch (state) {
212 	case ST_EOF:
213 		if (script == NULL) {
214 			if (more != NULL)
215 				*more = 0;
216 			return (NULL);
217 		}
218 		linenum = 0;
219 		switch (script->type) {
220 		case CU_FILE:
221 			if ((f = fopen(script->s, "r")) == NULL)
222 				err(1, "%s", script->s);
223 			fname = script->s;
224 			state = ST_FILE;
225 			goto again;
226 		case CU_STRING:
227 			if ((snprintf(string_ident,
228 			    sizeof(string_ident), "\"%s\"", script->s)) >=
229 			    sizeof(string_ident) - 1)
230 				(void)strcpy(string_ident +
231 				    sizeof(string_ident) - 6, " ...\"");
232 			fname = string_ident;
233 			s = script->s;
234 			state = ST_STRING;
235 			goto again;
236 		}
237 	case ST_FILE:
238 		if ((p = fgets(buf, n, f)) != NULL) {
239 			linenum++;
240 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
241 				nflag = 1;
242 			if (more != NULL)
243 				*more = !feof(f);
244 			return (p);
245 		}
246 		script = script->next;
247 		(void)fclose(f);
248 		state = ST_EOF;
249 		goto again;
250 	case ST_STRING:
251 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
252 			nflag = 1;
253 		p = buf;
254 		for (;;) {
255 			if (n-- <= 1) {
256 				*p = '\0';
257 				linenum++;
258 				if (more != NULL)
259 					*more = 1;
260 				return (buf);
261 			}
262 			switch (*s) {
263 			case '\0':
264 				state = ST_EOF;
265 				if (s == script->s) {
266 					script = script->next;
267 					goto again;
268 				} else {
269 					script = script->next;
270 					*p = '\0';
271 					linenum++;
272 					if (more != NULL)
273 						*more = 0;
274 					return (buf);
275 				}
276 			case '\n':
277 				*p++ = '\n';
278 				*p = '\0';
279 				s++;
280 				linenum++;
281 				if (more != NULL)
282 					*more = 0;
283 				return (buf);
284 			default:
285 				*p++ = *s++;
286 			}
287 		}
288 	}
289 	/* NOTREACHED */
290 	return (NULL);
291 }
292 
293 /*
294  * Like fgets, but go through the list of files chaining them together.
295  * Set len to the length of the line.
296  */
297 int
298 mf_fgets(sp, spflag)
299 	SPACE *sp;
300 	enum e_spflag spflag;
301 {
302 	size_t len;
303 	char *p;
304 	int c;
305 	static int firstfile;
306 
307 	if (curfile == NULL) {
308 		/* stdin? */
309 		if (files->fname == NULL) {
310 			if (inplace != NULL)
311 				errx(1, "-i may not be used with stdin");
312 			curfile = stdin;
313 			fname = "stdin";
314 		}
315 		firstfile = 1;
316 	}
317 
318 	for (;;) {
319 		if (curfile != NULL && (c = getc(curfile)) != EOF) {
320 			(void)ungetc(c, curfile);
321 			break;
322 		}
323 		/* If we are here then either eof or no files are open yet */
324 		if (curfile == stdin) {
325 			sp->len = 0;
326 			return (0);
327 		}
328 		if (curfile != NULL) {
329 			fclose(curfile);
330 		}
331 		if (firstfile == 0) {
332 			files = files->next;
333 		} else
334 			firstfile = 0;
335 		if (files == NULL) {
336 			sp->len = 0;
337 			return (0);
338 		}
339 		if (inplace != NULL) {
340 			if (inplace_edit(&files->fname) == -1)
341 				continue;
342 		}
343 		fname = files->fname;
344 		if ((curfile = fopen(fname, "r")) == NULL) {
345 			warn("%s", fname);
346 			rval = 1;
347 			continue;
348 		}
349 		if (inplace != NULL && *inplace == '\0')
350 			unlink(fname);
351 	}
352 	/*
353 	 * We are here only when curfile is open and we still have something
354 	 * to read from it.
355 	 *
356 	 * Use fgetln so that we can handle essentially infinite input data.
357 	 * Can't use the pointer into the stdio buffer as the process space
358 	 * because the ungetc() can cause it to move.
359 	 */
360 	p = fgetln(curfile, &len);
361 	if (ferror(curfile))
362 		errx(1, "%s: %s", fname, strerror(errno ? errno : EIO));
363 	if (len != 0 && p[len - 1] == '\n')
364 		len--;
365 	cspace(sp, p, len, spflag);
366 
367 	linenum++;
368 
369 	return (1);
370 }
371 
372 /*
373  * Add a compilation unit to the linked list
374  */
375 static void
376 add_compunit(type, s)
377 	enum e_cut type;
378 	char *s;
379 {
380 	struct s_compunit *cu;
381 
382 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
383 		err(1, "malloc");
384 	cu->type = type;
385 	cu->s = s;
386 	cu->next = NULL;
387 	*cu_nextp = cu;
388 	cu_nextp = &cu->next;
389 }
390 
391 /*
392  * Add a file to the linked list
393  */
394 static void
395 add_file(s)
396 	char *s;
397 {
398 	struct s_flist *fp;
399 
400 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
401 		err(1, "malloc");
402 	fp->next = NULL;
403 	*fl_nextp = fp;
404 	fp->fname = s;
405 	fl_nextp = &fp->next;
406 }
407 
408 /*
409  * Modify a pointer to a filename for inplace editing and reopen stdout
410  */
411 static int
412 inplace_edit(filename)
413 	char **filename;
414 {
415 	struct stat orig;
416 	int input, output;
417 	char backup[MAXPATHLEN];
418 	char *buffer;
419 
420 	if (lstat(*filename, &orig) == -1)
421 		err(1, "lstat");
422 	if ((orig.st_mode & S_IFREG) == 0) {
423 		warnx("cannot inplace edit %s, not a regular file", *filename);
424 		return -1;
425 	}
426 
427 	if (*inplace == '\0') {
428 		char template[] = "/tmp/sed.XXXXXXXXXX";
429 
430 		output = mkstemp(template);
431 		if (output == -1)
432 			err(1, "mkstemp");
433 		strlcpy(backup, template, MAXPATHLEN);
434 	} else {
435 		strlcpy(backup, *filename, MAXPATHLEN);
436 		strlcat(backup, inplace, MAXPATHLEN);
437 		output = open(backup, O_WRONLY | O_CREAT | O_TRUNC);
438 		if (output == -1)
439 			err(1, "open(%s)", backup);
440 	}
441 
442 	input = open(*filename, O_RDONLY);
443 	if (input == -1)
444 		err(1, "open(%s)", *filename);
445 	if (fchmod(output, orig.st_mode & ~S_IFMT) == -1)
446 		err(1, "chmod");
447 	buffer = (char *)mmap(0, orig.st_size, PROT_READ, MAP_SHARED, input, 0);
448 	if (buffer == MAP_FAILED)
449 		err(1, "mmap(%s)", *filename);
450 	if (write(output, buffer, orig.st_size) == -1)
451 		err(1, "write(%s)", backup);
452 	if (munmap(buffer, orig.st_size) == -1)
453 		err(1, "munmap(%s)", *filename);
454 	close(input);
455 	close(output);
456 	freopen(*filename, "w", stdout);
457 	*filename = strdup(backup);
458 	return 0;
459 }
460 
461 int
462 lastline(void)
463 {
464 	int ch;
465 
466 	if (files->next != NULL)
467 		return (0);
468 	if ((ch = getc(curfile)) == EOF)
469 		return (1);
470 	ungetc(ch, curfile);
471 	return (0);
472 }
473