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