1 /* filesubr.c --- subroutines for dealing with files
2 Jim Blandy <jimb@cyclic.com>
4 This file is part of GNU CVS.
6 GNU CVS is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details. */
16 /* These functions were moved out of subr.c because they need different
17 definitions under operating systems (like, say, Windows NT) with different
18 file system semantics. */
25 static int deep_remove_dir PROTO((const char *path));
28 * Copies "from" to "to".
40 (void) fprintf (stderr, "%s-> copy(%s,%s)\n",
41 CLIENT_SERVER_STR, from, to);
45 /* If the file to be copied is a link or a device, then just create
46 the new link or device appropriately. */
49 char *source = xreadlink (from);
57 #if defined(HAVE_MKNOD) && defined(HAVE_STRUCT_STAT_ST_RDEV)
58 if (stat (from, &sb) < 0)
59 error (1, errno, "cannot stat %s", from);
60 mknod (to, sb.st_mode, sb.st_rdev);
62 error (1, 0, "cannot copy device files on this system (%s)", from);
67 /* Not a link or a device... probably a regular file. */
68 if ((fdin = open (from, O_RDONLY)) < 0)
69 error (1, errno, "cannot open %s for copying", from);
70 if (fstat (fdin, &sb) < 0)
71 error (1, errno, "cannot fstat %s", from);
72 if ((fdout = creat (to, (int) sb.st_mode & 07777)) < 0)
73 error (1, errno, "cannot create %s for copying", to);
81 n = read (fdin, buf, sizeof(buf));
88 error (1, errno, "cannot read file %s for copying", from);
93 if (write(fdout, buf, n) != n) {
94 error (1, errno, "cannot write file %s for copying", to);
100 error (1, errno, "cannot fsync file %s after copying", to);
104 if (close (fdin) < 0)
105 error (0, errno, "cannot close %s", from);
106 if (close (fdout) < 0)
107 error (1, errno, "cannot close %s", to);
110 /* preserve last access & modification times */
111 memset ((char *) &t, 0, sizeof (t));
112 t.actime = sb.st_atime;
113 t.modtime = sb.st_mtime;
114 (void) utime (to, &t);
117 /* FIXME-krp: these functions would benefit from caching the char * &
121 * Returns non-zero if the argument file is a directory, or is a symbolic
122 * link which points to a directory.
130 if (stat (file, &sb) < 0)
132 return (S_ISDIR (sb.st_mode));
136 * Returns non-zero if the argument file is a symbolic link.
145 if (CVS_LSTAT (file, &sb) < 0)
147 return (S_ISLNK (sb.st_mode));
154 * Returns non-zero if the argument file is a block or
155 * character special device.
163 if (CVS_LSTAT (file, &sb) < 0)
166 if (S_ISBLK (sb.st_mode))
170 if (S_ISCHR (sb.st_mode))
177 * Returns non-zero if the argument file exists.
183 return isaccessible(file, F_OK);
187 * Returns non-zero if the argument file is readable.
193 return isaccessible(file, R_OK);
197 * Returns non-zero if the argument file is writable.
203 return isaccessible(file, W_OK);
207 * Returns non-zero if the argument file is accessable according to
208 * mode. If compiled with SETXID_SUPPORT also works if cvs has setxid
212 isaccessible (file, mode)
216 #ifdef SETXID_SUPPORT
223 if (stat(file, &sb) == -1)
229 if (uid == 0) /* superuser */
231 if (!(mode & X_OK) || (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
257 mask = sb.st_uid == uid ? umask : sb.st_gid == getegid() ? gmask : omask;
258 if ((sb.st_mode & mask) == mask)
263 return access(file, mode) == 0;
268 * Open a file and die if it fails
271 open_file (name, mode)
277 if ((fp = fopen (name, mode)) == NULL)
278 error (1, errno, "cannot open %s", name);
283 * Make a directory and die if it fails
286 make_directory (name)
291 if (stat (name, &sb) == 0 && (!S_ISDIR (sb.st_mode)))
292 error (0, 0, "%s already exists but is not a directory", name);
293 if (!noexec && mkdir (name, 0777) < 0)
294 error (1, errno, "cannot make directory %s", name);
298 * Make a path to the argument directory, printing a message if something
302 make_directories (name)
310 if (mkdir (name, 0777) == 0 || errno == EEXIST)
312 if (! existence_error (errno))
314 error (0, errno, "cannot make path to %s", name);
317 if ((cp = strrchr (name, '/')) == NULL)
320 make_directories (name);
324 (void) mkdir (name, 0777);
327 /* Create directory NAME if it does not already exist; fatal error for
328 other errors. Returns 0 if directory was created; 1 if it already
331 mkdir_if_needed (name)
334 if (mkdir (name, 0777) < 0)
336 int save_errno = errno;
337 if (save_errno != EEXIST && !isdir (name))
338 error (1, save_errno, "cannot make directory %s", name);
345 * Change the mode of a file, either adding write permissions, or removing
346 * all write permissions. Either change honors the current umask setting.
348 * Don't do anything if PreservePermissions is set to `yes'. This may
349 * have unexpected consequences for some uses of xchmod.
352 xchmod (fname, writable)
362 if (stat (fname, &sb) < 0)
365 error (0, errno, "cannot stat %s", fname);
369 (void) umask (oumask);
372 mode = sb.st_mode | (~oumask
373 & (((sb.st_mode & S_IRUSR) ? S_IWUSR : 0)
374 | ((sb.st_mode & S_IRGRP) ? S_IWGRP : 0)
375 | ((sb.st_mode & S_IROTH) ? S_IWOTH : 0)));
379 mode = sb.st_mode & ~(S_IWRITE | S_IWGRP | S_IWOTH) & ~oumask;
383 (void) fprintf (stderr, "%s-> chmod(%s,%o)\n",
384 CLIENT_SERVER_STR, fname,
385 (unsigned int) mode);
389 if (chmod (fname, mode) < 0)
390 error (0, errno, "cannot change mode of file %s", fname);
394 * Rename a file and die if it fails
397 rename_file (from, to)
402 (void) fprintf (stderr, "%s-> rename(%s,%s)\n",
403 CLIENT_SERVER_STR, from, to);
407 if (rename (from, to) < 0)
408 error (1, errno, "cannot rename file %s to %s", from, to);
412 * unlink a file, if possible.
419 (void) fprintf (stderr, "%s-> unlink_file(%s)\n",
420 CLIENT_SERVER_STR, f);
424 return (CVS_UNLINK (f));
428 * Unlink a file or dir, if possible. If it is a directory do a deep
429 * removal of all of the files in the directory. Return -1 on error
430 * (in which case errno is set).
438 /* This is called by the server parent process in contexts where
439 it is not OK to send output (e.g. after we sent "ok" to the
441 if (trace && !server_active)
442 (void) fprintf (stderr, "-> unlink_file_dir(%s)\n", f);
447 /* For at least some unices, if root tries to unlink() a directory,
448 instead of doing something rational like returning EISDIR,
449 the system will gleefully go ahead and corrupt the filesystem.
450 So we first call stat() to see if it is OK to call unlink(). This
451 doesn't quite work--if someone creates a directory between the
452 call to stat() and the call to unlink(), we'll still corrupt
453 the filesystem. Where is the Unix Haters Handbook when you need
455 if (stat (f, &sb) < 0)
457 if (existence_error (errno))
459 /* The file or directory doesn't exist anyhow. */
463 else if (S_ISDIR (sb.st_mode))
464 return deep_remove_dir (f);
466 return CVS_UNLINK (f);
469 /* Remove a directory and everything it contains. Returns 0 for
470 * success, -1 for failure (in which case errno is set).
474 deep_remove_dir (path)
480 if (rmdir (path) != 0)
482 if (errno == ENOTEMPTY
484 /* Ugly workaround for ugly AIX 4.1 (and 3.2) header bug
485 (it defines ENOTEMPTY and EEXIST to 17 but actually
487 || (ENOTEMPTY == 17 && EEXIST == 17 && errno == 87))
489 if ((dirp = CVS_OPENDIR (path)) == NULL)
490 /* If unable to open the directory return
496 while ((dp = CVS_READDIR (dirp)) != NULL)
500 if (strcmp (dp->d_name, ".") == 0 ||
501 strcmp (dp->d_name, "..") == 0)
504 buf = xmalloc (strlen (path) + strlen (dp->d_name) + 5);
505 sprintf (buf, "%s/%s", path, dp->d_name);
507 /* See comment in unlink_file_dir explanation of why we use
508 isdir instead of just calling unlink and checking the
512 if (deep_remove_dir(buf))
521 if (CVS_UNLINK (buf) != 0)
534 int save_errno = errno;
546 /* Was able to remove the directory return 0 */
550 /* Read NCHARS bytes from descriptor FD into BUF.
551 Return the number of characters successfully read.
552 The number returned is always NCHARS unless end-of-file or error. */
554 block_read (fd, buf, nchars)
564 nread = read (fd, bp, nchars);
565 if (nread == (size_t)-1)
579 } while (nchars != 0);
586 * Compare "file1" to "file2". Return non-zero if they don't compare exactly.
587 * If FILE1 and FILE2 are special files, compare their salient characteristics
588 * (i.e. major/minor device numbers, links, etc.
596 struct stat sb1, sb2;
600 if (CVS_LSTAT (file1, &sb1) < 0)
601 error (1, errno, "cannot lstat %s", file1);
602 if (CVS_LSTAT (file2, &sb2) < 0)
603 error (1, errno, "cannot lstat %s", file2);
605 /* If FILE1 and FILE2 are not the same file type, they are unequal. */
606 if ((sb1.st_mode & S_IFMT) != (sb2.st_mode & S_IFMT))
609 /* If FILE1 and FILE2 are symlinks, they are equal if they point to
612 if (S_ISLNK (sb1.st_mode) && S_ISLNK (sb2.st_mode))
615 buf1 = xreadlink (file1);
616 buf2 = xreadlink (file2);
617 result = (strcmp (buf1, buf2) == 0);
624 /* If FILE1 and FILE2 are devices, they are equal if their device
626 if (S_ISBLK (sb1.st_mode) || S_ISCHR (sb1.st_mode))
628 #ifdef HAVE_STRUCT_STAT_ST_RDEV
629 if (sb1.st_rdev == sb2.st_rdev)
634 error (1, 0, "cannot compare device files on this system (%s and %s)",
639 if ((fd1 = open (file1, O_RDONLY)) < 0)
640 error (1, errno, "cannot open file %s for comparing", file1);
641 if ((fd2 = open (file2, O_RDONLY)) < 0)
642 error (1, errno, "cannot open file %s for comparing", file2);
644 /* A generic file compare routine might compare st_dev & st_ino here
645 to see if the two files being compared are actually the same file.
646 But that won't happen in CVS, so we won't bother. */
648 if (sb1.st_size != sb2.st_size)
650 else if (sb1.st_size == 0)
654 /* FIXME: compute the optimal buffer size by computing the least
655 common multiple of the files st_blocks field */
656 size_t buf_size = 8 * 1024;
660 buf1 = xmalloc (buf_size);
661 buf2 = xmalloc (buf_size);
665 read1 = block_read (fd1, buf1, buf_size);
666 if (read1 == (size_t)-1)
667 error (1, errno, "cannot read file %s for comparing", file1);
669 read2 = block_read (fd2, buf2, buf_size);
670 if (read2 == (size_t)-1)
671 error (1, errno, "cannot read file %s for comparing", file2);
673 /* assert (read1 == read2); */
675 ret = memcmp(buf1, buf2, read1);
676 } while (ret == 0 && read1 == buf_size);
687 /* Generate a unique temporary filename. Returns a pointer to a newly
688 * malloc'd string containing the name. Returns successfully or not at
691 * THIS FUNCTION IS DEPRECATED!!! USE cvs_temp_file INSTEAD!!!
693 * and yes, I know about the way the rcs commands use temp files. I think
694 * they should be converted too but I don't have time to look into it right
703 fp = cvs_temp_file (&fn);
705 error (1, errno, "Failed to create temporary file %s",
707 if (fclose (fp) == EOF)
708 error (0, errno, "Failed to close temporary file %s", fn);
712 /* Generate a unique temporary filename and return an open file stream
713 * to the truncated file by that name
716 * filename where to place the pointer to the newly allocated file
720 * filename dereferenced, will point to the newly allocated file
721 * name string. This value is undefined if the function
725 * An open file pointer to a read/write mode empty temporary file with the
726 * unique file name or NULL on failure.
729 * on error, errno will be set to some value either by CVS_FOPEN or
730 * whatever system function is called to generate the temporary file name
732 /* There are at least four functions for generating temporary
733 * filenames. We use mkstemp (BSD 4.3) if possible, else tempnam (SVID 3),
734 * else mktemp (BSD 4.3), and as last resort tmpnam (POSIX). Reason is that
735 * mkstemp, tempnam, and mktemp both allow to specify the directory in which
736 * the temporary file will be created.
738 * And the _correct_ way to use the deprecated functions probably involves
739 * opening file descriptors using O_EXCL & O_CREAT and even doing the annoying
740 * NFS locking thing, but until I hear of more problems, I'm not going to
744 cvs_temp_file (filename)
750 /* FIXME - I'd like to be returning NULL here in noexec mode, but I think
751 * some of the rcs & diff functions which rely on a temp file run in
755 assert (filename != NULL);
762 fn = xmalloc (strlen (Tmpdir) + 11);
763 sprintf (fn, "%s/%s", Tmpdir, "cvsXXXXXX" );
766 /* a NULL return will be interpreted by callers as an error and
767 * errno should still be set
769 if (fd == -1) fp = NULL;
770 else if ((fp = CVS_FDOPEN (fd, "w+")) == NULL)
772 /* Attempt to close and unlink the file since mkstemp returned
773 * sucessfully and we believe it's been created and opened.
775 int save_errno = errno;
777 error (0, errno, "Failed to close temporary file %s", fn);
779 error (0, errno, "Failed to unlink temporary file %s", fn);
788 /* mkstemp is defined to open mode 0600 using glibc 2.0.7+ */
789 /* FIXME - configure can probably tell us which version of glibc we are
790 * linking to and not chmod for 2.0.7+
792 else chmod (fn, 0600);
798 /* tempnam has been deprecated due to under-specification */
800 fn = tempnam (Tmpdir, "cvs");
801 if (fn == NULL) fp = NULL;
802 else if ((fp = CVS_FOPEN (fn, "w+")) == NULL)
807 else chmod (fn, 0600);
809 /* tempnam returns a pointer to a newly malloc'd string, so there's
810 * no need for a xstrdup
815 /* mktemp has been deprecated due to the BSD 4.3 specification specifying
816 * that XXXXXX will be replaced by a PID and a letter, creating only 26
817 * possibilities, a security risk, and a race condition.
823 ifn = xmalloc (strlen (Tmpdir) + 11);
824 sprintf (ifn, "%s/%s", Tmpdir, "cvsXXXXXX" );
827 if (fn == NULL) fp = NULL;
828 else fp = CVS_FOPEN (fn, "w+");
830 if (fp == NULL) free (ifn);
831 else chmod (fn, 0600);
835 #else /* use tmpnam if all else fails */
837 /* tmpnam is deprecated */
840 char ifn[L_tmpnam + 1];
844 if (fn == NULL) fp = NULL;
845 else if ((fp = CVS_FOPEN (ifn, "w+")) != NULL)
856 if (fn == NULL && fp != NULL)
868 * xreadlink ( const char *link )
870 * Like the X/OPEN and 4.4BSD readlink() function, but allocates and returns
874 * link The original path.
877 * The resolution of the final symbolic link in the path.
880 * This function exits with a fatal error if it fails to read the link for
883 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
890 size_t buflen = BUFSIZ;
892 /* Get the name of the file to which `from' is linked. */
896 size_t link_name_len;
898 file = xrealloc (file, buflen);
899 r = readlink (link, file, buflen);
904 /* AIX 4 and HP-UX report ERANGE if the buffer is too small. */
908 error (1, errno, "cannot readlink %s", link);
910 /* If there is space for the NUL byte, set it and return. */
911 if (r >= 0 && link_name_len < buflen)
913 file[link_name_len] = '\0';
917 if (buflen <= MAXSIZE / 2)
919 else if (buflen < MAXSIZE)
922 /* Our buffer cannot grow any bigger. */
923 error (1, ENAMETOOLONG, "cannot readlink %s", link);
926 #endif /* HAVE_READLINK */
931 * xresolvepath ( const char *path )
933 * Like xreadlink(), but resolve all links in a path.
936 * path The original path.
939 * The path with any symbolic links expanded.
942 * This function exits with a fatal error if it fails to read the link for
946 xresolvepath ( path )
952 assert ( isdir ( path ) );
954 /* FIXME - If HAVE_READLINK is defined, we should probably walk the path
955 * bit by bit calling xreadlink().
959 if ( CVS_CHDIR ( path ) < 0)
960 error ( 1, errno, "cannot chdir to %s", path );
961 if ( ( hardpath = xgetwd() ) == NULL )
962 error (1, errno, "cannot getwd in %s", path);
963 if ( CVS_CHDIR ( owd ) < 0)
964 error ( 1, errno, "cannot chdir to %s", owd );
971 /* Return a pointer into PATH's last component. */
973 last_component (path)
976 const char *last = strrchr (path, '/');
979 if (last && (last != path))
985 /* Return the home directory. Returns a pointer to storage
986 managed by this function or its callees (currently getenv).
987 This function will return the same thing every time it is
988 called. Returns NULL if there is no home directory.
990 Note that for a pserver server, this may return root's home
991 directory. What typically happens is that upon being started from
992 inetd, before switching users, the code in cvsrc.c calls
993 get_homedir which remembers root's home directory in the static
994 variable. Then the switch happens and get_homedir might return a
995 directory that we don't even have read or execute permissions for
996 (which is bad, when various parts of CVS try to read there). One
997 fix would be to make the value returned by get_homedir only good
998 until the next call (which would free the old value). Another fix
999 would be to just always malloc our answer, and let the caller free
1000 it (that is best, because some day we may need to be reentrant).
1002 The workaround is to put -f in inetd.conf which means that
1003 get_homedir won't get called until after the switch in user ID.
1005 The whole concept of a "home directory" on the server is pretty
1006 iffy, although I suppose some people probably are relying on it for
1007 .cvsrc and such, in the cases where it works. */
1011 static char *home = NULL;
1018 if (!server_active && (env = getenv ("HOME")) != NULL)
1020 else if ((pw = (struct passwd *) getpwuid (getuid ()))
1022 home = xstrdup (pw->pw_dir);
1029 /* Compose a path to a file in the home directory. This is necessary because
1030 * of different behavior on UNIX and VMS. See the notes in vms/filesubr.c.
1032 * A more clean solution would be something more along the lines of a
1033 * "join a directory to a filename" kind of thing which was not specific to
1034 * the homedir. This should aid portability between UNIX, Mac, Windows, VMS,
1035 * and possibly others. This is already handled by Perl - it might be
1036 * interesting to see how much of the code was written in C since Perl is under
1037 * the GPL and the Artistic license - we might be able to use it.
1040 strcat_filename_onto_homedir (dir, file)
1044 char *path = xmalloc (strlen (dir) + 1 + strlen(file) + 1);
1045 sprintf (path, "%s/%s", dir, file);
1049 /* See cvs.h for description. On unix this does nothing, because the
1050 shell expands the wildcards. */
1052 expand_wild (argc, argv, pargc, pargv)
1059 assert (argv || !argc);
1060 if (size_overflow_p (xtimes (argc, sizeof (char *)))) {
1063 error (0, 0, "expand_wild: too many arguments");
1067 *pargv = xmalloc (xtimes (argc, sizeof (char *)));
1068 for (i = 0; i < argc; ++i)
1069 (*pargv)[i] = xstrdup (argv[i]);
1074 #ifdef SERVER_SUPPORT
1075 /* Case-insensitive string compare. I know that some systems
1076 have such a routine, but I'm not sure I see any reasons for
1077 dealing with the hair of figuring out whether they do (I haven't
1078 looked into whether this is a performance bottleneck; I would guess
1081 cvs_casecmp (str1, str2)
1091 while ((pqdiff = tolower (*p) - tolower (*q)) == 0)
1100 #endif /* SERVER_SUPPORT */