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$
28 */
29
30#include <sys/param.h>
31#include <sys/stat.h>
32
33#include <ctype.h>
34#include <errno.h>
35#include <fcntl.h>
36#include <libgen.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[MAXPATHLEN], *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 * Vanilla terminal output (buffered).
206 */
207void
208say(const char *fmt, ...)
209{
210	va_list	ap;
211
212	va_start(ap, fmt);
213	vfprintf(stdout, fmt, ap);
214	va_end(ap);
215	fflush(stdout);
216}
217
218/*
219 * Terminal output, pun intended.
220 */
221void
222fatal(const char *fmt, ...)
223{
224	va_list	ap;
225
226	va_start(ap, fmt);
227	fprintf(stderr, "patch: **** ");
228	vfprintf(stderr, fmt, ap);
229	va_end(ap);
230	my_exit(2);
231}
232
233/*
234 * Say something from patch, something from the system, then silence . . .
235 */
236void
237pfatal(const char *fmt, ...)
238{
239	va_list	ap;
240	int	errnum = errno;
241
242	fprintf(stderr, "patch: **** ");
243	va_start(ap, fmt);
244	vfprintf(stderr, fmt, ap);
245	va_end(ap);
246	fprintf(stderr, ": %s\n", strerror(errnum));
247	my_exit(2);
248}
249
250/*
251 * Get a response from the user via /dev/tty
252 */
253void
254ask(const char *fmt, ...)
255{
256	va_list	ap;
257	ssize_t	nr = 0;
258	static	int ttyfd = -1;
259
260	va_start(ap, fmt);
261	vfprintf(stdout, fmt, ap);
262	va_end(ap);
263	fflush(stdout);
264	if (ttyfd < 0)
265		ttyfd = open(_PATH_TTY, O_RDONLY);
266	if (ttyfd >= 0) {
267		if ((nr = read(ttyfd, buf, buf_size)) > 0 &&
268		    buf[nr - 1] == '\n')
269			buf[nr - 1] = '\0';
270	}
271	if (ttyfd < 0 || nr <= 0) {
272		/* no tty or error reading, pretend user entered 'return' */
273		putchar('\n');
274		buf[0] = '\0';
275	}
276}
277
278/*
279 * How to handle certain events when not in a critical region.
280 */
281void
282set_signals(int reset)
283{
284	static sig_t	hupval, intval;
285
286	if (!reset) {
287		hupval = signal(SIGHUP, SIG_IGN);
288		if (hupval != SIG_IGN)
289			hupval = my_exit;
290		intval = signal(SIGINT, SIG_IGN);
291		if (intval != SIG_IGN)
292			intval = my_exit;
293	}
294	signal(SIGHUP, hupval);
295	signal(SIGINT, intval);
296}
297
298/*
299 * How to handle certain events when in a critical region.
300 */
301void
302ignore_signals(void)
303{
304	signal(SIGHUP, SIG_IGN);
305	signal(SIGINT, SIG_IGN);
306}
307
308/*
309 * Make sure we'll have the directories to create a file. If `striplast' is
310 * true, ignore the last element of `filename'.
311 */
312
313void
314makedirs(const char *filename, bool striplast)
315{
316	char	*tmpbuf;
317
318	if ((tmpbuf = strdup(filename)) == NULL)
319		fatal("out of memory\n");
320
321	if (striplast) {
322		char	*s = strrchr(tmpbuf, '/');
323		if (s == NULL) {
324			free(tmpbuf);
325			return;	/* nothing to be done */
326		}
327		*s = '\0';
328	}
329	if (mkpath(tmpbuf) != 0)
330		pfatal("creation of %s failed", tmpbuf);
331	free(tmpbuf);
332}
333
334/*
335 * Make filenames more reasonable.
336 */
337char *
338fetchname(const char *at, bool *exists, int strip_leading)
339{
340	char		*fullname, *name, *t;
341	int		sleading, tab;
342	struct stat	filestat;
343
344	if (at == NULL || *at == '\0')
345		return NULL;
346	while (isspace((unsigned char)*at))
347		at++;
348#ifdef DEBUGGING
349	if (debug & 128)
350		say("fetchname %s %d\n", at, strip_leading);
351#endif
352	/* So files can be created by diffing against /dev/null.  */
353	if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1))
354		return NULL;
355	name = fullname = t = savestr(at);
356
357	tab = strchr(t, '\t') != NULL;
358	/* Strip off up to `strip_leading' path components and NUL terminate. */
359	for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') ||
360	    !isspace((unsigned char)*t)); t++) {
361		if (t[0] == '/' && t[1] != '/' && t[1] != '\0')
362			if (--sleading >= 0)
363				name = t + 1;
364	}
365	*t = '\0';
366
367	/*
368	 * If no -p option was given (957 is the default value!), we were
369	 * given a relative pathname, and the leading directories that we
370	 * just stripped off all exist, put them back on.
371	 */
372	if (strip_leading == 957 && name != fullname && *fullname != '/') {
373		name[-1] = '\0';
374		if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
375			name[-1] = '/';
376			name = fullname;
377		}
378	}
379	name = savestr(name);
380	free(fullname);
381
382	*exists = stat(name, &filestat) == 0;
383	return name;
384}
385
386/*
387 * Takes the name returned by fetchname and looks in RCS/SCCS directories
388 * for a checked in version.
389 */
390char *
391checked_in(char *file)
392{
393	char		*filebase, *filedir, tmpbuf[MAXPATHLEN];
394	struct stat	filestat;
395
396	filebase = basename(file);
397	filedir = dirname(file);
398
399#define try(f, a1, a2, a3) \
400(snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0)
401
402	if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
403	    try("%s/RCS/%s%s", filedir, filebase, "") ||
404	    try("%s/%s%s", filedir, filebase, RCSSUFFIX) ||
405	    try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
406	    try("%s/%s%s", filedir, SCCSPREFIX, filebase))
407		return file;
408
409	return NULL;
410}
411
412void
413version(void)
414{
415	fprintf(stderr, "patch 2.0-12u10 FreeBSD\n");
416	my_exit(EXIT_SUCCESS);
417}
418
419/*
420 * Exit with cleanup.
421 */
422void
423my_exit(int status)
424{
425	unlink(TMPINNAME);
426	if (!toutkeep)
427		unlink(TMPOUTNAME);
428	if (!trejkeep)
429		unlink(TMPREJNAME);
430	unlink(TMPPATNAME);
431	exit(status);
432}
433