main.c revision 1.28
1/*	$NetBSD: main.c,v 1.28 2014/06/21 17:43:04 christos 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.28 2014/06/21 17:43:04 christos 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::lnru")) != -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		case 'u':
181#ifdef _IONBF
182			c = setvbuf(stdout, NULL, _IONBF, 0);
183#else
184			c = -1;
185			errno = EOPNOTSUPP;
186#endif
187			if (c)
188				warn("setting unbuffered output failed");
189			break;
190		default:
191		case '?':
192			usage();
193		}
194	argc -= optind;
195	argv += optind;
196
197	/* First usage case; script is the first arg */
198	if (!eflag && !fflag && *argv) {
199		add_compunit(CU_STRING, *argv);
200		argv++;
201	}
202
203	compile();
204
205	/* Continue with first and start second usage */
206	if (*argv)
207		for (; *argv; argv++)
208			add_file(*argv);
209	else
210		add_file(NULL);
211	process();
212	cfclose(prog, NULL);
213	if (fclose(stdout))
214		err(1, "stdout");
215	exit(rval);
216}
217
218static void
219usage(void)
220{
221	(void)fprintf(stderr,
222	    "Usage:  %s [-aElnru] command [file ...]\n"
223	    "\t%s [-aElnru] [-e command] [-f command_file] [-I[extension]]\n"
224	    "\t    [-i[extension]] [file ...]\n", getprogname(), getprogname());
225	exit(1);
226}
227
228/*
229 * Like fgets, but go through the chain of compilation units chaining them
230 * together.  Empty strings and files are ignored.
231 */
232char *
233cu_fgets(char *buf, int n, int *more)
234{
235	static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
236	static FILE *f;		/* Current open file */
237	static char *s;		/* Current pointer inside string */
238	static char string_ident[30];
239	char *p;
240
241again:
242	switch (state) {
243	case ST_EOF:
244		if (script == NULL) {
245			if (more != NULL)
246				*more = 0;
247			return (NULL);
248		}
249		linenum = 0;
250		switch (script->type) {
251		case CU_FILE:
252			if ((f = fopen(script->s, "r")) == NULL)
253				err(1, "%s", script->s);
254			fname = script->s;
255			state = ST_FILE;
256			goto again;
257		case CU_STRING:
258			if (((size_t)snprintf(string_ident,
259			    sizeof(string_ident), "\"%s\"", script->s)) >=
260			    sizeof(string_ident) - 1)
261				(void)strcpy(string_ident +
262				    sizeof(string_ident) - 6, " ...\"");
263			fname = string_ident;
264			s = script->s;
265			state = ST_STRING;
266			goto again;
267		}
268	case ST_FILE:
269		if ((p = fgets(buf, n, f)) != NULL) {
270			linenum++;
271			if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
272				nflag = 1;
273			if (more != NULL)
274				*more = !feof(f);
275			return (p);
276		}
277		script = script->next;
278		(void)fclose(f);
279		state = ST_EOF;
280		goto again;
281	case ST_STRING:
282		if (linenum == 0 && s[0] == '#' && s[1] == 'n')
283			nflag = 1;
284		p = buf;
285		for (;;) {
286			if (n-- <= 1) {
287				*p = '\0';
288				linenum++;
289				if (more != NULL)
290					*more = 1;
291				return (buf);
292			}
293			switch (*s) {
294			case '\0':
295				state = ST_EOF;
296				if (s == script->s) {
297					script = script->next;
298					goto again;
299				} else {
300					script = script->next;
301					*p = '\0';
302					linenum++;
303					if (more != NULL)
304						*more = 0;
305					return (buf);
306				}
307			case '\n':
308				*p++ = '\n';
309				*p = '\0';
310				s++;
311				linenum++;
312				if (more != NULL)
313					*more = 0;
314				return (buf);
315			default:
316				*p++ = *s++;
317			}
318		}
319	}
320	/* NOTREACHED */
321	return (NULL);
322}
323
324/*
325 * Like fgets, but go through the list of files chaining them together.
326 * Set len to the length of the line.
327 */
328int
329mf_fgets(SPACE *sp, enum e_spflag spflag)
330{
331	struct stat sb;
332	size_t len;
333	static char *p = NULL;
334	static size_t plen = 0;
335	int c;
336	static int firstfile;
337
338	if (infile == NULL) {
339		/* stdin? */
340		if (files->fname == NULL) {
341			if (inplace != NULL)
342				errx(1, "-I or -i may not be used with stdin");
343			infile = stdin;
344			fname = "stdin";
345			outfile = stdout;
346			outfname = "stdout";
347		}
348		firstfile = 1;
349	}
350
351	for (;;) {
352		if (infile != NULL && (c = getc(infile)) != EOF) {
353			(void)ungetc(c, infile);
354			break;
355		}
356		/* If we are here then either eof or no files are open yet */
357		if (infile == stdin) {
358			sp->len = 0;
359			return (0);
360		}
361		if (infile != NULL) {
362			fclose(infile);
363			if (*oldfname != '\0') {
364				/* if there was a backup file, remove it */
365				unlink(oldfname);
366				/*
367				 * Backup the original.  Note that hard links
368				 * are not supported on all filesystems.
369				 */
370				if ((link(fname, oldfname) != 0) &&
371				   (rename(fname, oldfname) != 0)) {
372					warn("rename()");
373					if (*tmpfname)
374						unlink(tmpfname);
375					exit(1);
376				}
377				*oldfname = '\0';
378			}
379			if (*tmpfname != '\0') {
380				if (outfile != NULL && outfile != stdout)
381					if (fclose(outfile) != 0) {
382						warn("fclose()");
383						unlink(tmpfname);
384						exit(1);
385					}
386				outfile = NULL;
387				if (rename(tmpfname, fname) != 0) {
388					/* this should not happen really! */
389					warn("rename()");
390					unlink(tmpfname);
391					exit(1);
392				}
393				*tmpfname = '\0';
394			}
395			outfname = NULL;
396		}
397		if (firstfile == 0)
398			files = files->next;
399		else
400			firstfile = 0;
401		if (files == NULL) {
402			sp->len = 0;
403			return (0);
404		}
405		fname = files->fname;
406		if (inplace != NULL) {
407			if (lstat(fname, &sb) != 0)
408				err(1, "%s", fname);
409			if (!(sb.st_mode & S_IFREG))
410				errx(1, "%s: %s %s", fname,
411				    "in-place editing only",
412				    "works for regular files");
413			if (*inplace != '\0') {
414				strlcpy(oldfname, fname,
415				    sizeof(oldfname));
416				len = strlcat(oldfname, inplace,
417				    sizeof(oldfname));
418				if (len > sizeof(oldfname))
419					errx(1, "%s: name too long", fname);
420			}
421			char d_name[PATH_MAX], f_name[PATH_MAX];
422			(void)strlcpy(d_name, fname, sizeof(d_name));
423			(void)strlcpy(f_name, fname, sizeof(f_name));
424			len = (size_t)snprintf(tmpfname, sizeof(tmpfname),
425			    "%s/.!%ld!%s", dirname(d_name), (long)getpid(),
426			    basename(f_name));
427			if (len >= sizeof(tmpfname))
428				errx(1, "%s: name too long", fname);
429			unlink(tmpfname);
430			if (outfile != NULL && outfile != stdout)
431				flose(outfile);
432			if ((outfile = fopen(tmpfname, "w")) == NULL)
433				err(1, "%s", fname);
434			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
435			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
436			outfname = tmpfname;
437			if (!ispan) {
438				linenum = 0;
439				resetstate();
440			}
441		} else {
442			outfile = stdout;
443			outfname = "stdout";
444		}
445		if ((infile = fopen(fname, "r")) == NULL) {
446			warn("%s", fname);
447			rval = 1;
448			continue;
449		}
450	}
451	/*
452	 * We are here only when infile is open and we still have something
453	 * to read from it.
454	 *
455	 * Use getline() so that we can handle essentially infinite input
456	 * data.  The p and plen are static so each invocation gives
457	 * getline() the same buffer which is expanded as needed.
458	 */
459	ssize_t slen = getline(&p, &plen, infile);
460	if (slen == -1)
461		err(1, "%s", fname);
462	if (slen != 0 && p[slen - 1] == '\n')
463		slen--;
464	cspace(sp, p, (size_t)slen, spflag);
465
466	linenum++;
467
468	return (1);
469}
470
471/*
472 * Add a compilation unit to the linked list
473 */
474static void
475add_compunit(enum e_cut type, char *s)
476{
477	struct s_compunit *cu;
478
479	cu = xmalloc(sizeof(struct s_compunit));
480	cu->type = type;
481	cu->s = s;
482	cu->next = NULL;
483	*cu_nextp = cu;
484	cu_nextp = &cu->next;
485}
486
487/*
488 * Add a file to the linked list
489 */
490static void
491add_file(char *s)
492{
493	struct s_flist *fp;
494
495	fp = xmalloc(sizeof(struct s_flist));
496	fp->next = NULL;
497	*fl_nextp = fp;
498	fp->fname = s;
499	fl_nextp = &fp->next;
500}
501
502int
503lastline(void)
504{
505	int ch;
506
507	if (files->next != NULL && (inplace == NULL || ispan))
508		return (0);
509	if ((ch = getc(infile)) == EOF)
510		return (1);
511	ungetc(ch, infile);
512	return (0);
513}
514