util.c revision 246074
1/* $FreeBSD: head/usr.bin/patch/util.c 246074 2013-01-29 17:03:18Z gabor $ */
2/*-
3 *
4 * Copyright 1986, Larry Wall
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following condition is met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this condition and the following disclaimer.
10 *
11 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
12 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
13 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
15 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
16 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
17 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
18 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
19 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
20 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
21 * SUCH DAMAGE.
22 *
23 * patch - a program to apply diffs to original files
24 *
25 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
26 * behaviour
27 *
28 * $OpenBSD: util.c,v 1.32 2006/03/11 19:41:30 otto Exp $
29 * $DragonFly: src/usr.bin/patch/util.c,v 1.9 2007/09/29 23:11:10 swildner Exp $
30 */
31
32#include <sys/param.h>
33#include <sys/stat.h>
34
35#include <ctype.h>
36#include <errno.h>
37#include <fcntl.h>
38#include <libgen.h>
39#include <paths.h>
40#include <signal.h>
41#include <stdarg.h>
42#include <stdlib.h>
43#include <stdio.h>
44#include <string.h>
45#include <unistd.h>
46
47#include "common.h"
48#include "util.h"
49#include "backupfile.h"
50#include "pathnames.h"
51
52/* Rename a file, copying it if necessary. */
53
54int
55move_file(const char *from, const char *to)
56{
57	int	fromfd;
58	ssize_t	i;
59
60	/* to stdout? */
61
62	if (strEQ(to, "-")) {
63#ifdef DEBUGGING
64		if (debug & 4)
65			say("Moving %s to stdout.\n", from);
66#endif
67		fromfd = open(from, O_RDONLY);
68		if (fromfd < 0)
69			pfatal("internal error, can't reopen %s", from);
70		while ((i = read(fromfd, buf, buf_size)) > 0)
71			if (write(STDOUT_FILENO, buf, i) != i)
72				pfatal("write failed");
73		close(fromfd);
74		return 0;
75	}
76	if (backup_file(to) < 0) {
77		say("Can't backup %s, output is in %s: %s\n", to, from,
78		    strerror(errno));
79		return -1;
80	}
81#ifdef DEBUGGING
82	if (debug & 4)
83		say("Moving %s to %s.\n", from, to);
84#endif
85	if (rename(from, to) < 0) {
86		if (errno != EXDEV || copy_file(from, to) < 0) {
87			say("Can't create %s, output is in %s: %s\n",
88			    to, from, strerror(errno));
89			return -1;
90		}
91	}
92	return 0;
93}
94
95/* Backup the original file.  */
96
97int
98backup_file(const char *orig)
99{
100	struct stat	filestat;
101	char		bakname[MAXPATHLEN], *s, *simplename;
102	dev_t		orig_device;
103	ino_t		orig_inode;
104
105	if (backup_type == none || stat(orig, &filestat) != 0)
106		return 0;			/* nothing to do */
107	/*
108	 * If the user used zero prefixes or suffixes, then
109	 * he doesn't want backups.  Yet we have to remove
110	 * orig to break possible hardlinks.
111	 */
112	if ((origprae && *origprae == 0) || *simple_backup_suffix == 0) {
113		unlink(orig);
114		return 0;
115	}
116	orig_device = filestat.st_dev;
117	orig_inode = filestat.st_ino;
118
119	if (origprae) {
120		if (strlcpy(bakname, origprae, sizeof(bakname)) >= sizeof(bakname) ||
121		    strlcat(bakname, orig, sizeof(bakname)) >= sizeof(bakname))
122			fatal("filename %s too long for buffer\n", origprae);
123	} else {
124		if ((s = find_backup_file_name(orig)) == NULL)
125			fatal("out of memory\n");
126		if (strlcpy(bakname, s, sizeof(bakname)) >= sizeof(bakname))
127			fatal("filename %s too long for buffer\n", s);
128		free(s);
129	}
130
131	if ((simplename = strrchr(bakname, '/')) != NULL)
132		simplename = simplename + 1;
133	else
134		simplename = bakname;
135
136	/*
137	 * Find a backup name that is not the same file. Change the
138	 * first lowercase char into uppercase; if that isn't
139	 * sufficient, chop off the first char and try again.
140	 */
141	while (stat(bakname, &filestat) == 0 &&
142	    orig_device == filestat.st_dev && orig_inode == filestat.st_ino) {
143		/* Skip initial non-lowercase chars.  */
144		for (s = simplename; *s && !islower((unsigned char)*s); s++)
145			;
146		if (*s)
147			*s = toupper((unsigned char)*s);
148		else
149			memmove(simplename, simplename + 1,
150			    strlen(simplename + 1) + 1);
151	}
152#ifdef DEBUGGING
153	if (debug & 4)
154		say("Moving %s to %s.\n", orig, bakname);
155#endif
156	if (rename(orig, bakname) < 0) {
157		if (errno != EXDEV || copy_file(orig, bakname) < 0)
158			return -1;
159	}
160	return 0;
161}
162
163/*
164 * Copy a file.
165 */
166int
167copy_file(const char *from, const char *to)
168{
169	int	tofd, fromfd;
170	ssize_t	i;
171
172	tofd = open(to, O_CREAT|O_TRUNC|O_WRONLY, 0666);
173	if (tofd < 0)
174		return -1;
175	fromfd = open(from, O_RDONLY, 0);
176	if (fromfd < 0)
177		pfatal("internal error, can't reopen %s", from);
178	while ((i = read(fromfd, buf, buf_size)) > 0)
179		if (write(tofd, buf, i) != i)
180			pfatal("write to %s failed", to);
181	close(fromfd);
182	close(tofd);
183	return 0;
184}
185
186/*
187 * Allocate a unique area for a string.
188 */
189char *
190savestr(const char *s)
191{
192	char	*rv;
193
194	if (!s)
195		s = "Oops";
196	rv = strdup(s);
197	if (rv == NULL) {
198		if (using_plan_a)
199			out_of_mem = true;
200		else
201			fatal("out of memory\n");
202	}
203	return rv;
204}
205
206/*
207 * Vanilla terminal output (buffered).
208 */
209void
210say(const char *fmt, ...)
211{
212	va_list	ap;
213
214	va_start(ap, fmt);
215	vfprintf(stderr, fmt, ap);
216	va_end(ap);
217	fflush(stderr);
218}
219
220/*
221 * Terminal output, pun intended.
222 */
223void
224fatal(const char *fmt, ...)
225{
226	va_list	ap;
227
228	va_start(ap, fmt);
229	fprintf(stderr, "patch: **** ");
230	vfprintf(stderr, fmt, ap);
231	va_end(ap);
232	my_exit(2);
233}
234
235/*
236 * Say something from patch, something from the system, then silence . . .
237 */
238void
239pfatal(const char *fmt, ...)
240{
241	va_list	ap;
242	int	errnum = errno;
243
244	fprintf(stderr, "patch: **** ");
245	va_start(ap, fmt);
246	vfprintf(stderr, fmt, ap);
247	va_end(ap);
248	fprintf(stderr, ": %s\n", strerror(errnum));
249	my_exit(2);
250}
251
252/*
253 * Get a response from the user via /dev/tty
254 */
255void
256ask(const char *fmt, ...)
257{
258	va_list	ap;
259	ssize_t	nr = 0;
260	static	int ttyfd = -1;
261
262	va_start(ap, fmt);
263	vfprintf(stdout, fmt, ap);
264	va_end(ap);
265	fflush(stdout);
266	if (ttyfd < 0)
267		ttyfd = open(_PATH_TTY, O_RDONLY);
268	if (ttyfd >= 0) {
269		if ((nr = read(ttyfd, buf, buf_size)) > 0 &&
270		    buf[nr - 1] == '\n')
271			buf[nr - 1] = '\0';
272	}
273	if (ttyfd < 0 || nr <= 0) {
274		/* no tty or error reading, pretend user entered 'return' */
275		putchar('\n');
276		buf[0] = '\0';
277	}
278}
279
280/*
281 * How to handle certain events when not in a critical region.
282 */
283void
284set_signals(int reset)
285{
286	static sig_t	hupval, intval;
287
288	if (!reset) {
289		hupval = signal(SIGHUP, SIG_IGN);
290		if (hupval != SIG_IGN)
291			hupval = my_exit;
292		intval = signal(SIGINT, SIG_IGN);
293		if (intval != SIG_IGN)
294			intval = my_exit;
295	}
296	signal(SIGHUP, hupval);
297	signal(SIGINT, intval);
298}
299
300/*
301 * How to handle certain events when in a critical region.
302 */
303void
304ignore_signals(void)
305{
306	signal(SIGHUP, SIG_IGN);
307	signal(SIGINT, SIG_IGN);
308}
309
310/*
311 * Make sure we'll have the directories to create a file. If `striplast' is
312 * true, ignore the last element of `filename'.
313 */
314
315void
316makedirs(const char *filename, bool striplast)
317{
318	char	*tmpbuf;
319
320	if ((tmpbuf = strdup(filename)) == NULL)
321		fatal("out of memory\n");
322
323	if (striplast) {
324		char	*s = strrchr(tmpbuf, '/');
325		if (s == NULL) {
326			free(tmpbuf);
327			return;	/* nothing to be done */
328		}
329		*s = '\0';
330	}
331	if (mkpath(tmpbuf) != 0)
332		pfatal("creation of %s failed", tmpbuf);
333	free(tmpbuf);
334}
335
336/*
337 * Make filenames more reasonable.
338 */
339char *
340fetchname(const char *at, bool *exists, int strip_leading)
341{
342	char		*fullname, *name, *t;
343	int		sleading, tab;
344	struct stat	filestat;
345
346	if (at == NULL || *at == '\0')
347		return NULL;
348	while (isspace((unsigned char)*at))
349		at++;
350#ifdef DEBUGGING
351	if (debug & 128)
352		say("fetchname %s %d\n", at, strip_leading);
353#endif
354	/* So files can be created by diffing against /dev/null.  */
355	if (strnEQ(at, _PATH_DEVNULL, sizeof(_PATH_DEVNULL) - 1))
356		return NULL;
357	name = fullname = t = savestr(at);
358
359	tab = strchr(t, '\t') != NULL;
360	/* Strip off up to `strip_leading' path components and NUL terminate. */
361	for (sleading = strip_leading; *t != '\0' && ((tab && *t != '\t') ||
362	    !isspace((unsigned char)*t)); t++) {
363		if (t[0] == '/' && t[1] != '/' && t[1] != '\0')
364			if (--sleading >= 0)
365				name = t + 1;
366	}
367	*t = '\0';
368
369	/*
370	 * If no -p option was given (957 is the default value!), we were
371	 * given a relative pathname, and the leading directories that we
372	 * just stripped off all exist, put them back on.
373	 */
374	if (strip_leading == 957 && name != fullname && *fullname != '/') {
375		name[-1] = '\0';
376		if (stat(fullname, &filestat) == 0 && S_ISDIR(filestat.st_mode)) {
377			name[-1] = '/';
378			name = fullname;
379		}
380	}
381	name = savestr(name);
382	free(fullname);
383
384	*exists = stat(name, &filestat) == 0;
385	return name;
386}
387
388/*
389 * Takes the name returned by fetchname and looks in RCS/SCCS directories
390 * for a checked in version.
391 */
392char *
393checked_in(char *file)
394{
395	char		*filebase, *filedir, tmpbuf[MAXPATHLEN];
396	struct stat	filestat;
397
398	filebase = basename(file);
399	filedir = dirname(file);
400
401#define try(f, a1, a2, a3) \
402(snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0)
403
404	if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) ||
405	    try("%s/RCS/%s%s", filedir, filebase, "") ||
406	    try("%s/%s%s", filedir, filebase, RCSSUFFIX) ||
407	    try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) ||
408	    try("%s/%s%s", filedir, SCCSPREFIX, filebase))
409		return file;
410
411	return NULL;
412}
413
414void
415version(void)
416{
417	fprintf(stderr, "patch (BSD patch) 2.0-FreeBSD\n");
418	my_exit(EXIT_SUCCESS);
419}
420
421/*
422 * Exit with cleanup.
423 */
424void
425my_exit(int status)
426{
427	unlink(TMPINNAME);
428	if (!toutkeep)
429		unlink(TMPOUTNAME);
430	if (!trejkeep)
431		unlink(TMPREJNAME);
432	unlink(TMPPATNAME);
433	exit(status);
434}
435