X-Git-Url: http://git.linux-vserver.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=util-vserver%2Flib_internal%2Funify-unify.c;h=2cf41f970ef1acbbb5362219c0e0c75ce48b7e10;hb=88759454c4c613684321b74e7d7ebf05ac7913f2;hp=a3d6a18ab0baa8f3073c6b8b0cc959e56838848d;hpb=a65d8e1de995241719acb01faa74cd6f4e80848e;p=util-vserver.git diff --git a/util-vserver/lib_internal/unify-unify.c b/util-vserver/lib_internal/unify-unify.c index a3d6a18..2cf41f9 100644 --- a/util-vserver/lib_internal/unify-unify.c +++ b/util-vserver/lib_internal/unify-unify.c @@ -27,6 +27,7 @@ #include #include #include +#include #include bool @@ -37,6 +38,7 @@ Unify_unify(char const *src, struct stat const UNUSED *src_stat, char tmpfile[l + sizeof(";XXXXXX")]; int fd; bool res = false; + struct stat st; // at first, set the ILI flags on 'src' if (vc_set_iattr(src, @@ -45,33 +47,39 @@ Unify_unify(char const *src, struct stat const UNUSED *src_stat, VC_IATTR_IUNLINK|VC_IATTR_IMMUTABLE)==-1) return false; - // now, create a temporary filename - memcpy(tmpfile, dst, l); - memcpy(tmpfile+l, ";XXXXXX", 8); - fd = mkstemp(tmpfile); - close(fd); - - if (fd==-1) { - perror("mkstemp()"); - return false; - } + // check if 'dst' already exists + if (lstat(dst, &st)==0) { + // now, create a temporary filename + memcpy(tmpfile, dst, l); + memcpy(tmpfile+l, ";XXXXXX", 8); + fd = mkstemp(tmpfile); + close(fd); + + if (fd==-1) { + perror("mkstemp()"); + return false; + } - // and rename the old file to this name + // and rename the old file to this name - // NOTE: this rename() is race-free; when an attacker makes 'tmpfile' a - // directory, the operation would fail; when making it a symlink to a file - // or directory, the symlink but not the file/directory would be overridden - if (rename(dst, tmpfile)==-1) { - perror("rename()"); - goto err; + // NOTE: this rename() is race-free; when an attacker makes 'tmpfile' a + // directory, the operation would fail; when making it a symlink to a file + // or directory, the symlink but not the file/directory would be overridden + if (rename(dst, tmpfile)==-1) { + perror("rename()"); + goto err; + } } + else + tmpfile[0] = '\0'; // now, link the src-file to dst if (link(src, dst)==-1) { perror("link()"); unlink(dst); - if (rename(tmpfile, dst)==-1) { + if (tmpfile[0]!='\0' && + rename(tmpfile, dst)==-1) { perror("FATAL error in rename()"); _exit(1); } @@ -81,7 +89,11 @@ Unify_unify(char const *src, struct stat const UNUSED *src_stat, res = true; err: - unlink(tmpfile); + if (tmpfile[0]!='\0') { + int old_errno = errno; + unlink(tmpfile); + errno = old_errno; + } return res; }