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