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