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