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