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