Merge commit '8dff7262702aa449609f24db11ec821f1fa34bf6'
[unleashed.git] / bin / sed / main.c
blobddc01fd71018475f2ec7d7343b0f092f619d6a61
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.
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
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.
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.
35 #include <sys/types.h>
36 #include <sys/mman.h>
37 #include <sys/param.h>
38 #include <sys/stat.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <libgen.h>
44 #include <limits.h>
45 #include <locale.h>
46 #include <regex.h>
47 #include <stddef.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
53 #include "defs.h"
54 #include "extern.h"
55 #include "freebsd-compat.h"
58 * Linked list of units (strings and files) to be compiled
60 struct s_compunit {
61 struct s_compunit *next;
62 enum e_cut {CU_FILE, CU_STRING} type;
63 char *s; /* Pointer to string or fname */
67 * Linked list pointer to compilation units and pointer to current
68 * next pointer.
70 static struct s_compunit *script, **cu_nextp = &script;
73 * Linked list of files to be processed
75 struct s_flist {
76 char *fname;
77 struct s_flist *next;
81 * Linked list pointer to files and pointer to current
82 * next pointer.
84 static struct s_flist *files, **fl_nextp = &files;
86 FILE *infile; /* Current input file */
87 FILE *outfile; /* Current output file */
89 int aflag, eflag, nflag;
90 int rflags = 0;
91 static int rval; /* Exit status */
93 static int ispan; /* Whether inplace editing spans across files */
96 * Current file and line number; line numbers restart across compilation
97 * units, but span across input files. The latter is optional if editing
98 * in place.
100 const char *fname; /* File name. */
101 const char *outfname; /* Output file name */
102 static char oldfname[PATH_MAX]; /* Old file name (for in-place editing) */
103 static char tmpfname[PATH_MAX]; /* Temporary file name (for in-place editing) */
104 static const char *inplace; /* Inplace edit file extension. */
105 u_long linenum;
107 static void add_compunit(enum e_cut, char *);
108 static void add_file(char *);
109 static void usage(void);
112 main(int argc, char *argv[])
114 int c, fflag;
115 char *temp_arg;
117 (void) setlocale(LC_ALL, "");
119 fflag = 0;
120 inplace = NULL;
122 while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1)
123 switch (c) {
124 case 'r': /* Gnu sed compat */
125 case 'E':
126 rflags = REG_EXTENDED;
127 break;
128 case 'I':
129 inplace = optarg;
130 ispan = 1; /* span across input files */
131 break;
132 case 'a':
133 aflag = 1;
134 break;
135 case 'e':
136 eflag = 1;
137 if ((temp_arg = malloc(strlen(optarg) + 2)) == NULL)
138 err(1, "malloc");
139 strcpy(temp_arg, optarg);
140 strcat(temp_arg, "\n");
141 add_compunit(CU_STRING, temp_arg);
142 break;
143 case 'f':
144 fflag = 1;
145 add_compunit(CU_FILE, optarg);
146 break;
147 case 'i':
148 inplace = optarg;
149 ispan = 0; /* don't span across input files */
150 break;
151 case 'l':
152 if(setvbuf(stdout, NULL, _IOLBF, 0) != 0)
153 warnx("setting line buffered output failed");
154 break;
155 case 'n':
156 nflag = 1;
157 break;
158 case 'u':
159 if(setvbuf(stdout, NULL, _IONBF, 0) != 0)
160 warnx("setting unbuffered output failed");
161 break;
162 default:
163 case '?':
164 usage();
166 argc -= optind;
167 argv += optind;
169 /* First usage case; script is the first arg */
170 if (!eflag && !fflag && *argv) {
171 add_compunit(CU_STRING, *argv);
172 argv++;
175 compile();
177 /* Continue with first and start second usage */
178 if (*argv)
179 for (; *argv; argv++)
180 add_file(*argv);
181 else
182 add_file(NULL);
183 process();
184 cfclose(prog, NULL);
185 if (fclose(stdout))
186 err(1, "stdout");
187 exit(rval);
190 static void
191 usage(void)
193 (void)fprintf(stderr,
194 "usage: %s script [-Ealnru] [-i extension] [file ...]\n"
195 "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]"
196 " ... [file ...]\n", getprogname(), getprogname());
197 exit(1);
201 * Like fgets, but go through the chain of compilation units chaining them
202 * together. Empty strings and files are ignored.
204 char *
205 cu_fgets(char *buf, int n, int *more)
207 static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF;
208 static FILE *f; /* Current open file */
209 static char *s; /* Current pointer inside string */
210 static char string_ident[30];
211 char *p;
213 again:
214 switch (state) {
215 case ST_EOF:
216 if (script == NULL) {
217 if (more != NULL)
218 *more = 0;
219 return (NULL);
221 linenum = 0;
222 switch (script->type) {
223 case CU_FILE:
224 if ((f = fopen(script->s, "r")) == NULL)
225 err(1, "%s", script->s);
226 fname = script->s;
227 state = ST_FILE;
228 goto again;
229 case CU_STRING:
230 if (((size_t)snprintf(string_ident,
231 sizeof(string_ident), "\"%s\"", script->s)) >=
232 sizeof(string_ident) - 1)
233 (void)strcpy(string_ident +
234 sizeof(string_ident) - 6, " ...\"");
235 fname = string_ident;
236 s = script->s;
237 state = ST_STRING;
238 goto again;
240 case ST_FILE:
241 if ((p = fgets(buf, n, f)) != NULL) {
242 linenum++;
243 if (linenum == 1 && buf[0] == '#' && buf[1] == 'n')
244 nflag = 1;
245 if (more != NULL)
246 *more = !feof(f);
247 return (p);
249 script = script->next;
250 (void)fclose(f);
251 state = ST_EOF;
252 goto again;
253 case ST_STRING:
254 if (linenum == 0 && s[0] == '#' && s[1] == 'n')
255 nflag = 1;
256 p = buf;
257 for (;;) {
258 if (n-- <= 1) {
259 *p = '\0';
260 linenum++;
261 if (more != NULL)
262 *more = 1;
263 return (buf);
265 switch (*s) {
266 case '\0':
267 state = ST_EOF;
268 if (s == script->s) {
269 script = script->next;
270 goto again;
271 } else {
272 script = script->next;
273 *p = '\0';
274 linenum++;
275 if (more != NULL)
276 *more = 0;
277 return (buf);
279 case '\n':
280 *p++ = '\n';
281 *p = '\0';
282 s++;
283 linenum++;
284 if (more != NULL)
285 *more = 0;
286 return (buf);
287 default:
288 *p++ = *s++;
292 /* NOTREACHED */
293 return (NULL);
297 * Like fgets, but go through the list of files chaining them together.
298 * Set len to the length of the line.
301 mf_fgets(SPACE *sp, enum e_spflag spflag)
303 struct stat sb;
304 ssize_t len;
305 char *dirbuf, *basebuf;
306 static char *p = NULL;
307 static size_t plen = 0;
308 int c;
309 static int firstfile;
311 if (infile == NULL) {
312 /* stdin? */
313 if (files->fname == NULL) {
314 if (inplace != NULL)
315 errx(1, "-I or -i may not be used with stdin");
316 infile = stdin;
317 fname = "stdin";
318 outfile = stdout;
319 outfname = "stdout";
321 firstfile = 1;
324 for (;;) {
325 if (infile != NULL && (c = getc(infile)) != EOF) {
326 (void)ungetc(c, infile);
327 break;
329 /* If we are here then either eof or no files are open yet */
330 if (infile == stdin) {
331 sp->len = 0;
332 return (0);
334 if (infile != NULL) {
335 fclose(infile);
336 if (*oldfname != '\0') {
337 /* if there was a backup file, remove it */
338 unlink(oldfname);
340 * Backup the original. Note that hard links
341 * are not supported on all filesystems.
343 if ((link(fname, oldfname) != 0) &&
344 (rename(fname, oldfname) != 0)) {
345 warn("rename()");
346 if (*tmpfname)
347 unlink(tmpfname);
348 exit(1);
350 *oldfname = '\0';
352 if (*tmpfname != '\0') {
353 if (outfile != NULL && outfile != stdout)
354 if (fclose(outfile) != 0) {
355 warn("fclose()");
356 unlink(tmpfname);
357 exit(1);
359 outfile = NULL;
360 if (rename(tmpfname, fname) != 0) {
361 /* this should not happen really! */
362 warn("rename()");
363 unlink(tmpfname);
364 exit(1);
366 *tmpfname = '\0';
368 outfname = NULL;
370 if (firstfile == 0)
371 files = files->next;
372 else
373 firstfile = 0;
374 if (files == NULL) {
375 sp->len = 0;
376 return (0);
378 fname = files->fname;
379 if (inplace != NULL) {
380 if (lstat(fname, &sb) != 0)
381 err(1, "%s", fname);
382 if (!(sb.st_mode & S_IFREG))
383 errx(1, "%s: %s %s", fname,
384 "in-place editing only",
385 "works for regular files");
386 if (*inplace != '\0') {
387 strlcpy(oldfname, fname,
388 sizeof(oldfname));
389 len = strlcat(oldfname, inplace,
390 sizeof(oldfname));
391 if (len > (ssize_t)sizeof(oldfname))
392 errx(1, "%s: name too long", fname);
394 if ((dirbuf = strdup(fname)) == NULL ||
395 (basebuf = strdup(fname)) == NULL)
396 err(1, "strdup");
397 len = snprintf(tmpfname, sizeof(tmpfname),
398 "%s/.!%ld!%s", dirname(dirbuf), (long)getpid(),
399 basename(basebuf));
400 free(dirbuf);
401 free(basebuf);
402 if (len >= (ssize_t)sizeof(tmpfname))
403 errx(1, "%s: name too long", fname);
404 unlink(tmpfname);
405 if (outfile != NULL && outfile != stdout)
406 fclose(outfile);
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();
416 } else {
417 outfile = stdout;
418 outfname = "stdout";
420 if ((infile = fopen(fname, "r")) == NULL) {
421 warn("%s", fname);
422 rval = 1;
423 continue;
427 * We are here only when infile is open and we still have something
428 * to read from it.
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.
434 len = getline(&p, &plen, infile);
435 if (len == -1)
436 err(1, "%s", fname);
437 if (len != 0 && p[len - 1] == '\n') {
438 sp->append_newline = 1;
439 len--;
440 } else if (!lastline()) {
441 sp->append_newline = 1;
442 } else {
443 sp->append_newline = 0;
445 cspace(sp, p, len, spflag);
447 linenum++;
449 return (1);
453 * Add a compilation unit to the linked list
455 static void
456 add_compunit(enum e_cut type, char *s)
458 struct s_compunit *cu;
460 if ((cu = malloc(sizeof(struct s_compunit))) == NULL)
461 err(1, "malloc");
462 cu->type = type;
463 cu->s = s;
464 cu->next = NULL;
465 *cu_nextp = cu;
466 cu_nextp = &cu->next;
470 * Add a file to the linked list
472 static void
473 add_file(char *s)
475 struct s_flist *fp;
477 if ((fp = malloc(sizeof(struct s_flist))) == NULL)
478 err(1, "malloc");
479 fp->next = NULL;
480 *fl_nextp = fp;
481 fp->fname = s;
482 fl_nextp = &fp->next;
485 static int
486 next_files_have_lines(void)
488 struct s_flist *file;
489 FILE *file_fd;
490 int ch;
492 file = files;
493 while ((file = file->next) != NULL) {
494 if ((file_fd = fopen(file->fname, "r")) == NULL)
495 continue;
497 if ((ch = getc(file_fd)) != EOF) {
499 * This next file has content, therefore current
500 * file doesn't contains the last line.
502 ungetc(ch, file_fd);
503 fclose(file_fd);
504 return (1);
507 fclose(file_fd);
510 return (0);
514 lastline(void)
516 int ch;
518 if (feof(infile)) {
519 return !(
520 (inplace == NULL || ispan) &&
521 next_files_have_lines());
523 if ((ch = getc(infile)) == EOF) {
524 return !(
525 (inplace == NULL || ispan) &&
526 next_files_have_lines());
528 ungetc(ch, infile);
529 return (0);