X-Git-Url: http://git.linux-vserver.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=util-vserver%2Flib_internal%2Funify-unify.c;h=561792e267247edbf627d9003bed42b5cedf87e6;hb=8c87138af9755c6125ae79bb4c1890e6a33dc1a2;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..561792e 100644 --- a/util-vserver/lib_internal/unify-unify.c +++ b/util-vserver/lib_internal/unify-unify.c @@ -27,16 +27,19 @@ #include #include #include +#include #include bool Unify_unify(char const *src, struct stat const UNUSED *src_stat, - char const *dst) + char const *dst, bool ignore_zero) { size_t l = strlen(dst); char tmpfile[l + sizeof(";XXXXXX")]; int fd; bool res = false; + struct stat st; + bool lstat_succeeded; // at first, set the ILI flags on 'src' if (vc_set_iattr(src, @@ -45,25 +48,35 @@ 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); + lstat_succeeded = lstat(dst, &st)==0; - if (fd==-1) { - perror("mkstemp()"); - return false; - } + // check if 'dst' already exists + // when ignore_zero is true, do not make backups of empty destinations + if (lstat_succeeded && (st.st_size>0 || !ignore_zero)) { + // now, create a temporary filename + memcpy(tmpfile, dst, l); + memcpy(tmpfile+l, ";XXXXXX", 8); + fd = mkstemp(tmpfile); + close(fd); - // and rename the old file to this name + if (fd==-1) { + perror("mkstemp()"); + return false; + } - // 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; + // 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; + } + } + else { + if (lstat_succeeded) unlink(dst); + tmpfile[0] = '\0'; } // now, link the src-file to dst @@ -71,7 +84,8 @@ Unify_unify(char const *src, struct stat const UNUSED *src_stat, 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 +95,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; }