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