xref: /freebsd/usr.bin/sed/main.c (revision b9f654b163bce26de79705e77b872427c9f2afa1)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2013 Johann 'Myrkraverk' Oskarsson.
5  * Copyright (c) 1992 Diomidis Spinellis.
6  * Copyright (c) 1992, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Diomidis Spinellis of Imperial College, University of London.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #ifndef lint
41 static const char copyright[] =
42 "@(#) Copyright (c) 1992, 1993\n\
43 	The Regents of the University of California.  All rights reserved.\n";
44 #endif
45 
46 #ifndef lint
47 static const char sccsid[] = "@(#)main.c	8.2 (Berkeley) 1/3/94";
48 #endif
49 
50 #include <sys/types.h>
51 #include <sys/mman.h>
52 #include <sys/param.h>
53 #include <sys/stat.h>
54 
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <libgen.h>
59 #include <limits.h>
60 #include <locale.h>
61 #include <regex.h>
62 #include <stddef.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 
68 #include "defs.h"
69 #include "extern.h"
70 
71 /*
72  * Linked list of units (strings and files) to be compiled
73  */
74 struct s_compunit {
75 	struct s_compunit *next;
76 	enum e_cut {CU_FILE, CU_STRING} type;
77 	char *s;			/* Pointer to string or fname */
78 };
79 
80 /*
81  * Linked list pointer to compilation units and pointer to current
82  * next pointer.
83  */
84 static struct s_compunit *script, **cu_nextp = &script;
85 
86 /*
87  * Linked list of files to be processed
88  */
89 struct s_flist {
90 	char *fname;
91 	struct s_flist *next;
92 };
93 
94 /*
95  * Linked list pointer to files and pointer to current
96  * next pointer.
97  */
98 static struct s_flist *files, **fl_nextp = &files;
99 
100 FILE *infile;			/* Current input file */
101 FILE *outfile;			/* Current output file */
102 
103 int aflag, eflag, nflag;
104 int rflags = 0;
105 int quit = 0;
106 static int rval;		/* Exit status */
107 
108 static int ispan;		/* Whether inplace editing spans across files */
109 
110 /*
111  * Current file and line number; line numbers restart across compilation
112  * units, but span across input files.  The latter is optional if editing
113  * in place.
114  */
115 const char *fname;		/* File name. */
116 const char *outfname;		/* Output file name */
117 static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
118 static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
119 const char *inplace;		/* Inplace edit file extension. */
120 u_long linenum;
121 
122 static void add_compunit(enum e_cut, char *);
123 static void add_file(char *);
124 static void usage(void);
125 
126 int
127 main(int argc, char *argv[])
128 {
129 	int c, fflag;
130 	char *temp_arg;
131 
132 	(void) setlocale(LC_ALL, "");
133 
134 	fflag = 0;
135 	inplace = NULL;
136 
137 	while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
138 		switch (c) {
139 		case 'r':		/* Gnu sed compat */
140 		case 'E':
141 			rflags = REG_EXTENDED;
142 			break;
143 		case 'I':
144 			inplace = optarg;
145 			ispan = 1;	/* span across input files */
146 			break;
147 		case 'a':
148 			aflag = 1;
149 			break;
150 		case 'e':
151 			eflag = 1;
152 			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
153 				err(1, "malloc");
154 			strcpy(temp_arg, optarg);
155 			strcat(temp_arg, "\n");
156 			add_compunit(CU_STRING, temp_arg);
157 			break;
158 		case 'f':
159 			fflag = 1;
160 			add_compunit(CU_FILE, optarg);
161 			break;
162 		case 'i':
163 			inplace = optarg;
164 			ispan = 0;	/* don't span across input files */
165 			break;
166 		case 'l':
167 			if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
168 				warnx("setting line buffered output failed");
169 			break;
170 		case 'n':
171 			nflag = 1;
172 			break;
173 		case 'u':
174 			if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
175 				warnx("setting unbuffered output failed");
176 			break;
177 		default:
178 		case '?':
179 			usage();
180 		}
181 	argc -= optind;
182 	argv += optind;
183 
184 	/* First usage case; script is the first arg */
185 	if (!eflag && !fflag && *argv) {
186 		add_compunit(CU_STRING, *argv);
187 		argv++;
188 	}
189 
190 	compile();
191 
192 	/* Continue with first and start second usage */
193 	if (*argv)
194 		for (; *argv; argv++)
195 			add_file(*argv);
196 	else
197 		add_file(NULL);
198 	process();
199 	cfclose(prog, NULL);
200 	if (fclose(stdout))
201 		err(1, "stdout");
202 	exit(rval);
203 }
204 
205 static void
206 usage(void)
207 {
208 	(void)fprintf(stderr,
209 	    "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
210 	    "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
211 	    " ... [file ...]\n", getprogname(), getprogname());
212 	exit(1);
213 }
214 
215 /*
216  * Like fgets, but go through the chain of compilation units chaining them
217  * together.  Empty strings and files are ignored.
218  */
219 char *
220 cu_fgets(char *buf, int n, int *more)
221 {
222 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
223 	static FILE *f;		/* Current open file */
224 	static char *s;		/* Current pointer inside string */
225 	static char string_ident[30];
226 	char *p;
227 
228 again:
229 	switch (state) {
230 	case ST_EOF:
231 		if (script == NULL) {
232 			if (more != NULL)
233 				*more = 0;
234 			return (NULL);
235 		}
236 		linenum = 0;
237 		switch (script->type) {
238 		case CU_FILE:
239 			if ((f = fopen(script->s, "r")) == NULL)
240 				err(1, "%s", script->s);
241 			fname = script->s;
242 			state = ST_FILE;
243 			goto again;
244 		case CU_STRING:
245 			if (((size_t)snprintf(string_ident,
246 			    sizeof(string_ident), "\"%s\"", script->s)) >=
247 			    sizeof(string_ident) - 1)
248 				(void)strcpy(string_ident +
249 				    sizeof(string_ident) - 6, " ...\"");
250 			fname = string_ident;
251 			s = script->s;
252 			state = ST_STRING;
253 			goto again;
254 		default:
255 			__unreachable();
256 		}
257 	case ST_FILE:
258 		if ((p = fgets(buf, n, f)) != NULL) {
259 			linenum++;
260 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
261 				nflag = 1;
262 			if (more != NULL)
263 				*more = !feof(f);
264 			return (p);
265 		}
266 		script = script->next;
267 		(void)fclose(f);
268 		state = ST_EOF;
269 		goto again;
270 	case ST_STRING:
271 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
272 			nflag = 1;
273 		p = buf;
274 		for (;;) {
275 			if (n-- <= 1) {
276 				*p = '\0';
277 				linenum++;
278 				if (more != NULL)
279 					*more = 1;
280 				return (buf);
281 			}
282 			switch (*s) {
283 			case '\0':
284 				state = ST_EOF;
285 				if (s == script->s) {
286 					script = script->next;
287 					goto again;
288 				} else {
289 					script = script->next;
290 					*p = '\0';
291 					linenum++;
292 					if (more != NULL)
293 						*more = 0;
294 					return (buf);
295 				}
296 			case '\n':
297 				*p++ = '\n';
298 				*p = '\0';
299 				s++;
300 				linenum++;
301 				if (more != NULL)
302 					*more = 0;
303 				return (buf);
304 			default:
305 				*p++ = *s++;
306 			}
307 		}
308 	}
309 	/* NOTREACHED */
310 	return (NULL);
311 }
312 
313 /*
314  * Like fgets, but go through the list of files chaining them together.
315  * Set len to the length of the line.
316  */
317 int
318 mf_fgets(SPACE *sp, enum e_spflag spflag)
319 {
320 	struct stat sb;
321 	ssize_t len;
322 	char *dirbuf, *basebuf;
323 	static char *p = NULL;
324 	static size_t plen = 0;
325 	int c;
326 	static int firstfile;
327 
328 	if (infile == NULL) {
329 		/* stdin? */
330 		if (files->fname == NULL) {
331 			if (inplace != NULL)
332 				errx(1, "-I or -i may not be used with stdin");
333 			infile = stdin;
334 			fname = "stdin";
335 			outfile = stdout;
336 			outfname = "stdout";
337 		}
338 		firstfile = 1;
339 	}
340 
341 	for (;;) {
342 		if (infile != NULL && (c = getc(infile)) != EOF && !quit) {
343 			(void)ungetc(c, infile);
344 			break;
345 		}
346 		/* If we are here then either eof or no files are open yet */
347 		if (infile == stdin) {
348 			sp->len = 0;
349 			return (0);
350 		}
351 		if (infile != NULL) {
352 			fclose(infile);
353 			if (*oldfname != '\0') {
354 				/* if there was a backup file, remove it */
355 				unlink(oldfname);
356 				/*
357 				 * Backup the original.  Note that hard links
358 				 * are not supported on all filesystems.
359 				 */
360 				if ((link(fname, oldfname) != 0) &&
361 				   (rename(fname, oldfname) != 0)) {
362 					warn("rename()");
363 					if (*tmpfname)
364 						unlink(tmpfname);
365 					exit(1);
366 				}
367 				*oldfname = '\0';
368 			}
369 			if (*tmpfname != '\0') {
370 				if (outfile != NULL && outfile != stdout)
371 					if (fclose(outfile) != 0) {
372 						warn("fclose()");
373 						unlink(tmpfname);
374 						exit(1);
375 					}
376 				outfile = NULL;
377 				if (rename(tmpfname, fname) != 0) {
378 					/* this should not happen really! */
379 					warn("rename()");
380 					unlink(tmpfname);
381 					exit(1);
382 				}
383 				*tmpfname = '\0';
384 			}
385 			outfname = NULL;
386 		}
387 		if (firstfile == 0)
388 			files = files->next;
389 		else
390 			firstfile = 0;
391 		if (files == NULL) {
392 			sp->len = 0;
393 			return (0);
394 		}
395 		fname = files->fname;
396 		if (inplace != NULL) {
397 			if (lstat(fname, &sb) != 0)
398 				err(1, "%s", fname);
399 			if (!S_ISREG(sb.st_mode))
400 				errx(1, "%s: %s %s", fname,
401 				    "in-place editing only",
402 				    "works for regular files");
403 			if (*inplace != '\0') {
404 				strlcpy(oldfname, fname,
405 				    sizeof(oldfname));
406 				len = strlcat(oldfname, inplace,
407 				    sizeof(oldfname));
408 				if (len > (ssize_t)sizeof(oldfname))
409 					errx(1, "%s: name too long", fname);
410 			}
411 			if ((dirbuf = strdup(fname)) == NULL ||
412 			    (basebuf = strdup(fname)) == NULL)
413 				err(1, "strdup");
414 			len = snprintf(tmpfname, sizeof(tmpfname),
415 			    "%s/.!%ld!%s", dirname(dirbuf), (long)getpid(),
416 			    basename(basebuf));
417 			free(dirbuf);
418 			free(basebuf);
419 			if (len >= (ssize_t)sizeof(tmpfname))
420 				errx(1, "%s: name too long", fname);
421 			unlink(tmpfname);
422 			if (outfile != NULL && outfile != stdout)
423 				fclose(outfile);
424 			if ((outfile = fopen(tmpfname, "w")) == NULL)
425 				err(1, "%s", fname);
426 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
427 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
428 			outfname = tmpfname;
429 			if (!ispan) {
430 				linenum = 0;
431 				resetstate();
432 			}
433 		} else {
434 			outfile = stdout;
435 			outfname = "stdout";
436 		}
437 		if ((infile = fopen(fname, "r")) == NULL) {
438 			warn("%s", fname);
439 			rval = 1;
440 			continue;
441 		}
442 	}
443 	/*
444 	 * We are here only when infile is open and we still have something
445 	 * to read from it.
446 	 *
447 	 * Use getline() so that we can handle essentially infinite input
448 	 * data.  The p and plen are static so each invocation gives
449 	 * getline() the same buffer which is expanded as needed.
450 	 */
451 	len = getline(&p, &plen, infile);
452 	if (len == -1)
453 		err(1, "%s", fname);
454 	if (len != 0 && p[len - 1] == '\n') {
455 		sp->append_newline = 1;
456 		len--;
457 	} else if (!lastline()) {
458 		sp->append_newline = 1;
459 	} else {
460 		sp->append_newline = 0;
461 	}
462 	cspace(sp, p, len, spflag);
463 
464 	linenum++;
465 
466 	return (1);
467 }
468 
469 /*
470  * Add a compilation unit to the linked list
471  */
472 static void
473 add_compunit(enum e_cut type, char *s)
474 {
475 	struct s_compunit *cu;
476 
477 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
478 		err(1, "malloc");
479 	cu->type = type;
480 	cu->s = s;
481 	cu->next = NULL;
482 	*cu_nextp = cu;
483 	cu_nextp = &cu->next;
484 }
485 
486 /*
487  * Add a file to the linked list
488  */
489 static void
490 add_file(char *s)
491 {
492 	struct s_flist *fp;
493 
494 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
495 		err(1, "malloc");
496 	fp->next = NULL;
497 	*fl_nextp = fp;
498 	fp->fname = s;
499 	fl_nextp = &fp->next;
500 }
501 
502 static int
503 next_files_have_lines(void)
504 {
505 	struct s_flist *file;
506 	FILE *file_fd;
507 	int ch;
508 
509 	file = files;
510 	while ((file = file->next) != NULL) {
511 		if ((file_fd = fopen(file->fname, "r")) == NULL)
512 			continue;
513 
514 		if ((ch = getc(file_fd)) != EOF) {
515 			/*
516 			 * This next file has content, therefore current
517 			 * file doesn't contains the last line.
518 			 */
519 			ungetc(ch, file_fd);
520 			fclose(file_fd);
521 			return (1);
522 		}
523 
524 		fclose(file_fd);
525 	}
526 
527 	return (0);
528 }
529 
530 int
531 lastline(void)
532 {
533 	int ch;
534 
535 	if (feof(infile)) {
536 		return !(
537 		    (inplace == NULL || ispan) &&
538 		    next_files_have_lines());
539 	}
540 	if ((ch = getc(infile)) == EOF) {
541 		return !(
542 		    (inplace == NULL || ispan) &&
543 		    next_files_have_lines());
544 	}
545 	ungetc(ch, infile);
546 	return (0);
547 }
548