main.c revision 98201
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: head/usr.bin/sed/main.c 98201 2002-06-14 02:20:05Z tjr $");
40
41#ifndef lint
42static 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
48static 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 */
73struct 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 */
83static struct s_compunit *script, **cu_nextp = &script;
84
85/*
86 * Linked list of files to be processed
87 */
88struct 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 */
97static struct s_flist *files, **fl_nextp = &files;
98
99int aflag, eflag, nflag;
100int rflags = 0;
101static int rval;		/* Exit status */
102
103/*
104 * Current file and line number; line numbers restart across compilation
105 * units, but span across input files.
106 */
107const char *fname;		/* File name. */
108const char *inplace;		/* Inplace edit file extension. */
109u_long linenum;
110int lastline;			/* TRUE on the last line of the last file */
111
112static void add_compunit(enum e_cut, char *);
113static void add_file(char *);
114static int inplace_edit(char **);
115static void usage(void);
116
117int
118main(argc, argv)
119	int argc;
120	char *argv[];
121{
122	int c, fflag;
123	char *temp_arg;
124
125	(void) setlocale(LC_ALL, "");
126
127	fflag = 0;
128	inplace = NULL;
129
130	while ((c = getopt(argc, argv, "Eae:f:i:n")) != -1)
131		switch (c) {
132		case 'E':
133			rflags = REG_EXTENDED;
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			break;
153		case 'n':
154			nflag = 1;
155			break;
156		default:
157		case '?':
158			usage();
159		}
160	argc -= optind;
161	argv += optind;
162
163	/* First usage case; script is the first arg */
164	if (!eflag && !fflag && *argv) {
165		add_compunit(CU_STRING, *argv);
166		argv++;
167	}
168
169	compile();
170
171	/* Continue with first and start second usage */
172	if (*argv)
173		for (; *argv; argv++)
174			add_file(*argv);
175	else
176		add_file(NULL);
177	process();
178	cfclose(prog, NULL);
179	if (fclose(stdout))
180		err(1, "stdout");
181	exit(rval);
182}
183
184static void
185usage()
186{
187	(void)fprintf(stderr, "%s\n%s\n",
188		"usage: sed script [-Ean] [-i extension] [file ...]",
189		"       sed [-an] [-i extension] [-e script] ... [-f script_file] ... [file ...]");
190	exit(1);
191}
192
193/*
194 * Like fgets, but go through the chain of compilation units chaining them
195 * together.  Empty strings and files are ignored.
196 */
197char *
198cu_fgets(buf, n, more)
199	char *buf;
200	int n;
201	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
209again:
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 */
296int
297mf_fgets(sp, spflag)
298	SPACE *sp;
299	enum e_spflag spflag;
300{
301	static FILE *f;		/* Current open file */
302	size_t len;
303	char *p;
304	int c;
305	static int firstfile;
306
307	if (f == NULL) {
308		/* stdin? */
309		if (files->fname == NULL) {
310			if (inplace != NULL)
311				errx(1, "-i may not be used with stdin");
312			f = stdin;
313			fname = "stdin";
314		}
315		firstfile = 1;
316	}
317
318	sp->len = 0;
319	for (;;) {
320		if (f != NULL && (c = getc(f)) != EOF) {
321			(void)ungetc(c, f);
322			break;
323		}
324		/* If we are here then either eof or no files are open yet */
325		if (f == stdin) {
326			lastline = 1;
327			return (0);
328		}
329		if (f != NULL) {
330			fclose(f);
331		}
332		if (firstfile == 0) {
333			files = files->next;
334		} else
335			firstfile = 0;
336		if (files == NULL) {
337			lastline = 1;
338			return (0);
339		}
340		if (inplace != NULL) {
341			if (inplace_edit(&files->fname) == -1)
342				continue;
343		}
344		fname = files->fname;
345		if ((f = fopen(fname, "r")) == NULL) {
346			warn("%s", fname);
347			rval = 1;
348			continue;
349		}
350		if (inplace != NULL && *inplace == '\0')
351			unlink(fname);
352	}
353	/*
354	 * We are here only when f is open and we still have something to
355	 * read from it.
356	 *
357	 * Use fgetln so that we can handle essentially infinite input data.
358	 * Can't use the pointer into the stdio buffer as the process space
359	 * because the ungetc() can cause it to move.
360	 */
361	p = fgetln(f, &len);
362	if (ferror(f))
363		errx(1, "%s: %s", fname, strerror(errno ? errno : EIO));
364	cspace(sp, p, len, spflag);
365
366	linenum++;
367	if (files->next == NULL) {
368		if ((c = getc(f)) != EOF) {
369			(void)ungetc(c, f);
370		} else {
371			lastline = 1;
372		}
373	}
374
375	return (1);
376}
377
378/*
379 * Add a compilation unit to the linked list
380 */
381static void
382add_compunit(type, s)
383	enum e_cut type;
384	char *s;
385{
386	struct s_compunit *cu;
387
388	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
389		err(1, "malloc");
390	cu->type = type;
391	cu->s = s;
392	cu->next = NULL;
393	*cu_nextp = cu;
394	cu_nextp = &cu->next;
395}
396
397/*
398 * Add a file to the linked list
399 */
400static void
401add_file(s)
402	char *s;
403{
404	struct s_flist *fp;
405
406	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
407		err(1, "malloc");
408	fp->next = NULL;
409	*fl_nextp = fp;
410	fp->fname = s;
411	fl_nextp = &fp->next;
412}
413
414/*
415 * Modify a pointer to a filename for inplace editing and reopen stdout
416 */
417static int
418inplace_edit(filename)
419	char **filename;
420{
421	struct stat orig;
422	int input, output;
423	char backup[MAXPATHLEN];
424	char *buffer;
425
426	if (lstat(*filename, &orig) == -1)
427		err(1, "lstat");
428	if ((orig.st_mode & S_IFREG) == 0) {
429		warnx("cannot inplace edit %s, not a regular file", *filename);
430		return -1;
431	}
432
433	if (*inplace == '\0') {
434		char template[] = "/tmp/sed.XXXXXXXXXX";
435
436		output = mkstemp(template);
437		if (output == -1)
438			err(1, "mkstemp");
439		strlcpy(backup, template, MAXPATHLEN);
440	} else {
441		strlcpy(backup, *filename, MAXPATHLEN);
442		strlcat(backup, inplace, MAXPATHLEN);
443		output = open(backup, O_WRONLY | O_CREAT | O_TRUNC);
444		if (output == -1)
445			err(1, "open(%s)", backup);
446	}
447
448	input = open(*filename, O_RDONLY);
449	if (input == -1)
450		err(1, "open(%s)", *filename);
451	if (fchmod(output, orig.st_mode & ~S_IFMT) == -1)
452		err(1, "chmod");
453	buffer = (char *)mmap(0, orig.st_size, PROT_READ, MAP_SHARED, input, 0);
454	if (buffer == MAP_FAILED)
455		err(1, "mmap(%s)", *filename);
456	if (write(output, buffer, orig.st_size) == -1)
457		err(1, "write(%s)", backup);
458	if (munmap(buffer, orig.st_size) == -1)
459		err(1, "munmap(%s)", *filename);
460	close(input);
461	close(output);
462	freopen(*filename, "w", stdout);
463	*filename = strdup(backup);
464	return 0;
465}
466