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