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