2 * Copyright 1986, Larry Wall
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.
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
21 * patch - a program to apply diffs to original files
23 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * $OpenBSD: inp.c,v 1.36 2012/04/10 14:46:34 ajacoutot Exp $
27 * $FreeBSD: head/usr.bin/patch/inp.c 246091 2013-01-29 20:05:16Z delphij $
30 #include <sys/types.h>
50 /* Input-file-with-indexable-lines abstract type */
52 static size_t i_size; /* size of the input file */
53 static char *i_womp; /* plan a buffer for entire file */
54 static char **i_ptr; /* pointers to lines in i_womp */
55 static char empty_line[] = { '\0' };
57 static int tifd = -1; /* plan b virtual string array */
58 static char *tibuf[2]; /* plan b buffers */
59 static LINENUM tiline[2] = {-1, -1}; /* 1st line in each buffer */
60 static LINENUM lines_per_buf; /* how many lines per buffer */
61 static int tireclen; /* length of records in tmp file */
63 static bool rev_in_string(const char *);
64 static bool reallocate_lines(size_t *);
66 /* returns false if insufficient memory */
67 static bool plan_a(const char *);
69 static void plan_b(const char *);
71 /* New patch--prepare to edit another file. */
80 munmap(i_womp, i_size);
85 using_plan_a = true; /* maybe the next one is smaller */
90 tibuf[0] = tibuf[1] = NULL;
91 tiline[0] = tiline[1] = -1;
96 /* Construct the line index, somehow or other. */
99 scan_input(const char *filename)
101 if (!plan_a(filename))
104 say("Patching file %s using Plan %s...\n", filename,
105 (using_plan_a ? "A" : "B"));
110 reallocate_lines(size_t *lines_allocated)
115 new_size = *lines_allocated * 3 / 2;
116 p = realloc(i_ptr, (new_size + 2) * sizeof(char *));
117 if (p == NULL) { /* shucks, it was a near thing */
118 munmap(i_womp, i_size);
122 *lines_allocated = 0;
125 *lines_allocated = new_size;
130 /* Try keeping everything in memory. */
133 plan_a(const char *filename)
137 struct stat filestat;
140 size_t iline, lines_allocated;
147 if (filename == NULL || *filename == '\0')
150 statfailed = stat(filename, &filestat);
151 if (statfailed && ok_to_create_file) {
153 say("(Creating file %s...)\n", filename);
156 * in check_patch case, we still display `Creating file' even
157 * though we're not. The rule is that -C should be as similar
158 * to normal patch behavior as possible
162 makedirs(filename, true);
163 close(creat(filename, 0666));
164 statfailed = stat(filename, &filestat);
166 if (statfailed && check_only)
167 fatal("%s not found, -C mode, can't probe further\n", filename);
169 * For nonexistent or read-only files we no longer attempt to locate
170 * or checkout the file via RCS or SCCS, or do any call to system()
171 * whatsoever. CVE-2015-1416.
174 /* No one can write to it. */
175 (filestat.st_mode & 0222) == 0 ||
176 /* I can't write to it. */
177 ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
179 fatal("can't find %s\n", filename);
181 filemode = filestat.st_mode;
182 if (!S_ISREG(filemode))
183 fatal("%s is not a normal file--can't patch\n", filename);
184 if ((uint64_t)filestat.st_size > SIZE_MAX) {
185 say("block too large to mmap\n");
188 i_size = (size_t)filestat.st_size;
190 set_hunkmax(); /* make sure dynamic arrays are allocated */
192 return false; /* force plan b because plan a bombed */
194 if ((ifd = open(filename, O_RDONLY)) < 0)
195 pfatal("can't open file %s", filename);
198 i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
199 if (i_womp == MAP_FAILED) {
200 perror("mmap failed");
211 madvise(i_womp, i_size, MADV_SEQUENTIAL);
213 /* estimate the number of lines */
214 lines_allocated = i_size / 25;
215 if (lines_allocated < 100)
216 lines_allocated = 100;
218 if (!reallocate_lines(&lines_allocated))
221 /* now scan the buffer and build pointer array */
223 i_ptr[iline] = i_womp;
224 /* test for NUL too, to maintain the behavior of the original code */
225 for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
227 if (iline == lines_allocated) {
228 if (!reallocate_lines(&lines_allocated))
231 /* these are NOT NUL terminated */
232 i_ptr[++iline] = s + 1;
235 /* if the last line contains no EOL, append one */
236 if (i_size > 0 && i_womp[i_size - 1] != '\n') {
237 last_line_missing_eol = true;
239 sz = s - i_ptr[iline];
244 munmap(i_womp, i_size);
249 memcpy(p, i_ptr[iline], sz);
252 /* count the extra line and make it point to some valid mem */
253 i_ptr[++iline] = empty_line;
255 last_line_missing_eol = false;
257 input_lines = iline - 1;
259 /* now check for revision, if any */
261 if (revision != NULL) {
262 if (!rev_in_string(i_womp)) {
265 say("Warning: this file doesn't appear "
266 "to be the %s version--patching anyway.\n",
269 fatal("this file doesn't appear to be the "
270 "%s version--aborting.\n",
273 ask("This file doesn't appear to be the "
274 "%s version--patch anyway? [n] ",
280 say("Good. This file appears to be the %s version.\n",
283 return true; /* plan a will work */
286 /* Keep (virtually) nothing in memory. */
289 plan_b(const char *filename)
292 size_t i = 0, j, maxlen = 1;
294 bool found_revision = (revision == NULL);
296 using_plan_a = false;
297 if ((ifp = fopen(filename, "r")) == NULL)
298 pfatal("can't open file %s", filename);
300 if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
301 pfatal("can't open file %s", TMPINNAME);
302 while (fgets(buf, buf_size, ifp) != NULL) {
303 if (revision != NULL && !found_revision && rev_in_string(buf))
304 found_revision = true;
305 if ((i = strlen(buf)) > maxlen)
306 maxlen = i; /* find longest line */
308 last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
309 if (last_line_missing_eol && maxlen == i)
312 if (revision != NULL) {
313 if (!found_revision) {
316 say("Warning: this file doesn't appear "
317 "to be the %s version--patching anyway.\n",
320 fatal("this file doesn't appear to be the "
321 "%s version--aborting.\n",
324 ask("This file doesn't appear to be the %s "
325 "version--patch anyway? [n] ",
331 say("Good. This file appears to be the %s version.\n",
334 fseek(ifp, 0L, SEEK_SET); /* rewind file */
335 lines_per_buf = BUFFERSIZE / maxlen;
337 tibuf[0] = malloc(BUFFERSIZE + 1);
338 if (tibuf[0] == NULL)
339 fatal("out of memory\n");
340 tibuf[1] = malloc(BUFFERSIZE + 1);
341 if (tibuf[1] == NULL)
342 fatal("out of memory\n");
344 p = tibuf[0] + maxlen * (i % lines_per_buf);
345 if (i % lines_per_buf == 0) /* new block */
346 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
347 pfatal("can't write temp file");
348 if (fgets(p, maxlen + 1, ifp) == NULL) {
350 if (i % lines_per_buf != 0)
351 if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
352 pfatal("can't write temp file");
356 /* These are '\n' terminated strings, so no need to add a NUL */
357 if (j == 0 || p[j - 1] != '\n')
362 if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
363 pfatal("can't reopen file %s", TMPINNAME);
367 * Fetch a line from the input file, \n terminated, not necessarily \0.
370 ifetch(LINENUM line, int whichbuf)
372 if (line < 1 || line > input_lines) {
373 if (warn_on_invalid_line) {
374 say("No such line %ld in input file, ignoring\n", line);
375 warn_on_invalid_line = false;
382 LINENUM offline = line % lines_per_buf;
383 LINENUM baseline = line - offline;
385 if (tiline[0] == baseline)
387 else if (tiline[1] == baseline)
390 tiline[whichbuf] = baseline;
392 if (lseek(tifd, (off_t) (baseline / lines_per_buf *
393 BUFFERSIZE), SEEK_SET) < 0)
394 pfatal("cannot seek in the temporary input file");
396 if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
397 pfatal("error reading tmp file %s", TMPINNAME);
399 return tibuf[whichbuf] + (tireclen * offline);
404 * True if the string argument contains the revision number we want.
407 rev_in_string(const char *string)
412 if (revision == NULL)
414 patlen = strlen(revision);
415 if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
417 for (s = string; *s; s++) {
418 if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
419 isspace((unsigned char)s[patlen + 1])) {