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