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