make zero prefix or suffix tell patch not to produce backups at all
[dragonfly.git] / usr.bin / patch / util.c
1 /*
2  * $OpenBSD: util.c,v 1.29 2004/11/19 20:00:57 otto Exp $
3  * $DragonFly: src/usr.bin/patch/util.c,v 1.5 2006/01/19 04:51:30 corecode Exp $
4  */
5
6 /*
7  * patch - a program to apply diffs to original files
8  * 
9  * Copyright 1986, Larry Wall
10  * 
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following condition is met:
13  * 1. Redistributions of source code must retain the above copyright notice,
14  * this condition and the following disclaimer.
15  * 
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  * 
28  * -C option added in 1998, original code by Marc Espie, based on FreeBSD
29  * behaviour
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 <stdarg.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <unistd.h>
45
46 #include "common.h"
47 #include "util.h"
48 #include "backupfile.h"
49 #include "pathnames.h"
50
51
52 /* Rename a file, copying it if necessary. */
53
54 int
55 move_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, sizeof buf)) > 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
97 int
98 backup_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
110          */
111         if ((origprae && *origprae == 0) || *simple_backup_suffix == 0)
112                 return 0;
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(*s); s++)
142                         ;
143                 if (*s)
144                         *s = toupper(*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
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, sizeof buf)) > 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 *
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  * Vanilla terminal output (buffered).
205  */
206 void
207 say(const char *fmt, ...)
208 {
209         va_list ap;
210
211         va_start(ap, fmt);
212         vfprintf(stderr, fmt, ap);
213         va_end(ap);
214         fflush(stderr);
215 }
216
217 /*
218  * Terminal output, pun intended.
219  */
220 void
221 fatal(const char *fmt, ...)
222 {
223         va_list ap;
224
225         va_start(ap, fmt);
226         fprintf(stderr, "patch: **** ");
227         vfprintf(stderr, fmt, ap);
228         va_end(ap);
229         my_exit(2);
230 }
231
232 /*
233  * Say something from patch, something from the system, then silence . . .
234  */
235 void
236 pfatal(const char *fmt, ...)
237 {
238         va_list ap;
239         int     errnum = errno;
240
241         fprintf(stderr, "patch: **** ");
242         va_start(ap, fmt);
243         vfprintf(stderr, fmt, ap);
244         va_end(ap);
245         fprintf(stderr, ": %s\n", strerror(errnum));
246         my_exit(2);
247 }
248
249 /*
250  * Get a response from the user via /dev/tty
251  */
252 void
253 ask(const char *fmt, ...)
254 {
255         va_list ap;
256         ssize_t nr = 0;
257         static  int ttyfd = -1;
258
259         va_start(ap, fmt);
260         vfprintf(stdout, fmt, ap);
261         va_end(ap);
262         fflush(stdout);
263         if (ttyfd < 0)
264                 ttyfd = open(_PATH_TTY, O_RDONLY);
265         if (ttyfd >= 0) {
266                 if ((nr = read(ttyfd, buf, sizeof(buf))) > 0 &&
267                     buf[nr - 1] == '\n')
268                         buf[nr - 1] = '\0';
269         }
270         if (ttyfd < 0 || nr <= 0) {
271                 /* no tty or error reading, pretend user entered 'return' */
272                 putchar('\n');
273                 buf[0] = '\0';
274         }
275 }
276
277 /*
278  * How to handle certain events when not in a critical region.
279  */
280 void
281 set_signals(int reset)
282 {
283         static sig_t    hupval, intval;
284
285         if (!reset) {
286                 hupval = signal(SIGHUP, SIG_IGN);
287                 if (hupval != SIG_IGN)
288                         hupval = my_exit;
289                 intval = signal(SIGINT, SIG_IGN);
290                 if (intval != SIG_IGN)
291                         intval = my_exit;
292         }
293         signal(SIGHUP, hupval);
294         signal(SIGINT, intval);
295 }
296
297 /*
298  * How to handle certain events when in a critical region.
299  */
300 void
301 ignore_signals(void)
302 {
303         signal(SIGHUP, SIG_IGN);
304         signal(SIGINT, SIG_IGN);
305 }
306
307 /*
308  * Make sure we'll have the directories to create a file. If `striplast' is
309  * true, ignore the last element of `filename'.
310  */
311
312 void
313 makedirs(const char *filename, bool striplast)
314 {
315         char    *tmpbuf;
316
317         if ((tmpbuf = strdup(filename)) == NULL)
318                 fatal("out of memory\n");
319
320         if (striplast) {
321                 char    *s = strrchr(tmpbuf, '/');
322                 if (s == NULL)
323                         return; /* nothing to be done */
324                 *s = '\0';
325         }
326         if (snprintf(buf, sizeof(buf), "%s -p %s", _PATH_MKDIR, tmpbuf)
327             >= (int)sizeof(buf))
328                 fatal("buffer too small to hold %.20s...\n", tmpbuf);
329
330         if (system(buf))
331                 pfatal("%.40s failed", buf);
332 }
333
334 /*
335  * Make filenames more reasonable.
336  */
337 char *
338 fetchname(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(*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(*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  */
390 char *
391 checked_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
412 void
413 version(void)
414 {
415         fprintf(stderr, "Patch version 2.0-12u8-OpenBSD\n");
416         my_exit(EXIT_SUCCESS);
417 }
418
419 /*
420  * Exit with cleanup.
421  */
422 void
423 my_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 }