Home | History | Annotate | Line # | Download | only in sed
main.c revision 1.25
      1 /*	$NetBSD: main.c,v 1.25 2014/06/17 16:39:02 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.25 2014/06/17 16:39:02 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  */
     77 struct 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  */
     87 static struct s_compunit *script, **cu_nextp = &script;
     88 
     89 /*
     90  * Linked list of files to be processed
     91  */
     92 struct 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  */
    101 static struct s_flist *files, **fl_nextp = &files;
    102 
    103 FILE *infile;			/* Current input file */
    104 FILE *outfile;			/* Current output file */
    105 
    106 int aflag, eflag, nflag;
    107 int rflags = 0;
    108 static int rval;		/* Exit status */
    109 
    110 static 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  */
    117 const char *fname;		/* File name. */
    118 const char *outfname;		/* Output file name */
    119 static char oldfname[PATH_MAX];	/* Old file name (for in-place editing) */
    120 static char tmpfname[PATH_MAX];	/* Temporary file name (for in-place editing) */
    121 static const char *inplace;	/* Inplace edit file extension. */
    122 u_long linenum;
    123 
    124 static void add_compunit(enum e_cut, char *);
    125 static void add_file(char *);
    126 static void usage(void) __dead;
    127 
    128 int
    129 main(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 
    218 static void
    219 usage(void)
    220 {
    221 	(void)fprintf(stderr,
    222 	    "Usage: %s script [-Ealnu] [-i[<extension>]] [file ...]\n"
    223 	    "\t%s [-Ealnu] [-i[<extension>]] [-e script] ... [-f script_file]"
    224 	    " ... [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  */
    232 char *
    233 cu_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 
    241 again:
    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  */
    328 int
    329 mf_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 = fopen(tmpfname, "w")) == NULL)
    431 				err(1, "%s", fname);
    432 			fchown(fileno(outfile), sb.st_uid, sb.st_gid);
    433 			fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
    434 			outfname = tmpfname;
    435 			if (!ispan) {
    436 				linenum = 0;
    437 				resetstate();
    438 			}
    439 		} else {
    440 			outfile = stdout;
    441 			outfname = "stdout";
    442 		}
    443 		if ((infile = fopen(fname, "r")) == NULL) {
    444 			warn("%s", fname);
    445 			rval = 1;
    446 			continue;
    447 		}
    448 	}
    449 	/*
    450 	 * We are here only when infile is open and we still have something
    451 	 * to read from it.
    452 	 *
    453 	 * Use getline() so that we can handle essentially infinite input
    454 	 * data.  The p and plen are static so each invocation gives
    455 	 * getline() the same buffer which is expanded as needed.
    456 	 */
    457 	ssize_t slen = getline(&p, &plen, infile);
    458 	if (slen == -1)
    459 		err(1, "%s", fname);
    460 	if (slen != 0 && p[slen - 1] == '\n')
    461 		slen--;
    462 	cspace(sp, p, (size_t)slen, spflag);
    463 
    464 	linenum++;
    465 
    466 	return (1);
    467 }
    468 
    469 /*
    470  * Add a compilation unit to the linked list
    471  */
    472 static void
    473 add_compunit(enum e_cut type, char *s)
    474 {
    475 	struct s_compunit *cu;
    476 
    477 	cu = xmalloc(sizeof(struct s_compunit));
    478 	cu->type = type;
    479 	cu->s = s;
    480 	cu->next = NULL;
    481 	*cu_nextp = cu;
    482 	cu_nextp = &cu->next;
    483 }
    484 
    485 /*
    486  * Add a file to the linked list
    487  */
    488 static void
    489 add_file(char *s)
    490 {
    491 	struct s_flist *fp;
    492 
    493 	fp = xmalloc(sizeof(struct s_flist));
    494 	fp->next = NULL;
    495 	*fl_nextp = fp;
    496 	fp->fname = s;
    497 	fl_nextp = &fp->next;
    498 }
    499 
    500 int
    501 lastline(void)
    502 {
    503 	int ch;
    504 
    505 	if (files->next != NULL && (inplace == NULL || ispan))
    506 		return (0);
    507 	if ((ch = getc(infile)) == EOF)
    508 		return (1);
    509 	ungetc(ch, infile);
    510 	return (0);
    511 }
    512