xref: /openbsd/gnu/usr.bin/cvs/lib/rename.c (revision 7b36286a)
1 /* rename.c -- BSD compatible directory function for System V
2    Copyright (C) 1988, 1990 Free Software Foundation, Inc.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.  */
13 
14 #ifdef HAVE_CONFIG_H
15 #include "config.h"
16 #endif
17 
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21 #ifndef STDC_HEADERS
22 extern int errno;
23 #endif
24 
25 /* Rename file FROM to file TO.
26    Return 0 if successful, -1 if not. */
27 
28 int
29 rename (from, to)
30      char *from;
31      char *to;
32 {
33   struct stat from_stats;
34   int pid, status;
35 
36   if (stat (from, &from_stats) == 0)
37     {
38       /* We don't check existence_error because the systems which need it
39 	 have rename().  */
40       if (CVS_UNLINK (to) && errno != ENOENT)
41 	return -1;
42       if ((from_stats.st_mode & S_IFMT) == S_IFDIR)
43 	{
44 #ifdef MVDIR
45 	  /* I don't think MVDIR ever gets defined, but I don't think
46 	     it matters, because I don't think CVS ever calls rename()
47 	     on directories.  */
48 
49 	  /* Need a setuid root process to link and unlink directories. */
50 	  pid = fork ();
51 	  switch (pid)
52 	    {
53 	    case -1:		/* Error. */
54 	      error (1, errno, "cannot fork");
55 
56 	    case 0:		/* Child. */
57 	      execl (MVDIR, "mvdir", from, to, (char *) 0);
58 	      error (255, errno, "cannot run `%s'", MVDIR);
59 
60 	    default:		/* Parent. */
61 	      while (wait (&status) != pid)
62 		/* Do nothing. */ ;
63 
64 	      errno = 0;	/* mvdir printed the system error message. */
65 	      return status != 0 ? -1 : 0;
66 	    }
67 #else /* no MVDIR */
68 	  error (1, 0, "internal error: cannot move directories");
69 #endif /* no MVDIR */
70 	}
71       else
72 	{
73 	  /* We don't check existence_error because the systems which need it
74 	     have rename().  */
75 	  if (link (from, to) == 0 && (CVS_UNLINK (from) == 0 || errno == ENOENT))
76 	    return 0;
77 	}
78     }
79   return -1;
80 }
81