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