1 /*- 2 * Copyright (c) 1992 Diomidis Spinellis. 3 * Copyright (c) 1992, 1993, 1994 4 * The Regents of the University of California. All rights reserved. 5 * 6 * This code is derived from software contributed to Berkeley by 7 * Diomidis Spinellis of Imperial College, University of London. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 4. Neither the name of the University nor the names of its contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 */ 33 34 #include <sys/cdefs.h> 35 __FBSDID("$FreeBSD$"); 36 37 #ifndef lint 38 static const char sccsid[] = "@(#)process.c 8.6 (Berkeley) 4/20/94"; 39 #endif 40 41 #include <sys/types.h> 42 #include <sys/stat.h> 43 #include <sys/ioctl.h> 44 #include <sys/uio.h> 45 46 #include <ctype.h> 47 #include <err.h> 48 #include <errno.h> 49 #include <fcntl.h> 50 #include <limits.h> 51 #include <regex.h> 52 #include <stdio.h> 53 #include <stdlib.h> 54 #include <string.h> 55 #include <unistd.h> 56 #include <wchar.h> 57 #include <wctype.h> 58 59 #include "defs.h" 60 #include "extern.h" 61 62 static SPACE HS, PS, SS, YS; 63 #define pd PS.deleted 64 #define ps PS.space 65 #define psl PS.len 66 #define hs HS.space 67 #define hsl HS.len 68 69 static __inline int applies(struct s_command *); 70 static void do_tr(struct s_tr *); 71 static void flush_appends(void); 72 static void lputs(char *, size_t); 73 static __inline int regexec_e(regex_t *, const char *, int, int, size_t); 74 static void regsub(SPACE *, char *, char *); 75 static int substitute(struct s_command *); 76 77 struct s_appends *appends; /* Array of pointers to strings to append. */ 78 static int appendx; /* Index into appends array. */ 79 int appendnum; /* Size of appends array. */ 80 81 static int lastaddr; /* Set by applies if last address of a range. */ 82 static int sdone; /* If any substitutes since last line input. */ 83 /* Iov structure for 'w' commands. */ 84 static regex_t *defpreg; 85 size_t maxnsub; 86 regmatch_t *match; 87 88 #define OUT(s) { fwrite(s, sizeof(u_char), psl, outfile); fputc('\n', outfile); } 89 90 void 91 process(void) 92 { 93 struct s_command *cp; 94 SPACE tspace; 95 size_t oldpsl = 0; 96 char *p; 97 98 p = NULL; 99 100 for (linenum = 0; mf_fgets(&PS, REPLACE);) { 101 pd = 0; 102 top: 103 cp = prog; 104 redirect: 105 while (cp != NULL) { 106 if (!applies(cp)) { 107 cp = cp->next; 108 continue; 109 } 110 switch (cp->code) { 111 case '{': 112 cp = cp->u.c; 113 goto redirect; 114 case 'a': 115 if (appendx >= appendnum) 116 if ((appends = realloc(appends, 117 sizeof(struct s_appends) * 118 (appendnum *= 2))) == NULL) 119 err(1, "realloc"); 120 appends[appendx].type = AP_STRING; 121 appends[appendx].s = cp->t; 122 appends[appendx].len = strlen(cp->t); 123 appendx++; 124 break; 125 case 'b': 126 cp = cp->u.c; 127 goto redirect; 128 case 'c': 129 pd = 1; 130 psl = 0; 131 if (cp->a2 == NULL || lastaddr || lastline()) 132 (void)fprintf(outfile, "%s", cp->t); 133 break; 134 case 'd': 135 pd = 1; 136 goto new; 137 case 'D': 138 if (pd) 139 goto new; 140 if (psl == 0 || 141 (p = memchr(ps, '\n', psl)) == NULL) { 142 pd = 1; 143 goto new; 144 } else { 145 psl -= (p + 1) - ps; 146 memmove(ps, p + 1, psl); 147 goto top; 148 } 149 case 'g': 150 cspace(&PS, hs, hsl, REPLACE); 151 break; 152 case 'G': 153 cspace(&PS, "\n", 1, 0); 154 cspace(&PS, hs, hsl, 0); 155 break; 156 case 'h': 157 cspace(&HS, ps, psl, REPLACE); 158 break; 159 case 'H': 160 cspace(&HS, "\n", 1, 0); 161 cspace(&HS, ps, psl, 0); 162 break; 163 case 'i': 164 (void)fprintf(outfile, "%s", cp->t); 165 break; 166 case 'l': 167 lputs(ps, psl); 168 break; 169 case 'n': 170 if (!nflag && !pd) 171 OUT(ps) 172 flush_appends(); 173 if (!mf_fgets(&PS, REPLACE)) 174 exit(0); 175 pd = 0; 176 break; 177 case 'N': 178 flush_appends(); 179 cspace(&PS, "\n", 1, 0); 180 if (!mf_fgets(&PS, 0)) 181 exit(0); 182 break; 183 case 'p': 184 if (pd) 185 break; 186 OUT(ps) 187 break; 188 case 'P': 189 if (pd) 190 break; 191 if ((p = memchr(ps, '\n', psl)) != NULL) { 192 oldpsl = psl; 193 psl = p - ps; 194 } 195 OUT(ps) 196 if (p != NULL) 197 psl = oldpsl; 198 break; 199 case 'q': 200 if (!nflag && !pd) 201 OUT(ps) 202 flush_appends(); 203 exit(0); 204 case 'r': 205 if (appendx >= appendnum) 206 if ((appends = realloc(appends, 207 sizeof(struct s_appends) * 208 (appendnum *= 2))) == NULL) 209 err(1, "realloc"); 210 appends[appendx].type = AP_FILE; 211 appends[appendx].s = cp->t; 212 appends[appendx].len = strlen(cp->t); 213 appendx++; 214 break; 215 case 's': 216 sdone |= substitute(cp); 217 break; 218 case 't': 219 if (sdone) { 220 sdone = 0; 221 cp = cp->u.c; 222 goto redirect; 223 } 224 break; 225 case 'w': 226 if (pd) 227 break; 228 if (cp->u.fd == -1 && (cp->u.fd = open(cp->t, 229 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, 230 DEFFILEMODE)) == -1) 231 err(1, "%s", cp->t); 232 if (write(cp->u.fd, ps, psl) != psl || 233 write(cp->u.fd, "\n", 1) != 1) 234 err(1, "%s", cp->t); 235 break; 236 case 'x': 237 if (hs == NULL) 238 cspace(&HS, "", 0, REPLACE); 239 tspace = PS; 240 PS = HS; 241 HS = tspace; 242 break; 243 case 'y': 244 if (pd || psl == 0) 245 break; 246 do_tr(cp->u.y); 247 break; 248 case ':': 249 case '}': 250 break; 251 case '=': 252 (void)fprintf(outfile, "%lu\n", linenum); 253 } 254 cp = cp->next; 255 } /* for all cp */ 256 257 new: if (!nflag && !pd) 258 OUT(ps) 259 flush_appends(); 260 } /* for all lines */ 261 } 262 263 /* 264 * TRUE if the address passed matches the current program state 265 * (lastline, linenumber, ps). 266 */ 267 #define MATCH(a) \ 268 ((a)->type == AT_RE ? regexec_e((a)->u.r, ps, 0, 1, psl) : \ 269 (a)->type == AT_LINE ? linenum == (a)->u.l : lastline()) 270 271 /* 272 * Return TRUE if the command applies to the current line. Sets the inrange 273 * flag to process ranges. Interprets the non-select (``!'') flag. 274 */ 275 static __inline int 276 applies(struct s_command *cp) 277 { 278 int r; 279 280 lastaddr = 0; 281 if (cp->a1 == NULL && cp->a2 == NULL) 282 r = 1; 283 else if (cp->a2) 284 if (cp->inrange) { 285 if (MATCH(cp->a2)) { 286 cp->inrange = 0; 287 lastaddr = 1; 288 r = 1; 289 } else if (cp->a2->type == AT_LINE && 290 linenum > cp->a2->u.l) { 291 /* 292 * We missed the 2nd address due to a branch, 293 * so just close the range and return false. 294 */ 295 cp->inrange = 0; 296 r = 0; 297 } else 298 r = 1; 299 } else if (MATCH(cp->a1)) { 300 /* 301 * If the second address is a number less than or 302 * equal to the line number first selected, only 303 * one line shall be selected. 304 * -- POSIX 1003.2 305 */ 306 if (cp->a2->type == AT_LINE && 307 linenum >= cp->a2->u.l) 308 lastaddr = 1; 309 else 310 cp->inrange = 1; 311 r = 1; 312 } else 313 r = 0; 314 else 315 r = MATCH(cp->a1); 316 return (cp->nonsel ? ! r : r); 317 } 318 319 /* 320 * Reset all inrange markers. 321 */ 322 void 323 resetranges(void) 324 { 325 struct s_command *cp; 326 327 for (cp = prog; cp; cp = cp->code == '{' ? cp->u.c : cp->next) 328 if (cp->a2) 329 cp->inrange = 0; 330 } 331 332 /* 333 * substitute -- 334 * Do substitutions in the pattern space. Currently, we build a 335 * copy of the new pattern space in the substitute space structure 336 * and then swap them. 337 */ 338 static int 339 substitute(struct s_command *cp) 340 { 341 SPACE tspace; 342 regex_t *re; 343 regoff_t re_off, slen; 344 int lastempty, n; 345 char *s; 346 347 s = ps; 348 re = cp->u.s->re; 349 if (re == NULL) { 350 if (defpreg != NULL && cp->u.s->maxbref > defpreg->re_nsub) { 351 linenum = cp->u.s->linenum; 352 errx(1, "%lu: %s: \\%d not defined in the RE", 353 linenum, fname, cp->u.s->maxbref); 354 } 355 } 356 if (!regexec_e(re, s, 0, 0, psl)) 357 return (0); 358 359 SS.len = 0; /* Clean substitute space. */ 360 slen = psl; 361 n = cp->u.s->n; 362 lastempty = 1; 363 364 switch (n) { 365 case 0: /* Global */ 366 do { 367 if (lastempty || match[0].rm_so != match[0].rm_eo) { 368 /* Locate start of replaced string. */ 369 re_off = match[0].rm_so; 370 /* Copy leading retained string. */ 371 cspace(&SS, s, re_off, APPEND); 372 /* Add in regular expression. */ 373 regsub(&SS, s, cp->u.s->new); 374 } 375 376 /* Move past this match. */ 377 if (match[0].rm_so != match[0].rm_eo) { 378 s += match[0].rm_eo; 379 slen -= match[0].rm_eo; 380 lastempty = 0; 381 } else { 382 if (match[0].rm_so < slen) 383 cspace(&SS, s + match[0].rm_so, 1, 384 APPEND); 385 s += match[0].rm_so + 1; 386 slen -= match[0].rm_so + 1; 387 lastempty = 1; 388 } 389 } while (slen >= 0 && regexec_e(re, s, REG_NOTBOL, 0, slen)); 390 /* Copy trailing retained string. */ 391 if (slen > 0) 392 cspace(&SS, s, slen, APPEND); 393 break; 394 default: /* Nth occurrence */ 395 while (--n) { 396 if (match[0].rm_eo == match[0].rm_so) 397 match[0].rm_eo = match[0].rm_so + 1; 398 s += match[0].rm_eo; 399 slen -= match[0].rm_eo; 400 if (slen < 0) 401 return (0); 402 if (!regexec_e(re, s, REG_NOTBOL, 0, slen)) 403 return (0); 404 } 405 /* FALLTHROUGH */ 406 case 1: /* 1st occurrence */ 407 /* Locate start of replaced string. */ 408 re_off = match[0].rm_so + (s - ps); 409 /* Copy leading retained string. */ 410 cspace(&SS, ps, re_off, APPEND); 411 /* Add in regular expression. */ 412 regsub(&SS, s, cp->u.s->new); 413 /* Copy trailing retained string. */ 414 s += match[0].rm_eo; 415 slen -= match[0].rm_eo; 416 cspace(&SS, s, slen, APPEND); 417 break; 418 } 419 420 /* 421 * Swap the substitute space and the pattern space, and make sure 422 * that any leftover pointers into stdio memory get lost. 423 */ 424 tspace = PS; 425 PS = SS; 426 SS = tspace; 427 SS.space = SS.back; 428 429 /* Handle the 'p' flag. */ 430 if (cp->u.s->p) 431 OUT(ps) 432 433 /* Handle the 'w' flag. */ 434 if (cp->u.s->wfile && !pd) { 435 if (cp->u.s->wfd == -1 && (cp->u.s->wfd = open(cp->u.s->wfile, 436 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC, DEFFILEMODE)) == -1) 437 err(1, "%s", cp->u.s->wfile); 438 if (write(cp->u.s->wfd, ps, psl) != psl || 439 write(cp->u.s->wfd, "\n", 1) != 1) 440 err(1, "%s", cp->u.s->wfile); 441 } 442 return (1); 443 } 444 445 /* 446 * do_tr -- 447 * Perform translation ('y' command) in the pattern space. 448 */ 449 static void 450 do_tr(struct s_tr *y) 451 { 452 SPACE tmp; 453 char c, *p; 454 size_t clen, left; 455 int i; 456 457 if (MB_CUR_MAX == 1) { 458 /* 459 * Single-byte encoding: perform in-place translation 460 * of the pattern space. 461 */ 462 for (p = ps; p < &ps[psl]; p++) 463 *p = y->bytetab[(u_char)*p]; 464 } else { 465 /* 466 * Multi-byte encoding: perform translation into the 467 * translation space, then swap the translation and 468 * pattern spaces. 469 */ 470 /* Clean translation space. */ 471 YS.len = 0; 472 for (p = ps, left = psl; left > 0; p += clen, left -= clen) { 473 if ((c = y->bytetab[(u_char)*p]) != '\0') { 474 cspace(&YS, &c, 1, APPEND); 475 clen = 1; 476 continue; 477 } 478 for (i = 0; i < y->nmultis; i++) 479 if (left >= y->multis[i].fromlen && 480 memcmp(p, y->multis[i].from, 481 y->multis[i].fromlen) == 0) 482 break; 483 if (i < y->nmultis) { 484 cspace(&YS, y->multis[i].to, 485 y->multis[i].tolen, APPEND); 486 clen = y->multis[i].fromlen; 487 } else { 488 cspace(&YS, p, 1, APPEND); 489 clen = 1; 490 } 491 } 492 /* Swap the translation space and the pattern space. */ 493 tmp = PS; 494 PS = YS; 495 YS = tmp; 496 YS.space = YS.back; 497 } 498 } 499 500 /* 501 * Flush append requests. Always called before reading a line, 502 * therefore it also resets the substitution done (sdone) flag. 503 */ 504 static void 505 flush_appends(void) 506 { 507 FILE *f; 508 int count, i; 509 char buf[8 * 1024]; 510 511 for (i = 0; i < appendx; i++) 512 switch (appends[i].type) { 513 case AP_STRING: 514 fwrite(appends[i].s, sizeof(char), appends[i].len, 515 outfile); 516 break; 517 case AP_FILE: 518 /* 519 * Read files probably shouldn't be cached. Since 520 * it's not an error to read a non-existent file, 521 * it's possible that another program is interacting 522 * with the sed script through the filesystem. It 523 * would be truly bizarre, but possible. It's probably 524 * not that big a performance win, anyhow. 525 */ 526 if ((f = fopen(appends[i].s, "r")) == NULL) 527 break; 528 while ((count = fread(buf, sizeof(char), sizeof(buf), f))) 529 (void)fwrite(buf, sizeof(char), count, outfile); 530 (void)fclose(f); 531 break; 532 } 533 if (ferror(outfile)) 534 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); 535 appendx = sdone = 0; 536 } 537 538 static void 539 lputs(char *s, size_t len) 540 { 541 static const char escapes[] = "\\\a\b\f\r\t\v"; 542 int c, col, width; 543 char *p; 544 struct winsize win; 545 static int termwidth = -1; 546 size_t clen, i; 547 wchar_t wc; 548 mbstate_t mbs; 549 550 if (outfile != stdout) 551 termwidth = 60; 552 if (termwidth == -1) { 553 if ((p = getenv("COLUMNS")) && *p != '\0') 554 termwidth = atoi(p); 555 else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &win) == 0 && 556 win.ws_col > 0) 557 termwidth = win.ws_col; 558 else 559 termwidth = 60; 560 } 561 562 memset(&mbs, 0, sizeof(mbs)); 563 col = 0; 564 while (len != 0) { 565 clen = mbrtowc(&wc, s, len, &mbs); 566 if (clen == 0) 567 clen = 1; 568 if (clen == (size_t)-1 || clen == (size_t)-2) { 569 wc = (unsigned char)*s; 570 clen = 1; 571 memset(&mbs, 0, sizeof(mbs)); 572 } 573 if (wc == '\n') { 574 if (col + 1 >= termwidth) 575 fprintf(outfile, "\\\n"); 576 fputc('$', outfile); 577 fputc('\n', outfile); 578 col = 0; 579 } else if (iswprint(wc)) { 580 width = wcwidth(wc); 581 if (col + width >= termwidth) { 582 fprintf(outfile, "\\\n"); 583 col = 0; 584 } 585 fwrite(s, 1, clen, outfile); 586 col += width; 587 } else if (wc != L'\0' && (c = wctob(wc)) != EOF && 588 (p = strchr(escapes, c)) != NULL) { 589 if (col + 2 >= termwidth) { 590 fprintf(outfile, "\\\n"); 591 col = 0; 592 } 593 fprintf(outfile, "\\%c", "\\abfrtv"[p - escapes]); 594 col += 2; 595 } else { 596 if (col + 4 * clen >= termwidth) { 597 fprintf(outfile, "\\\n"); 598 col = 0; 599 } 600 for (i = 0; i < clen; i++) 601 fprintf(outfile, "\\%03o", 602 (int)(unsigned char)s[i]); 603 col += 4 * clen; 604 } 605 s += clen; 606 len -= clen; 607 } 608 if (col + 1 >= termwidth) 609 fprintf(outfile, "\\\n"); 610 (void)fputc('$', outfile); 611 (void)fputc('\n', outfile); 612 if (ferror(outfile)) 613 errx(1, "%s: %s", outfname, strerror(errno ? errno : EIO)); 614 } 615 616 static __inline int 617 regexec_e(regex_t *preg, const char *string, int eflags, int nomatch, 618 size_t slen) 619 { 620 int eval; 621 622 if (preg == NULL) { 623 if (defpreg == NULL) 624 errx(1, "first RE may not be empty"); 625 } else 626 defpreg = preg; 627 628 /* Set anchors */ 629 match[0].rm_so = 0; 630 match[0].rm_eo = slen; 631 632 eval = regexec(defpreg, string, 633 nomatch ? 0 : maxnsub + 1, match, eflags | REG_STARTEND); 634 switch(eval) { 635 case 0: 636 return (1); 637 case REG_NOMATCH: 638 return (0); 639 } 640 errx(1, "RE error: %s", strregerror(eval, defpreg)); 641 /* NOTREACHED */ 642 } 643 644 /* 645 * regsub - perform substitutions after a regexp match 646 * Based on a routine by Henry Spencer 647 */ 648 static void 649 regsub(SPACE *sp, char *string, char *src) 650 { 651 int len, no; 652 char c, *dst; 653 654 #define NEEDSP(reqlen) \ 655 /* XXX What is the +1 for? */ \ 656 if (sp->len + (reqlen) + 1 >= sp->blen) { \ 657 sp->blen += (reqlen) + 1024; \ 658 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) \ 659 == NULL) \ 660 err(1, "realloc"); \ 661 dst = sp->space + sp->len; \ 662 } 663 664 dst = sp->space + sp->len; 665 while ((c = *src++) != '\0') { 666 if (c == '&') 667 no = 0; 668 else if (c == '\\' && isdigit((unsigned char)*src)) 669 no = *src++ - '0'; 670 else 671 no = -1; 672 if (no < 0) { /* Ordinary character. */ 673 if (c == '\\' && (*src == '\\' || *src == '&')) 674 c = *src++; 675 NEEDSP(1); 676 *dst++ = c; 677 ++sp->len; 678 } else if (match[no].rm_so != -1 && match[no].rm_eo != -1) { 679 len = match[no].rm_eo - match[no].rm_so; 680 NEEDSP(len); 681 memmove(dst, string + match[no].rm_so, len); 682 dst += len; 683 sp->len += len; 684 } 685 } 686 NEEDSP(1); 687 *dst = '\0'; 688 } 689 690 /* 691 * cspace -- 692 * Concatenate space: append the source space to the destination space, 693 * allocating new space as necessary. 694 */ 695 void 696 cspace(SPACE *sp, const char *p, size_t len, enum e_spflag spflag) 697 { 698 size_t tlen; 699 700 /* Make sure SPACE has enough memory and ramp up quickly. */ 701 tlen = sp->len + len + 1; 702 if (tlen > sp->blen) { 703 sp->blen = tlen + 1024; 704 if ((sp->space = sp->back = realloc(sp->back, sp->blen)) == 705 NULL) 706 err(1, "realloc"); 707 } 708 709 if (spflag == REPLACE) 710 sp->len = 0; 711 712 memmove(sp->space + sp->len, p, len); 713 714 sp->space[sp->len += len] = '\0'; 715 } 716 717 /* 718 * Close all cached opened files and report any errors 719 */ 720 void 721 cfclose(struct s_command *cp, struct s_command *end) 722 { 723 724 for (; cp != end; cp = cp->next) 725 switch(cp->code) { 726 case 's': 727 if (cp->u.s->wfd != -1 && close(cp->u.s->wfd)) 728 err(1, "%s", cp->u.s->wfile); 729 cp->u.s->wfd = -1; 730 break; 731 case 'w': 732 if (cp->u.fd != -1 && close(cp->u.fd)) 733 err(1, "%s", cp->t); 734 cp->u.fd = -1; 735 break; 736 case '{': 737 cfclose(cp->u.c, cp->next); 738 break; 739 } 740 } 741