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. 6 * 7 * This code is derived from software contributed to Berkeley by 8 * Diomidis Spinellis of Imperial College, University of London. 9 * 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. 21 * 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. 33 */ 34 35 #include <sys/cdefs.h> 36 __FBSDID("$FreeBSD$"); 37 38 #ifndef lint 39 static const char copyright[] = 40 "@(#) Copyright (c) 1992, 1993\n\ 41 The Regents of the University of California. All rights reserved.\n"; 42 #endif 43 44 #ifndef lint 45 static const char sccsid[] = "@(#)main.c 8.2 (Berkeley) 1/3/94"; 46 #endif 47 48 #include <sys/types.h> 49 #include <sys/mman.h> 50 #include <sys/param.h> 51 #include <sys/stat.h> 52 53 #include <err.h> 54 #include <errno.h> 55 #include <fcntl.h> 56 #include <libgen.h> 57 #include <limits.h> 58 #include <locale.h> 59 #include <regex.h> 60 #include <stddef.h> 61 #define _WITH_GETLINE 62 #include <stdio.h> 63 #include <stdlib.h> 64 #include <string.h> 65 #include <unistd.h> 66 67 #include "defs.h" 68 #include "extern.h" 69 70 /* 71 * Linked list of units (strings and files) to be compiled 72 */ 73 struct s_compunit { 74 struct s_compunit *next; 75 enum e_cut {CU_FILE, CU_STRING} type; 76 const char *s; /* Pointer to string or fname */ 77 }; 78 79 /* 80 * Linked list pointer to compilation units and pointer to current 81 * next pointer. 82 */ 83 static struct s_compunit *script, **cu_nextp = &script; 84 85 /* 86 * Linked list of files to be processed 87 */ 88 struct s_flist { 89 const char *fname; 90 struct s_flist *next; 91 }; 92 93 /* 94 * Linked list pointer to files and pointer to current 95 * next pointer. 96 */ 97 static struct s_flist *files, **fl_nextp = &files; 98 99 FILE *infile; /* Current input file */ 100 FILE *outfile; /* Current output file */ 101 102 int aflag, eflag, nflag; 103 int rflags = 0; 104 static int rval; /* Exit status */ 105 106 static int ispan; /* Whether inplace editing spans across files */ 107 108 /* 109 * Current file and line number; line numbers restart across compilation 110 * units, but span across input files. The latter is optional if editing 111 * in place. 112 */ 113 const char *fname; /* File name. */ 114 const char *outfname; /* Output file name */ 115 static char oldfname[PATH_MAX]; /* Old file name (for in-place editing) */ 116 static char tmpfname[PATH_MAX]; /* Temporary file name (for in-place editing) */ 117 static const char *inplace; /* Inplace edit file extension. */ 118 u_long linenum; 119 120 static void add_compunit(enum e_cut, const char *); 121 static void add_file(const char *); 122 static void usage(void); 123 124 int 125 main(int argc, char *argv[]) 126 { 127 int c, fflag; 128 129 (void) setlocale(LC_ALL, ""); 130 131 fflag = 0; 132 inplace = NULL; 133 134 while ((c = getopt(argc, argv, "EI:ae:f:i:lnru")) != -1) 135 switch (c) { 136 case 'r': /* Gnu sed compat */ 137 case 'E': 138 rflags = REG_EXTENDED; 139 break; 140 case 'I': 141 inplace = optarg; 142 ispan = 1; /* span across input files */ 143 break; 144 case 'a': 145 aflag = 1; 146 break; 147 case 'e': 148 eflag = 1; 149 add_compunit(CU_STRING, optarg); 150 break; 151 case 'f': 152 fflag = 1; 153 add_compunit(CU_FILE, optarg); 154 break; 155 case 'i': 156 inplace = optarg; 157 ispan = 0; /* don't span across input files */ 158 break; 159 case 'l': 160 if(setvbuf(stdout, NULL, _IOLBF, 0) != 0) 161 warnx("setting line buffered output failed"); 162 break; 163 case 'n': 164 nflag = 1; 165 break; 166 case 'u': 167 if(setvbuf(stdout, NULL, _IONBF, 0) != 0) 168 warnx("setting unbuffered output failed"); 169 break; 170 default: 171 case '?': 172 usage(); 173 } 174 argc -= optind; 175 argv += optind; 176 177 /* First usage case; script is the first arg */ 178 if (!eflag && !fflag && *argv) { 179 add_compunit(CU_STRING, *argv); 180 argv++; 181 } 182 183 compile(); 184 185 /* Continue with first and start second usage */ 186 if (*argv) 187 for (; *argv; argv++) 188 add_file(*argv); 189 else 190 add_file(NULL); 191 process(); 192 cfclose(prog, NULL); 193 if (fclose(stdout)) 194 err(1, "stdout"); 195 exit(rval); 196 } 197 198 static void 199 usage(void) 200 { 201 (void)fprintf(stderr, 202 "usage: %s script [-Ealnru] [-i extension] [file ...]\n" 203 "\t%s [-Ealnu] [-i extension] [-e script] ... [-f script_file]" 204 " ... [file ...]\n", getprogname(), getprogname()); 205 exit(1); 206 } 207 208 /* 209 * Like fgets, but go through the chain of compilation units chaining them 210 * together. Empty strings and files are ignored. 211 */ 212 const char * 213 cu_fgets(int *more) 214 { 215 static enum {ST_EOF, ST_FILE, ST_STRING} state = ST_EOF; 216 static FILE *f; /* Current open file */ 217 static const char *s; /* Current pointer inside string */ 218 static char string_ident[30], *lastresult; 219 static size_t lastsize; 220 char *p; 221 const char *start; 222 223 again: 224 switch (state) { 225 case ST_EOF: 226 if (script == NULL) { 227 if (more != NULL) 228 *more = 0; 229 return (NULL); 230 } 231 linenum = 0; 232 switch (script->type) { 233 case CU_FILE: 234 if ((f = fopen(script->s, "r")) == NULL) 235 err(1, "%s", script->s); 236 fname = script->s; 237 state = ST_FILE; 238 goto again; 239 case CU_STRING: 240 if (((size_t)snprintf(string_ident, 241 sizeof(string_ident), "\"%s\"", script->s)) >= 242 sizeof(string_ident) - 1) 243 (void)strcpy(string_ident + 244 sizeof(string_ident) - 6, " ...\""); 245 fname = string_ident; 246 s = script->s; 247 state = ST_STRING; 248 goto again; 249 } 250 case ST_FILE: 251 p = lastresult; 252 if (getline(&p, &lastsize, f) != -1) { 253 linenum++; 254 if (linenum == 1 && p[0] == '#' && p[1] == 'n') 255 nflag = 1; 256 if (more != NULL) 257 *more = !feof(f); 258 return (lastresult = p); 259 } else if (ferror(f)) 260 err(1, "%s", script->s); 261 script = script->next; 262 (void)fclose(f); 263 state = ST_EOF; 264 goto again; 265 case ST_STRING: 266 if (linenum == 0 && s[0] == '#' && s[1] == 'n') 267 nflag = 1; 268 else if (s[0] == '\0') { 269 state = ST_EOF; 270 script = script->next; 271 goto again; 272 } 273 start = s; 274 for (;;) { 275 switch (*s) { 276 case '\0': 277 state = ST_EOF; 278 script = script->next; 279 /* FALLTHROUGH */ 280 case '\n': 281 s++; 282 linenum++; 283 if (more != NULL) 284 *more = 0; 285 return (start); 286 default: 287 s++; 288 } 289 } 290 } 291 /* NOTREACHED */ 292 return (NULL); 293 } 294 295 /* 296 * Like fgets, but go through the list of files chaining them together. 297 * Set len to the length of the line. 298 */ 299 int 300 mf_fgets(SPACE *sp, enum e_spflag spflag) 301 { 302 struct stat sb; 303 ssize_t len; 304 static char *p = NULL; 305 static size_t plen = 0; 306 int c; 307 static int firstfile; 308 309 if (infile == NULL) { 310 /* stdin? */ 311 if (files->fname == NULL) { 312 if (inplace != NULL) 313 errx(1, "-I or -i may not be used with stdin"); 314 infile = stdin; 315 fname = "stdin"; 316 outfile = stdout; 317 outfname = "stdout"; 318 } 319 firstfile = 1; 320 } 321 322 for (;;) { 323 if (infile != NULL && (c = getc(infile)) != EOF) { 324 (void)ungetc(c, infile); 325 break; 326 } 327 /* If we are here then either eof or no files are open yet */ 328 if (infile == stdin) { 329 sp->len = 0; 330 return (0); 331 } 332 if (infile != NULL) { 333 fclose(infile); 334 if (*oldfname != '\0') { 335 /* if there was a backup file, remove it */ 336 unlink(oldfname); 337 /* 338 * Backup the original. Note that hard links 339 * are not supported on all filesystems. 340 */ 341 if ((link(fname, oldfname) != 0) && 342 (rename(fname, oldfname) != 0)) { 343 warn("rename()"); 344 if (*tmpfname) 345 unlink(tmpfname); 346 exit(1); 347 } 348 *oldfname = '\0'; 349 } 350 if (*tmpfname != '\0') { 351 if (outfile != NULL && outfile != stdout) 352 if (fclose(outfile) != 0) { 353 warn("fclose()"); 354 unlink(tmpfname); 355 exit(1); 356 } 357 outfile = NULL; 358 if (rename(tmpfname, fname) != 0) { 359 /* this should not happen really! */ 360 warn("rename()"); 361 unlink(tmpfname); 362 exit(1); 363 } 364 *tmpfname = '\0'; 365 } 366 outfname = NULL; 367 } 368 if (firstfile == 0) 369 files = files->next; 370 else 371 firstfile = 0; 372 if (files == NULL) { 373 sp->len = 0; 374 return (0); 375 } 376 fname = files->fname; 377 if (inplace != NULL) { 378 if (lstat(fname, &sb) != 0) 379 err(1, "%s", fname); 380 if (!(sb.st_mode & S_IFREG)) 381 errx(1, "%s: %s %s", fname, 382 "in-place editing only", 383 "works for regular files"); 384 if (*inplace != '\0') { 385 strlcpy(oldfname, fname, 386 sizeof(oldfname)); 387 len = strlcat(oldfname, inplace, 388 sizeof(oldfname)); 389 if ((size_t)len > sizeof(oldfname)) 390 errx(1, "%s: name too long", fname); 391 } 392 len = snprintf(tmpfname, sizeof(tmpfname), 393 "%s/.!%ld!%s", dirname(fname), (long)getpid(), 394 basename(fname)); 395 if ((size_t)len >= sizeof(tmpfname)) 396 errx(1, "%s: name too long", fname); 397 unlink(tmpfname); 398 if (outfile != NULL && outfile != stdout) 399 fclose(outfile); 400 if ((outfile = fopen(tmpfname, "w")) == NULL) 401 err(1, "%s", fname); 402 fchown(fileno(outfile), sb.st_uid, sb.st_gid); 403 fchmod(fileno(outfile), sb.st_mode & ALLPERMS); 404 outfname = tmpfname; 405 if (!ispan) { 406 linenum = 0; 407 resetstate(); 408 } 409 } else { 410 outfile = stdout; 411 outfname = "stdout"; 412 } 413 if ((infile = fopen(fname, "r")) == NULL) { 414 warn("%s", fname); 415 rval = 1; 416 continue; 417 } 418 } 419 /* 420 * We are here only when infile is open and we still have something 421 * to read from it. 422 * 423 * Use getline() so that we can handle essentially infinite input 424 * data. The p and plen are static so each invocation gives 425 * getline() the same buffer which is expanded as needed. 426 */ 427 len = getline(&p, &plen, infile); 428 if (len == -1) 429 err(1, "%s", fname); 430 if (len != 0 && p[len - 1] == '\n') { 431 sp->append_newline = 1; 432 len--; 433 } else if (!lastline()) { 434 sp->append_newline = 1; 435 } else { 436 sp->append_newline = 0; 437 } 438 cspace(sp, p, len, spflag); 439 440 linenum++; 441 442 return (1); 443 } 444 445 /* 446 * Add a compilation unit to the linked list 447 */ 448 static void 449 add_compunit(enum e_cut type, const char *s) 450 { 451 struct s_compunit *cu; 452 453 if ((cu = malloc(sizeof(struct s_compunit))) == NULL) 454 err(1, "malloc"); 455 cu->type = type; 456 cu->s = s; 457 cu->next = NULL; 458 *cu_nextp = cu; 459 cu_nextp = &cu->next; 460 } 461 462 /* 463 * Add a file to the linked list 464 */ 465 static void 466 add_file(const char *s) 467 { 468 struct s_flist *fp; 469 470 if ((fp = malloc(sizeof(struct s_flist))) == NULL) 471 err(1, "malloc"); 472 fp->next = NULL; 473 *fl_nextp = fp; 474 fp->fname = s; 475 fl_nextp = &fp->next; 476 } 477 478 static int 479 next_files_have_lines(void) 480 { 481 struct s_flist *file; 482 FILE *file_fd; 483 int ch; 484 485 file = files; 486 while ((file = file->next) != NULL) { 487 if ((file_fd = fopen(file->fname, "r")) == NULL) 488 continue; 489 490 if ((ch = getc(file_fd)) != EOF) { 491 /* 492 * This next file has content, therefore current 493 * file doesn't contains the last line. 494 */ 495 ungetc(ch, file_fd); 496 fclose(file_fd); 497 return (1); 498 } 499 500 fclose(file_fd); 501 } 502 503 return (0); 504 } 505 506 int 507 lastline(void) 508 { 509 int ch; 510 511 if (feof(infile)) { 512 return !( 513 (inplace == NULL || ispan) && 514 next_files_have_lines()); 515 } 516 if ((ch = getc(infile)) == EOF) { 517 return !( 518 (inplace == NULL || ispan) && 519 next_files_have_lines()); 520 } 521 ungetc(ch, infile); 522 return (0); 523 } 524