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