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