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