xref: /dragonfly/usr.bin/patch/inp.c (revision 32c20b8b)
1 /*
2  * $OpenBSD: inp.c,v 1.34 2006/03/11 19:41:30 otto Exp $
3  * $DragonFly: src/usr.bin/patch/inp.c,v 1.6 2007/09/29 23:11:10 swildner Exp $
4  */
5 
6 /*
7  * patch - a program to apply diffs to original files
8  *
9  * Copyright 1986, Larry Wall
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following condition is met:
13  * 1. Redistributions of source code must retain the above copyright notice,
14  * this condition and the following disclaimer.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
29  * behaviour
30  */
31 
32 #include <sys/types.h>
33 #include <sys/file.h>
34 #include <sys/stat.h>
35 #include <sys/mman.h>
36 
37 #include <ctype.h>
38 #include <libgen.h>
39 #include <limits.h>
40 #include <stddef.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #include "common.h"
47 #include "util.h"
48 #include "pch.h"
49 #include "inp.h"
50 
51 
52 /* Input-file-with-indexable-lines abstract type */
53 
54 static size_t	i_size;		/* size of the input file */
55 static char	*i_womp;	/* plan a buffer for entire file */
56 static char	**i_ptr;	/* pointers to lines in i_womp */
57 static char	empty_line[] = { '\0' };
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 		free(i_ptr);
80 		i_ptr = NULL;
81 		if (i_womp != NULL) {
82 			munmap(i_womp, i_size);
83 			i_womp = NULL;
84 		}
85 		i_size = 0;
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 	ptrdiff_t	sz;
141 	size_t		i;
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 		const char	*cs = NULL, *filebase, *filedir;
177 		struct stat	cstat;
178 		char *tmp_filename1, *tmp_filename2;
179 
180 		tmp_filename1 = strdup(filename);
181 		tmp_filename2 = strdup(filename);
182 		if (tmp_filename1 == NULL || tmp_filename2 == NULL)
183 			fatal("strdupping filename");
184 		filebase = basename(tmp_filename1);
185 		filedir = dirname(tmp_filename2);
186 
187 		/* Leave room in lbuf for the diff command.  */
188 		s = lbuf + 20;
189 
190 #define try(f, a1, a2, a3) \
191 	(snprintf(s, sizeof lbuf - 20, f, a1, a2, a3), stat(s, &cstat) == 0)
192 
193 		if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
194 		    try("%s/RCS/%s%s", filedir, filebase, "") ||
195 		    try("%s/%s%s", filedir, filebase, RCSSUFFIX)) {
196 			snprintf(buf, buf_len, CHECKOUT, filename);
197 			snprintf(lbuf, sizeof lbuf, RCSDIFF, filename);
198 			cs = "RCS";
199 		} else if (try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
200 		    try("%s/%s%s", filedir, SCCSPREFIX, filebase)) {
201 			snprintf(buf, buf_len, GET, s);
202 			snprintf(lbuf, sizeof lbuf, SCCSDIFF, s, filename);
203 			cs = "SCCS";
204 		} else if (statfailed)
205 			fatal("can't find %s\n", filename);
206 
207 		free(tmp_filename1);
208 		free(tmp_filename2);
209 
210 		/*
211 		 * else we can't write to it but it's not under a version
212 		 * control system, so just proceed.
213 		 */
214 		if (cs) {
215 			if (!statfailed) {
216 				if ((filestat.st_mode & 0222) != 0)
217 					/* The owner can write to it.  */
218 					fatal("file %s seems to be locked "
219 					    "by somebody else under %s\n",
220 					    filename, cs);
221 				/*
222 				 * It might be checked out unlocked.  See if
223 				 * it's safe to check out the default version
224 				 * locked.
225 				 */
226 				if (verbose)
227 					say("Comparing file %s to default "
228 					    "%s version...\n",
229 					    filename, cs);
230 				if (system(lbuf))
231 					fatal("can't check out file %s: "
232 					    "differs from default %s version\n",
233 					    filename, cs);
234 			}
235 			if (verbose)
236 				say("Checking out file %s from %s...\n",
237 				    filename, cs);
238 			if (system(buf) || stat(filename, &filestat))
239 				fatal("can't check out file %s from %s\n",
240 				    filename, cs);
241 		}
242 	}
243 	filemode = filestat.st_mode;
244 	if (!S_ISREG(filemode))
245 		fatal("%s is not a normal file--can't patch\n", filename);
246 	if ((uint64_t)filestat.st_size > SIZE_MAX) {
247 		say("block too large to mmap\n");
248 		return false;
249 	}
250 	i_size = (size_t)filestat.st_size;
251 	if (out_of_mem) {
252 		set_hunkmax();	/* make sure dynamic arrays are allocated */
253 		out_of_mem = false;
254 		return false;	/* force plan b because plan a bombed */
255 	}
256 	if ((ifd = open(filename, O_RDONLY)) < 0)
257 		pfatal("can't open file %s", filename);
258 
259 	i_womp = mmap(NULL, i_size, PROT_READ, MAP_PRIVATE, ifd, 0);
260 	if (i_womp == MAP_FAILED) {
261 		perror("mmap failed");
262 		i_womp = NULL;
263 		close(ifd);
264 		return false;
265 	}
266 
267 	close(ifd);
268 	if (i_size)
269 		madvise(i_womp, i_size, MADV_SEQUENTIAL);
270 
271 	/* estimate the number of lines */
272 	lines_allocated = i_size / 25;
273 	if (lines_allocated < 100)
274 		lines_allocated = 100;
275 
276 	if (!reallocate_lines(&lines_allocated))
277 		return false;
278 
279 	/* now scan the buffer and build pointer array */
280 	iline = 1;
281 	i_ptr[iline] = i_womp;
282 	/* test for NUL too, to maintain the behavior of the original code */
283 	for (s = i_womp, i = 0; i < i_size && *s != '\0'; s++, i++) {
284 		if (*s == '\n') {
285 			if (iline == lines_allocated) {
286 				if (!reallocate_lines(&lines_allocated))
287 					return false;
288 			}
289 			/* these are NOT NUL terminated */
290 			i_ptr[++iline] = s + 1;
291 		}
292 	}
293 	/* if the last line contains no EOL, append one */
294 	if (i_size > 0 && i_womp[i_size - 1] != '\n') {
295 		last_line_missing_eol = true;
296 		/* fix last line */
297 		sz = s - i_ptr[iline];
298 		p = malloc(sz + 1);
299 		if (p == NULL) {
300 			free(i_ptr);
301 			i_ptr = NULL;
302 			munmap(i_womp, i_size);
303 			i_womp = NULL;
304 			return false;
305 		}
306 
307 		memcpy(p, i_ptr[iline], sz);
308 		p[sz] = '\n';
309 		i_ptr[iline] = p;
310 		/* count the extra line and make it point to some valid mem */
311 		i_ptr[++iline] = empty_line;
312 	} else
313 		last_line_missing_eol = false;
314 
315 	input_lines = iline - 1;
316 
317 	/* now check for revision, if any */
318 
319 	if (revision != NULL) {
320 		if (!rev_in_string(i_womp)) {
321 			if (force) {
322 				if (verbose)
323 					say("Warning: this file doesn't appear "
324 					    "to be the %s version--patching anyway.\n",
325 					    revision);
326 			} else if (batch) {
327 				fatal("this file doesn't appear to be the "
328 				    "%s version--aborting.\n",
329 				    revision);
330 			} else {
331 				ask("This file doesn't appear to be the "
332 				    "%s version--patch anyway? [n] ",
333 				    revision);
334 				if (*buf != 'y')
335 					fatal("aborted\n");
336 			}
337 		} else if (verbose)
338 			say("Good.  This file appears to be the %s version.\n",
339 			    revision);
340 	}
341 	return true;		/* plan a will work */
342 }
343 
344 /* Keep (virtually) nothing in memory. */
345 
346 static void
347 plan_b(const char *filename)
348 {
349 	FILE	*ifp;
350 	size_t	i = 0, j, maxlen = 1;
351 	char	*p;
352 	bool	found_revision = (revision == NULL);
353 
354 	using_plan_a = false;
355 	if ((ifp = fopen(filename, "r")) == NULL)
356 		pfatal("can't open file %s", filename);
357 	unlink(TMPINNAME);
358 	if ((tifd = open(TMPINNAME, O_EXCL | O_CREAT | O_WRONLY, 0666)) < 0)
359 		pfatal("can't open file %s", TMPINNAME);
360 	while (fgets(buf, buf_len, ifp) != NULL) {
361 		if (revision != NULL && !found_revision && rev_in_string(buf))
362 			found_revision = true;
363 		if ((i = strlen(buf)) > maxlen)
364 			maxlen = i;	/* find longest line */
365 	}
366 	last_line_missing_eol = i > 0 && buf[i - 1] != '\n';
367 	if (last_line_missing_eol && maxlen == i)
368 		maxlen++;
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 	lines_per_buf = BUFFERSIZE / maxlen;
394 	tireclen = maxlen;
395 	tibuf[0] = malloc(BUFFERSIZE + 1);
396 	if (tibuf[0] == NULL)
397 		fatal("out of memory\n");
398 	tibuf[1] = malloc(BUFFERSIZE + 1);
399 	if (tibuf[1] == NULL)
400 		fatal("out of memory\n");
401 	for (i = 1;; i++) {
402 		p = tibuf[0] + maxlen * (i % lines_per_buf);
403 		if (i % lines_per_buf == 0)	/* new block */
404 			if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
405 				pfatal("can't write temp file");
406 		if (fgets(p, maxlen + 1, ifp) == NULL) {
407 			input_lines = i - 1;
408 			if (i % lines_per_buf != 0)
409 				if (write(tifd, tibuf[0], BUFFERSIZE) < BUFFERSIZE)
410 					pfatal("can't write temp file");
411 			break;
412 		}
413 		j = strlen(p);
414 		/* These are '\n' terminated strings, so no need to add a NUL */
415 		if (j == 0 || p[j - 1] != '\n')
416 			p[j] = '\n';
417 	}
418 	fclose(ifp);
419 	close(tifd);
420 	if ((tifd = open(TMPINNAME, O_RDONLY)) < 0)
421 		pfatal("can't reopen file %s", TMPINNAME);
422 }
423 
424 /*
425  * Fetch a line from the input file, \n terminated, not necessarily \0.
426  */
427 char *
428 ifetch(LINENUM line, int whichbuf)
429 {
430 	if (line < 1 || line > input_lines) {
431 		if (warn_on_invalid_line) {
432 			say("No such line %ld in input file, ignoring\n", line);
433 			warn_on_invalid_line = false;
434 		}
435 		return NULL;
436 	}
437 	if (using_plan_a)
438 		return i_ptr[line];
439 	else {
440 		LINENUM	offline = line % lines_per_buf;
441 		LINENUM	baseline = line - offline;
442 
443 		if (tiline[0] == baseline)
444 			whichbuf = 0;
445 		else if (tiline[1] == baseline)
446 			whichbuf = 1;
447 		else {
448 			tiline[whichbuf] = baseline;
449 
450 			if (lseek(tifd, (off_t) (baseline / lines_per_buf *
451 			    BUFFERSIZE), SEEK_SET) < 0)
452 				pfatal("cannot seek in the temporary input file");
453 
454 			if (read(tifd, tibuf[whichbuf], BUFFERSIZE) < 0)
455 				pfatal("error reading tmp file %s", TMPINNAME);
456 		}
457 		return tibuf[whichbuf] + (tireclen * offline);
458 	}
459 }
460 
461 /*
462  * True if the string argument contains the revision number we want.
463  */
464 static bool
465 rev_in_string(const char *string)
466 {
467 	const char	*s;
468 	size_t		patlen;
469 
470 	if (revision == NULL)
471 		return true;
472 	patlen = strlen(revision);
473 	if (strnEQ(string, revision, patlen) && isspace((unsigned char)string[patlen]))
474 		return true;
475 	for (s = string; *s; s++) {
476 		if (isspace((unsigned char)*s) && strnEQ(s + 1, revision, patlen) &&
477 		    isspace((unsigned char)s[patlen + 1])) {
478 			return true;
479 		}
480 	}
481 	return false;
482 }
483