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