xref: /freebsd/usr.bin/sed/main.c (revision a5921bc3653e2e286715e6fe8d473ec0d02da38c)
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  * 4. 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 #define _WITH_GETLINE
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 FILE *infile;			/* Current input file */
100 FILE *outfile;			/* Current output file */
101 
102 int aflag, eflag, nflag;
103 int rflags = 0;
104 static int rval;		/* Exit status */
105 
106 static int ispan;		/* Whether inplace editing spans across files */
107 
108 /*
109  * Current file and line number; line numbers restart across compilation
110  * units, but span across input files.  The latter is optional if editing
111  * in place.
112  */
113 const char *fname;		/* File name. */
114 const char *outfname;		/* Output file name */
115 static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
116 static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
117 static const char *inplace;	/* Inplace edit file extension. */
118 u_long linenum;
119 
120 static void add_compunit(enum e_cut, char *);
121 static void add_file(char *);
122 static void usage(void);
123 
124 int
125 main(int argc, char *argv[])
126 {
127 	int c, fflag;
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 			add_compunit(CU_STRING, optarg);
150 			break;
151 		case 'f':
152 			fflag = 1;
153 			add_compunit(CU_FILE, optarg);
154 			break;
155 		case 'i':
156 			inplace = optarg;
157 			ispan = 0;	/* don't span across input files */
158 			break;
159 		case 'l':
160 			if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
161 				warnx("setting line buffered output failed");
162 			break;
163 		case 'n':
164 			nflag = 1;
165 			break;
166 		case 'u':
167 			if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
168 				warnx("setting unbuffered output failed");
169 			break;
170 		default:
171 		case '?':
172 			usage();
173 		}
174 	argc -= optind;
175 	argv += optind;
176 
177 	/* First usage case; script is the first arg */
178 	if (!eflag && !fflag && *argv) {
179 		add_compunit(CU_STRING, *argv);
180 		argv++;
181 	}
182 
183 	compile();
184 
185 	/* Continue with first and start second usage */
186 	if (*argv)
187 		for (; *argv; argv++)
188 			add_file(*argv);
189 	else
190 		add_file(NULL);
191 	process();
192 	cfclose(prog, NULL);
193 	if (fclose(stdout))
194 		err(1, "stdout");
195 	exit(rval);
196 }
197 
198 static void
199 usage(void)
200 {
201 	(void)fprintf(stderr,
202 	    "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
203 	    "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
204 	    " ... [file ...]\n", getprogname(), getprogname());
205 	exit(1);
206 }
207 
208 /*
209  * Like fgets, but go through the chain of compilation units chaining them
210  * together.  Empty strings and files are ignored.
211  */
212 char *
213 cu_fgets(char *buf, int n, int *more)
214 {
215 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
216 	static FILE *f;		/* Current open file */
217 	static char *s;		/* Current pointer inside string */
218 	static char string_ident[30];
219 	char *p;
220 
221 again:
222 	switch (state) {
223 	case ST_EOF:
224 		if (script == NULL) {
225 			if (more != NULL)
226 				*more = 0;
227 			return (NULL);
228 		}
229 		linenum = 0;
230 		switch (script->type) {
231 		case CU_FILE:
232 			if ((f = fopen(script->s, "r")) == NULL)
233 				err(1, "%s", script->s);
234 			fname = script->s;
235 			state = ST_FILE;
236 			goto again;
237 		case CU_STRING:
238 			if (((size_t)snprintf(string_ident,
239 			    sizeof(string_ident), "\"%s\"", script->s)) >=
240 			    sizeof(string_ident) - 1)
241 				(void)strcpy(string_ident +
242 				    sizeof(string_ident) - 6, " ...\"");
243 			fname = string_ident;
244 			s = script->s;
245 			state = ST_STRING;
246 			goto again;
247 		}
248 	case ST_FILE:
249 		if ((p = fgets(buf, n, f)) != NULL) {
250 			linenum++;
251 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
252 				nflag = 1;
253 			if (more != NULL)
254 				*more = !feof(f);
255 			return (p);
256 		}
257 		script = script->next;
258 		(void)fclose(f);
259 		state = ST_EOF;
260 		goto again;
261 	case ST_STRING:
262 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
263 			nflag = 1;
264 		p = buf;
265 		for (;;) {
266 			if (n-- <= 1) {
267 				*p = '\0';
268 				linenum++;
269 				if (more != NULL)
270 					*more = 1;
271 				return (buf);
272 			}
273 			switch (*s) {
274 			case '\0':
275 				state = ST_EOF;
276 				if (s == script->s) {
277 					script = script->next;
278 					goto again;
279 				} else {
280 					script = script->next;
281 					*p = '\0';
282 					linenum++;
283 					if (more != NULL)
284 						*more = 0;
285 					return (buf);
286 				}
287 			case '\n':
288 				*p++ = '\n';
289 				*p = '\0';
290 				s++;
291 				linenum++;
292 				if (more != NULL)
293 					*more = 0;
294 				return (buf);
295 			default:
296 				*p++ = *s++;
297 			}
298 		}
299 	}
300 	/* NOTREACHED */
301 	return (NULL);
302 }
303 
304 /*
305  * Like fgets, but go through the list of files chaining them together.
306  * Set len to the length of the line.
307  */
308 int
309 mf_fgets(SPACE *sp, enum e_spflag spflag)
310 {
311 	struct stat sb;
312 	ssize_t len;
313 	static char *p = NULL;
314 	static size_t plen = 0;
315 	int c;
316 	static int firstfile;
317 
318 	if (infile == NULL) {
319 		/* stdin? */
320 		if (files->fname == NULL) {
321 			if (inplace != NULL)
322 				errx(1, "-I or -i may not be used with stdin");
323 			infile = stdin;
324 			fname = "stdin";
325 			outfile = stdout;
326 			outfname = "stdout";
327 		}
328 		firstfile = 1;
329 	}
330 
331 	for (;;) {
332 		if (infile != NULL && (c = getc(infile)) != EOF) {
333 			(void)ungetc(c, infile);
334 			break;
335 		}
336 		/* If we are here then either eof or no files are open yet */
337 		if (infile == stdin) {
338 			sp->len = 0;
339 			return (0);
340 		}
341 		if (infile != NULL) {
342 			fclose(infile);
343 			if (*oldfname != '\0') {
344 				/* if there was a backup file, remove it */
345 				unlink(oldfname);
346 				/*
347 				 * Backup the original.  Note that hard links
348 				 * are not supported on all filesystems.
349 				 */
350 				if ((link(fname, oldfname) != 0) &&
351 				   (rename(fname, oldfname) != 0)) {
352 					warn("rename()");
353 					if (*tmpfname)
354 						unlink(tmpfname);
355 					exit(1);
356 				}
357 				*oldfname = '\0';
358 			}
359 			if (*tmpfname != '\0') {
360 				if (outfile != NULL && outfile != stdout)
361 					if (fclose(outfile) != 0) {
362 						warn("fclose()");
363 						unlink(tmpfname);
364 						exit(1);
365 					}
366 				outfile = NULL;
367 				if (rename(tmpfname, fname) != 0) {
368 					/* this should not happen really! */
369 					warn("rename()");
370 					unlink(tmpfname);
371 					exit(1);
372 				}
373 				*tmpfname = '\0';
374 			}
375 			outfname = NULL;
376 		}
377 		if (firstfile == 0)
378 			files = files->next;
379 		else
380 			firstfile = 0;
381 		if (files == NULL) {
382 			sp->len = 0;
383 			return (0);
384 		}
385 		fname = files->fname;
386 		if (inplace != NULL) {
387 			if (lstat(fname, &sb) != 0)
388 				err(1, "%s", fname);
389 			if (!(sb.st_mode & S_IFREG))
390 				errx(1, "%s: %s %s", fname,
391 				    "in-place editing only",
392 				    "works for regular files");
393 			if (*inplace != '\0') {
394 				strlcpy(oldfname, fname,
395 				    sizeof(oldfname));
396 				len = strlcat(oldfname, inplace,
397 				    sizeof(oldfname));
398 				if (len > (ssize_t)sizeof(oldfname))
399 					errx(1, "%s: name too long", fname);
400 			}
401 			len = snprintf(tmpfname, sizeof(tmpfname),
402 			    "%s/.!%ld!%s", dirname(fname), (long)getpid(),
403 			    basename(fname));
404 			if (len >= (ssize_t)sizeof(tmpfname))
405 				errx(1, "%s: name too long", fname);
406 			unlink(tmpfname);
407 			if (outfile != NULL && outfile != stdout)
408 				fclose(outfile);
409 			if ((outfile = fopen(tmpfname, "w")) == NULL)
410 				err(1, "%s", fname);
411 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
412 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
413 			outfname = tmpfname;
414 			if (!ispan) {
415 				linenum = 0;
416 				resetstate();
417 			}
418 		} else {
419 			outfile = stdout;
420 			outfname = "stdout";
421 		}
422 		if ((infile = fopen(fname, "r")) == NULL) {
423 			warn("%s", fname);
424 			rval = 1;
425 			continue;
426 		}
427 	}
428 	/*
429 	 * We are here only when infile is open and we still have something
430 	 * to read from it.
431 	 *
432 	 * Use getline() so that we can handle essentially infinite input
433 	 * data.  The p and plen are static so each invocation gives
434 	 * getline() the same buffer which is expanded as needed.
435 	 */
436 	len = getline(&p, &plen, infile);
437 	if (len == -1)
438 		err(1, "%s", fname);
439 	if (len != 0 && p[len - 1] == '\n') {
440 		sp->append_newline = 1;
441 		len--;
442 	} else if (!lastline()) {
443 		sp->append_newline = 1;
444 	} else {
445 		sp->append_newline = 0;
446 	}
447 	cspace(sp, p, len, spflag);
448 
449 	linenum++;
450 
451 	return (1);
452 }
453 
454 /*
455  * Add a compilation unit to the linked list
456  */
457 static void
458 add_compunit(enum e_cut type, char *s)
459 {
460 	struct s_compunit *cu;
461 
462 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
463 		err(1, "malloc");
464 	cu->type = type;
465 	cu->s = s;
466 	cu->next = NULL;
467 	*cu_nextp = cu;
468 	cu_nextp = &cu->next;
469 }
470 
471 /*
472  * Add a file to the linked list
473  */
474 static void
475 add_file(char *s)
476 {
477 	struct s_flist *fp;
478 
479 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
480 		err(1, "malloc");
481 	fp->next = NULL;
482 	*fl_nextp = fp;
483 	fp->fname = s;
484 	fl_nextp = &fp->next;
485 }
486 
487 static int
488 next_files_have_lines(void)
489 {
490 	struct s_flist *file;
491 	FILE *file_fd;
492 	int ch;
493 
494 	file = files;
495 	while ((file = file->next) != NULL) {
496 		if ((file_fd = fopen(file->fname, "r")) == NULL)
497 			continue;
498 
499 		if ((ch = getc(file_fd)) != EOF) {
500 			/*
501 			 * This next file has content, therefore current
502 			 * file doesn't contains the last line.
503 			 */
504 			ungetc(ch, file_fd);
505 			fclose(file_fd);
506 			return (1);
507 		}
508 
509 		fclose(file_fd);
510 	}
511 
512 	return (0);
513 }
514 
515 int
516 lastline(void)
517 {
518 	int ch;
519 
520 	if (feof(infile)) {
521 		return !(
522 		    (inplace == NULL || ispan) &&
523 		    next_files_have_lines());
524 	}
525 	if ((ch = getc(infile)) == EOF) {
526 		return !(
527 		    (inplace == NULL || ispan) &&
528 		    next_files_have_lines());
529 	}
530 	ungetc(ch, infile);
531 	return (0);
532 }
533