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