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.
7 * This code is derived from software contributed to Berkeley by
8 * Diomidis Spinellis of Imperial College, University of London.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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 * 3. 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.
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
34 * @(#) Copyright (c) 1992, 1993 The Regents of the University of California. All rights reserved.
35 * @(#)main.c 8.2 (Berkeley) 1/3/94
36 * $FreeBSD: head/usr.bin/sed/main.c 303662 2016-08-02 15:35:53Z pfg $
39 #include <sys/types.h>
41 #include <sys/param.h>
61 * Linked list of units (strings and files) to be compiled
64 struct s_compunit *next;
65 enum e_cut {CU_FILE, CU_STRING} type;
66 char *s; /* Pointer to string or fname */
70 * Linked list pointer to compilation units and pointer to current
73 static struct s_compunit *script, **cu_nextp = &script;
76 * Linked list of files to be processed
84 * Linked list pointer to files and pointer to current
87 static struct s_flist *files, **fl_nextp = &files;
89 FILE *infile; /* Current input file */
90 FILE *outfile; /* Current output file */
92 int aflag, eflag, nflag;
94 static int rval; /* Exit status */
96 static int ispan; /* Whether inplace editing spans across files */
99 * Current file and line number; line numbers restart across compilation
100 * units, but span across input files. The latter is optional if editing
103 const char *fname; /* File name. */
104 const char *outfname; /* Output file name */
105 static char oldfname[PATH_MAX]; /* Old file name (for in-place editing) */
106 static char tmpfname[PATH_MAX]; /* Temporary file name (for in-place editing) */
107 static const char *inplace; /* Inplace edit file extension. */
110 static void add_compunit(enum e_cut, char *);
111 static void add_file(char *);
112 static void usage(void);
115 main(int argc, char *argv[])
120 (void) setlocale(LC_ALL, "");
125 while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
127 case 'r': /* GNU sed compat */
129 rflags = REG_EXTENDED;
133 ispan = 1; /* span across input files */
140 if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
142 strcpy(temp_arg, optarg);
143 strcat(temp_arg, "\n");
144 add_compunit(CU_STRING, temp_arg);
148 add_compunit(CU_FILE, optarg);
152 ispan = 0; /* don't span across input files */
155 if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
156 warnx("setting line buffered output failed");
162 if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
163 warnx("setting unbuffered output failed");
172 /* First usage case; script is the first arg */
173 if (!eflag && !fflag && *argv) {
174 add_compunit(CU_STRING, *argv);
180 /* Continue with first and start second usage */
182 for (; *argv; argv++)
196 (void)fprintf(stderr,
197 "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
198 "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
199 " ... [file ...]\n", getprogname(), getprogname());
204 * Like fgets, but go through the chain of compilation units chaining them
205 * together. Empty strings and files are ignored.
208 cu_fgets(char *buf, int n, int *more)
210 static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
211 static FILE *f; /* Current open file */
212 static char *s; /* Current pointer inside string */
213 static char string_ident[30];
219 if (script == NULL) {
225 switch (script->type) {
227 if ((f = fopen(script->s, "r")) == NULL)
228 err(1, "%s", script->s);
233 if (((size_t)snprintf(string_ident,
234 sizeof(string_ident), "\"%s\"", script->s)) >=
235 sizeof(string_ident) - 1)
236 (void)strcpy(string_ident +
237 sizeof(string_ident) - 6, " ...\"");
238 fname = string_ident;
244 if ((p = fgets(buf, n, f)) != NULL) {
246 if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
252 script = script->next;
257 if (linenum == 0 && s[0] == '#' && s[1] == 'n')
271 if (s == script->s) {
272 script = script->next;
275 script = script->next;
300 * Like fgets, but go through the list of files chaining them together.
301 * Set len to the length of the line.
304 mf_fgets(SPACE *sp, enum e_spflag spflag)
308 char *dirbuf, *basebuf;
309 static char *p = NULL;
310 static size_t plen = 0;
312 static int firstfile;
314 if (infile == NULL) {
316 if (files->fname == NULL) {
318 errx(1, "-I or -i may not be used with stdin");
328 if (infile != NULL && (c = getc(infile)) != EOF) {
329 (void)ungetc(c, infile);
332 /* If we are here then either eof or no files are open yet */
333 if (infile == stdin) {
337 if (infile != NULL) {
339 if (*oldfname != '\0') {
340 /* if there was a backup file, remove it */
343 * Backup the original. Note that hard links
344 * are not supported on all filesystems.
346 if ((link(fname, oldfname) != 0) &&
347 (rename(fname, oldfname) != 0)) {
355 if (*tmpfname != '\0') {
356 if (outfile != NULL && outfile != stdout)
357 if (fclose(outfile) != 0) {
363 if (rename(tmpfname, fname) != 0) {
364 /* this should not happen really! */
381 fname = files->fname;
382 if (inplace != NULL) {
383 if (lstat(fname, &sb) != 0)
385 if (!(sb.st_mode & S_IFREG))
386 errx(1, "%s: %s %s", fname,
387 "in-place editing only",
388 "works for regular files");
389 if (*inplace != '\0') {
390 strlcpy(oldfname, fname,
392 len = strlcat(oldfname, inplace,
394 if (len > (ssize_t)sizeof(oldfname))
395 errx(1, "%s: name too long", fname);
397 if ((dirbuf = strdup(fname)) == NULL ||
398 (basebuf = strdup(fname)) == NULL)
400 len = snprintf(tmpfname, sizeof(tmpfname),
401 "%s/.!%ld!%s", dirname(dirbuf), (long)getpid(),
405 if (len >= (ssize_t)sizeof(tmpfname))
406 errx(1, "%s: name too long", fname);
408 if (outfile != NULL && outfile != stdout)
410 if ((outfile = fopen(tmpfname, "w")) == NULL)
412 fchown(fileno(outfile), sb.st_uid, sb.st_gid);
413 fchmod(fileno(outfile), sb.st_mode & ALLPERMS);
423 if ((infile = fopen(fname, "r")) == NULL) {
430 * We are here only when infile is open and we still have something
433 * Use getline() so that we can handle essentially infinite input
434 * data. The p and plen are static so each invocation gives
435 * getline() the same buffer which is expanded as needed.
437 len = getline(&p, &plen, infile);
440 if (len != 0 && p[len - 1] == '\n') {
441 sp->append_newline = 1;
443 } else if (!lastline()) {
444 sp->append_newline = 1;
446 sp->append_newline = 0;
448 cspace(sp, p, len, spflag);
456 * Add a compilation unit to the linked list
459 add_compunit(enum e_cut type, char *s)
461 struct s_compunit *cu;
463 if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
469 cu_nextp = &cu->next;
473 * Add a file to the linked list
480 if ((fp = malloc(sizeof(struct s_flist))) == NULL)
485 fl_nextp = &fp->next;
489 next_files_have_lines(void)
491 struct s_flist *file;
496 while ((file = file->next) != NULL) {
497 if ((file_fd = fopen(file->fname, "r")) == NULL)
500 if ((ch = getc(file_fd)) != EOF) {
502 * This next file has content, therefore current
503 * file doesn't contains the last line.
523 (inplace == NULL || ispan) &&
524 next_files_have_lines());
526 if ((ch = getc(infile)) == EOF) {
528 (inplace == NULL || ispan) &&
529 next_files_have_lines());