xref: /freebsd/usr.bin/sed/main.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
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 			    rename(fname, oldfname) != 0) {
332 				warn("rename()");
333 				unlink(tmpfname);
334 				exit(1);
335 			}
336 			if (*tmpfname != '\0')
337 				rename(tmpfname, fname);
338 			*tmpfname = *oldfname = '\0';
339 			outfname = NULL;
340 		}
341 		if (firstfile == 0)
342 			files = files->next;
343 		else
344 			firstfile = 0;
345 		if (files == NULL) {
346 			sp->len = 0;
347 			return (0);
348 		}
349 		fname = files->fname;
350 		if (inplace != NULL) {
351 			if (lstat(fname, &sb) != 0)
352 				err(1, "%s", fname);
353 			if (!(sb.st_mode & S_IFREG))
354 				errx(1, "%s: %s %s", fname,
355 				    "in-place editing only",
356 				    "works for regular files");
357 			if (*inplace != '\0') {
358 				strlcpy(oldfname, fname,
359 				    sizeof(oldfname));
360 				len = strlcat(oldfname, inplace,
361 				    sizeof(oldfname));
362 				if (len > sizeof(oldfname))
363 					errx(1, "%s: name too long", fname);
364 			}
365 			len = snprintf(tmpfname, sizeof(tmpfname),
366 			    "%s/.!%ld!%s", dirname(fname), (long)getpid(),
367 			    basename(fname));
368 			if (len >= sizeof(tmpfname))
369 				errx(1, "%s: name too long", fname);
370 			unlink(tmpfname);
371 			if ((outfile = fopen(tmpfname, "w")) == NULL)
372 				err(1, "%s", fname);
373 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
374 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
375 			outfname = tmpfname;
376 		} else {
377 			outfile = stdout;
378 			outfname = "stdout";
379 		}
380 		if ((infile = fopen(fname, "r")) == NULL) {
381 			warn("%s", fname);
382 			rval = 1;
383 			continue;
384 		}
385 	}
386 	/*
387 	 * We are here only when infile is open and we still have something
388 	 * to read from it.
389 	 *
390 	 * Use fgetln so that we can handle essentially infinite input data.
391 	 * Can't use the pointer into the stdio buffer as the process space
392 	 * because the ungetc() can cause it to move.
393 	 */
394 	p = fgetln(infile, &len);
395 	if (ferror(infile))
396 		errx(1, "%s: %s", fname, strerror(errno ? errno : EIO));
397 	if (len != 0 && p[len - 1] == '\n')
398 		len--;
399 	cspace(sp, p, len, spflag);
400 
401 	linenum++;
402 
403 	return (1);
404 }
405 
406 /*
407  * Add a compilation unit to the linked list
408  */
409 static void
410 add_compunit(enum e_cut type, char *s)
411 {
412 	struct s_compunit *cu;
413 
414 	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
415 		err(1, "malloc");
416 	cu->type = type;
417 	cu->s = s;
418 	cu->next = NULL;
419 	*cu_nextp = cu;
420 	cu_nextp = &cu->next;
421 }
422 
423 /*
424  * Add a file to the linked list
425  */
426 static void
427 add_file(char *s)
428 {
429 	struct s_flist *fp;
430 
431 	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
432 		err(1, "malloc");
433 	fp->next = NULL;
434 	*fl_nextp = fp;
435 	fp->fname = s;
436 	fl_nextp = &fp->next;
437 }
438 
439 int
440 lastline(void)
441 {
442 	int ch;
443 
444 	if (files->next != NULL)
445 		return (0);
446 	if ((ch = getc(infile)) == EOF)
447 		return (1);
448 	ungetc(ch, infile);
449 	return (0);
450 }
451