xref: /openbsd/usr.bin/patch/inp.c (revision cecf84d4)
1 /*	$OpenBSD: inp.c,v 1.43 2015/02/05 12:59:57 millert Exp $	*/
2 
3 /*
4  * patch - a program to apply diffs to original files
5  *
6  * Copyright 1986, Larry Wall
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following condition is met:
10  * 1. Redistributions of source code must retain the above copyright notice,
11  * this condition and the following disclaimer.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
17  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26  * behaviour
27  */
28 
29 #include <sys/types.h>
30 #include <sys/file.h>
31 #include <sys/stat.h>
32 #include <sys/mman.h>
33 
34 #include <ctype.h>
35 #include <libgen.h>
36 #include <stddef.h>
37 #include <stdint.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 #include "common.h"
44 #include "util.h"
45 #include "pch.h"
46 #include "inp.h"
47 
48 
49 /* Input-file-with-indexable-lines abstract type */
50 
51 static off_t	i_size;		/* size of the input file */
52 static char	*i_womp;	/* plan a buffer for entire file */
53 static char	**i_ptr;	/* pointers to lines in i_womp */
54 
55 static int	tifd = -1;	/* plan b virtual string array */
56 static char	*tibuf[2];	/* plan b buffers */
57 static LINENUM	tiline[2] = {-1, -1};	/* 1st line in each buffer */
58 static size_t	lines_per_buf;	/* how many lines per buffer */
59 static size_t	tibuflen;	/* plan b buffer length */
60 static size_t	tireclen;	/* length of records in tmp file */
61 
62 static bool	rev_in_string(const char *);
63 static bool	reallocate_lines(size_t *);
64 
65 /* returns false if insufficient memory */
66 static bool	plan_a(const char *);
67 
68 static void	plan_b(const char *);
69 
70 /* New patch--prepare to edit another file. */
71 
72 void
73 re_input(void)
74 {
75 	if (using_plan_a) {
76 		free(i_ptr);
77 		i_ptr = NULL;
78 		if (i_womp != NULL) {
79 			munmap(i_womp, i_size);
80 			i_womp = NULL;
81 		}
82 		i_size = 0;
83 	} else {
84 		using_plan_a = true;	/* maybe the next one is smaller */
85 		close(tifd);
86 		tifd = -1;
87 		free(tibuf[0]);
88 		free(tibuf[1]);
89 		tibuf[0] = tibuf[1] = NULL;
90 		tiline[0] = tiline[1] = -1;
91 		tireclen = 0;
92 	}
93 }
94 
95 /* Construct the line index, somehow or other. */
96 
97 void
98 scan_input(const char *filename)
99 {
100 	if (!plan_a(filename))
101 		plan_b(filename);
102 	if (verbose) {
103 		say("Patching file %s using Plan %s...\n", filename,
104 		    (using_plan_a ? "A" : "B"));
105 	}
106 }
107 
108 static bool
109 reallocate_lines(size_t *lines_allocated)
110 {
111 	char	**p;
112 	size_t	new_size;
113 
114 	new_size = *lines_allocated * 3 / 2;
115 	p = reallocarray(i_ptr, new_size + 2, sizeof(char *));
116 	if (p == NULL) {	/* shucks, it was a near thing */
117 		munmap(i_womp, i_size);
118 		i_womp = NULL;
119 		free(i_ptr);
120 		i_ptr = NULL;
121 		*lines_allocated = 0;
122 		return false;
123 	}
124 	*lines_allocated = new_size;
125 	i_ptr = p;
126 	return true;
127 }
128 
129 /* Try keeping everything in memory. */
130 
131 static bool
132 plan_a(const char *filename)
133 {
134 	int		ifd, statfailed;
135 	char		*p, *s, lbuf[MAXLINELEN];
136 	struct stat	filestat;
137 	off_t		i;
138 	ptrdiff_t	sz;
139 	size_t		iline, lines_allocated;
140 
141 #ifdef DEBUGGING
142 	if (debug & 8)
143 		return false;
144 #endif
145 
146 	if (filename == NULL || *filename == '\0')
147 		return false;
148 
149 	statfailed = stat(filename, &filestat);
150 	if (statfailed && ok_to_create_file) {
151 		if (verbose)
152 			say("(Creating file %s...)\n", filename);
153 
154 		/*
155 		 * in check_patch case, we still display `Creating file' even
156 		 * though we're not. The rule is that -C should be as similar
157 		 * to normal patch behavior as possible
158 		 */
159 		if (check_only)
160 			return true;
161 		makedirs(filename, true);
162 		close(creat(filename, 0666));
163 		statfailed = stat(filename, &filestat);
164 	}
165 	if (statfailed && check_only)
166 		fatal("%s not found, -C mode, can't probe further\n", filename);
167 	/* For nonexistent or read-only files, look for RCS versions.  */
168 	if (statfailed ||
169 	    /* No one can write to it.  */
170 	    (filestat.st_mode & 0222) == 0 ||
171 	    /* I can't write to it.  */
172 	    ((filestat.st_mode & 0022) == 0 && filestat.st_uid != getuid())) {
173 		char	*cs = NULL, *filebase, *filedir;
174 		struct stat	cstat;
175 
176 		filebase = basename(filename);
177 		filedir = dirname(filename);
178 
179 		/* Leave room in lbuf for the diff command.  */
180 		s = lbuf + 20;
181 
182 #define try(f, a1, a2, a3) \
183 	(snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
184 
185 		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
186 		    try("%s/RCS/%s%s", filedir, filebase, "") ||
187 		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
188 			snprintf(buf, sizeof buf, CHECKOUT, filename);
189 			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
190 			cs = "RCS";
191 		} else if (statfailed)
192 			fatal("can't find %s\n", filename);
193 		/*
194 		 * else we can't write to it but it's not under a version
195 		 * control system, so just proceed.
196 		 */
197 		if (cs) {
198 			if (!statfailed) {
199 				if ((filestat.st_mode & 0222) != 0)
200 					/* The owner can write to it.  */
201 					fatal("file %s seems to be locked "
202 					    "by somebody else under %s\n",
203 					    filename, cs);
204 				/*
205 				 * It might be checked out unlocked.  See if
206 				 * it's safe to check out the default version
207 				 * locked.
208 				 */
209 				if (verbose)
210 					say("Comparing file %s to default "
211 					    "%s version...\n",
212 					    filename, cs);
213 				if (system(lbuf))
214 					fatal("can't check out file %s: "
215 					    "differs from default %s version\n",
216 					    filename, cs);
217 			}
218 			if (verbose)
219 				say("Checking out file %s from %s...\n",
220 				    filename, cs);
221 			if (system(buf) || stat(filename, &filestat))
222 				fatal("can't check out file %s from %s\n",
223 				    filename, cs);
224 		}
225 	}
226 	filemode = filestat.st_mode;
227 	if (!S_ISREG(filemode))
228 		fatal("%s is not a normal file--can't patch\n", filename);
229 	i_size = filestat.st_size;
230 	if (out_of_mem) {
231 		set_hunkmax();	/* make sure dynamic arrays are allocated */
232 		out_of_mem = false;
233 		return false;	/* force plan b because plan a bombed */
234 	}
235 	if (i_size > SIZE_MAX) {
236 		say("block too large to mmap\n");
237 		return false;
238 	}
239 	if ((ifd = open(filename, O_RDONLY)) < 0)
240 		pfatal("can't open file %s", filename);
241 
242 	if (i_size) {
243 		i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
244 		if (i_womp == MAP_FAILED) {
245 			perror("mmap failed");
246 			i_womp = NULL;
247 			close(ifd);
248 			return false;
249 		}
250 	} else {
251 		i_womp = NULL;
252 	}
253 
254 	close(ifd);
255 	if (i_size)
256 		madvise(i_womp, i_size, MADV_SEQUENTIAL);
257 
258 	/* estimate the number of lines */
259 	lines_allocated = i_size / 25;
260 	if (lines_allocated < 100)
261 		lines_allocated = 100;
262 
263 	if (!reallocate_lines(&lines_allocated))
264 		return false;
265 
266 	/* now scan the buffer and build pointer array */
267 	iline = 1;
268 	i_ptr[iline] = i_womp;
269 	/* test for NUL too, to maintain the behavior of the original code */
270 	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
271 		if (*s == '\n') {
272 			if (iline == lines_allocated) {
273 				if (!reallocate_lines(&lines_allocated))
274 					return false;
275 			}
276 			/* these are NOT NUL terminated */
277 			i_ptr[++iline] = s + 1;
278 		}
279 	}
280 	/* if the last line contains no EOL, append one */
281 	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
282 		last_line_missing_eol = true;
283 		/* fix last line */
284 		sz = s - i_ptr[iline];
285 		p = malloc(sz + 1);
286 		if (p == NULL) {
287 			free(i_ptr);
288 			i_ptr = NULL;
289 			munmap(i_womp, i_size);
290 			i_womp = NULL;
291 			return false;
292 		}
293 
294 		memcpy(p, i_ptr[iline], sz);
295 		p[sz] = '\n';
296 		i_ptr[iline] = p;
297 		/* count the extra line and make it point to some valid mem */
298 		i_ptr[++iline] = "";
299 	} else
300 		last_line_missing_eol = false;
301 
302 	input_lines = iline - 1;
303 
304 	/* now check for revision, if any */
305 
306 	if (revision != NULL) {
307 		if (i_womp == NULL || !rev_in_string(i_womp)) {
308 			if (force) {
309 				if (verbose)
310 					say("Warning: this file doesn't appear "
311 					    "to be the %s version--patching anyway.\n",
312 					    revision);
313 			} else if (batch) {
314 				fatal("this file doesn't appear to be the "
315 				    "%s version--aborting.\n",
316 				    revision);
317 			} else {
318 				ask("This file doesn't appear to be the "
319 				    "%s version--patch anyway? [n] ",
320 				    revision);
321 				if (*buf != 'y')
322 					fatal("aborted\n");
323 			}
324 		} else if (verbose)
325 			say("Good.  This file appears to be the %s version.\n",
326 			    revision);
327 	}
328 	return true;		/* plan a will work */
329 }
330 
331 /* Keep (virtually) nothing in memory. */
332 
333 static void
334 plan_b(const char *filename)
335 {
336 	FILE	*ifp;
337 	size_t	i = 0, j, len, maxlen = 1;
338 	char	*lbuf = NULL, *p;
339 	bool	found_revision = (revision == NULL);
340 
341 	using_plan_a = false;
342 	if ((ifp = fopen(filename, "r")) == NULL)
343 		pfatal("can't open file %s", filename);
344 	(void) unlink(TMPINNAME);
345 	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
346 		pfatal("can't open file %s", TMPINNAME);
347 	while ((p = fgetln(ifp, &len)) != NULL) {
348 		if (p[len - 1] == '\n')
349 			p[len - 1] = '\0';
350 		else {
351 			/* EOF without EOL, copy and add the NUL */
352 			if ((lbuf = malloc(len + 1)) == NULL)
353 				fatal("out of memory\n");
354 			memcpy(lbuf, p, len);
355 			lbuf[len] = '\0';
356 			p = lbuf;
357 
358 			last_line_missing_eol = true;
359 			len++;
360 		}
361 		if (revision != NULL && !found_revision && rev_in_string(p))
362 			found_revision = true;
363 		if (len > maxlen)
364 			maxlen = len;	/* find longest line */
365 	}
366 	free(lbuf);
367 	if (ferror(ifp))
368 		pfatal("can't read file %s", filename);
369 
370 	if (revision != NULL) {
371 		if (!found_revision) {
372 			if (force) {
373 				if (verbose)
374 					say("Warning: this file doesn't appear "
375 					    "to be the %s version--patching anyway.\n",
376 					    revision);
377 			} else if (batch) {
378 				fatal("this file doesn't appear to be the "
379 				    "%s version--aborting.\n",
380 				    revision);
381 			} else {
382 				ask("This file doesn't appear to be the %s "
383 				    "version--patch anyway? [n] ",
384 				    revision);
385 				if (*buf != 'y')
386 					fatal("aborted\n");
387 			}
388 		} else if (verbose)
389 			say("Good.  This file appears to be the %s version.\n",
390 			    revision);
391 	}
392 	fseek(ifp, 0L, SEEK_SET);	/* rewind file */
393 	tireclen = maxlen;
394 	tibuflen = maxlen > BUFFERSIZE ? maxlen : BUFFERSIZE;
395 	lines_per_buf = tibuflen / maxlen;
396 	tibuf[0] = malloc(tibuflen + 1);
397 	if (tibuf[0] == NULL)
398 		fatal("out of memory\n");
399 	tibuf[1] = malloc(tibuflen + 1);
400 	if (tibuf[1] == NULL)
401 		fatal("out of memory\n");
402 	for (i = 1;; i++) {
403 		p = tibuf[0] + maxlen * (i % lines_per_buf);
404 		if (i % lines_per_buf == 0)	/* new block */
405 			if (write(tifd, tibuf[0], tibuflen) !=
406 			    (ssize_t) tibuflen)
407 				pfatal("can't write temp file");
408 		if (fgets(p, maxlen + 1, ifp) == NULL) {
409 			input_lines = i - 1;
410 			if (i % lines_per_buf != 0)
411 				if (write(tifd, tibuf[0], tibuflen) !=
412 				    (ssize_t) tibuflen)
413 					pfatal("can't write temp file");
414 			break;
415 		}
416 		j = strlen(p);
417 		/* These are '\n' terminated strings, so no need to add a NUL */
418 		if (j == 0 || p[j - 1] != '\n')
419 			p[j] = '\n';
420 	}
421 	fclose(ifp);
422 	close(tifd);
423 	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
424 		pfatal("can't reopen file %s", TMPINNAME);
425 }
426 
427 /*
428  * Fetch a line from the input file, \n terminated, not necessarily \0.
429  */
430 char *
431 ifetch(LINENUM line, int whichbuf)
432 {
433 	if (line < 1 || line > input_lines) {
434 		if (warn_on_invalid_line) {
435 			say("No such line %ld in input file, ignoring\n", line);
436 			warn_on_invalid_line = false;
437 		}
438 		return NULL;
439 	}
440 	if (using_plan_a)
441 		return i_ptr[line];
442 	else {
443 		LINENUM	offline = line % lines_per_buf;
444 		LINENUM	baseline = line - offline;
445 
446 		if (tiline[0] == baseline)
447 			whichbuf = 0;
448 		else if (tiline[1] == baseline)
449 			whichbuf = 1;
450 		else {
451 			tiline[whichbuf] = baseline;
452 
453 			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
454 			    tibuflen), SEEK_SET) < 0)
455 				pfatal("cannot seek in the temporary input file");
456 
457 			if (read(tifd, tibuf[whichbuf], tibuflen)
458 			    != (ssize_t) tibuflen)
459 				pfatal("error reading tmp file %s", TMPINNAME);
460 		}
461 		return tibuf[whichbuf] + (tireclen * offline);
462 	}
463 }
464 
465 /*
466  * True if the string argument contains the revision number we want.
467  */
468 static bool
469 rev_in_string(const char *string)
470 {
471 	const char	*s;
472 	size_t		patlen;
473 
474 	if (revision == NULL)
475 		return true;
476 	patlen = strlen(revision);
477 	if (strnEQ(string, revision, patlen) &&
478 	    isspace((unsigned char)string[patlen]))
479 		return true;
480 	for (s = string; *s; s++) {
481 		if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
482 		    isspace((unsigned char)s[patlen + 1])) {
483 			return true;
484 		}
485 	}
486 	return false;
487 }
488