]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - usr.bin/patch/pch.c
Fix patch(1) shell injection vulnerability via ed(1). [SA-15:18]
[FreeBSD/releng/10.2.git] / usr.bin / patch / pch.c
1 /*-
2  * Copyright 1986, Larry Wall
3  * 
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following condition is met:
6  * 1. Redistributions of source code must retain the above copyright notice,
7  * this condition and the following disclaimer.
8  * 
9  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
10  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
11  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
12  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
13  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
15  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
16  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
17  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
19  * SUCH DAMAGE.
20  * 
21  * patch - a program to apply diffs to original files
22  *
23  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
24  * behaviour
25  *
26  * $OpenBSD: pch.c,v 1.43 2014/11/18 17:03:35 tobias Exp $
27  * $FreeBSD$
28  */
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32
33 #include <ctype.h>
34 #include <libgen.h>
35 #include <limits.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40
41 #include "common.h"
42 #include "util.h"
43 #include "pch.h"
44 #include "pathnames.h"
45
46 /* Patch (diff listing) abstract type. */
47
48 static off_t    p_filesize;     /* size of the patch file */
49 static LINENUM  p_first;        /* 1st line number */
50 static LINENUM  p_newfirst;     /* 1st line number of replacement */
51 static LINENUM  p_ptrn_lines;   /* # lines in pattern */
52 static LINENUM  p_repl_lines;   /* # lines in replacement text */
53 static LINENUM  p_end = -1;     /* last line in hunk */
54 static LINENUM  p_max;          /* max allowed value of p_end */
55 static LINENUM  p_context = 3;  /* # of context lines */
56 static LINENUM  p_input_line = 0;       /* current line # from patch file */
57 static char     **p_line = NULL;/* the text of the hunk */
58 static unsigned short   *p_len = NULL; /* length of each line */
59 static char     *p_char = NULL; /* +, -, and ! */
60 static int      hunkmax = INITHUNKMAX;  /* size of above arrays to begin with */
61 static int      p_indent;       /* indent to patch */
62 static off_t    p_base;         /* where to intuit this time */
63 static LINENUM  p_bline;        /* line # of p_base */
64 static off_t    p_start;        /* where intuit found a patch */
65 static LINENUM  p_sline;        /* and the line number for it */
66 static LINENUM  p_hunk_beg;     /* line number of current hunk */
67 static LINENUM  p_efake = -1;   /* end of faked up lines--don't free */
68 static LINENUM  p_bfake = -1;   /* beg of faked up lines */
69 static FILE     *pfp = NULL;    /* patch file pointer */
70 static char     *bestguess = NULL;      /* guess at correct filename */
71
72 static void     grow_hunkmax(void);
73 static int      intuit_diff_type(void);
74 static void     next_intuit_at(off_t, LINENUM);
75 static void     skip_to(off_t, LINENUM);
76 static size_t   pgets(bool _do_indent);
77 static char     *best_name(const struct file_name *, bool);
78 static char     *posix_name(const struct file_name *, bool);
79 static size_t   num_components(const char *);
80 static LINENUM  strtolinenum(char *, char **);
81
82 /*
83  * Prepare to look for the next patch in the patch file.
84  */
85 void
86 re_patch(void)
87 {
88         p_first = 0;
89         p_newfirst = 0;
90         p_ptrn_lines = 0;
91         p_repl_lines = 0;
92         p_end = (LINENUM) - 1;
93         p_max = 0;
94         p_indent = 0;
95 }
96
97 /*
98  * Open the patch file at the beginning of time.
99  */
100 void
101 open_patch_file(const char *filename)
102 {
103         struct stat filestat;
104         int nr, nw;
105
106         if (filename == NULL || *filename == '\0' || strEQ(filename, "-")) {
107                 pfp = fopen(TMPPATNAME, "w");
108                 if (pfp == NULL)
109                         pfatal("can't create %s", TMPPATNAME);
110                 while ((nr = fread(buf, 1, buf_size, stdin)) > 0) {
111                         nw = fwrite(buf, 1, nr, pfp);
112                         if (nr != nw)
113                                 pfatal("write error to %s", TMPPATNAME);
114                 }
115                 if (ferror(pfp) || fclose(pfp))
116                         pfatal("can't write %s", TMPPATNAME);
117                 filename = TMPPATNAME;
118         }
119         pfp = fopen(filename, "r");
120         if (pfp == NULL)
121                 pfatal("patch file %s not found", filename);
122         if (fstat(fileno(pfp), &filestat))
123                 pfatal("can't stat %s", filename);
124         p_filesize = filestat.st_size;
125         next_intuit_at(0, 1L);  /* start at the beginning */
126         set_hunkmax();
127 }
128
129 /*
130  * Make sure our dynamically realloced tables are malloced to begin with.
131  */
132 void
133 set_hunkmax(void)
134 {
135         if (p_line == NULL)
136                 p_line = malloc(hunkmax * sizeof(char *));
137         if (p_len == NULL)
138                 p_len = malloc(hunkmax * sizeof(unsigned short));
139         if (p_char == NULL)
140                 p_char = malloc(hunkmax * sizeof(char));
141 }
142
143 /*
144  * Enlarge the arrays containing the current hunk of patch.
145  */
146 static void
147 grow_hunkmax(void)
148 {
149         int new_hunkmax = hunkmax * 2;
150
151         if (p_line == NULL || p_len == NULL || p_char == NULL)
152                 fatal("Internal memory allocation error\n");
153
154         p_line = reallocf(p_line, new_hunkmax * sizeof(char *));
155         p_len = reallocf(p_len, new_hunkmax * sizeof(unsigned short));
156         p_char = reallocf(p_char, new_hunkmax * sizeof(char));
157
158         if (p_line != NULL && p_len != NULL && p_char != NULL) {
159                 hunkmax = new_hunkmax;
160                 return;
161         }
162
163         if (!using_plan_a)
164                 fatal("out of memory\n");
165         out_of_mem = true;      /* whatever is null will be allocated again */
166                                 /* from within plan_a(), of all places */
167 }
168
169 /* True if the remainder of the patch file contains a diff of some sort. */
170
171 bool
172 there_is_another_patch(void)
173 {
174         bool exists = false;
175
176         if (p_base != 0 && p_base >= p_filesize) {
177                 if (verbose)
178                         say("done\n");
179                 return false;
180         }
181         if (verbose)
182                 say("Hmm...");
183         diff_type = intuit_diff_type();
184         if (!diff_type) {
185                 if (p_base != 0) {
186                         if (verbose)
187                                 say("  Ignoring the trailing garbage.\ndone\n");
188                 } else
189                         say("  I can't seem to find a patch in there anywhere.\n");
190                 return false;
191         }
192         if (verbose)
193                 say("  %sooks like %s to me...\n",
194                     (p_base == 0 ? "L" : "The next patch l"),
195                     diff_type == UNI_DIFF ? "a unified diff" :
196                     diff_type == CONTEXT_DIFF ? "a context diff" :
197                 diff_type == NEW_CONTEXT_DIFF ? "a new-style context diff" :
198                     diff_type == NORMAL_DIFF ? "a normal diff" :
199                     "an ed script");
200         if (p_indent && verbose)
201                 say("(Patch is indented %d space%s.)\n", p_indent,
202                     p_indent == 1 ? "" : "s");
203         skip_to(p_start, p_sline);
204         while (filearg[0] == NULL) {
205                 if (force || batch) {
206                         say("No file to patch.  Skipping...\n");
207                         filearg[0] = xstrdup(bestguess);
208                         skip_rest_of_patch = true;
209                         return true;
210                 }
211                 ask("File to patch: ");
212                 if (*buf != '\n') {
213                         free(bestguess);
214                         bestguess = xstrdup(buf);
215                         filearg[0] = fetchname(buf, &exists, 0);
216                 }
217                 if (!exists) {
218                         ask("No file found--skip this patch? [n] ");
219                         if (*buf != 'y')
220                                 continue;
221                         if (verbose)
222                                 say("Skipping patch...\n");
223                         free(filearg[0]);
224                         filearg[0] = fetchname(bestguess, &exists, 0);
225                         skip_rest_of_patch = true;
226                         return true;
227                 }
228         }
229         return true;
230 }
231
232 static void
233 p4_fetchname(struct file_name *name, char *str)
234 {
235         char *t, *h;
236
237         /* Skip leading whitespace. */
238         while (isspace((unsigned char)*str))
239                 str++;
240
241         /* Remove the file revision number. */
242         for (t = str, h = NULL; *t != '\0' && !isspace((unsigned char)*t); t++)
243                 if (*t == '#')
244                         h = t;
245         if (h != NULL)
246                 *h = '\0';
247
248         name->path = fetchname(str, &name->exists, strippath);
249 }
250
251 /* Determine what kind of diff is in the remaining part of the patch file. */
252
253 static int
254 intuit_diff_type(void)
255 {
256         off_t   this_line = 0, previous_line;
257         off_t   first_command_line = -1;
258         LINENUM fcl_line = -1;
259         bool    last_line_was_command = false, this_is_a_command = false;
260         bool    stars_last_line = false, stars_this_line = false;
261         char    *s, *t;
262         int     indent, retval;
263         struct file_name names[MAX_FILE];
264
265         memset(names, 0, sizeof(names));
266         ok_to_create_file = false;
267         fseeko(pfp, p_base, SEEK_SET);
268         p_input_line = p_bline - 1;
269         for (;;) {
270                 previous_line = this_line;
271                 last_line_was_command = this_is_a_command;
272                 stars_last_line = stars_this_line;
273                 this_line = ftello(pfp);
274                 indent = 0;
275                 p_input_line++;
276                 if (pgets(false) == 0) {
277                         if (first_command_line >= 0) {
278                                 /* nothing but deletes!? */
279                                 p_start = first_command_line;
280                                 p_sline = fcl_line;
281                                 retval = ED_DIFF;
282                                 goto scan_exit;
283                         } else {
284                                 p_start = this_line;
285                                 p_sline = p_input_line;
286                                 retval = 0;
287                                 goto scan_exit;
288                         }
289                 }
290                 for (s = buf; *s == ' ' || *s == '\t' || *s == 'X'; s++) {
291                         if (*s == '\t')
292                                 indent += 8 - (indent % 8);
293                         else
294                                 indent++;
295                 }
296                 for (t = s; isdigit((unsigned char)*t) || *t == ','; t++)
297                         ;
298                 this_is_a_command = (isdigit((unsigned char)*s) &&
299                     (*t == 'd' || *t == 'c' || *t == 'a'));
300                 if (first_command_line < 0 && this_is_a_command) {
301                         first_command_line = this_line;
302                         fcl_line = p_input_line;
303                         p_indent = indent;      /* assume this for now */
304                 }
305                 if (!stars_last_line && strnEQ(s, "*** ", 4))
306                         names[OLD_FILE].path = fetchname(s + 4,
307                             &names[OLD_FILE].exists, strippath);
308                 else if (strnEQ(s, "--- ", 4))
309                         names[NEW_FILE].path = fetchname(s + 4,
310                             &names[NEW_FILE].exists, strippath);
311                 else if (strnEQ(s, "+++ ", 4))
312                         /* pretend it is the old name */
313                         names[OLD_FILE].path = fetchname(s + 4,
314                             &names[OLD_FILE].exists, strippath);
315                 else if (strnEQ(s, "Index:", 6))
316                         names[INDEX_FILE].path = fetchname(s + 6,
317                             &names[INDEX_FILE].exists, strippath);
318                 else if (strnEQ(s, "Prereq:", 7)) {
319                         for (t = s + 7; isspace((unsigned char)*t); t++)
320                                 ;
321                         revision = xstrdup(t);
322                         for (t = revision;
323                              *t && !isspace((unsigned char)*t); t++)
324                                 ;
325                         *t = '\0';
326                         if (*revision == '\0') {
327                                 free(revision);
328                                 revision = NULL;
329                         }
330                 } else if (strnEQ(s, "==== ", 5)) {
331                         /* Perforce-style diffs. */
332                         if ((t = strstr(s + 5, " - ")) != NULL)
333                                 p4_fetchname(&names[NEW_FILE], t + 3);
334                         p4_fetchname(&names[OLD_FILE], s + 5);
335                 }
336                 if ((!diff_type || diff_type == ED_DIFF) &&
337                     first_command_line >= 0 &&
338                     strEQ(s, ".\n")) {
339                         p_indent = indent;
340                         p_start = first_command_line;
341                         p_sline = fcl_line;
342                         retval = ED_DIFF;
343                         goto scan_exit;
344                 }
345                 if ((!diff_type || diff_type == UNI_DIFF) && strnEQ(s, "@@ -", 4)) {
346                         if (strnEQ(s + 4, "0,0", 3))
347                                 ok_to_create_file = true;
348                         p_indent = indent;
349                         p_start = this_line;
350                         p_sline = p_input_line;
351                         retval = UNI_DIFF;
352                         goto scan_exit;
353                 }
354                 stars_this_line = strnEQ(s, "********", 8);
355                 if ((!diff_type || diff_type == CONTEXT_DIFF) && stars_last_line &&
356                     strnEQ(s, "*** ", 4)) {
357                         if (strtolinenum(s + 4, &s) == 0)
358                                 ok_to_create_file = true;
359                         /*
360                          * If this is a new context diff the character just
361                          * at the end of the line is a '*'.
362                          */
363                         while (*s && *s != '\n')
364                                 s++;
365                         p_indent = indent;
366                         p_start = previous_line;
367                         p_sline = p_input_line - 1;
368                         retval = (*(s - 1) == '*' ? NEW_CONTEXT_DIFF : CONTEXT_DIFF);
369                         goto scan_exit;
370                 }
371                 if ((!diff_type || diff_type == NORMAL_DIFF) &&
372                     last_line_was_command &&
373                     (strnEQ(s, "< ", 2) || strnEQ(s, "> ", 2))) {
374                         p_start = previous_line;
375                         p_sline = p_input_line - 1;
376                         p_indent = indent;
377                         retval = NORMAL_DIFF;
378                         goto scan_exit;
379                 }
380         }
381 scan_exit:
382         if (retval == UNI_DIFF) {
383                 /* unswap old and new */
384                 struct file_name tmp = names[OLD_FILE];
385                 names[OLD_FILE] = names[NEW_FILE];
386                 names[NEW_FILE] = tmp;
387         }
388         if (filearg[0] == NULL) {
389                 if (posix)
390                         filearg[0] = posix_name(names, ok_to_create_file);
391                 else {
392                         /* Ignore the Index: name for context diffs, like GNU */
393                         if (names[OLD_FILE].path != NULL ||
394                             names[NEW_FILE].path != NULL) {
395                                 free(names[INDEX_FILE].path);
396                                 names[INDEX_FILE].path = NULL;
397                         }
398                         filearg[0] = best_name(names, ok_to_create_file);
399                 }
400         }
401
402         free(bestguess);
403         bestguess = NULL;
404         if (filearg[0] != NULL)
405                 bestguess = xstrdup(filearg[0]);
406         else if (!ok_to_create_file) {
407                 /*
408                  * We don't want to create a new file but we need a
409                  * filename to set bestguess.  Avoid setting filearg[0]
410                  * so the file is not created automatically.
411                  */
412                 if (posix)
413                         bestguess = posix_name(names, true);
414                 else
415                         bestguess = best_name(names, true);
416         }
417         free(names[OLD_FILE].path);
418         free(names[NEW_FILE].path);
419         free(names[INDEX_FILE].path);
420         return retval;
421 }
422
423 /*
424  * Remember where this patch ends so we know where to start up again.
425  */
426 static void
427 next_intuit_at(off_t file_pos, LINENUM file_line)
428 {
429         p_base = file_pos;
430         p_bline = file_line;
431 }
432
433 /*
434  * Basically a verbose fseeko() to the actual diff listing.
435  */
436 static void
437 skip_to(off_t file_pos, LINENUM file_line)
438 {
439         size_t  len;
440
441         if (p_base > file_pos)
442                 fatal("Internal error: seek %lld>%lld\n",
443                    (long long)p_base, (long long)file_pos);
444         if (verbose && p_base < file_pos) {
445                 fseeko(pfp, p_base, SEEK_SET);
446                 say("The text leading up to this was:\n--------------------------\n");
447                 while (ftello(pfp) < file_pos) {
448                         len = pgets(false);
449                         if (len == 0)
450                                 fatal("Unexpected end of file\n");
451                         say("|%s", buf);
452                 }
453                 say("--------------------------\n");
454         } else
455                 fseeko(pfp, file_pos, SEEK_SET);
456         p_input_line = file_line - 1;
457 }
458
459 /* Make this a function for better debugging.  */
460 static void
461 malformed(void)
462 {
463         fatal("malformed patch at line %ld: %s", p_input_line, buf);
464         /* about as informative as "Syntax error" in C */
465 }
466
467 /*
468  * True if the line has been discarded (i.e. it is a line saying
469  *  "\ No newline at end of file".)
470  */
471 static bool
472 remove_special_line(void)
473 {
474         int     c;
475
476         c = fgetc(pfp);
477         if (c == '\\') {
478                 do {
479                         c = fgetc(pfp);
480                 } while (c != EOF && c != '\n');
481
482                 return true;
483         }
484         if (c != EOF)
485                 fseeko(pfp, -1, SEEK_CUR);
486
487         return false;
488 }
489
490 /*
491  * True if there is more of the current diff listing to process.
492  */
493 bool
494 another_hunk(void)
495 {
496         off_t   line_beginning;                 /* file pos of the current line */
497         LINENUM repl_beginning;                 /* index of --- line */
498         LINENUM fillcnt;                        /* #lines of missing ptrn or repl */
499         LINENUM fillsrc;                        /* index of first line to copy */
500         LINENUM filldst;                        /* index of first missing line */
501         bool    ptrn_spaces_eaten;              /* ptrn was slightly misformed */
502         bool    repl_could_be_missing;          /* no + or ! lines in this hunk */
503         bool    repl_missing;                   /* we are now backtracking */
504         off_t   repl_backtrack_position;        /* file pos of first repl line */
505         LINENUM repl_patch_line;                /* input line number for same */
506         LINENUM ptrn_copiable;                  /* # of copiable lines in ptrn */
507         char    *s;
508         size_t  len;
509         int     context = 0;
510
511         while (p_end >= 0) {
512                 if (p_end == p_efake)
513                         p_end = p_bfake;        /* don't free twice */
514                 else
515                         free(p_line[p_end]);
516                 p_end--;
517         }
518         p_efake = -1;
519
520         p_max = hunkmax;        /* gets reduced when --- found */
521         if (diff_type == CONTEXT_DIFF || diff_type == NEW_CONTEXT_DIFF) {
522                 line_beginning = ftello(pfp);
523                 repl_beginning = 0;
524                 fillcnt = 0;
525                 fillsrc = 0;
526                 filldst = 0;
527                 ptrn_spaces_eaten = false;
528                 repl_could_be_missing = true;
529                 repl_missing = false;
530                 repl_backtrack_position = 0;
531                 repl_patch_line = 0;
532                 ptrn_copiable = 0;
533
534                 len = pgets(true);
535                 p_input_line++;
536                 if (len == 0 || strnNE(buf, "********", 8)) {
537                         next_intuit_at(line_beginning, p_input_line);
538                         return false;
539                 }
540                 p_context = 100;
541                 p_hunk_beg = p_input_line + 1;
542                 while (p_end < p_max) {
543                         line_beginning = ftello(pfp);
544                         len = pgets(true);
545                         p_input_line++;
546                         if (len == 0) {
547                                 if (p_max - p_end < 4) {
548                                         /* assume blank lines got chopped */
549                                         strlcpy(buf, "  \n", buf_size);
550                                 } else {
551                                         if (repl_beginning && repl_could_be_missing) {
552                                                 repl_missing = true;
553                                                 goto hunk_done;
554                                         }
555                                         fatal("unexpected end of file in patch\n");
556                                 }
557                         }
558                         p_end++;
559                         if (p_end >= hunkmax)
560                                 fatal("Internal error: hunk larger than hunk "
561                                     "buffer size");
562                         p_char[p_end] = *buf;
563                         p_line[p_end] = NULL;
564                         switch (*buf) {
565                         case '*':
566                                 if (strnEQ(buf, "********", 8)) {
567                                         if (repl_beginning && repl_could_be_missing) {
568                                                 repl_missing = true;
569                                                 goto hunk_done;
570                                         } else
571                                                 fatal("unexpected end of hunk "
572                                                     "at line %ld\n",
573                                                     p_input_line);
574                                 }
575                                 if (p_end != 0) {
576                                         if (repl_beginning && repl_could_be_missing) {
577                                                 repl_missing = true;
578                                                 goto hunk_done;
579                                         }
580                                         fatal("unexpected *** at line %ld: %s",
581                                             p_input_line, buf);
582                                 }
583                                 context = 0;
584                                 p_line[p_end] = savestr(buf);
585                                 if (out_of_mem) {
586                                         p_end--;
587                                         return false;
588                                 }
589                                 for (s = buf;
590                                      *s && !isdigit((unsigned char)*s); s++)
591                                         ;
592                                 if (!*s)
593                                         malformed();
594                                 if (strnEQ(s, "0,0", 3))
595                                         memmove(s, s + 2, strlen(s + 2) + 1);
596                                 p_first = strtolinenum(s, &s);
597                                 if (*s == ',') {
598                                         for (;
599                                              *s && !isdigit((unsigned char)*s); s++)
600                                                 ;
601                                         if (!*s)
602                                                 malformed();
603                                         p_ptrn_lines = strtolinenum(s, &s) - p_first + 1;
604                                         if (p_ptrn_lines < 0)
605                                                 malformed();
606                                 } else if (p_first)
607                                         p_ptrn_lines = 1;
608                                 else {
609                                         p_ptrn_lines = 0;
610                                         p_first = 1;
611                                 }
612                                 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
613                                     p_ptrn_lines >= LINENUM_MAX - 6)
614                                         malformed();
615
616                                 /* we need this much at least */
617                                 p_max = p_ptrn_lines + 6;
618                                 while (p_max >= hunkmax)
619                                         grow_hunkmax();
620                                 p_max = hunkmax;
621                                 break;
622                         case '-':
623                                 if (buf[1] == '-') {
624                                         if (repl_beginning ||
625                                             (p_end != p_ptrn_lines + 1 +
626                                             (p_char[p_end - 1] == '\n'))) {
627                                                 if (p_end == 1) {
628                                                         /*
629                                                          * `old' lines were omitted;
630                                                          * set up to fill them in
631                                                          * from 'new' context lines.
632                                                          */
633                                                         p_end = p_ptrn_lines + 1;
634                                                         fillsrc = p_end + 1;
635                                                         filldst = 1;
636                                                         fillcnt = p_ptrn_lines;
637                                                 } else {
638                                                         if (repl_beginning) {
639                                                                 if (repl_could_be_missing) {
640                                                                         repl_missing = true;
641                                                                         goto hunk_done;
642                                                                 }
643                                                                 fatal("duplicate \"---\" at line %ld--check line numbers at line %ld\n",
644                                                                     p_input_line, p_hunk_beg + repl_beginning);
645                                                         } else {
646                                                                 fatal("%s \"---\" at line %ld--check line numbers at line %ld\n",
647                                                                     (p_end <= p_ptrn_lines
648                                                                     ? "Premature"
649                                                                     : "Overdue"),
650                                                                     p_input_line, p_hunk_beg);
651                                                         }
652                                                 }
653                                         }
654                                         repl_beginning = p_end;
655                                         repl_backtrack_position = ftello(pfp);
656                                         repl_patch_line = p_input_line;
657                                         p_line[p_end] = savestr(buf);
658                                         if (out_of_mem) {
659                                                 p_end--;
660                                                 return false;
661                                         }
662                                         p_char[p_end] = '=';
663                                         for (s = buf; *s && !isdigit((unsigned char)*s); s++)
664                                                 ;
665                                         if (!*s)
666                                                 malformed();
667                                         p_newfirst = strtolinenum(s, &s);
668                                         if (*s == ',') {
669                                                 for (; *s && !isdigit((unsigned char)*s); s++)
670                                                         ;
671                                                 if (!*s)
672                                                         malformed();
673                                                 p_repl_lines = strtolinenum(s, &s) -
674                                                     p_newfirst + 1;
675                                                 if (p_repl_lines < 0)
676                                                         malformed();
677                                         } else if (p_newfirst)
678                                                 p_repl_lines = 1;
679                                         else {
680                                                 p_repl_lines = 0;
681                                                 p_newfirst = 1;
682                                         }
683                                         if (p_newfirst >= LINENUM_MAX - p_repl_lines ||
684                                             p_repl_lines >= LINENUM_MAX - p_end)
685                                                 malformed();
686                                         p_max = p_repl_lines + p_end;
687                                         if (p_max > MAXHUNKSIZE)
688                                                 fatal("hunk too large (%ld lines) at line %ld: %s",
689                                                     p_max, p_input_line, buf);
690                                         while (p_max >= hunkmax)
691                                                 grow_hunkmax();
692                                         if (p_repl_lines != ptrn_copiable &&
693                                             (p_context != 0 || p_repl_lines != 1))
694                                                 repl_could_be_missing = false;
695                                         break;
696                                 }
697                                 goto change_line;
698                         case '+':
699                         case '!':
700                                 repl_could_be_missing = false;
701                 change_line:
702                                 if (buf[1] == '\n' && canonicalize)
703                                         strlcpy(buf + 1, " \n", buf_size - 1);
704                                 if (!isspace((unsigned char)buf[1]) &&
705                                     buf[1] != '>' && buf[1] != '<' &&
706                                     repl_beginning && repl_could_be_missing) {
707                                         repl_missing = true;
708                                         goto hunk_done;
709                                 }
710                                 if (context >= 0) {
711                                         if (context < p_context)
712                                                 p_context = context;
713                                         context = -1000;
714                                 }
715                                 p_line[p_end] = savestr(buf + 2);
716                                 if (out_of_mem) {
717                                         p_end--;
718                                         return false;
719                                 }
720                                 if (p_end == p_ptrn_lines) {
721                                         if (remove_special_line()) {
722                                                 int     l;
723
724                                                 l = strlen(p_line[p_end]) - 1;
725                                                 (p_line[p_end])[l] = 0;
726                                         }
727                                 }
728                                 break;
729                         case '\t':
730                         case '\n':      /* assume the 2 spaces got eaten */
731                                 if (repl_beginning && repl_could_be_missing &&
732                                     (!ptrn_spaces_eaten ||
733                                     diff_type == NEW_CONTEXT_DIFF)) {
734                                         repl_missing = true;
735                                         goto hunk_done;
736                                 }
737                                 p_line[p_end] = savestr(buf);
738                                 if (out_of_mem) {
739                                         p_end--;
740                                         return false;
741                                 }
742                                 if (p_end != p_ptrn_lines + 1) {
743                                         ptrn_spaces_eaten |= (repl_beginning != 0);
744                                         context++;
745                                         if (!repl_beginning)
746                                                 ptrn_copiable++;
747                                         p_char[p_end] = ' ';
748                                 }
749                                 break;
750                         case ' ':
751                                 if (!isspace((unsigned char)buf[1]) &&
752                                     repl_beginning && repl_could_be_missing) {
753                                         repl_missing = true;
754                                         goto hunk_done;
755                                 }
756                                 context++;
757                                 if (!repl_beginning)
758                                         ptrn_copiable++;
759                                 p_line[p_end] = savestr(buf + 2);
760                                 if (out_of_mem) {
761                                         p_end--;
762                                         return false;
763                                 }
764                                 break;
765                         default:
766                                 if (repl_beginning && repl_could_be_missing) {
767                                         repl_missing = true;
768                                         goto hunk_done;
769                                 }
770                                 malformed();
771                         }
772                         /* set up p_len for strncmp() so we don't have to */
773                         /* assume null termination */
774                         if (p_line[p_end])
775                                 p_len[p_end] = strlen(p_line[p_end]);
776                         else
777                                 p_len[p_end] = 0;
778                 }
779
780 hunk_done:
781                 if (p_end >= 0 && !repl_beginning)
782                         fatal("no --- found in patch at line %ld\n", pch_hunk_beg());
783
784                 if (repl_missing) {
785
786                         /* reset state back to just after --- */
787                         p_input_line = repl_patch_line;
788                         for (p_end--; p_end > repl_beginning; p_end--)
789                                 free(p_line[p_end]);
790                         fseeko(pfp, repl_backtrack_position, SEEK_SET);
791
792                         /* redundant 'new' context lines were omitted - set */
793                         /* up to fill them in from the old file context */
794                         if (!p_context && p_repl_lines == 1) {
795                                 p_repl_lines = 0;
796                                 p_max--;
797                         }
798                         fillsrc = 1;
799                         filldst = repl_beginning + 1;
800                         fillcnt = p_repl_lines;
801                         p_end = p_max;
802                 } else if (!p_context && fillcnt == 1) {
803                         /* the first hunk was a null hunk with no context */
804                         /* and we were expecting one line -- fix it up. */
805                         while (filldst < p_end) {
806                                 p_line[filldst] = p_line[filldst + 1];
807                                 p_char[filldst] = p_char[filldst + 1];
808                                 p_len[filldst] = p_len[filldst + 1];
809                                 filldst++;
810                         }
811 #if 0
812                         repl_beginning--;       /* this doesn't need to be fixed */
813 #endif
814                         p_end--;
815                         p_first++;      /* do append rather than insert */
816                         fillcnt = 0;
817                         p_ptrn_lines = 0;
818                 }
819                 if (diff_type == CONTEXT_DIFF &&
820                     (fillcnt || (p_first > 1 && ptrn_copiable > 2 * p_context))) {
821                         if (verbose)
822                                 say("%s\n%s\n%s\n",
823                                     "(Fascinating--this is really a new-style context diff but without",
824                                     "the telltale extra asterisks on the *** line that usually indicate",
825                                     "the new style...)");
826                         diff_type = NEW_CONTEXT_DIFF;
827                 }
828                 /* if there were omitted context lines, fill them in now */
829                 if (fillcnt) {
830                         p_bfake = filldst;      /* remember where not to free() */
831                         p_efake = filldst + fillcnt - 1;
832                         while (fillcnt-- > 0) {
833                                 while (fillsrc <= p_end && p_char[fillsrc] != ' ')
834                                         fillsrc++;
835                                 if (fillsrc > p_end)
836                                         fatal("replacement text or line numbers mangled in hunk at line %ld\n",
837                                             p_hunk_beg);
838                                 p_line[filldst] = p_line[fillsrc];
839                                 p_char[filldst] = p_char[fillsrc];
840                                 p_len[filldst] = p_len[fillsrc];
841                                 fillsrc++;
842                                 filldst++;
843                         }
844                         while (fillsrc <= p_end && fillsrc != repl_beginning &&
845                             p_char[fillsrc] != ' ')
846                                 fillsrc++;
847 #ifdef DEBUGGING
848                         if (debug & 64)
849                                 printf("fillsrc %ld, filldst %ld, rb %ld, e+1 %ld\n",
850                                 fillsrc, filldst, repl_beginning, p_end + 1);
851 #endif
852                         if (fillsrc != p_end + 1 && fillsrc != repl_beginning)
853                                 malformed();
854                         if (filldst != p_end + 1 && filldst != repl_beginning)
855                                 malformed();
856                 }
857                 if (p_line[p_end] != NULL) {
858                         if (remove_special_line()) {
859                                 p_len[p_end] -= 1;
860                                 (p_line[p_end])[p_len[p_end]] = 0;
861                         }
862                 }
863         } else if (diff_type == UNI_DIFF) {
864                 LINENUM fillold;        /* index of old lines */
865                 LINENUM fillnew;        /* index of new lines */
866                 char    ch;
867
868                 line_beginning = ftello(pfp); /* file pos of the current line */
869                 len = pgets(true);
870                 p_input_line++;
871                 if (len == 0 || strnNE(buf, "@@ -", 4)) {
872                         next_intuit_at(line_beginning, p_input_line);
873                         return false;
874                 }
875                 s = buf + 4;
876                 if (!*s)
877                         malformed();
878                 p_first = strtolinenum(s, &s);
879                 if (*s == ',') {
880                         p_ptrn_lines = strtolinenum(s + 1, &s);
881                 } else
882                         p_ptrn_lines = 1;
883                 if (*s == ' ')
884                         s++;
885                 if (*s != '+' || !*++s)
886                         malformed();
887                 p_newfirst = strtolinenum(s, &s);
888                 if (*s == ',') {
889                         p_repl_lines = strtolinenum(s + 1, &s);
890                 } else
891                         p_repl_lines = 1;
892                 if (*s == ' ')
893                         s++;
894                 if (*s != '@')
895                         malformed();
896                 if (p_first >= LINENUM_MAX - p_ptrn_lines ||
897                     p_newfirst > LINENUM_MAX - p_repl_lines ||
898                     p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
899                         malformed();
900                 if (!p_ptrn_lines)
901                         p_first++;      /* do append rather than insert */
902                 p_max = p_ptrn_lines + p_repl_lines + 1;
903                 while (p_max >= hunkmax)
904                         grow_hunkmax();
905                 fillold = 1;
906                 fillnew = fillold + p_ptrn_lines;
907                 p_end = fillnew + p_repl_lines;
908                 snprintf(buf, buf_size, "*** %ld,%ld ****\n", p_first,
909                     p_first + p_ptrn_lines - 1);
910                 p_line[0] = savestr(buf);
911                 if (out_of_mem) {
912                         p_end = -1;
913                         return false;
914                 }
915                 p_char[0] = '*';
916                 snprintf(buf, buf_size, "--- %ld,%ld ----\n", p_newfirst,
917                     p_newfirst + p_repl_lines - 1);
918                 p_line[fillnew] = savestr(buf);
919                 if (out_of_mem) {
920                         p_end = 0;
921                         return false;
922                 }
923                 p_char[fillnew++] = '=';
924                 p_context = 100;
925                 context = 0;
926                 p_hunk_beg = p_input_line + 1;
927                 while (fillold <= p_ptrn_lines || fillnew <= p_end) {
928                         line_beginning = ftello(pfp);
929                         len = pgets(true);
930                         p_input_line++;
931                         if (len == 0) {
932                                 if (p_max - fillnew < 3) {
933                                         /* assume blank lines got chopped */
934                                         strlcpy(buf, " \n", buf_size);
935                                 } else {
936                                         fatal("unexpected end of file in patch\n");
937                                 }
938                         }
939                         if (*buf == '\t' || *buf == '\n') {
940                                 ch = ' ';       /* assume the space got eaten */
941                                 s = savestr(buf);
942                         } else {
943                                 ch = *buf;
944                                 s = savestr(buf + 1);
945                         }
946                         if (out_of_mem) {
947                                 while (--fillnew > p_ptrn_lines)
948                                         free(p_line[fillnew]);
949                                 p_end = fillold - 1;
950                                 return false;
951                         }
952                         switch (ch) {
953                         case '-':
954                                 if (fillold > p_ptrn_lines) {
955                                         free(s);
956                                         p_end = fillnew - 1;
957                                         malformed();
958                                 }
959                                 p_char[fillold] = ch;
960                                 p_line[fillold] = s;
961                                 p_len[fillold++] = strlen(s);
962                                 if (fillold > p_ptrn_lines) {
963                                         if (remove_special_line()) {
964                                                 p_len[fillold - 1] -= 1;
965                                                 s[p_len[fillold - 1]] = 0;
966                                         }
967                                 }
968                                 break;
969                         case '=':
970                                 ch = ' ';
971                                 /* FALL THROUGH */
972                         case ' ':
973                                 if (fillold > p_ptrn_lines) {
974                                         free(s);
975                                         while (--fillnew > p_ptrn_lines)
976                                                 free(p_line[fillnew]);
977                                         p_end = fillold - 1;
978                                         malformed();
979                                 }
980                                 context++;
981                                 p_char[fillold] = ch;
982                                 p_line[fillold] = s;
983                                 p_len[fillold++] = strlen(s);
984                                 s = savestr(s);
985                                 if (out_of_mem) {
986                                         while (--fillnew > p_ptrn_lines)
987                                                 free(p_line[fillnew]);
988                                         p_end = fillold - 1;
989                                         return false;
990                                 }
991                                 if (fillold > p_ptrn_lines) {
992                                         if (remove_special_line()) {
993                                                 p_len[fillold - 1] -= 1;
994                                                 s[p_len[fillold - 1]] = 0;
995                                         }
996                                 }
997                                 /* FALL THROUGH */
998                         case '+':
999                                 if (fillnew > p_end) {
1000                                         free(s);
1001                                         while (--fillnew > p_ptrn_lines)
1002                                                 free(p_line[fillnew]);
1003                                         p_end = fillold - 1;
1004                                         malformed();
1005                                 }
1006                                 p_char[fillnew] = ch;
1007                                 p_line[fillnew] = s;
1008                                 p_len[fillnew++] = strlen(s);
1009                                 if (fillold > p_ptrn_lines) {
1010                                         if (remove_special_line()) {
1011                                                 p_len[fillnew - 1] -= 1;
1012                                                 s[p_len[fillnew - 1]] = 0;
1013                                         }
1014                                 }
1015                                 break;
1016                         default:
1017                                 p_end = fillnew;
1018                                 malformed();
1019                         }
1020                         if (ch != ' ' && context > 0) {
1021                                 if (context < p_context)
1022                                         p_context = context;
1023                                 context = -1000;
1024                         }
1025                 }               /* while */
1026         } else {                /* normal diff--fake it up */
1027                 char    hunk_type;
1028                 int     i;
1029                 LINENUM min, max;
1030
1031                 line_beginning = ftello(pfp);
1032                 p_context = 0;
1033                 len = pgets(true);
1034                 p_input_line++;
1035                 if (len == 0 || !isdigit((unsigned char)*buf)) {
1036                         next_intuit_at(line_beginning, p_input_line);
1037                         return false;
1038                 }
1039                 p_first = strtolinenum(buf, &s);
1040                 if (*s == ',') {
1041                         p_ptrn_lines = strtolinenum(s + 1, &s) - p_first + 1;
1042                         if (p_ptrn_lines < 0)
1043                                 malformed();
1044                 } else
1045                         p_ptrn_lines = (*s != 'a');
1046                 hunk_type = *s;
1047                 if (hunk_type == 'a')
1048                         p_first++;      /* do append rather than insert */
1049                 min = strtolinenum(s + 1, &s);
1050                 if (*s == ',')
1051                         max = strtolinenum(s + 1, &s);
1052                 else
1053                         max = min;
1054                 if (min < 0 || min > max || max - min == LINENUM_MAX)
1055                         malformed();
1056                 if (hunk_type == 'd')
1057                         min++;
1058                 p_newfirst = min;
1059                 p_repl_lines = max - min + 1;
1060                 if (p_newfirst > LINENUM_MAX - p_repl_lines ||
1061                     p_ptrn_lines >= LINENUM_MAX - p_repl_lines - 1)
1062                         malformed();
1063                 p_end = p_ptrn_lines + p_repl_lines + 1;
1064                 if (p_end > MAXHUNKSIZE)
1065                         fatal("hunk too large (%ld lines) at line %ld: %s",
1066                             p_end, p_input_line, buf);
1067                 while (p_end >= hunkmax)
1068                         grow_hunkmax();
1069                 snprintf(buf, buf_size, "*** %ld,%ld\n", p_first,
1070                     p_first + p_ptrn_lines - 1);
1071                 p_line[0] = savestr(buf);
1072                 if (out_of_mem) {
1073                         p_end = -1;
1074                         return false;
1075                 }
1076                 p_char[0] = '*';
1077                 for (i = 1; i <= p_ptrn_lines; i++) {
1078                         len = pgets(true);
1079                         p_input_line++;
1080                         if (len == 0)
1081                                 fatal("unexpected end of file in patch at line %ld\n",
1082                                     p_input_line);
1083                         if (*buf != '<')
1084                                 fatal("< expected at line %ld of patch\n",
1085                                     p_input_line);
1086                         p_line[i] = savestr(buf + 2);
1087                         if (out_of_mem) {
1088                                 p_end = i - 1;
1089                                 return false;
1090                         }
1091                         p_len[i] = strlen(p_line[i]);
1092                         p_char[i] = '-';
1093                 }
1094
1095                 if (remove_special_line()) {
1096                         p_len[i - 1] -= 1;
1097                         (p_line[i - 1])[p_len[i - 1]] = 0;
1098                 }
1099                 if (hunk_type == 'c') {
1100                         len = pgets(true);
1101                         p_input_line++;
1102                         if (len == 0)
1103                                 fatal("unexpected end of file in patch at line %ld\n",
1104                                     p_input_line);
1105                         if (*buf != '-')
1106                                 fatal("--- expected at line %ld of patch\n",
1107                                     p_input_line);
1108                 }
1109                 snprintf(buf, buf_size, "--- %ld,%ld\n", min, max);
1110                 p_line[i] = savestr(buf);
1111                 if (out_of_mem) {
1112                         p_end = i - 1;
1113                         return false;
1114                 }
1115                 p_char[i] = '=';
1116                 for (i++; i <= p_end; i++) {
1117                         len = pgets(true);
1118                         p_input_line++;
1119                         if (len == 0)
1120                                 fatal("unexpected end of file in patch at line %ld\n",
1121                                     p_input_line);
1122                         if (*buf != '>')
1123                                 fatal("> expected at line %ld of patch\n",
1124                                     p_input_line);
1125                         p_line[i] = savestr(buf + 2);
1126                         if (out_of_mem) {
1127                                 p_end = i - 1;
1128                                 return false;
1129                         }
1130                         p_len[i] = strlen(p_line[i]);
1131                         p_char[i] = '+';
1132                 }
1133
1134                 if (remove_special_line()) {
1135                         p_len[i - 1] -= 1;
1136                         (p_line[i - 1])[p_len[i - 1]] = 0;
1137                 }
1138         }
1139         if (reverse)            /* backwards patch? */
1140                 if (!pch_swap())
1141                         say("Not enough memory to swap next hunk!\n");
1142 #ifdef DEBUGGING
1143         if (debug & 2) {
1144                 int     i;
1145                 char    special;
1146
1147                 for (i = 0; i <= p_end; i++) {
1148                         if (i == p_ptrn_lines)
1149                                 special = '^';
1150                         else
1151                                 special = ' ';
1152                         fprintf(stderr, "%3d %c %c %s", i, p_char[i],
1153                             special, p_line[i]);
1154                         fflush(stderr);
1155                 }
1156         }
1157 #endif
1158         if (p_end + 1 < hunkmax)/* paranoia reigns supreme... */
1159                 p_char[p_end + 1] = '^';        /* add a stopper for apply_hunk */
1160         return true;
1161 }
1162
1163 /*
1164  * Input a line from the patch file.
1165  * Worry about indentation if do_indent is true.
1166  * The line is read directly into the buf global variable which
1167  * is resized if necessary in order to hold the complete line.
1168  * Returns the number of characters read including the terminating
1169  * '\n', if any.
1170  */
1171 size_t
1172 pgets(bool do_indent)
1173 {
1174         char *line;
1175         size_t len;
1176         int indent = 0, skipped = 0;
1177
1178         line = fgetln(pfp, &len);
1179         if (line != NULL) {
1180                 if (len + 1 > buf_size) {
1181                         while (len + 1 > buf_size)
1182                                 buf_size *= 2;
1183                         free(buf);
1184                         buf = malloc(buf_size);
1185                         if (buf == NULL)
1186                                 fatal("out of memory\n");
1187                 }
1188                 if (do_indent == 1 && p_indent) {
1189                         for (;
1190                             indent < p_indent && (*line == ' ' || *line == '\t' || *line == 'X');
1191                             line++, skipped++) {
1192                                 if (*line == '\t')
1193                                         indent += 8 - (indent %7);
1194                                 else
1195                                         indent++;
1196                         }
1197                 }
1198                 memcpy(buf, line, len - skipped);
1199                 buf[len - skipped] = '\0';
1200         }
1201         return len;
1202 }
1203
1204
1205 /*
1206  * Reverse the old and new portions of the current hunk.
1207  */
1208 bool
1209 pch_swap(void)
1210 {
1211         char    **tp_line;      /* the text of the hunk */
1212         unsigned short  *tp_len;/* length of each line */
1213         char    *tp_char;       /* +, -, and ! */
1214         LINENUM i;
1215         LINENUM n;
1216         bool    blankline = false;
1217         char    *s;
1218
1219         i = p_first;
1220         p_first = p_newfirst;
1221         p_newfirst = i;
1222
1223         /* make a scratch copy */
1224
1225         tp_line = p_line;
1226         tp_len = p_len;
1227         tp_char = p_char;
1228         p_line = NULL;  /* force set_hunkmax to allocate again */
1229         p_len = NULL;
1230         p_char = NULL;
1231         set_hunkmax();
1232         if (p_line == NULL || p_len == NULL || p_char == NULL) {
1233
1234                 free(p_line);
1235                 p_line = tp_line;
1236                 free(p_len);
1237                 p_len = tp_len;
1238                 free(p_char);
1239                 p_char = tp_char;
1240                 return false;   /* not enough memory to swap hunk! */
1241         }
1242         /* now turn the new into the old */
1243
1244         i = p_ptrn_lines + 1;
1245         if (tp_char[i] == '\n') {       /* account for possible blank line */
1246                 blankline = true;
1247                 i++;
1248         }
1249         if (p_efake >= 0) {     /* fix non-freeable ptr range */
1250                 if (p_efake <= i)
1251                         n = p_end - i + 1;
1252                 else
1253                         n = -i;
1254                 p_efake += n;
1255                 p_bfake += n;
1256         }
1257         for (n = 0; i <= p_end; i++, n++) {
1258                 p_line[n] = tp_line[i];
1259                 p_char[n] = tp_char[i];
1260                 if (p_char[n] == '+')
1261                         p_char[n] = '-';
1262                 p_len[n] = tp_len[i];
1263         }
1264         if (blankline) {
1265                 i = p_ptrn_lines + 1;
1266                 p_line[n] = tp_line[i];
1267                 p_char[n] = tp_char[i];
1268                 p_len[n] = tp_len[i];
1269                 n++;
1270         }
1271         if (p_char[0] != '=')
1272                 fatal("Malformed patch at line %ld: expected '=' found '%c'\n",
1273                     p_input_line, p_char[0]);
1274         p_char[0] = '*';
1275         for (s = p_line[0]; *s; s++)
1276                 if (*s == '-')
1277                         *s = '*';
1278
1279         /* now turn the old into the new */
1280
1281         if (p_char[0] != '*')
1282                 fatal("Malformed patch at line %ld: expected '*' found '%c'\n",
1283                     p_input_line, p_char[0]);
1284         tp_char[0] = '=';
1285         for (s = tp_line[0]; *s; s++)
1286                 if (*s == '*')
1287                         *s = '-';
1288         for (i = 0; n <= p_end; i++, n++) {
1289                 p_line[n] = tp_line[i];
1290                 p_char[n] = tp_char[i];
1291                 if (p_char[n] == '-')
1292                         p_char[n] = '+';
1293                 p_len[n] = tp_len[i];
1294         }
1295
1296         if (i != p_ptrn_lines + 1)
1297                 fatal("Malformed patch at line %ld: expected %ld lines, "
1298                     "got %ld\n",
1299                     p_input_line, p_ptrn_lines + 1, i);
1300
1301         i = p_ptrn_lines;
1302         p_ptrn_lines = p_repl_lines;
1303         p_repl_lines = i;
1304
1305         free(tp_line);
1306         free(tp_len);
1307         free(tp_char);
1308
1309         return true;
1310 }
1311
1312 /*
1313  * Return the specified line position in the old file of the old context.
1314  */
1315 LINENUM
1316 pch_first(void)
1317 {
1318         return p_first;
1319 }
1320
1321 /*
1322  * Return the number of lines of old context.
1323  */
1324 LINENUM
1325 pch_ptrn_lines(void)
1326 {
1327         return p_ptrn_lines;
1328 }
1329
1330 /*
1331  * Return the probable line position in the new file of the first line.
1332  */
1333 LINENUM
1334 pch_newfirst(void)
1335 {
1336         return p_newfirst;
1337 }
1338
1339 /*
1340  * Return the number of lines in the replacement text including context.
1341  */
1342 LINENUM
1343 pch_repl_lines(void)
1344 {
1345         return p_repl_lines;
1346 }
1347
1348 /*
1349  * Return the number of lines in the whole hunk.
1350  */
1351 LINENUM
1352 pch_end(void)
1353 {
1354         return p_end;
1355 }
1356
1357 /*
1358  * Return the number of context lines before the first changed line.
1359  */
1360 LINENUM
1361 pch_context(void)
1362 {
1363         return p_context;
1364 }
1365
1366 /*
1367  * Return the length of a particular patch line.
1368  */
1369 unsigned short
1370 pch_line_len(LINENUM line)
1371 {
1372         return p_len[line];
1373 }
1374
1375 /*
1376  * Return the control character (+, -, *, !, etc) for a patch line.
1377  */
1378 char
1379 pch_char(LINENUM line)
1380 {
1381         return p_char[line];
1382 }
1383
1384 /*
1385  * Return a pointer to a particular patch line.
1386  */
1387 char *
1388 pfetch(LINENUM line)
1389 {
1390         return p_line[line];
1391 }
1392
1393 /*
1394  * Return where in the patch file this hunk began, for error messages.
1395  */
1396 LINENUM
1397 pch_hunk_beg(void)
1398 {
1399         return p_hunk_beg;
1400 }
1401
1402 /*
1403  * Apply an ed script by feeding ed itself.
1404  */
1405 void
1406 do_ed_script(void)
1407 {
1408         char    *t;
1409         off_t   beginning_of_this_line;
1410         FILE    *pipefp = NULL;
1411         int     continuation;
1412
1413         if (!skip_rest_of_patch) {
1414                 if (copy_file(filearg[0], TMPOUTNAME) < 0) {
1415                         unlink(TMPOUTNAME);
1416                         fatal("can't create temp file %s", TMPOUTNAME);
1417                 }
1418                 snprintf(buf, buf_size, "%s%s%s", _PATH_RED,
1419                     verbose ? " " : " -s ", TMPOUTNAME);
1420                 pipefp = popen(buf, "w");
1421         }
1422         for (;;) {
1423                 beginning_of_this_line = ftello(pfp);
1424                 if (pgets(true) == 0) {
1425                         next_intuit_at(beginning_of_this_line, p_input_line);
1426                         break;
1427                 }
1428                 p_input_line++;
1429                 for (t = buf; isdigit((unsigned char)*t) || *t == ','; t++)
1430                         ;
1431                 /* POSIX defines allowed commands as {a,c,d,i,s} */
1432                 if (isdigit((unsigned char)*buf) &&
1433                     (*t == 'a' || *t == 'c' || *t == 'd' || *t == 'i' || *t == 's')) {
1434                         if (pipefp != NULL)
1435                                 fputs(buf, pipefp);
1436                         if (*t == 's') {
1437                                 for (;;) {
1438                                         continuation = 0;
1439                                         t = strchr(buf, '\0') - 1;
1440                                         while (--t >= buf && *t == '\\')
1441                                                 continuation = !continuation;
1442                                         if (!continuation ||
1443                                             pgets(true) == 0)
1444                                                 break;
1445                                         if (pipefp != NULL)
1446                                                 fputs(buf, pipefp);
1447                                 }
1448                         } else if (*t != 'd') {
1449                                 while (pgets(true)) {
1450                                         p_input_line++;
1451                                         if (pipefp != NULL)
1452                                                 fputs(buf, pipefp);
1453                                         if (strEQ(buf, ".\n"))
1454                                                 break;
1455                                 }
1456                         }
1457                 } else {
1458                         next_intuit_at(beginning_of_this_line, p_input_line);
1459                         break;
1460                 }
1461         }
1462         if (pipefp == NULL)
1463                 return;
1464         fprintf(pipefp, "w\n");
1465         fprintf(pipefp, "q\n");
1466         fflush(pipefp);
1467         pclose(pipefp);
1468         ignore_signals();
1469         if (!check_only) {
1470                 if (move_file(TMPOUTNAME, outname) < 0) {
1471                         toutkeep = true;
1472                         chmod(TMPOUTNAME, filemode);
1473                 } else
1474                         chmod(outname, filemode);
1475         }
1476         set_signals(1);
1477 }
1478
1479 /*
1480  * Choose the name of the file to be patched based on POSIX rules.
1481  * NOTE: the POSIX rules are amazingly stupid and we only follow them
1482  *       if the user specified --posix or set POSIXLY_CORRECT.
1483  */
1484 static char *
1485 posix_name(const struct file_name *names, bool assume_exists)
1486 {
1487         char *path = NULL;
1488         int i;
1489
1490         /*
1491          * POSIX states that the filename will be chosen from one
1492          * of the old, new and index names (in that order) if
1493          * the file exists relative to CWD after -p stripping.
1494          */
1495         for (i = 0; i < MAX_FILE; i++) {
1496                 if (names[i].path != NULL && names[i].exists) {
1497                         path = names[i].path;
1498                         break;
1499                 }
1500         }
1501         if (path == NULL && !assume_exists) {
1502                 /*
1503                  * No files found, look for something we can checkout from
1504                  * RCS/SCCS dirs.  Same order as above.
1505                  */
1506                 for (i = 0; i < MAX_FILE; i++) {
1507                         if (names[i].path != NULL &&
1508                             (path = checked_in(names[i].path)) != NULL)
1509                                 break;
1510                 }
1511                 /*
1512                  * Still no match?  Check to see if the diff could be creating
1513                  * a new file.
1514                  */
1515                 if (path == NULL && ok_to_create_file &&
1516                     names[NEW_FILE].path != NULL)
1517                         path = names[NEW_FILE].path;
1518         }
1519
1520         return path ? xstrdup(path) : NULL;
1521 }
1522
1523 static char *
1524 compare_names(const struct file_name *names, bool assume_exists, int phase)
1525 {
1526         size_t min_components, min_baselen, min_len, tmp;
1527         char *best = NULL;
1528         char *path;
1529         int i;
1530
1531         /*
1532          * The "best" name is the one with the fewest number of path
1533          * components, the shortest basename length, and the shortest
1534          * overall length (in that order).  We only use the Index: file
1535          * if neither of the old or new files could be intuited from
1536          * the diff header.
1537          */
1538         min_components = min_baselen = min_len = SIZE_MAX;
1539         for (i = INDEX_FILE; i >= OLD_FILE; i--) {
1540                 path = names[i].path;
1541                 if (path == NULL ||
1542                     (phase == 1 && !names[i].exists && !assume_exists) ||
1543                     (phase == 2 && checked_in(path) == NULL))
1544                         continue;
1545                 if ((tmp = num_components(path)) > min_components)
1546                         continue;
1547                 if (tmp < min_components) {
1548                         min_components = tmp;
1549                         best = path;
1550                 }
1551                 if ((tmp = strlen(basename(path))) > min_baselen)
1552                         continue;
1553                 if (tmp < min_baselen) {
1554                         min_baselen = tmp;
1555                         best = path;
1556                 }
1557                 if ((tmp = strlen(path)) > min_len)
1558                         continue;
1559                 min_len = tmp;
1560                 best = path;
1561         }
1562         return best;
1563 }
1564
1565 /*
1566  * Choose the name of the file to be patched based the "best" one
1567  * available.
1568  */
1569 static char *
1570 best_name(const struct file_name *names, bool assume_exists)
1571 {
1572         char *best;
1573
1574         best = compare_names(names, assume_exists, 1);
1575         if (best == NULL) {
1576                 best = compare_names(names, assume_exists, 2);
1577                 /*
1578                  * Still no match?  Check to see if the diff could be creating
1579                  * a new file.
1580                  */
1581                 if (best == NULL && ok_to_create_file &&
1582                     names[NEW_FILE].path != NULL)
1583                         best = names[NEW_FILE].path;
1584         }
1585
1586         return best ? xstrdup(best) : NULL;
1587 }
1588
1589 static size_t
1590 num_components(const char *path)
1591 {
1592         size_t n;
1593         const char *cp;
1594
1595         for (n = 0, cp = path; (cp = strchr(cp, '/')) != NULL; n++, cp++) {
1596                 while (*cp == '/')
1597                         cp++;           /* skip consecutive slashes */
1598         }
1599         return n;
1600 }
1601
1602 /*
1603  * Convert number at NPTR into LINENUM and save address of first
1604  * character that is not a digit in ENDPTR.  If conversion is not
1605  * possible, call fatal.
1606  */
1607 static LINENUM
1608 strtolinenum(char *nptr, char **endptr)
1609 {
1610         LINENUM rv;
1611         char c;
1612         char *p;
1613         const char *errstr;
1614
1615         for (p = nptr; isdigit((unsigned char)*p); p++)
1616                 ;
1617
1618         if (p == nptr)
1619                 malformed();
1620
1621         c = *p;
1622         *p = '\0';
1623
1624         rv = strtonum(nptr, 0, LINENUM_MAX, &errstr);
1625         if (errstr != NULL)
1626                 fatal("invalid line number at line %ld: `%s' is %s\n",
1627                     p_input_line, nptr, errstr);
1628
1629         *p = c;
1630         *endptr = p;
1631
1632         return rv;
1633 }