1 /* utility functions for `patch' */
3 /* $Id: util.c,v 1.24 1997/07/10 08:16:12 eggert Exp $ */
6 Copyright 1986 Larry Wall
7 Copyright 1992, 1993, 1997 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; see the file COPYING.
21 If not, write to the Free Software Foundation,
22 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 #include <backupfile.h>
38 #if !defined SIGCHLD && defined SIGCLD
39 #define SIGCHLD SIGCLD
42 # define raise(sig) kill (getpid (), sig)
47 # define vararg_start va_start
49 # define vararg_start(ap,p) va_start (ap)
53 typedef char *va_list;
54 # define va_dcl int va_alist;
55 # define va_start(ap) ((ap) = (va_list) &va_alist)
56 # define va_arg(ap, t) (((t *) ((ap) += sizeof (t))) [-1])
61 static void makedirs PARAMS ((char *));
63 /* Move a file FROM to TO, renaming it if possible and copying it if necessary.
64 If we must create TO, use MODE to create it.
65 If FROM is null, remove TO (ignoring FROMSTAT).
66 Back up TO if BACKUP is nonzero. */
69 /* If mode_t doesn't promote to itself, we can't use old-style definition. */
71 move_file (char const *from, char *to, mode_t mode, int backup)
74 move_file (from, to, mode, backup)
82 int to_errno = ! backup ? -1 : stat (to, &to_st) == 0 ? 0 : errno;
86 int try_makedirs_errno = 0;
89 if (origprae || origbase)
91 char const *p = origprae ? origprae : "";
92 char const *b = origbase ? origbase : "";
93 char const *o = base_name (to);
94 size_t plen = strlen (p);
96 size_t blen = strlen (b);
97 size_t osize = strlen (o) + 1;
98 bakname = xmalloc (plen + tlen + blen + osize);
99 memcpy (bakname, p, plen);
100 memcpy (bakname + plen, to, tlen);
101 memcpy (bakname + plen + tlen, b, blen);
102 memcpy (bakname + plen + tlen + blen, o, osize);
103 for (p += FILESYSTEM_PREFIX_LEN (p); *p; p++)
106 try_makedirs_errno = ENOENT;
112 bakname = find_backup_file_name (to);
121 say ("creating empty unreadable file `%s'\n", bakname);
122 try_makedirs_errno = ENOENT;
124 while ((fd = creat (bakname, 0)) < 0)
126 if (errno != try_makedirs_errno)
127 pfatal ("can't create file `%s'", bakname);
129 try_makedirs_errno = 0;
132 pfatal ("can't close `%s'", bakname);
137 say ("renaming `%s' to `%s'\n", to, bakname);
138 while (rename (to, bakname) != 0)
140 if (errno != try_makedirs_errno)
141 pfatal ("can't rename `%s' to `%s'", to, bakname);
143 try_makedirs_errno = 0;
153 say ("renaming `%s' to `%s'\n", from, to);
155 if (rename (from, to) != 0)
157 int to_dir_known_to_exist = 0;
160 && (to_errno == -1 || to_errno == ENOENT))
163 to_dir_known_to_exist = 1;
164 if (rename (from, to) == 0)
172 if (unlink (to) == 0)
173 to_dir_known_to_exist = 1;
174 else if (errno != ENOENT)
175 pfatal ("can't remove `%s'", to);
177 if (! to_dir_known_to_exist)
179 copy_file (from, to, mode);
183 pfatal ("can't rename `%s' to `%s'", from, to);
189 say ("removing `%s'\n", to);
190 if (unlink (to) != 0)
191 pfatal ("can't remove `%s'", to);
195 /* Create FILE with OPEN_FLAGS, and with MODE adjusted so that
196 we can read and write the file and that the file is not executable.
197 Return the file descriptor. */
199 /* If mode_t doesn't promote to itself, we can't use old-style definition. */
201 create_file (char const *file, int open_flags, mode_t mode)
204 create_file (file, open_flags, mode)
211 mode |= S_IRUSR | S_IWUSR;
212 mode &= ~ (S_IXUSR | S_IXGRP | S_IXOTH);
213 if (! (O_CREAT && O_TRUNC))
214 close (creat (file, mode));
215 fd = open (file, O_CREAT | O_TRUNC | open_flags, mode);
217 pfatal ("can't create `%s'", file);
224 /* If mode_t doesn't promote to itself, we can't use old-style definition. */
226 copy_file (char const *from, char const *to, mode_t mode)
229 copy_file (from, to, mode)
239 if ((fromfd = open (from, O_RDONLY | O_BINARY)) < 0)
240 pfatal ("can't reopen `%s'", from);
241 tofd = create_file (to, O_WRONLY | O_BINARY, mode);
242 while ((i = read (fromfd, buf, bufsize)) != 0)
246 if (write (tofd, buf, i) != i)
249 if (close (fromfd) != 0)
251 if (close (tofd) != 0)
255 static char const DEV_NULL[] = NULL_DEVICE;
257 static char const SCCSPREFIX[] = "s.";
258 static char const GET[] = "get ";
259 static char const GET_LOCKED[] = "get -e ";
260 static char const SCCSDIFF1[] = "get -p ";
261 static char const SCCSDIFF2[] = "|diff - %s";
263 static char const RCSSUFFIX[] = ",v";
264 static char const CHECKOUT[] = "co %s";
265 static char const CHECKOUT_LOCKED[] = "co -l %s";
266 static char const RCSDIFF1[] = "rcsdiff %s";
268 /* Return "RCS" if FILENAME is controlled by RCS,
269 "SCCS" if it is controlled by SCCS, and 0 otherwise.
270 READONLY is nonzero if we desire only readonly access to FILENAME.
271 FILESTAT describes FILENAME's status or is 0 if FILENAME does not exist.
272 If successful and if GETBUF is nonzero, set *GETBUF to a command
273 that gets the file; similarly for DIFFBUF and a command to diff the file.
274 *GETBUF and *DIFFBUF must be freed by the caller. */
276 version_controller (filename, readonly, filestat, getbuf, diffbuf)
277 char const *filename;
279 struct stat const *filestat;
284 char const *filebase = base_name (filename);
285 char const *dotslash = *filename == '-' ? "./" : "";
286 size_t dir_len = filebase - filename;
287 size_t filenamelen = strlen (filename);
288 size_t maxfixlen = sizeof "SCCS/" - 1 + sizeof SCCSPREFIX - 1;
289 size_t maxtrysize = filenamelen + maxfixlen + 1;
290 size_t quotelen = quote_system_arg (0, filename);
291 size_t maxgetsize = sizeof GET_LOCKED + quotelen + maxfixlen;
293 (sizeof SCCSDIFF1 + sizeof SCCSDIFF2 + sizeof DEV_NULL - 1
294 + 2 * quotelen + maxfixlen);
295 char *trybuf = xmalloc (maxtrysize);
298 strcpy (trybuf, filename);
300 #define try1(f,a1) (sprintf (trybuf + dir_len, f, a1), stat (trybuf, &cstat) == 0)
301 #define try2(f,a1,a2) (sprintf (trybuf + dir_len, f, a1,a2), stat (trybuf, &cstat) == 0)
303 /* Check that RCS file is not working file.
304 Some hosts don't report file name length errors. */
306 if ((try2 ("RCS/%s%s", filebase, RCSSUFFIX)
307 || try1 ("RCS/%s", filebase)
308 || try2 ("%s%s", filebase, RCSSUFFIX))
310 && filestat->st_dev == cstat.st_dev
311 && filestat->st_ino == cstat.st_ino))
315 char *p = *getbuf = xmalloc (maxgetsize);
316 sprintf (p, readonly ? CHECKOUT : CHECKOUT_LOCKED, dotslash);
318 p += quote_system_arg (p, filename);
324 char *p = *diffbuf = xmalloc (maxdiffsize);
325 sprintf (p, RCSDIFF1, dotslash);
327 p += quote_system_arg (p, filename);
329 strcpy (p, DEV_NULL);
334 else if (try2 ("SCCS/%s%s", SCCSPREFIX, filebase)
335 || try2 ("%s%s", SCCSPREFIX, filebase))
339 char *p = *getbuf = xmalloc (maxgetsize);
340 sprintf (p, readonly ? GET : GET_LOCKED);
342 p += quote_system_arg (p, trybuf);
348 char *p = *diffbuf = xmalloc (maxdiffsize);
349 strcpy (p, SCCSDIFF1);
350 p += sizeof SCCSDIFF1 - 1;
351 p += quote_system_arg (p, trybuf);
352 sprintf (p, SCCSDIFF2, dotslash);
354 p += quote_system_arg (p, filename);
356 strcpy (p, DEV_NULL);
366 /* Get FILENAME from version control system CS. The file already exists if
367 EXISTS is nonzero. Only readonly access is needed if READONLY is nonzero.
368 Use the command GETBUF to actually get the named file.
369 Store the resulting file status into *FILESTAT.
370 Return nonzero if successful. */
372 version_get (filename, cs, exists, readonly, getbuf, filestat)
373 char const *filename;
378 struct stat *filestat;
382 ask ("Get file `%s' from %s%s? [y] ", filename,
383 cs, readonly ? "" : " with lock");
391 fatal ("can't do dry run on nonexistent version-controlled file `%s'; invoke `%s' and try again",
396 if (verbosity == VERBOSE)
397 say ("Getting file `%s' from %s%s...\n", filename,
398 cs, readonly ? "" : " with lock");
399 if (systemic (getbuf) != 0)
400 fatal ("can't get file `%s' from %s", filename, cs);
401 if (stat (filename, filestat) != 0)
402 pfatal ("%s", filename);
408 /* Allocate a unique area for a string. */
412 register char const *s;
413 register size_t size;
426 memcpy (rv, s, size);
435 return savebuf (s, strlen (s) + 1);
439 remove_prefix (p, prefixlen)
443 char const *s = p + prefixlen;
444 while ((*p++ = *s++))
449 #define vfprintf my_vfprintf
450 static int vfprintf PARAMS ((FILE *, char const *, va_list));
452 vfprintf (stream, format, args)
457 #if !HAVE_DOPRNT && HAVE__DOPRINTF
458 # define _doprnt _doprintf
460 #if HAVE_DOPRNT || HAVE__DOPRINTF
461 _doprnt (format, args, stream);
462 return ferror (stream) ? -1 : 0;
464 int *a = (int *) args;
465 return fprintf (stream, format,
466 a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9]);
469 #endif /* !HAVE_VPRINTF */
471 /* Terminal output, pun intended. */
475 fatal (char const *format, ...)
478 fatal (format, va_alist)
484 fprintf (stderr, "%s: **** ", program_name);
485 vararg_start (args, format);
486 vfprintf (stderr, format, args);
496 fatal ("out of memory");
502 pfatal ("read error");
508 pfatal ("write error");
511 /* Say something from patch, something from the system, then silence . . . */
515 pfatal (char const *format, ...)
518 pfatal (format, va_alist)
525 fprintf (stderr, "%s: **** ", program_name);
526 vararg_start (args, format);
527 vfprintf (stderr, format, args);
529 fflush (stderr); /* perror bypasses stdio on some hosts. */
536 /* Tell the user something. */
540 say (char const *format, ...)
543 say (format, va_alist)
549 vararg_start (args, format);
550 vfprintf (stdout, format, args);
555 /* Get a response from the user, somehow or other. */
559 ask (char const *format, ...)
562 ask (format, va_alist)
567 static int ttyfd = -2;
571 vararg_start (args, format);
572 vfprintf (stdout, format, args);
578 /* If standard output is not a tty, don't bother opening /dev/tty,
579 since it's unlikely that stdout will be seen by the tty user.
580 The isatty test also works around a bug in GNU Emacs 19.34 under Linux
581 which makes a call-process `patch' hang when it reads from /dev/tty.
582 POSIX.2 requires that we read /dev/tty, though. */
583 ttyfd = (posixly_correct || isatty (STDOUT_FILENO)
584 ? open (TTY_DEVICE, O_RDONLY)
590 /* No terminal at all -- default it. */
598 while ((r = read (ttyfd, buf + s, bufsize - 1 - s)) == bufsize - 1 - s
599 && buf[bufsize - 2] != '\n')
603 buf = realloc (buf, bufsize);
621 /* Return nonzero if it OK to reverse a patch. */
625 ok_to_reverse (char const *format, ...)
627 ok_to_reverse (format, va_alist)
634 if (noreverse || ! (force && verbosity == SILENT))
637 vararg_start (args, format);
638 vfprintf (stdout, format, args);
644 printf (" Skipping patch.\n");
645 skip_rest_of_patch = TRUE;
650 if (verbosity != SILENT)
651 printf (" Applying it anyway.\n");
656 say (reverse ? " Ignoring -R.\n" : " Assuming -R.\n");
661 ask (reverse ? " Ignore -R? [n] " : " Assume -R? [n] ");
665 ask ("Apply anyway? [n] ");
668 if (verbosity != SILENT)
669 say ("Skipping patch.\n");
670 skip_rest_of_patch = TRUE;
678 /* How to handle certain events when not in a critical region. */
680 #define NUM_SIGS (sizeof (sigs) / sizeof (*sigs))
681 static int const sigs[] = {
700 #if !HAVE_SIGPROCMASK
702 #define sigemptyset(s) (*(s) = 0)
704 #define sigmask(sig) (1 << ((sig) - 1))
706 #define sigaddset(s, sig) (*(s) |= sigmask (sig))
707 #define sigismember(s, sig) ((*(s) & sigmask (sig)) != 0)
712 #define SIG_UNBLOCK (SIG_BLOCK + 1)
715 #define SIG_SETMASK (SIG_BLOCK + 2)
717 #define sigprocmask(how, n, o) \
718 ((how) == SIG_BLOCK \
719 ? ((o) ? *(o) = sigblock (*(n)) : sigblock (*(n))) \
720 : (how) == SIG_UNBLOCK \
721 ? sigsetmask (((o) ? *(o) = sigblock (0) : sigblock (0)) & ~*(n)) \
722 : (o ? *(o) = sigsetmask (*(n)) : sigsetmask (*(n))))
724 #define sigblock(mask) 0
725 #define sigsetmask(mask) 0
729 static sigset_t initial_signal_mask;
730 static sigset_t signals_to_block;
733 static RETSIGTYPE fatal_exit_handler PARAMS ((int)) __attribute__ ((noreturn));
735 fatal_exit_handler (sig)
738 signal (sig, SIG_IGN);
749 struct sigaction initial_act, fatal_act;
750 fatal_act.sa_handler = fatal_exit;
751 sigemptyset (&fatal_act.sa_mask);
752 fatal_act.sa_flags = 0;
753 #define setup_handler(sig) sigaction (sig, &fatal_act, (struct sigaction *) 0)
755 #define setup_handler(sig) signal (sig, fatal_exit_handler)
761 /* System V fork+wait does not work if SIGCHLD is ignored. */
762 signal (SIGCHLD, SIG_DFL);
764 sigemptyset (&signals_to_block);
765 for (i = 0; i < NUM_SIGS; i++)
769 if (sigaction (sigs[i], (struct sigaction *) 0, &initial_act) != 0)
771 ignoring_signal = initial_act.sa_handler == SIG_IGN;
773 ignoring_signal = signal (sigs[i], SIG_IGN) == SIG_IGN;
775 if (! ignoring_signal)
777 sigaddset (&signals_to_block, sigs[i]);
778 setup_handler (sigs[i]);
784 /* Undo the effect of ignore_signals. */
785 #if HAVE_SIGPROCMASK || HAVE_SIGSETMASK
786 sigprocmask (SIG_SETMASK, &initial_signal_mask, (sigset_t *) 0);
788 for (i = 0; i < NUM_SIGS; i++)
789 if (sigismember (&signals_to_block, sigs[i]))
790 setup_handler (sigs[i]);
795 /* How to handle certain events when in a critical region. */
800 #if HAVE_SIGPROCMASK || HAVE_SIGSETMASK
801 sigprocmask (SIG_BLOCK, &signals_to_block, &initial_signal_mask);
804 for (i = 0; i < NUM_SIGS; i++)
805 if (sigismember (&signals_to_block, sigs[i]))
806 signal (sigs[i], SIG_IGN);
811 exit_with_signal (sig)
815 signal (sig, SIG_DFL);
818 sigprocmask (SIG_UNBLOCK, &s, (sigset_t *) 0);
828 say ("+ %s\n", command);
830 return system (command);
834 /* These mkdir and rmdir substitutes are good enough for `patch';
835 they are not general emulators. */
837 static int doprogram PARAMS ((char const *, char const *));
838 static int mkdir PARAMS ((char const *, mode_t));
839 static int rmdir PARAMS ((char const *));
842 doprogram (program, arg)
847 static char const DISCARD_OUTPUT[] = " 2>/dev/null";
848 size_t program_len = strlen (program);
849 char *cmd = xmalloc (program_len + 1 + quote_system_arg (0, arg)
850 + sizeof DISCARD_OUTPUT);
855 p += quote_system_arg (p, arg);
856 strcpy (p, DISCARD_OUTPUT);
857 result = systemic (cmd);
863 /* If mode_t doesn't promote to itself, we can't use old-style definition. */
865 mkdir (char const *path, mode_t mode)
870 mode_t mode; /* ignored */
873 return doprogram ("mkdir", path);
880 int result = doprogram ("rmdir", path);
886 /* Replace '/' with '\0' in FILENAME if it marks a place that
887 needs testing for the existence of directory. Return the address
888 of the last location replaced, or 0 if none were replaced. */
889 static char *replace_slashes PARAMS ((char *));
891 replace_slashes (filename)
895 char *last_location_replaced = 0;
896 char const *component_start;
898 for (f = filename + FILESYSTEM_PREFIX_LEN (filename); ISSLASH (*f); f++)
908 /* Treat multiple slashes as if they were one slash. */
909 while (ISSLASH (f[1]))
912 /* Ignore slashes at the end of the path. */
916 /* "." and ".." need not be tested. */
917 if (! (slash - component_start <= 2
918 && component_start[0] == '.' && slash[-1] == '.'))
921 last_location_replaced = slash;
924 component_start = f + 1;
927 return last_location_replaced;
930 /* Make sure we'll have the directories to create a file.
931 Ignore the last element of `filename'. */
935 register char *filename;
938 register char *flim = replace_slashes (filename);
942 /* Create any missing directories, replacing NULs by '/'s.
943 Ignore errors. We may have to keep going even after an EEXIST,
944 since the path may contain ".."s; and when there is an EEXIST
945 failure the system may return some other error number.
946 Any problems will eventually be reported when we create the file. */
947 for (f = filename; f <= flim; f++)
951 S_IRUSR|S_IWUSR|S_IXUSR
952 |S_IRGRP|S_IWGRP|S_IXGRP
953 |S_IROTH|S_IWOTH|S_IXOTH);
959 /* Remove empty ancestor directories of FILENAME.
960 Ignore errors, since the path may contain ".."s, and when there
961 is an EEXIST failure the system may return some other error number. */
963 removedirs (filename)
968 for (i = strlen (filename); i != 0; i--)
969 if (ISSLASH (filename[i])
970 && ! (ISSLASH (filename[i - 1])
971 || (filename[i - 1] == '.'
973 || ISSLASH (filename[i - 2])
974 || (filename[i - 2] == '.'
976 || ISSLASH (filename[i - 3])))))))
979 if (rmdir (filename) == 0 && verbosity == VERBOSE)
980 say ("Removed empty directory `%s'.\n", filename);
985 static time_t initial_time;
990 time (&initial_time);
993 /* Make filenames more reasonable. */
996 fetchname (at, strip_leading, pstamp)
1003 int sleading = strip_leading;
1004 time_t stamp = (time_t) -1;
1006 while (ISSPACE ((unsigned char) *at))
1009 say ("fetchname %s %d\n", at, strip_leading);
1012 /* Strip off up to `sleading' leading slashes and null terminate. */
1013 for (t = at; *t; t++)
1017 while (ISSLASH (t[1]))
1019 if (--sleading >= 0)
1022 else if (ISSPACE ((unsigned char) *t))
1024 if (set_time | set_utc)
1025 stamp = str2time (t, initial_time, set_utc ? 0L : TM_LOCAL_ZONE);
1028 /* The head says the file is nonexistent if the timestamp
1029 is the epoch; but the listed time is local time, not UTC,
1030 and POSIX.1 allows local time to be 24 hours away from UTC.
1031 So match any time within 24 hours of the epoch.
1032 Use a default time zone 24 hours behind UTC so that any
1033 non-zoned time within 24 hours of the epoch is valid. */
1034 stamp = str2time (t, initial_time, -24L * 60 * 60);
1035 if (0 <= stamp && stamp <= 2 * 24L * 60 * 60)
1047 /* Allow files to be created by diffing against /dev/null. */
1048 if (strcmp (at, "/dev/null") == 0)
1058 return savestr (name);
1065 register GENERIC_OBJECT *p = malloc (size);
1072 Fseek (stream, offset, ptrname)
1077 if (file_seek (stream, offset, ptrname) != 0)