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