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: util.c,v 1.35 2010/07/24 01:10:12 ray Exp $
27 * $FreeBSD: stable/11/usr.bin/patch/util.c 355351 2019-12-03 18:55:09Z kevans $
28 */
29
30#include <sys/stat.h>
31
32#include <ctype.h>
33#include <errno.h>
34#include <fcntl.h>
35#include <libgen.h>
36#include <limits.h>
37#include <paths.h>
38#include <signal.h>
39#include <stdarg.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <string.h>
43#include <unistd.h>
44
45#include "common.h"
46#include "util.h"
47#include "backupfile.h"
48#include "pathnames.h"
49
50/* Rename a file, copying it if necessary. */
51
52int
53move_file(const char *from, const char *to)
54{
55	int	fromfd;
56	ssize_t	i;
57
58	/* to stdout? */
59
60	if (strEQ(to, "-")) {
61#ifdef DEBUGGING
62		if (debug & 4)
63			say("Moving %s to stdout.\n", from);
64#endif
65		fromfd = open(from, O_RDONLY);
66		if (fromfd < 0)
67			pfatal("internal error, can't reopen %s", from);
68		while ((i = read(fromfd, buf, buf_size)) > 0)
69			if (write(STDOUT_FILENO, buf, i) != i)
70				pfatal("write failed");
71		close(fromfd);
72		return 0;
73	}
74	if (backup_file(to) < 0) {
75		say("Can't backup %s, output is in %s: %s\n", to, from,
76		    strerror(errno));
77		return -1;
78	}
79#ifdef DEBUGGING
80	if (debug & 4)
81		say("Moving %s to %s.\n", from, to);
82#endif
83	if (rename(from, to) < 0) {
84		if (errno != EXDEV || copy_file(from, to) < 0) {
85			say("Can't create %s, output is in %s: %s\n",
86			    to, from, strerror(errno));
87			return -1;
88		}
89	}
90	return 0;
91}
92
93/* Backup the original file.  */
94
95int
96backup_file(const char *orig)
97{
98	struct stat	filestat;
99	char		bakname[PATH_MAX], *s, *simplename;
100	dev_t		orig_device;
101	ino_t		orig_inode;
102
103	if (backup_type == none || stat(orig, &filestat) != 0)
104		return 0;			/* nothing to do */
105	/*
106	 * If the user used zero prefixes or suffixes, then
107	 * he doesn't want backups.  Yet we have to remove
108	 * orig to break possible hardlinks.
109	 */
110	if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) {
111		unlink(orig);
112		return 0;
113	}
114	orig_device = filestat.st_dev;
115	orig_inode = filestat.st_ino;
116
117	if (origprae) {
118		if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) ||
119		    strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname))
120			fatal("filename %s too long for buffer\n", origprae);
121	} else {
122		if ((s = find_backup_file_name(orig)) == NULL)
123			fatal("out of memory\n");
124		if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname))
125			fatal("filename %s too long for buffer\n", s);
126		free(s);
127	}
128
129	if ((simplename = strrchr(bakname, '/')) != NULL)
130		simplename = simplename + 1;
131	else
132		simplename = bakname;
133
134	/*
135	 * Find a backup name that is not the same file. Change the
136	 * first lowercase char into uppercase; if that isn't
137	 * sufficient, chop off the first char and try again.
138	 */
139	while (stat(bakname, &filestat) == 0 &&
140	    orig_device == filestat.st_dev && orig_inode == filestat.st_ino) {
141		/* Skip initial non-lowercase chars.  */
142		for (s = simplename; *s && !islower((unsigned char)*s); s++)
143			;
144		if (*s)
145			*s = toupper((unsigned char)*s);
146		else
147			memmove(simplename, simplename + 1,
148			    strlen(simplename + 1) + 1);
149	}
150#ifdef DEBUGGING
151	if (debug & 4)
152		say("Moving %s to %s.\n", orig, bakname);
153#endif
154	if (rename(orig, bakname) < 0) {
155		if (errno != EXDEV || copy_file(orig, bakname) < 0)
156			return -1;
157	}
158	return 0;
159}
160
161/*
162 * Copy a file.
163 */
164int
165copy_file(const char *from, const char *to)
166{
167	int	tofd, fromfd;
168	ssize_t	i;
169
170	tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666);
171	if (tofd < 0)
172		return -1;
173	fromfd = open(from, O_RDONLY, 0);
174	if (fromfd < 0)
175		pfatal("internal error, can't reopen %s", from);
176	while ((i = read(fromfd, buf, buf_size)) > 0)
177		if (write(tofd, buf, i) != i)
178			pfatal("write to %s failed", to);
179	close(fromfd);
180	close(tofd);
181	return 0;
182}
183
184/*
185 * Allocate a unique area for a string.
186 */
187char *
188savestr(const char *s)
189{
190	char	*rv;
191
192	if (!s)
193		s = "Oops";
194	rv = strdup(s);
195	if (rv == NULL) {
196		if (using_plan_a)
197			out_of_mem = true;
198		else
199			fatal("out of memory\n");
200	}
201	return rv;
202}
203
204/*
205 * Allocate a unique area for a string.  Call fatal if out of memory.
206 */
207char *
208xstrdup(const char *s)
209{
210	char	*rv;
211
212	if (!s)
213		s = "Oops";
214	rv = strdup(s);
215	if (rv == NULL)
216		fatal("out of memory\n");
217	return rv;
218}
219
220/*
221 * Vanilla terminal output (buffered).
222 */
223void
224say(const char *fmt, ...)
225{
226	va_list	ap;
227
228	va_start(ap, fmt);
229	vfprintf(stdout, fmt, ap);
230	va_end(ap);
231	fflush(stdout);
232}
233
234/*
235 * Terminal output, pun intended.
236 */
237void
238fatal(const char *fmt, ...)
239{
240	va_list	ap;
241
242	va_start(ap, fmt);
243	fprintf(stderr, "patch: **** ");
244	vfprintf(stderr, fmt, ap);
245	va_end(ap);
246	my_exit(2);
247}
248
249/*
250 * Say something from patch, something from the system, then silence . . .
251 */
252void
253pfatal(const char *fmt, ...)
254{
255	va_list	ap;
256	int	errnum = errno;
257
258	fprintf(stderr, "patch: **** ");
259	va_start(ap, fmt);
260	vfprintf(stderr, fmt, ap);
261	va_end(ap);
262	fprintf(stderr, ": %s\n", strerror(errnum));
263	my_exit(2);
264}
265
266/*
267 * Get a response from the user via /dev/tty
268 */
269void
270ask(const char *fmt, ...)
271{
272	va_list	ap;
273	ssize_t	nr = 0;
274	static	int ttyfd = -1;
275
276	va_start(ap, fmt);
277	vfprintf(stdout, fmt, ap);
278	va_end(ap);
279	fflush(stdout);
280	if (ttyfd < 0)
281		ttyfd = open(_PATH_TTY, O_RDONLY);
282	if (ttyfd >= 0) {
283		if ((nr = read(ttyfd, buf, buf_size)) > 0 &&
284		    buf[nr - 1] == '\n')
285			buf[nr - 1] = '\0';
286	}
287	if (ttyfd < 0 || nr <= 0) {
288		/* no tty or error reading, pretend user entered 'return' */
289		putchar('\n');
290		buf[0] = '\0';
291	}
292}
293
294/*
295 * How to handle certain events when not in a critical region.
296 */
297void
298set_signals(int reset)
299{
300	static sig_t	hupval, intval;
301
302	if (!reset) {
303		hupval = signal(SIGHUP, SIG_IGN);
304		if (hupval != SIG_IGN)
305			hupval = my_exit;
306		intval = signal(SIGINT, SIG_IGN);
307		if (intval != SIG_IGN)
308			intval = my_exit;
309	}
310	signal(SIGHUP, hupval);
311	signal(SIGINT, intval);
312}
313
314/*
315 * How to handle certain events when in a critical region.
316 */
317void
318ignore_signals(void)
319{
320	signal(SIGHUP, SIG_IGN);
321	signal(SIGINT, SIG_IGN);
322}
323
324/*
325 * Make sure we'll have the directories to create a file. If `striplast' is
326 * true, ignore the last element of `filename'.
327 */
328
329void
330makedirs(const char *filename, bool striplast)
331{
332	char	*tmpbuf;
333
334	if ((tmpbuf = strdup(filename)) == NULL)
335		fatal("out of memory\n");
336
337	if (striplast) {
338		char	*s = strrchr(tmpbuf, '/');
339		if (s == NULL) {
340			free(tmpbuf);
341			return;	/* nothing to be done */
342		}
343		*s = '\0';
344	}
345	if (mkpath(tmpbuf) != 0)
346		pfatal("creation of %s failed", tmpbuf);
347	free(tmpbuf);
348}
349
350/*
351 * Make filenames more reasonable.
352 */
353char *
354fetchname(const char *at, bool *exists, int strip_leading)
355{
356	char		*fullname, *name, *t;
357	int		sleading, tab;
358	struct stat	filestat;
359
360	if (at == NULL || *at == '\0')
361		return NULL;
362	while (isspace((unsigned char)*at))
363		at++;
364#ifdef DEBUGGING
365	if (debug & 128)
366		say("fetchname %s %d\n", at, strip_leading);
367#endif
368	/* So files can be created by diffing against /dev/null.  */
369	if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1)) {
370		*exists = true;
371		return NULL;
372	}
373	name = fullname = t = savestr(at);
374
375	tab = strchr(t, '\t') != NULL;
376	/* Strip off up to `strip_leading' path components and NUL terminate. */
377	for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') ||
378	    !isspace((unsigned char)*t)); t++) {
379		if (t[0] == '/' && t[1] != '/' && t[1] != '\0')
380			if (--sleading >= 0)
381				name = t + 1;
382	}
383	*t = '\0';
384
385	/*
386	 * If no -p option was given (957 is the default value!), we were
387	 * given a relative pathname, and the leading directories that we
388	 * just stripped off all exist, put them back on.
389	 */
390	if (strip_leading == 957 && name != fullname && *fullname != '/') {
391		name[-1] = '\0';
392		if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
393			name[-1] = '/';
394			name = fullname;
395		}
396	}
397	name = savestr(name);
398	free(fullname);
399
400	*exists = stat(name, &filestat) == 0;
401	return name;
402}
403
404void
405version(void)
406{
407	printf("patch 2.0-12u11 FreeBSD\n");
408	my_exit(EXIT_SUCCESS);
409}
410
411/*
412 * Exit with cleanup.
413 */
414void
415my_exit(int status)
416{
417	unlink(TMPINNAME);
418	if (!toutkeep)
419		unlink(TMPOUTNAME);
420	if (!trejkeep)
421		unlink(TMPREJNAME);
422	unlink(TMPPATNAME);
423	exit(status);
424}
425