retain 'errno' on the final unlink()
[util-vserver.git] / util-vserver / lib_internal / unify-unify.c
1 // $Id$    --*- c -*--
2
3 // Copyright (C) 2004 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
4 //  
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; version 2 of the License.
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 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include "unify.h"
24 #include "vserver.h"
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <errno.h>
31 #include <sys/stat.h>
32
33 bool
34 Unify_unify(char const *src, struct stat const UNUSED *src_stat,
35             char const *dst)
36 {
37   size_t        l = strlen(dst);
38   char          tmpfile[l + sizeof(";XXXXXX")];
39   int           fd;
40   bool          res = false;
41   struct stat   st;
42
43   // at first, set the ILI flags on 'src'
44   if (vc_set_iattr(src,
45                    0,
46                    VC_IATTR_IUNLINK|VC_IATTR_IMMUTABLE,
47                    VC_IATTR_IUNLINK|VC_IATTR_IMMUTABLE)==-1)
48     return false;
49
50   // check if 'dst' already exists
51   if (lstat(dst, &st)==0) {
52       // now, create a temporary filename
53     memcpy(tmpfile,   dst, l);
54     memcpy(tmpfile+l, ";XXXXXX", 8);
55     fd = mkstemp(tmpfile);
56     close(fd);
57
58     if (fd==-1) {
59       perror("mkstemp()");
60       return false;
61     }
62
63       // and rename the old file to this name
64
65       // NOTE: this rename() is race-free; when an attacker makes 'tmpfile' a
66       // directory, the operation would fail; when making it a symlink to a file
67       // or directory, the symlink but not the file/directory would be overridden
68     if (rename(dst, tmpfile)==-1) {
69       perror("rename()");
70       goto err;
71     }
72   }
73   else
74     tmpfile[0] = '\0';
75
76   // now, link the src-file to dst
77   if (link(src, dst)==-1) {
78     perror("link()");
79
80     unlink(dst);
81     if (tmpfile[0]!='\0' &&
82         rename(tmpfile, dst)==-1) {
83       perror("FATAL error in rename()");
84       _exit(1);
85     }
86     goto err;
87   }
88
89   res = true;
90
91   err:
92   if (tmpfile[0]!='\0') {
93     int old_errno = errno;
94     unlink(tmpfile);
95     errno = old_errno;
96   }
97
98   return res;
99 }