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