xref: /freebsd/usr.bin/sed/main.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
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  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1992, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif
42 
43 #ifndef lint
44 static const char sccsid[] = "@(#)main.c	8.2 (Berkeley) 1/3/94";
45 #endif
46 
47 #include <sys/types.h>
48 #include <sys/mman.h>
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <libgen.h>
56 #include <limits.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 FILE *infile;			/* Current input file */
98 FILE *outfile;			/* Current output file */
99 
100 int aflag, eflag, nflag;
101 int rflags = 0;
102 static int rval;		/* Exit status */
103 
104 /*
105  * Current file and line number; line numbers restart across compilation
106  * units, but span across input files.
107  */
108 const char *fname;		/* File name. */
109 const char *outfname;		/* Output file name */
110 static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
111 static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
112 const char *inplace;		/* Inplace edit file extension. */
113 u_long linenum;
114 
115 static void add_compunit(enum e_cut, char *);
116 static void add_file(char *);
117 static int inplace_edit(char **);
118 static void usage(void);
119 
120 int
121 main(int argc, char *argv[])
122 {
123 	int c, fflag;
124 	char *temp_arg;
125 
126 	(void) setlocale(LC_ALL, "");
127 
128 	fflag = 0;
129 	inplace = NULL;
130 
131 	while ((c = getopt(argc, argv, "Eae:f:i:n")) != -1)
132 		switch (c) {
133 		case 'E':
134 			rflags = REG_EXTENDED;
135 			break;
136 		case 'a':
137 			aflag = 1;
138 			break;
139 		case 'e':
140 			eflag = 1;
141 			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
142 				err(1, "malloc");
143 			strcpy(temp_arg, optarg);
144 			strcat(temp_arg, "\n");
145 			add_compunit(CU_STRING, temp_arg);
146 			break;
147 		case 'f':
148 			fflag = 1;
149 			add_compunit(CU_FILE, optarg);
150 			break;
151 		case 'i':
152 			inplace = optarg;
153 			break;
154 		case 'n':
155 			nflag = 1;
156 			break;
157 		default:
158 		case '?':
159 			usage();
160 		}
161 	argc -= optind;
162 	argv += optind;
163 
164 	/* First usage case; script is the first arg */
165 	if (!eflag && !fflag && *argv) {
166 		add_compunit(CU_STRING, *argv);
167 		argv++;
168 	}
169 
170 	compile();
171 
172 	/* Continue with first and start second usage */
173 	if (*argv)
174 		for (; *argv; argv++)
175 			add_file(*argv);
176 	else
177 		add_file(NULL);
178 	process();
179 	cfclose(prog, NULL);
180 	if (fclose(stdout))
181 		err(1, "stdout");
182 	exit(rval);
183 }
184 
185 static void
186 usage(void)
187 {
188 	(void)fprintf(stderr, "%s\n%s\n",
189 		"usage: sed script [-Ean] [-i extension] [file ...]",
190 		"       sed [-an] [-i extension] [-e script] ... [-f script_file] ... [file ...]");
191 	exit(1);
192 }
193 
194 /*
195  * Like fgets, but go through the chain of compilation units chaining them
196  * together.  Empty strings and files are ignored.
197  */
198 char *
199 cu_fgets(char *buf, int n, int *more)
200 {
201 	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
202 	static FILE *f;		/* Current open file */
203 	static char *s;		/* Current pointer inside string */
204 	static char string_ident[30];
205 	char *p;
206 
207 again:
208 	switch (state) {
209 	case ST_EOF:
210 		if (script == NULL) {
211 			if (more != NULL)
212 				*more = 0;
213 			return (NULL);
214 		}
215 		linenum = 0;
216 		switch (script->type) {
217 		case CU_FILE:
218 			if ((f = fopen(script->s, "r")) == NULL)
219 				err(1, "%s", script->s);
220 			fname = script->s;
221 			state = ST_FILE;
222 			goto again;
223 		case CU_STRING:
224 			if ((snprintf(string_ident,
225 			    sizeof(string_ident), "\"%s\"", script->s)) >=
226 			    sizeof(string_ident) - 1)
227 				(void)strcpy(string_ident +
228 				    sizeof(string_ident) - 6, " ...\"");
229 			fname = string_ident;
230 			s = script->s;
231 			state = ST_STRING;
232 			goto again;
233 		}
234 	case ST_FILE:
235 		if ((p = fgets(buf, n, f)) != NULL) {
236 			linenum++;
237 			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
238 				nflag = 1;
239 			if (more != NULL)
240 				*more = !feof(f);
241 			return (p);
242 		}
243 		script = script->next;
244 		(void)fclose(f);
245 		state = ST_EOF;
246 		goto again;
247 	case ST_STRING:
248 		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
249 			nflag = 1;
250 		p = buf;
251 		for (;;) {
252 			if (n-- <= 1) {
253 				*p = '\0';
254 				linenum++;
255 				if (more != NULL)
256 					*more = 1;
257 				return (buf);
258 			}
259 			switch (*s) {
260 			case '\0':
261 				state = ST_EOF;
262 				if (s == script->s) {
263 					script = script->next;
264 					goto again;
265 				} else {
266 					script = script->next;
267 					*p = '\0';
268 					linenum++;
269 					if (more != NULL)
270 						*more = 0;
271 					return (buf);
272 				}
273 			case '\n':
274 				*p++ = '\n';
275 				*p = '\0';
276 				s++;
277 				linenum++;
278 				if (more != NULL)
279 					*more = 0;
280 				return (buf);
281 			default:
282 				*p++ = *s++;
283 			}
284 		}
285 	}
286 	/* NOTREACHED */
287 	return (NULL);
288 }
289 
290 /*
291  * Like fgets, but go through the list of files chaining them together.
292  * Set len to the length of the line.
293  */
294 int
295 mf_fgets(SPACE *sp, enum e_spflag spflag)
296 {
297 	struct stat sb;
298 	size_t len;
299 	char *p;
300 	int c;
301 	static int firstfile;
302 
303 	if (infile == NULL) {
304 		/* stdin? */
305 		if (files->fname == NULL) {
306 			if (inplace != NULL)
307 				errx(1, "-i may not be used with stdin");
308 			infile = stdin;
309 			fname = "stdin";
310 			outfile = stdout;
311 			outfname = "stdout";
312 		}
313 		firstfile = 1;
314 	}
315 
316 	for (;;) {
317 		if (infile != NULL && (c = getc(infile)) != EOF) {
318 			(void)ungetc(c, infile);
319 			break;
320 		}
321 		/* If we are here then either eof or no files are open yet */
322 		if (infile == stdin) {
323 			sp->len = 0;
324 			return (0);
325 		}
326 		if (infile != NULL) {
327 			fclose(infile);
328 			if (*oldfname != '\0') {
329 				if (rename(fname, oldfname) != 0) {
330 					warn("rename()");
331 					unlink(tmpfname);
332 					exit(1);
333 				}
334 				*oldfname = '\0';
335 			}
336 			if (*tmpfname != '\0') {
337 				if (outfile != NULL && outfile != stdout)
338 					fclose(outfile);
339 				outfile = NULL;
340 				rename(tmpfname, fname);
341 				*tmpfname = '\0';
342 			}
343 			outfname = NULL;
344 		}
345 		if (firstfile == 0)
346 			files = files->next;
347 		else
348 			firstfile = 0;
349 		if (files == NULL) {
350 			sp->len = 0;
351 			return (0);
352 		}
353 		fname = files->fname;
354 		if (inplace != NULL) {
355 			if (lstat(fname, &sb) != 0)
356 				err(1, "%s", fname);
357 			if (!(sb.st_mode & S_IFREG))
358 				errx(1, "%s: %s %s", fname,
359 				    "in-place editing only",
360 				    "works for regular files");
361 			if (*inplace != '\0') {
362 				strlcpy(oldfname, fname,
363 				    sizeof(oldfname));
364 				len = strlcat(oldfname, inplace,
365 				    sizeof(oldfname));
366 				if (len > sizeof(oldfname))
367 					errx(1, "%s: name too long", fname);
368 			}
369 			len = snprintf(tmpfname, sizeof(tmpfname),
370 			    "%s/.!%ld!%s", dirname(fname), (long)getpid(),
371 			    basename(fname));
372 			if (len >= sizeof(tmpfname))
373 				errx(1, "%s: name too long", fname);
374 			unlink(tmpfname);
375 			if ((outfile = fopen(tmpfname, "w")) == NULL)
376 				err(1, "%s", fname);
377 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
378 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
379 			outfname = tmpfname;
380 		} else {
381 			outfile = stdout;
382 			outfname = "stdout";
383 		}
384 		if ((infile = fopen(fname, "r")) == NULL) {
385 			warn("%s", fname);
386 			rval = 1;
387 			continue;
388 		}
389 	}
390 	/*
391 	 * We are here only when infile is open and we still have something
392 	 * to read from it.
393 	 *
394 	 * Use fgetln so that we can handle essentially infinite input data.
395 	 * Can't use the pointer into the stdio buffer as the process space
396 	 * because the ungetc() can cause it to move.
397 	 */
398 	p = fgetln(infile, &len);
399 	if (ferror(infile))
400 		errx(1, "%s: %s", fname, strerror(errno ? errno : EIO));
401 	if (len != 0 && p[len - 1] == '\n')
402 		len--;
403 	cspace(sp, p, len, spflag);
404 
405 	linenum++;
406 
407 	return (1);
408 }
409 
410 /*
411  * Add a compilation unit to the linked list
412  */
413 static void
414 add_compunit(enum e_cut type, char *s)
415 {
416 	struct s_compunit *cu;
417 
418 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
419 		err(1, "malloc");
420 	cu->type = type;
421 	cu->s = s;
422 	cu->next = NULL;
423 	*cu_nextp = cu;
424 	cu_nextp = &cu->next;
425 }
426 
427 /*
428  * Add a file to the linked list
429  */
430 static void
431 add_file(char *s)
432 {
433 	struct s_flist *fp;
434 
435 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
436 		err(1, "malloc");
437 	fp->next = NULL;
438 	*fl_nextp = fp;
439 	fp->fname = s;
440 	fl_nextp = &fp->next;
441 }
442 
443 int
444 lastline(void)
445 {
446 	int ch;
447 
448 	if (files->next != NULL)
449 		return (0);
450 	if ((ch = getc(infile)) == EOF)
451 		return (1);
452 	ungetc(ch, infile);
453 	return (0);
454 }
455