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