Rob Landley writes:
[oweals/busybox.git] / editors / sed.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * sed.c - very minimalist version of sed
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7  * Copyright (C) 2002  Matt Kraai
8  * Copyright (C) 2003 by Glenn McGrath <bug1@optushome.com.au>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  *
24  */
25
26 /* Code overview.
27
28   Files are laid out to avoid unnecessary function declarations.  So for
29   example, every function add_cmd calls occurs before add_cmd in this file.
30
31   add_cmd() is called on each line of sed command text (from a file or from
32   the command line).  It calls get_address() and parse_cmd_args().  The
33   resulting sed_cmd_t structures are appended to a linked list
34   (sed_cmd_head/sed_cmd_tail).
35
36   process_file() does actual sedding, reading data lines from an input FILE *
37   (which could be stdin) and applying the sed command list (sed_cmd_head) to
38   each of the resulting lines.
39
40   sed_main() is where external code calls into this, with a command line.
41 */
42
43
44 /*
45         Supported features and commands in this version of sed:
46
47          - comments ('#')
48          - address matching: num|/matchstr/[,num|/matchstr/|$]command
49          - commands: (p)rint, (d)elete, (s)ubstitue (with g & I flags)
50          - edit commands: (a)ppend, (i)nsert, (c)hange
51          - file commands: (r)ead
52          - backreferences in substitution expressions (\1, \2...\9)
53          - grouped commands: {cmd1;cmd2}
54          - transliteration (y/source-chars/dest-chars/)
55          - pattern space hold space storing / swapping (g, h, x)
56          - labels / branching (: label, b, t)
57
58          (Note: Specifying an address (range) to match is *optional*; commands
59          default to the whole pattern space if no specific address match was
60          requested.)
61
62         Unsupported features:
63
64          - GNU extensions
65          - and more.
66
67         Todo:
68
69          - Create a wrapper around regex to make libc's regex conform with sed
70          - Fix bugs
71
72
73         Reference http://www.opengroup.org/onlinepubs/007904975/utilities/sed.html
74 */
75
76 #include <stdio.h>
77 #include <unistd.h>             /* for getopt() */
78 #include <regex.h>
79 #include <string.h>             /* for strdup() */
80 #include <errno.h>
81 #include <ctype.h>              /* for isspace() */
82 #include <stdlib.h>
83 #include "busybox.h"
84
85 typedef struct sed_cmd_s {
86     /* Ordered by alignment requirements: currently 36 bytes on x86 */
87
88     /* address storage */
89     regex_t *beg_match; /* sed -e '/match/cmd' */
90     regex_t *end_match; /* sed -e '/match/,/end_match/cmd' */
91     regex_t *sub_match; /* For 's/sub_match/string/' */
92     int beg_line;               /* 'sed 1p'   0 == apply commands to all lines */
93     int end_line;               /* 'sed 1,3p' 0 == one line only. -1 = last line ($) */
94
95     FILE *file;                 /* File (sr) command writes to, -1 for none. */
96     char *string;               /* Data string for (saicytb) commands. */
97
98     unsigned short which_match;         /* (s) Which match to replace (0 for all) */
99
100     /* Bitfields (gcc won't group them if we don't) */
101     unsigned int invert:1;                      /* the '!' after the address */
102     unsigned int in_match:1;            /* Next line also included in match? */
103     unsigned int no_newline:1;          /* Last line written by (sr) had no '\n' */
104     unsigned int sub_p:1;                       /* (s) print option */
105
106
107     /* GENERAL FIELDS */
108     char cmd;                           /* The command char: abcdDgGhHilnNpPqrstwxy:={} */
109     struct sed_cmd_s *next;     /* Next command (linked list, NULL terminated) */
110 } sed_cmd_t;
111
112 /* globals */
113 /* options */
114 static int be_quiet = 0;
115
116 static const char bad_format_in_subst[] =
117         "bad format in substitution expression";
118 const char *const semicolon_whitespace = "; \n\r\t\v";
119
120 regmatch_t regmatch[10];
121 static regex_t *previous_regex_ptr = NULL;
122
123 /* linked list of sed commands */
124 static sed_cmd_t sed_cmd_head;
125 static sed_cmd_t *sed_cmd_tail = &sed_cmd_head;
126
127 /* Linked list of append lines */
128 struct append_list {
129         char *string;
130         struct append_list *next;
131 };
132 struct append_list *append_head=NULL, *append_tail=NULL;
133
134 #ifdef CONFIG_FEATURE_CLEAN_UP
135 static void free_and_close_stuff(void)
136 {
137         sed_cmd_t *sed_cmd = sed_cmd_head.next;
138
139         while(append_head) {
140                 append_tail=append_head->next;
141                 free(append_head->string);
142                 free(append_head);
143                 append_head=append_tail;
144         }
145
146         while (sed_cmd) {
147                 sed_cmd_t *sed_cmd_next = sed_cmd->next;
148
149                 if(sed_cmd->file)
150                         bb_xprint_and_close_file(sed_cmd->file);
151
152                 if (sed_cmd->beg_match) {
153                         regfree(sed_cmd->beg_match);
154                         free(sed_cmd->beg_match);
155                 }
156                 if (sed_cmd->end_match) {
157                         regfree(sed_cmd->end_match);
158                         free(sed_cmd->end_match);
159                 }
160                 if (sed_cmd->sub_match) {
161                         regfree(sed_cmd->sub_match);
162                         free(sed_cmd->sub_match);
163                 }
164                 free(sed_cmd->string);
165                 free(sed_cmd);
166                 sed_cmd = sed_cmd_next;
167         }
168 }
169 #endif
170
171 /* strdup, replacing "\n" with '\n', and "\delimiter" with 'delimiter' */
172
173 static void parse_escapes(char *dest, const char *string, int len, char from, char to)
174 {
175         int i=0;
176
177         while(i<len) {
178                 if(string[i] == '\\') {
179                         if(!to || string[i+1] == from) {
180                                 *(dest++) = to ? to : string[i+1];
181                                 i+=2;
182                                 continue;
183                         } else *(dest++)=string[i++];
184                 }
185                 *(dest++) = string[i++];
186         }
187         *dest=0;
188 }
189
190 static char *copy_parsing_slashn(const char *string, int len)
191 {
192         char *dest=xmalloc(len+1);
193
194         parse_escapes(dest,string,len,'n','\n');
195         return dest;
196 }
197
198
199 /*
200  * index_of_next_unescaped_regexp_delim - walks left to right through a string
201  * beginning at a specified index and returns the index of the next regular
202  * expression delimiter (typically a forward * slash ('/')) not preceeded by 
203  * a backslash ('\').
204  */
205 static int index_of_next_unescaped_regexp_delim(const char delimiter,
206         const char *str)
207 {
208         int bracket = -1;
209         int escaped = 0;
210         int idx = 0;
211         char ch;
212
213         for (; (ch = str[idx]); idx++) {
214                 if (bracket != -1) {
215                         if (ch == ']' && !(bracket == idx - 1 || (bracket == idx - 2
216                                         && str[idx - 1] == '^')))
217                                 bracket = -1;
218                 } else if (escaped)
219                         escaped = 0;
220                 else if (ch == '\\')
221                         escaped = 1;
222                 else if (ch == '[')
223                         bracket = idx;
224                 else if (ch == delimiter)
225                         return idx;
226         }
227
228         /* if we make it to here, we've hit the end of the string */
229         return -1;
230 }
231
232 /*
233  *  Returns the index of the third delimiter
234  */
235 static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
236 {
237         const char *cmdstr_ptr = cmdstr;
238         char delimiter;
239         int idx = 0;
240
241         /* verify that the 's' or 'y' is followed by something.  That something
242          * (typically a 'slash') is now our regexp delimiter... */
243         if (*cmdstr == '\0') bb_error_msg_and_die(bad_format_in_subst);
244         delimiter = *(cmdstr_ptr++);
245
246         /* save the match string */
247         idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
248         if (idx == -1) {
249                 bb_error_msg_and_die(bad_format_in_subst);
250         }
251         *match = copy_parsing_slashn(cmdstr_ptr, idx);
252
253         /* save the replacement string */
254         cmdstr_ptr += idx + 1;
255         idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
256         if (idx == -1) {
257                 bb_error_msg_and_die(bad_format_in_subst);
258         }
259         *replace = copy_parsing_slashn(cmdstr_ptr, idx);
260
261         return ((cmdstr_ptr - cmdstr) + idx);
262 }
263
264 /*
265  * returns the index in the string just past where the address ends.
266  */
267 static int get_address(char *my_str, int *linenum, regex_t ** regex)
268 {
269         char *pos = my_str;
270
271         if (isdigit(*my_str)) {
272                 *linenum = strtol(my_str, &pos, 10);
273                 /* endstr shouldnt ever equal NULL */
274         } else if (*my_str == '$') {
275                 *linenum = -1;
276                 pos++;
277         } else if (*my_str == '/' || *my_str == '\\') {
278                 int next;
279                 char delimiter;
280                 char *temp;
281
282                 if (*my_str == '\\') delimiter = *(++pos);
283                 else delimiter = '/';
284                 next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
285                 if (next == -1)
286                         bb_error_msg_and_die("unterminated match expression");
287                 
288                 temp=copy_parsing_slashn(pos,next);
289                 *regex = (regex_t *) xmalloc(sizeof(regex_t));
290                 xregcomp(*regex, temp, REG_NEWLINE);
291                 free(temp);
292                 /* Move position to next character after last delimiter */
293                 pos+=(next+1);
294         }
295         return pos - my_str;
296 }
297
298 /* Grab a filename.  Whitespace at start is skipped, then goes to EOL. */
299 static int parse_file_cmd(sed_cmd_t * sed_cmd, const char *filecmdstr, char **retval)
300 {
301         int start = 0, idx, hack=0;
302
303         /* Skip whitespace, then grab filename to end of line */
304         while (isspace(filecmdstr[start])) start++;
305         idx=start;
306         while(filecmdstr[idx] && filecmdstr[idx]!='\n') idx++;
307         /* If lines glued together, put backslash back. */
308         if(filecmdstr[idx]=='\n') hack=1;
309         if(idx==start) bb_error_msg_and_die("Empty filename");
310         *retval = bb_xstrndup(filecmdstr+start, idx-start+hack+1);
311         if(hack) *(idx+*retval)='\\';
312
313         return idx;
314 }
315
316 static int parse_subst_cmd(sed_cmd_t * const sed_cmd, char *substr)
317 {
318         int cflags = 0;
319         char *match;
320         int idx = 0;
321
322         /*
323          * A substitution command should look something like this:
324          *    s/match/replace/ #gIpw
325          *    ||     |        |||
326          *    mandatory       optional
327          */
328         idx = parse_regex_delim(substr, &match, &sed_cmd->string);
329
330         /* determine the number of back references in the match string */
331         /* Note: we compute this here rather than in the do_subst_command()
332          * function to save processor time, at the expense of a little more memory
333          * (4 bits) per sed_cmd */
334
335         /* process the flags */
336
337         sed_cmd->which_match=1;
338         while (substr[++idx]) {
339                 /* Parse match number */
340                 if(isdigit(substr[idx])) {
341                         if(match[0]!='^') {
342                                 /* Match 0 treated as all, multiple matches we take the last one. */
343                                 char *pos=substr+idx;
344                                 sed_cmd->which_match=(unsigned short)strtol(substr+idx,&pos,10);
345                                 idx=pos-substr;
346                         }
347                         continue;
348                 }
349                 /* Skip spaces */
350                 if(isspace(substr[idx])) continue;
351
352                 switch (substr[idx]) {
353                         /* Replace all occurrences */
354                         case 'g':
355                                 if (match[0] != '^') sed_cmd->which_match = 0;
356                                 break;
357                         /* Print pattern space */
358                         case 'p':
359                                 sed_cmd->sub_p = 1;
360                                 break;
361                         case 'w':
362                         {
363                                 char *temp;
364                                 idx+=parse_file_cmd(sed_cmd,substr+idx,&temp);
365                                 
366                                 break;
367                         }
368                         /* Ignore case (gnu exension) */
369                         case 'I':
370                                 cflags |= REG_ICASE;
371                                 break;
372                         case ';':
373                         case '}':
374                                 goto out;
375                         default:
376                                 bb_error_msg_and_die("bad option in substitution expression");
377                 }
378         }
379 out:
380         /* compile the match string into a regex */
381         if (*match != '\0') {
382                 /* If match is empty, we use last regex used at runtime */
383                 sed_cmd->sub_match = (regex_t *) xmalloc(sizeof(regex_t));
384                 xregcomp(sed_cmd->sub_match, match, cflags);
385         }
386         free(match);
387
388         return idx;
389 }
390
391 /*
392  *  Process the commands arguments
393  */
394 static char *parse_cmd_args(sed_cmd_t *sed_cmd, char *cmdstr)
395 {
396         /* handle (s)ubstitution command */
397         if (sed_cmd->cmd == 's') cmdstr += parse_subst_cmd(sed_cmd, cmdstr);
398         /* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
399         else if (strchr("aic", sed_cmd->cmd)) {
400                 if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
401                         bb_error_msg_and_die
402                                 ("only a beginning address can be specified for edit commands");
403                 while(isspace(*cmdstr)) cmdstr++;
404                 sed_cmd->string = bb_xstrdup(cmdstr);
405                 parse_escapes(sed_cmd->string,sed_cmd->string,strlen(cmdstr),0,0);
406                 cmdstr += strlen(cmdstr);
407         /* handle file cmds: (r)ead */
408         } else if(strchr("rw", sed_cmd->cmd)) {
409                 if (sed_cmd->end_line || sed_cmd->end_match)
410                         bb_error_msg_and_die("Command only uses one address");
411                 cmdstr += parse_file_cmd(sed_cmd, cmdstr, &sed_cmd->string);
412                 if(sed_cmd->cmd=='w')
413                         sed_cmd->file=bb_xfopen(sed_cmd->string,"w");
414         /* handle branch commands */
415         } else if (strchr(":bt", sed_cmd->cmd)) {
416                 int length;
417
418                 while(isspace(*cmdstr)) cmdstr++;
419                 length = strcspn(cmdstr, semicolon_whitespace);
420                 if (length) {
421                         sed_cmd->string = strndup(cmdstr, length);
422                         cmdstr += length;
423                 }
424         }
425         /* translation command */
426         else if (sed_cmd->cmd == 'y') {
427                 char *match, *replace;
428                 int i=cmdstr[0];
429
430                 cmdstr+=parse_regex_delim(cmdstr, &match, &replace)+1;
431                 /* \n already parsed, but \delimiter needs unescaping. */
432                 parse_escapes(match,match,strlen(match),i,i);
433                 parse_escapes(replace,replace,strlen(replace),i,i);
434
435                 sed_cmd->string = xcalloc(1, (strlen(match) + 1) * 2);
436                 for (i = 0; match[i] && replace[i]; i++) {
437                         sed_cmd->string[i * 2] = match[i];
438                         sed_cmd->string[(i * 2) + 1] = replace[i];
439                 }
440                 free(match);
441                 free(replace);
442         }
443         /* if it wasnt a single-letter command that takes no arguments
444          * then it must be an invalid command.
445          */
446         else if (strchr("dDgGhHlnNpPqx={}", sed_cmd->cmd) == 0) {
447                 bb_error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
448         }
449
450         /* give back whatever's left over */
451         return (cmdstr);
452 }
453
454
455 /* Parse address+command sets, skipping comment lines. */
456
457 void add_cmd(char *cmdstr)
458 {
459         static char *add_cmd_line=NULL;
460         sed_cmd_t *sed_cmd;
461         int temp;
462
463         /* Append this line to any unfinished line from last time. */
464         if(add_cmd_line) {
465                 int lastlen=strlen(add_cmd_line);
466                 char *tmp=xmalloc(lastlen+strlen(cmdstr)+2);
467
468                 memcpy(tmp,add_cmd_line,lastlen);
469                 tmp[lastlen]='\n';
470                 strcpy(tmp+lastlen+1,cmdstr);
471                 free(add_cmd_line);
472                 cmdstr=add_cmd_line=tmp;
473         } else add_cmd_line=NULL;
474
475         /* If this line ends with backslash, request next line. */
476         temp=strlen(cmdstr);
477         if(temp && cmdstr[temp-1]=='\\') {
478                 if(!add_cmd_line) add_cmd_line=strdup(cmdstr);
479                 add_cmd_line[temp-1]=0;
480                 return;
481         }
482
483         /* Loop parsing all commands in this line. */
484         while(*cmdstr) {
485                 /* Skip leading whitespace and semicolons */
486                 cmdstr += strspn(cmdstr, semicolon_whitespace);
487
488                 /* If no more commands, exit. */
489                 if(!*cmdstr) break;
490
491                 /* if this is a comment, jump past it and keep going */
492                 if (*cmdstr == '#') {
493                         /* "#n" is the same as using -n on the command line */
494                         if (cmdstr[1] == 'n') be_quiet++;
495                         if(!(cmdstr=strpbrk(cmdstr, "\n\r"))) break;
496                         continue;
497                 }
498
499                 /* parse the command
500                  * format is: [addr][,addr][!]cmd
501                  *            |----||-----||-|
502                  *            part1 part2  part3
503                  */
504
505                 sed_cmd = xcalloc(1, sizeof(sed_cmd_t));
506
507                 /* first part (if present) is an address: either a '$', a number or a /regex/ */
508                 cmdstr += get_address(cmdstr, &sed_cmd->beg_line, &sed_cmd->beg_match);
509
510                 /* second part (if present) will begin with a comma */
511                 if (*cmdstr == ',') {
512                         int idx;
513
514                         cmdstr++;
515                         idx = get_address(cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
516                         if (!idx) bb_error_msg_and_die("get_address: no address found in string\n");
517                         cmdstr += idx;
518                 }
519
520                 /* skip whitespace before the command */
521                 while (isspace(*cmdstr)) cmdstr++;
522
523                 /* Check for inversion flag */
524                 if (*cmdstr == '!') {
525                         sed_cmd->invert = 1;
526                         cmdstr++;
527
528                         /* skip whitespace before the command */
529                         while (isspace(*cmdstr)) cmdstr++;
530                 }
531
532                 /* last part (mandatory) will be a command */
533                 if (!*cmdstr) bb_error_msg_and_die("missing command");
534                 sed_cmd->cmd = *(cmdstr++);
535                 cmdstr = parse_cmd_args(sed_cmd, cmdstr);
536
537                 /* Add the command to the command array */
538                 sed_cmd_tail->next = sed_cmd;
539                 sed_cmd_tail = sed_cmd_tail->next;
540         }
541
542         /* If we glued multiple lines together, free the memory. */
543         if(add_cmd_line) {
544                 free(add_cmd_line);
545                 add_cmd_line=NULL;
546         }
547 }
548
549 struct pipeline {
550         char *buf;      /* Space to hold string */
551         int idx;        /* Space used */
552         int len;        /* Space allocated */
553 } pipeline;
554
555 #define PIPE_GROW 64
556
557 void pipe_putc(char c)
558 {
559         if(pipeline.idx==pipeline.len) {
560                 pipeline.buf = xrealloc(pipeline.buf, pipeline.len + PIPE_GROW);
561                 pipeline.len+=PIPE_GROW;
562         }
563         pipeline.buf[pipeline.idx++] = (c);
564 }
565
566 static void do_subst_w_backrefs(const char *line, const char *replace)
567 {
568         int i,j;
569
570         /* go through the replacement string */
571         for (i = 0; replace[i]; i++) {
572                 /* if we find a backreference (\1, \2, etc.) print the backref'ed * text */
573                 if (replace[i] == '\\' && replace[i+1]>'0' && replace[i+1]<='9') {
574                         int backref=replace[++i]-'0';
575
576                         /* print out the text held in regmatch[backref] */
577                         if(regmatch[backref].rm_so != -1)
578                                 for (j = regmatch[backref].rm_so; j < regmatch[backref].rm_eo; j++)
579                                         pipe_putc(line[j]);
580                 }
581
582                 /* if we find a backslash escaped character, print the character */
583                 else if (replace[i] == '\\') pipe_putc(replace[++i]);
584
585                 /* if we find an unescaped '&' print out the whole matched text. */
586                 else if (replace[i] == '&')
587                         for (j = regmatch[0].rm_so; j < regmatch[0].rm_eo; j++)
588                                 pipe_putc(line[j]);
589                 /* Otherwise just output the character. */
590                 else pipe_putc(replace[i]);
591         }
592 }
593
594 static int do_subst_command(sed_cmd_t * sed_cmd, char **line)
595 {
596         char *oldline = *line;
597         int altered = 0;
598         int match_count=0;
599         regex_t *current_regex;
600
601         /* Handle empty regex. */
602         if (sed_cmd->sub_match == NULL) {
603                 current_regex = previous_regex_ptr;
604                 if(!current_regex)
605                         bb_error_msg_and_die("No previous regexp.");
606         } else previous_regex_ptr = current_regex = sed_cmd->sub_match;
607
608         /* Find the first match */
609         if(REG_NOMATCH==regexec(current_regex, oldline, 10, regmatch, 0))
610                 return 0;
611
612         /* Initialize temporary output buffer. */
613         pipeline.buf=xmalloc(PIPE_GROW);
614         pipeline.len=PIPE_GROW;
615         pipeline.idx=0;
616
617         /* Now loop through, substituting for matches */
618         do {
619                 int i;
620
621                 /* Work around bug in glibc regexec, demonstrated by:
622                    echo " a.b" | busybox sed 's [^ .]* x g'
623                    The match_count check is so not to break
624                    echo "hi" | busybox sed 's/^/!/g' */
625                 if(!regmatch[0].rm_so && !regmatch[0].rm_eo && match_count) {
626                         pipe_putc(*(oldline++));
627                         continue;
628                 }
629
630                 match_count++;
631
632                 /* If we aren't interested in this match, output old line to
633                    end of match and continue */
634                 if(sed_cmd->which_match && sed_cmd->which_match!=match_count) {
635                         for(i=0;i<regmatch[0].rm_eo;i++)
636                                 pipe_putc(oldline[i]);
637                         continue;
638                 }
639
640                 /* print everything before the match */
641                 for (i = 0; i < regmatch[0].rm_so; i++) pipe_putc(oldline[i]);
642
643                 /* then print the substitution string */
644                 do_subst_w_backrefs(oldline, sed_cmd->string);
645
646                 /* advance past the match */
647                 oldline += regmatch[0].rm_eo;
648                 /* flag that something has changed */
649                 altered++;
650
651                 /* if we're not doing this globally, get out now */
652                 if (sed_cmd->which_match) break;
653         } while (*oldline && (regexec(current_regex, oldline, 10, regmatch, 0) != REG_NOMATCH));
654
655         /* Copy rest of string into output pipeline */
656
657         while(*oldline) pipe_putc(*(oldline++));
658         pipe_putc(0);
659
660         free(*line);
661         *line = pipeline.buf;
662         return altered;
663 }
664
665 /* Set command pointer to point to this label.  (Does not handle null label.) */
666 static sed_cmd_t *branch_to(const char *label)
667 {
668         sed_cmd_t *sed_cmd;
669
670         for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
671                 if ((sed_cmd->cmd == ':') && (sed_cmd->string) && (strcmp(sed_cmd->string, label) == 0)) {
672                         return (sed_cmd);
673                 }
674         }
675         bb_error_msg_and_die("Can't find label for jump to `%s'", label);
676 }
677
678 /* Append copy of string to append buffer */
679 static void append(char *s)
680 {
681         struct append_list *temp=calloc(1,sizeof(struct append_list));
682
683         if(append_head)
684                 append_tail=(append_tail->next=temp);
685         else append_head=append_tail=temp;
686         temp->string=strdup(s);
687 }
688
689 static void flush_append(void)
690 {
691         /* Output appended lines. */
692         while(append_head) {
693                 puts(append_head->string);
694                 append_tail=append_head->next;
695                 free(append_head->string);
696                 free(append_head);
697                 append_head=append_tail;
698         }
699         append_head=append_tail=NULL;
700 }
701
702 /* Get next line of input, flushing append buffer and noting if we hit EOF
703  * without a newline on the last line.
704  */
705 static char *get_next_line(FILE * file, int *no_newline)
706 {
707         char *temp;
708         int len;
709
710         flush_append();
711         temp=bb_get_line_from_file(file);
712         if(temp) {
713                 len=strlen(temp);
714                 if(len && temp[len-1]=='\n') temp[len-1]=0;
715                 else *no_newline=1;
716         }
717
718         return temp;
719 }
720
721 /* Output line of text.  missing_newline means the last line output did not
722    end with a newline.  no_newline means this line does not end with a
723    newline. */
724
725 static int puts_maybe_newline(char *s, FILE *file, int missing_newline, int no_newline)
726 {
727         if(missing_newline) fputc('\n',file);
728         fputs(s,file);
729         if(!no_newline) fputc('\n',file);
730
731         return no_newline;
732 }
733
734 #define sed_puts(s,n) missing_newline=puts_maybe_newline(s,stdout,missing_newline,n)
735
736 static void process_file(FILE * file)
737 {
738         char *pattern_space, *next_line, *hold_space=NULL;
739         static int linenum = 0, missing_newline=0;
740         int no_newline,next_no_newline=0;
741
742         next_line = get_next_line(file,&next_no_newline);
743
744         /* go through every line in the file */
745         for(;;) {
746                 sed_cmd_t *sed_cmd;
747                 int substituted=0;
748
749                 /* Advance to next line.  Stop if out of lines. */
750                 if(!(pattern_space=next_line)) break;
751                 no_newline=next_no_newline;
752
753                 /* Read one line in advance so we can act on the last line, the '$' address */
754                 next_line = get_next_line(file,&next_no_newline);
755                 linenum++;
756 restart:
757                 /* for every line, go through all the commands */
758                 for (sed_cmd = sed_cmd_head.next; sed_cmd; sed_cmd = sed_cmd->next) {
759                         int old_matched, matched;
760
761                         old_matched = sed_cmd->in_match;
762
763                         /* Determine if this command matches this line: */
764
765                         /* Are we continuing a previous multi-line match? */
766
767                         sed_cmd->in_match = sed_cmd->in_match
768
769                         /* Or is no range necessary? */
770                                 || (!sed_cmd->beg_line && !sed_cmd->end_line
771                                         && !sed_cmd->beg_match && !sed_cmd->end_match)
772
773                         /* Or did we match the start of a numerical range? */
774                                 || (sed_cmd->beg_line > 0 && (sed_cmd->beg_line == linenum))
775
776                         /* Or does this line match our begin address regex? */
777                                 || (sed_cmd->beg_match &&
778                                     !regexec(sed_cmd->beg_match, pattern_space, 0, NULL, 0))
779
780                         /* Or did we match last line of input? */
781                                 || (sed_cmd->beg_line == -1 && next_line == NULL);
782
783                         /* Snapshot the value */
784
785                         matched = sed_cmd->in_match;
786
787                         /* Is this line the end of the current match? */
788
789                         if(matched) {
790                                 sed_cmd->in_match = !(
791                                         /* has the ending line come, or is this a single address command? */
792                                         (sed_cmd->end_line ?
793                                                 sed_cmd->end_line==-1 ?
794                                                         !next_line
795                                                         : sed_cmd->end_line<=linenum
796                                                 : !sed_cmd->end_match)
797                                         /* or does this line matches our last address regex */
798                                         || (sed_cmd->end_match && old_matched && (regexec(sed_cmd->end_match, pattern_space, 0, NULL, 0) == 0))
799                                 );
800                         }
801
802                         /* Skip blocks of commands we didn't match. */
803                         if (sed_cmd->cmd == '{') {
804                                 if(sed_cmd->invert ? matched : !matched)
805                                         while(sed_cmd && sed_cmd->cmd!='}') sed_cmd=sed_cmd->next;
806                                 if(!sed_cmd) bb_error_msg_and_die("Unterminated {");
807                                 continue;
808                         }
809
810                         /* Okay, so did this line match? */
811                         if (sed_cmd->invert ? !matched : matched) {
812                                 /* Update last used regex in case a blank substitute BRE is found */
813                                 if (sed_cmd->beg_match) {
814                                         previous_regex_ptr = sed_cmd->beg_match;
815                                 }
816
817                                 /* actual sedding */
818                                 switch (sed_cmd->cmd) {
819
820                                         /* Print line number */
821                                         case '=':
822                                                 printf("%d\n", linenum);
823                                                 break;
824
825                                         /* Write the current pattern space up to the first newline */
826                                         case 'P':
827                                         {
828                                                 char *tmp = strchr(pattern_space, '\n');
829
830                                                 if (tmp) {
831                                                         *tmp = '\0';
832                                                         sed_puts(pattern_space,1);
833                                                         *tmp = '\n';
834                                                         break;
835                                                 }
836                                                 /* Fall Through */
837                                         }
838
839                                         /* Write the current pattern space to output */
840                                         case 'p':
841                                                 sed_puts(pattern_space,no_newline);
842                                                 break;
843                                         /* Delete up through first newline */
844                                         case 'D':
845                                         {
846                                                 char *tmp = strchr(pattern_space,'\n');
847
848                                                 if(tmp) {
849                                                         tmp=bb_xstrdup(tmp+1);
850                                                         free(pattern_space);
851                                                         pattern_space=tmp;
852                                                         goto restart;
853                                                 }
854                                         }
855                                         /* discard this line. */
856                                         case 'd':
857                                                 goto discard_line;
858
859                                         /* Substitute with regex */
860                                         case 's':
861                                                 if(do_subst_command(sed_cmd, &pattern_space)) {
862                                                         substituted|=1;
863
864                                                         /* handle p option */
865                                                         if(sed_cmd->sub_p)
866                                                                 sed_puts(pattern_space,no_newline);
867                                                         /* handle w option */
868                                                         if(sed_cmd->file)
869                                                                 sed_cmd->no_newline=puts_maybe_newline(pattern_space, sed_cmd->file, sed_cmd->no_newline, no_newline);
870
871                                                 }
872                                                 break;
873
874                                         /* Append line to linked list to be printed later */
875                                         case 'a':
876                                         {
877                                                 append(sed_cmd->string);
878                                                 break;
879                                         }
880
881                                         /* Insert text before this line */
882                                         case 'i':
883                                                 sed_puts(sed_cmd->string,1);
884                                                 break;
885
886                                         /* Cut and paste text (replace) */
887                                         case 'c':
888                                                 /* Only triggers on last line of a matching range. */
889                                                 if (!sed_cmd->in_match) sed_puts(sed_cmd->string,1);
890                                                 goto discard_line;
891
892                                         /* Read file, append contents to output */
893                                         case 'r':
894                                         {
895                                                 FILE *outfile;
896
897                                                 outfile = fopen(sed_cmd->string, "r");
898                                                 if (outfile) {
899                                                         char *line;
900
901                                                         while ((line = bb_get_chomped_line_from_file(outfile))
902                                                                         != NULL)
903                                                                 append(line);
904                                                         bb_xprint_and_close_file(outfile);
905                                                 }
906
907                                                 break;
908                                         }
909
910                                         /* Write pattern space to file. */
911                                         case 'w':
912                                                 sed_cmd->no_newline=puts_maybe_newline(pattern_space,sed_cmd->file, sed_cmd->no_newline,no_newline);
913                                                 break;
914
915                                         /* Read next line from input */
916                                         case 'n':
917                                                 if (!be_quiet)
918                                                         sed_puts(pattern_space,no_newline);
919                                                 if (next_line) {
920                                                         free(pattern_space);
921                                                         pattern_space = next_line;
922                                                         no_newline=next_no_newline;
923                                                         next_line = get_next_line(file,&next_no_newline);
924                                                         linenum++;
925                                                         break;
926                                                 }
927                                                 /* fall through */
928
929                                         /* Quit.  End of script, end of input. */
930                                         case 'q':
931                                                 /* Exit the outer while loop */
932                                                 free(next_line);
933                                                 next_line = NULL;
934                                                 goto discard_commands;
935
936                                         /* Append the next line to the current line */
937                                         case 'N':
938                                         {
939                                                 /* If no next line, jump to end of script and exit. */
940                                                 if (next_line == NULL) {
941                                                         /* Jump to end of script and exit */
942                                                         free(next_line);
943                                                         next_line = NULL;
944                                                         goto discard_line;
945                                                 /* append next_line, read new next_line. */
946                                                 } else {
947                                                         int len=strlen(pattern_space);
948
949                                                         pattern_space = realloc(pattern_space, len + strlen(next_line) + 2);
950                                                         pattern_space[len]='\n';
951                                                         strcpy(pattern_space+len+1, next_line);
952                                                         no_newline=next_no_newline;
953                                                         next_line = get_next_line(file,&next_no_newline);
954                                                         linenum++;
955                                                 }
956                                                 break;
957                                         }
958
959                                         /* Test if substition worked, branch if so. */
960                                         case 't':
961                                                 if (!substituted) break;
962                                                 substituted=0;
963                                                         /* Fall through */
964                                         /* Branch to label */
965                                         case 'b':
966                                                 if (!sed_cmd->string) goto discard_commands;
967                                                 else sed_cmd = branch_to(sed_cmd->string);
968                                                 break;
969                                         /* Transliterate characters */
970                                         case 'y':
971                                         {
972                                                 int i;
973
974                                                 for (i = 0; pattern_space[i]; i++) {
975                                                         int j;
976
977                                                         for (j = 0; sed_cmd->string[j]; j += 2) {
978                                                                 if (pattern_space[i] == sed_cmd->string[j]) {
979                                                                         pattern_space[i] = sed_cmd->string[j + 1];
980                                                                 }
981                                                         }
982                                                 }
983
984                                                 break;
985                                         }
986                                         case 'g':       /* Replace pattern space with hold space */
987                                                 free(pattern_space);
988                                                 if (hold_space) {
989                                                         pattern_space = strdup(hold_space);
990                                                         no_newline=0;
991                                                 }
992                                                 break;
993                                         case 'G':       /* Append newline and hold space to pattern space */
994                                         {
995                                                 int pattern_space_size = 2;
996                                                 int hold_space_size = 0;
997
998                                                 if (pattern_space)
999                                                         pattern_space_size += strlen(pattern_space);
1000                                                 if (hold_space) hold_space_size = strlen(hold_space);
1001                                                 pattern_space = xrealloc(pattern_space, pattern_space_size + hold_space_size);
1002                                                 if (pattern_space_size == 2) pattern_space[0]=0;
1003                                                 strcat(pattern_space, "\n");
1004                                                 if (hold_space) strcat(pattern_space, hold_space);
1005                                                 no_newline=0;
1006
1007                                                 break;
1008                                         }
1009                                         case 'h':       /* Replace hold space with pattern space */
1010                                                 free(hold_space);
1011                                                 hold_space = strdup(pattern_space);
1012                                                 break;
1013                                         case 'H':       /* Append newline and pattern space to hold space */
1014                                         {
1015                                                 int hold_space_size = 2;
1016                                                 int pattern_space_size = 0;
1017
1018                                                 if (hold_space) hold_space_size += strlen(hold_space);
1019                                                 if (pattern_space)
1020                                                         pattern_space_size = strlen(pattern_space);
1021                                                 hold_space = xrealloc(hold_space,
1022                                                                                         hold_space_size + pattern_space_size);
1023
1024                                                 if (hold_space_size == 2) hold_space[0]=0;
1025                                                 strcat(hold_space, "\n");
1026                                                 if (pattern_space) strcat(hold_space, pattern_space);
1027
1028                                                 break;
1029                                         }
1030                                         case 'x': /* Exchange hold and pattern space */
1031                                         {
1032                                                 char *tmp = pattern_space;
1033                                                 pattern_space = hold_space;
1034                                                 no_newline=0;
1035                                                 hold_space = tmp;
1036                                                 break;
1037                                         }
1038                                 }
1039                         }
1040                 }
1041
1042                 /*
1043                  * exit point from sedding...
1044                  */
1045 discard_commands:
1046                 /* we will print the line unless we were told to be quiet ('-n')
1047                    or if the line was suppressed (ala 'd'elete) */
1048                 if (!be_quiet) sed_puts(pattern_space,no_newline);
1049
1050                 /* Delete and such jump here. */
1051 discard_line:
1052                 flush_append();
1053                 free(pattern_space);
1054         }
1055 }
1056
1057 /* It is possible to have a command line argument with embedded
1058    newlines.  This counts as multiple command lines. */
1059
1060 static void add_cmd_block(char *cmdstr)
1061 {
1062         int go=1;
1063         char *temp=bb_xstrdup(cmdstr),*temp2=temp;
1064
1065         while(go) {
1066                 int len=strcspn(temp2,"\n");
1067                 if(!temp2[len]) go=0;
1068                 else temp2[len]=0;
1069                 add_cmd(temp2);
1070                 temp2+=len+1;
1071         }
1072         free(temp);
1073 }
1074
1075 extern int sed_main(int argc, char **argv)
1076 {
1077         int opt, status = EXIT_SUCCESS;
1078
1079 #ifdef CONFIG_FEATURE_CLEAN_UP
1080         /* destroy command strings on exit */
1081         if (atexit(free_and_close_stuff) == -1)
1082                 bb_perror_msg_and_die("atexit");
1083 #endif
1084
1085 #define LIE_TO_AUTOCONF
1086 #ifdef LIE_TO_AUTOCONF
1087         if(argc==2 && !strcmp(argv[1],"--version")) {
1088                 printf("This is not GNU sed version 4.0\n");
1089                 exit(0);
1090         }
1091 #endif
1092
1093         /* do normal option parsing */
1094         while ((opt = getopt(argc, argv, "ne:f:")) > 0) {
1095                 switch (opt) {
1096                 case 'n':
1097                         be_quiet++;
1098                         break;
1099                 case 'e':
1100                         add_cmd_block(optarg);
1101                         break;
1102                 case 'f':
1103                 {
1104                         FILE *cmdfile;
1105                         char *line;
1106
1107                         cmdfile = bb_xfopen(optarg, "r");
1108
1109                         while ((line = bb_get_chomped_line_from_file(cmdfile))
1110                                  != NULL) {
1111                                 add_cmd(line);
1112                                 free(line);
1113                         }
1114                         bb_xprint_and_close_file(cmdfile);
1115
1116                         break;
1117                 }
1118                 default:
1119                         bb_show_usage();
1120                 }
1121         }
1122
1123         /* if we didn't get a pattern from a -e and no command file was specified,
1124          * argv[optind] should be the pattern. no pattern, no worky */
1125         if (sed_cmd_head.next == NULL) {
1126                 if (argv[optind] == NULL)
1127                         bb_show_usage();
1128                 else
1129                         add_cmd_block(argv[optind++]);
1130         }
1131         /* Flush any unfinished commands. */
1132         add_cmd("");
1133
1134         /* argv[(optind)..(argc-1)] should be names of file to process. If no
1135          * files were specified or '-' was specified, take input from stdin.
1136          * Otherwise, we process all the files specified. */
1137         if (argv[optind] == NULL) {
1138                 process_file(stdin);
1139         } else {
1140                 int i;
1141                 FILE *file;
1142
1143                 for (i = optind; i < argc; i++) {
1144                         if(!strcmp(argv[i], "-")) {
1145                                 process_file(stdin);
1146                         } else {
1147                                 file = bb_wfopen(argv[i], "r");
1148                                 if (file) {
1149                                         process_file(file);
1150                                         fclose(file);
1151                                 } else {
1152                                         status = EXIT_FAILURE;
1153                                 }
1154                         }
1155                 }
1156         }
1157
1158         return status;
1159 }