main.c revision 96175
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 96175 2002-05-07 18:32:18Z jmallett $");
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/param.h>
52#include <sys/stat.h>
53
54#include <err.h>
55#include <errno.h>
56#include <fcntl.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 */
71struct 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 */
81static struct s_compunit *script, **cu_nextp = &script;
82
83/*
84 * Linked list of files to be processed
85 */
86struct 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 */
95static struct s_flist *files, **fl_nextp = &files;
96
97int aflag, eflag, nflag;
98int rflags = 0;
99
100/*
101 * Current file and line number; line numbers restart across compilation
102 * units, but span across input files.
103 */
104const char *fname;		/* File name. */
105const char *inplace;		/* Inplace edit file extension. */
106u_long linenum;
107int lastline;			/* TRUE on the last line of the last file */
108
109static void add_compunit(enum e_cut, char *);
110static void add_file(char *);
111static int inplace_edit(char **);
112static void usage(void);
113
114int
115main(argc, argv)
116	int argc;
117	char *argv[];
118{
119	int c, fflag;
120	char *temp_arg;
121
122	(void) setlocale(LC_ALL, "");
123
124	fflag = 0;
125	inplace = NULL;
126
127	while ((c = getopt(argc, argv, "Eae:f:i:n")) != -1)
128		switch (c) {
129		case 'E':
130			rflags = REG_EXTENDED;
131			break;
132		case 'a':
133			aflag = 1;
134			break;
135		case 'e':
136			eflag = 1;
137			if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
138				err(1, "malloc");
139			strcpy(temp_arg, optarg);
140			strcat(temp_arg, "\n");
141			add_compunit(CU_STRING, temp_arg);
142			break;
143		case 'f':
144			fflag = 1;
145			add_compunit(CU_FILE, optarg);
146			break;
147		case 'i':
148			inplace = optarg;
149			break;
150		case 'n':
151			nflag = 1;
152			break;
153		default:
154		case '?':
155			usage();
156		}
157	argc -= optind;
158	argv += optind;
159
160	/* First usage case; script is the first arg */
161	if (!eflag && !fflag && *argv) {
162		add_compunit(CU_STRING, *argv);
163		argv++;
164	}
165
166	compile();
167
168	/* Continue with first and start second usage */
169	if (*argv)
170		for (; *argv; argv++)
171			add_file(*argv);
172	else
173		add_file(NULL);
174	process();
175	cfclose(prog, NULL);
176	if (fclose(stdout))
177		err(1, "stdout");
178	exit (0);
179}
180
181static void
182usage()
183{
184	(void)fprintf(stderr, "%s\n%s\n",
185		"usage: sed script [-Ean] [file ...]",
186		"       sed [-an] [-e script] ... [-f script_file] ... [file ...]");
187	exit(1);
188}
189
190/*
191 * Like fgets, but go through the chain of compilation units chaining them
192 * together.  Empty strings and files are ignored.
193 */
194char *
195cu_fgets(buf, n, more)
196	char *buf;
197	int n;
198	int *more;
199{
200	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
201	static FILE *f;		/* Current open file */
202	static char *s;		/* Current pointer inside string */
203	static char string_ident[30];
204	char *p;
205
206again:
207	switch (state) {
208	case ST_EOF:
209		if (script == NULL) {
210			if (more != NULL)
211				*more = 0;
212			return (NULL);
213		}
214		linenum = 0;
215		switch (script->type) {
216		case CU_FILE:
217			if ((f = fopen(script->s, "r")) == NULL)
218				err(1, "%s", script->s);
219			fname = script->s;
220			state = ST_FILE;
221			goto again;
222		case CU_STRING:
223			if ((snprintf(string_ident,
224			    sizeof(string_ident), "\"%s\"", script->s)) >=
225			    sizeof(string_ident) - 1)
226				(void)strcpy(string_ident +
227				    sizeof(string_ident) - 6, " ...\"");
228			fname = string_ident;
229			s = script->s;
230			state = ST_STRING;
231			goto again;
232		}
233	case ST_FILE:
234		if ((p = fgets(buf, n, f)) != NULL) {
235			linenum++;
236			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
237				nflag = 1;
238			if (more != NULL)
239				*more = !feof(f);
240			return (p);
241		}
242		script = script->next;
243		(void)fclose(f);
244		state = ST_EOF;
245		goto again;
246	case ST_STRING:
247		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
248			nflag = 1;
249		p = buf;
250		for (;;) {
251			if (n-- <= 1) {
252				*p = '\0';
253				linenum++;
254				if (more != NULL)
255					*more = 1;
256				return (buf);
257			}
258			switch (*s) {
259			case '\0':
260				state = ST_EOF;
261				if (s == script->s) {
262					script = script->next;
263					goto again;
264				} else {
265					script = script->next;
266					*p = '\0';
267					linenum++;
268					if (more != NULL)
269						*more = 0;
270					return (buf);
271				}
272			case '\n':
273				*p++ = '\n';
274				*p = '\0';
275				s++;
276				linenum++;
277				if (more != NULL)
278					*more = 0;
279				return (buf);
280			default:
281				*p++ = *s++;
282			}
283		}
284	}
285	/* NOTREACHED */
286	return (NULL);
287}
288
289/*
290 * Like fgets, but go through the list of files chaining them together.
291 * Set len to the length of the line.
292 */
293int
294mf_fgets(sp, spflag)
295	SPACE *sp;
296	enum e_spflag spflag;
297{
298	static FILE *f;		/* Current open file */
299	size_t len;
300	char *p;
301	int c;
302
303	if (f == NULL)
304		/* Advance to first non-empty file */
305		for (;;) {
306			if (files == NULL) {
307				lastline = 1;
308				return (0);
309			}
310			if (files->fname == NULL) {
311				if (inplace != NULL)
312					errx(1, "-i may not be used with stdin");
313				f = stdin;
314				fname = "stdin";
315			} else {
316				if (inplace != NULL) {
317					if (inplace_edit(&files->fname) == -1)
318						continue;
319				}
320				fname = files->fname;
321				if ((f = fopen(fname, "r")) == NULL)
322					err(1, "%s", fname);
323			}
324			if ((c = getc(f)) != EOF) {
325				(void)ungetc(c, f);
326				break;
327			}
328			(void)fclose(f);
329			files = files->next;
330		}
331
332	if (lastline) {
333		sp->len = 0;
334		return (0);
335	}
336
337	/*
338	 * Use fgetln so that we can handle essentially infinite input data.
339	 * Can't use the pointer into the stdio buffer as the process space
340	 * because the ungetc() can cause it to move.
341	 */
342	p = fgetln(f, &len);
343	if (ferror(f))
344		errx(1, "%s: %s", fname, strerror(errno ? errno : EIO));
345	cspace(sp, p, len, spflag);
346
347	linenum++;
348	/* Advance to next non-empty file */
349	while ((c = getc(f)) == EOF) {
350		(void)fclose(f);
351		files = files->next;
352		if (files == NULL) {
353			lastline = 1;
354			return (1);
355		}
356		if (files->fname == NULL) {
357			if (inplace != NULL)
358				errx(1, "-i may not be used with stdin");
359			f = stdin;
360			fname = "stdin";
361		} else {
362			if (inplace != NULL) {
363				if (inplace_edit(&files->fname) == -1)
364					continue;
365			}
366			fname = files->fname;
367			if ((f = fopen(fname, "r")) == NULL)
368				err(1, "%s", fname);
369		}
370	}
371	(void)ungetc(c, f);
372	return (1);
373}
374
375/*
376 * Add a compilation unit to the linked list
377 */
378static void
379add_compunit(type, s)
380	enum e_cut type;
381	char *s;
382{
383	struct s_compunit *cu;
384
385	if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
386		err(1, "malloc");
387	cu->type = type;
388	cu->s = s;
389	cu->next = NULL;
390	*cu_nextp = cu;
391	cu_nextp = &cu->next;
392}
393
394/*
395 * Add a file to the linked list
396 */
397static void
398add_file(s)
399	char *s;
400{
401	struct s_flist *fp;
402
403	if ((fp = malloc(sizeof(struct s_flist))) == NULL)
404		err(1, "malloc");
405	fp->next = NULL;
406	*fl_nextp = fp;
407	fp->fname = s;
408	fl_nextp = &fp->next;
409}
410
411/*
412 * Modify a pointer to a filename for inplace editing and reopen stdout
413 */
414static int
415inplace_edit(fname)
416	char **fname;
417{
418	struct stat orig;
419	int input, output;
420	char backup[MAXPATHLEN];
421	char *buffer;
422
423	if (lstat(*fname, &orig) == -1)
424		err(1, "lstat");
425	if ((orig.st_mode & S_IFREG) == 0) {
426		warnx("cannot inplace edit %s, not a regular file", fname);
427		return -1;
428	}
429
430	strlcpy(backup, *fname, MAXPATHLEN);
431	strlcat(backup, inplace, MAXPATHLEN);
432
433	input = open(*fname, O_RDONLY);
434	if (input == -1)
435		err(1, "open(%s)", fname);
436	output = open(backup, O_WRONLY|O_CREAT);
437	if (output == -1)
438		err(1, "open(%s)", backup);
439	if (fchmod(output, orig.st_mode & ~S_IFMT) == -1)
440		err(1, "chmod");
441	buffer = malloc(orig.st_size);
442	if (buffer == NULL)
443		errx(1, "malloc failed");
444	if (read(input, buffer, orig.st_size) == -1)
445		err(1, "read");
446	if (write(output, buffer, orig.st_size) == -1)
447		err(1, "write");
448	close(input);
449	close(output);
450	freopen(*fname, "w", stdout);
451	*fname = strdup(backup);
452	return 0;
453}
454