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