Fix zlib CVE-2016-9840.
[rsync.git] / util.c
diff --git a/util.c b/util.c
index 5200a9aae1efe9b3a68dfd6be31652e7cc208ace..3e8803218d1f4bcb575c1f58d3f640f7c41fda6a 100644 (file)
--- a/util.c
+++ b/util.c
@@ -4,7 +4,7 @@
  * Copyright (C) 1996-2000 Andrew Tridgell
  * Copyright (C) 1996 Paul Mackerras
  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
- * Copyright (C) 2003-2009 Wayne Davison
+ * Copyright (C) 2003-2019 Wayne Davison
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -25,7 +25,9 @@
 #include "itypes.h"
 #include "inums.h"
 
+extern int dry_run;
 extern int module_id;
+extern int protect_args;
 extern int modify_window;
 extern int relative_paths;
 extern int preserve_times;
@@ -94,6 +96,7 @@ int fd_pair(int fd[2])
 
 void print_child_argv(const char *prefix, char **cmd)
 {
+       int cnt = 0;
        rprintf(FCLIENT, "%s ", prefix);
        for (; *cmd; cmd++) {
                /* Look for characters that ought to be quoted.  This
@@ -107,20 +110,9 @@ void print_child_argv(const char *prefix, char **cmd)
                } else {
                        rprintf(FCLIENT, "%s ", *cmd);
                }
+               cnt++;
        }
-       rprintf(FCLIENT, "\n");
-}
-
-NORETURN void out_of_memory(const char *str)
-{
-       rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
-       exit_cleanup(RERR_MALLOC);
-}
-
-NORETURN void overflow_exit(const char *str)
-{
-       rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
-       exit_cleanup(RERR_MALLOC);
+       rprintf(FCLIENT, " (%d args)\n", cnt);
 }
 
 /* This returns 0 for success, 1 for a symlink if symlink time-setting
@@ -136,6 +128,15 @@ int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
        }
 
        switch (switch_step) {
+#ifdef HAVE_SETATTRLIST
+#include "case_N.h"
+               if (do_setattrlist_times(fname, modtime, mod_nsec) == 0)
+                       break;
+               if (errno != ENOSYS)
+                       return -1;
+               switch_step++;
+#endif
+
 #ifdef HAVE_UTIMENSAT
 #include "case_N.h"
                if (do_utimensat(fname, modtime, mod_nsec) == 0)
@@ -143,7 +144,6 @@ int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
                if (errno != ENOSYS)
                        return -1;
                switch_step++;
-               /* FALLTHROUGH */
 #endif
 
 #ifdef HAVE_LUTIMES
@@ -153,7 +153,6 @@ int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
                if (errno != ENOSYS)
                        return -1;
                switch_step++;
-               /* FALLTHROUGH */
 #endif
 
 #include "case_N.h"
@@ -163,7 +162,6 @@ int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
                        if (S_ISLNK(mode))
                                return 1;
                }
-               /* FALLTHROUGH */
 
 #include "case_N.h"
 #ifdef HAVE_UTIMES
@@ -198,7 +196,7 @@ int make_path(char *fname, int flags)
 
        if (flags & MKP_DROP_NAME) {
                end = strrchr(fname, '/');
-               if (!end)
+               if (!end || end == fname)
                        return 0;
                *end = '\0';
        } else
@@ -206,23 +204,35 @@ int make_path(char *fname, int flags)
 
        /* Try to find an existing dir, starting from the deepest dir. */
        for (p = end; ; ) {
-               if (do_mkdir(fname, ACCESSPERMS) == 0) {
+               if (dry_run) {
+                       STRUCT_STAT st;
+                       if (do_stat(fname, &st) == 0) {
+                               if (S_ISDIR(st.st_mode))
+                                       errno = EEXIST;
+                               else
+                                       errno = ENOTDIR;
+                       }
+               } else if (do_mkdir(fname, ACCESSPERMS) == 0) {
                        ret++;
                        break;
                }
+
                if (errno != ENOENT) {
-                       if (errno != EEXIST)
+                       STRUCT_STAT st;
+                       if (errno != EEXIST || (do_stat(fname, &st) == 0 && !S_ISDIR(st.st_mode)))
                                ret = -ret - 1;
                        break;
                }
                while (1) {
                        if (p == fname) {
-                               ret = -ret - 1;
+                               /* We got a relative path that doesn't exist, so assume that '.'
+                                * is there and just break out and create the whole thing. */
+                               p = NULL;
                                goto double_break;
                        }
                        if (*--p == '/') {
                                if (p == fname) {
-                                       ret = -ret - 1; /* impossible... */
+                                       /* We reached the "/" dir, which we assume is there. */
                                        goto double_break;
                                }
                                *p = '\0';
@@ -234,7 +244,10 @@ int make_path(char *fname, int flags)
 
        /* Make all the dirs that we didn't find on the way here. */
        while (p != end) {
-               *p = '/';
+               if (p)
+                       *p = '/';
+               else
+                       p = fname;
                p += strlen(p);
                if (ret < 0) /* Skip mkdir on error, but keep restoring the path. */
                        continue;
@@ -316,9 +329,7 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
        int ifd;
        char buf[1024 * 8];
        int len;   /* Number of bytes read into `buf'. */
-#ifdef PREALLOCATE_NEEDS_TRUNCATE
-       OFF_T preallocated_len = 0, offset = 0;
-#endif
+       OFF_T prealloc_len = 0, offset = 0;
 
        if ((ifd = do_open(source, O_RDONLY, 0)) < 0) {
                int save_errno = errno;
@@ -331,6 +342,7 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
                if (robust_unlink(dest) && errno != ENOENT) {
                        int save_errno = errno;
                        rsyserr(FERROR_XFER, errno, "unlink %s", full_fname(dest));
+                       close(ifd);
                        errno = save_errno;
                        return -1;
                }
@@ -358,11 +370,8 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
                if (do_fstat(ifd, &srcst) < 0)
                        rsyserr(FWARNING, errno, "fstat %s", full_fname(source));
                else if (srcst.st_size > 0) {
-                       if (do_fallocate(ofd, 0, srcst.st_size) == 0) {
-#ifdef PREALLOCATE_NEEDS_TRUNCATE
-                               preallocated_len = srcst.st_size;
-#endif
-                       } else
+                       prealloc_len = do_fallocate(ofd, 0, srcst.st_size);
+                       if (prealloc_len < 0)
                                rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest));
                }
        }
@@ -377,9 +386,7 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
                        errno = save_errno;
                        return -1;
                }
-#ifdef PREALLOCATE_NEEDS_TRUNCATE
                offset += len;
-#endif
        }
 
        if (len < 0) {
@@ -396,15 +403,13 @@ int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
                        full_fname(source));
        }
 
-#ifdef PREALLOCATE_NEEDS_TRUNCATE
        /* Source file might have shrunk since we fstatted it.
         * Cut off any extra preallocated zeros from dest file. */
-       if (offset < preallocated_len && do_ftruncate(ofd, offset) < 0) {
+       if (offset < prealloc_len && do_ftruncate(ofd, offset) < 0) {
                /* If we fail to truncate, the dest file may be wrong, so we
                 * must trigger the "partial transfer" error. */
                rsyserr(FERROR_XFER, errno, "ftruncate %s", full_fname(dest));
        }
-#endif
 
        if (close(ofd) < 0) {
                int save_errno = errno;
@@ -757,10 +762,15 @@ void glob_expand_module(char *base1, char *arg, char ***argv_p, int *argc_p, int
        if (strncmp(arg, base, base_len) == 0)
                arg += base_len;
 
+       if (protect_args) {
+               glob_expand(arg, argv_p, argc_p, maxargs_p);
+               return;
+       }
+
        if (!(arg = strdup(arg)))
                out_of_memory("glob_expand_module");
 
-       if (asprintf(&base," %s/", base1) <= 0)
+       if (asprintf(&base," %s/", base1) < 0)
                out_of_memory("glob_expand_module");
        base_len++;
 
@@ -788,6 +798,41 @@ void strlower(char *s)
        }
 }
 
+/**
+ * Split a string into tokens based (usually) on whitespace & commas.  If the
+ * string starts with a comma (after skipping any leading whitespace), then
+ * splitting is done only on commas. No empty tokens are ever returned. */
+char *conf_strtok(char *str)
+{
+       static int commas_only = 0;
+
+       if (str) {
+               while (isSpace(str)) str++;
+               if (*str == ',') {
+                       commas_only = 1;
+                       str++;
+               } else
+                       commas_only = 0;
+       }
+
+       while (commas_only) {
+               char *end, *tok = strtok(str, ",");
+               if (!tok)
+                       return NULL;
+               /* Trim just leading and trailing whitespace. */
+               while (isSpace(tok))
+                       tok++;
+               end = tok + strlen(tok);
+               while (end > tok && isSpace(end-1))
+                       *--end = '\0';
+               if (*tok)
+                       return tok;
+               str = NULL;
+       }
+
+       return strtok(str, " ,\t\r\n");
+}
+
 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them.  (If
  * p1 ends with a '/', no extra '/' is inserted.)  Returns the length of both
  * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
@@ -862,7 +907,7 @@ int count_dir_elements(const char *p)
  * CFN_KEEP_TRAILING_SLASH is flagged, and will also collapse ".." elements
  * (except at the start) if CFN_COLLAPSE_DOT_DOT_DIRS is flagged.  If the
  * resulting name would be empty, returns ".". */
-unsigned int clean_fname(char *name, int flags)
+int clean_fname(char *name, int flags)
 {
        char *limit = name - 1, *t = name, *f = name;
        int anchored;
@@ -870,6 +915,8 @@ unsigned int clean_fname(char *name, int flags)
        if (!name)
                return 0;
 
+#define DOT_IS_DOT_DOT_DIR(bp) (bp[1] == '.' && (bp[2] == '/' || !bp[2]))
+
        if ((anchored = *f == '/') != 0) {
                *t++ = *f++;
 #ifdef __CYGWIN__
@@ -882,7 +929,8 @@ unsigned int clean_fname(char *name, int flags)
        } else if (flags & CFN_KEEP_DOT_DIRS && *f == '.' && f[1] == '/') {
                *t++ = *f++;
                *t++ = *f++;
-       }
+       } else if (flags & CFN_REFUSE_DOT_DOT_DIRS && *f == '.' && DOT_IS_DOT_DOT_DIR(f))
+               return -1;
        while (*f) {
                /* discard extra slashes */
                if (*f == '/') {
@@ -898,9 +946,10 @@ unsigned int clean_fname(char *name, int flags)
                        if (f[1] == '\0' && flags & CFN_DROP_TRAILING_DOT_DIR)
                                break;
                        /* collapse ".." dirs */
-                       if (flags & CFN_COLLAPSE_DOT_DOT_DIRS
-                        && f[1] == '.' && (f[2] == '/' || !f[2])) {
+                       if (flags & (CFN_COLLAPSE_DOT_DOT_DIRS|CFN_REFUSE_DOT_DOT_DIRS) && DOT_IS_DOT_DOT_DIR(f)) {
                                char *s = t - 1;
+                               if (flags & CFN_REFUSE_DOT_DOT_DIRS)
+                                       return -1;
                                if (s == name && anchored) {
                                        f += 2;
                                        continue;
@@ -923,6 +972,8 @@ unsigned int clean_fname(char *name, int flags)
                *t++ = '.';
        *t = '\0';
 
+#undef DOT_IS_DOT_DOT_DIR
+
        return t - name;
 }
 
@@ -955,7 +1006,7 @@ char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
        int rlen = 0, drop_dot_dirs = !relative_paths || !(flags & SP_KEEP_DOT_DIRS);
 
        if (dest != p) {
-               int plen = strlen(p);
+               int plen = strlen(p); /* the path len INCLUDING any separating slash */
                if (*p == '/') {
                        if (!rootdir)
                                rootdir = module_dir;
@@ -966,11 +1017,11 @@ char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
                if (dest) {
                        if (rlen + plen + 1 >= MAXPATHLEN)
                                return NULL;
-               } else if (!(dest = new_array(char, rlen + plen + 1)))
+               } else if (!(dest = new_array(char, MAX(rlen + plen + 1, 2))))
                        out_of_memory("sanitize_path");
-               if (rlen) {
+               if (rlen) { /* only true if p previously started with a slash */
                        memcpy(dest, rootdir, rlen);
-                       if (rlen > 1)
+                       if (rlen > 1) /* a rootdir of len 1 is "/", so this avoids a 2nd slash */
                                dest[rlen++] = '/';
                }
        }
@@ -1030,7 +1081,7 @@ char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
  * Also cleans the path using the clean_fname() function. */
 int change_dir(const char *dir, int set_path_only)
 {
-       static int initialised;
+       static int initialised, skipped_chdir;
        unsigned int len;
 
        if (!initialised) {
@@ -1046,7 +1097,7 @@ int change_dir(const char *dir, int set_path_only)
                return 0;
 
        len = strlen(dir);
-       if (len == 1 && *dir == '.')
+       if (len == 1 && *dir == '.' && (!skipped_chdir || set_path_only))
                return 1;
 
        if (*dir == '/') {
@@ -1056,6 +1107,7 @@ int change_dir(const char *dir, int set_path_only)
                }
                if (!set_path_only && chdir(dir))
                        return 0;
+               skipped_chdir = set_path_only;
                memcpy(curr_dir, dir, len + 1);
        } else {
                if (curr_dir_len + 1 + len >= sizeof curr_dir) {
@@ -1070,9 +1122,10 @@ int change_dir(const char *dir, int set_path_only)
                        curr_dir[curr_dir_len] = '\0';
                        return 0;
                }
+               skipped_chdir = set_path_only;
        }
 
-       curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS);
+       curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
        if (sanitize_paths) {
                if (module_dirlen > curr_dir_len)
                        module_dirlen = curr_dir_len;
@@ -1142,7 +1195,7 @@ char *full_fname(const char *fn)
        } else
                m1 = m2 = m3 = "";
 
-       if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) <= 0)
+       if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) < 0)
                out_of_memory("full_fname");
 
        return result;
@@ -1295,34 +1348,6 @@ char *timestring(time_t t)
        return TimeBuf;
 }
 
-/**
- * Sleep for a specified number of milliseconds.
- *
- * Always returns TRUE.  (In the future it might return FALSE if
- * interrupted.)
- **/
-int msleep(int t)
-{
-       int tdiff = 0;
-       struct timeval tval, t1, t2;
-
-       gettimeofday(&t1, NULL);
-
-       while (tdiff < t) {
-               tval.tv_sec = (t-tdiff)/1000;
-               tval.tv_usec = 1000*((t-tdiff)%1000);
-
-               errno = 0;
-               select(0,NULL,NULL, NULL, &tval);
-
-               gettimeofday(&t2, NULL);
-               tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
-                       (t2.tv_usec - t1.tv_usec)/1000;
-       }
-
-       return True;
-}
-
 /* Determine if two time_t values are equivalent (either exact, or in
  * the modification timestamp window established by --modify-window).
  *
@@ -1332,19 +1357,25 @@ int msleep(int t)
  *
  * @retval -1 if the 2nd is later
  **/
-int cmp_time(time_t file1, time_t file2)
+int cmp_time(time_t f1_sec, unsigned long f1_nsec, time_t f2_sec, unsigned long f2_nsec)
 {
-       if (file2 > file1) {
-               if (file2 - file1 <= modify_window)
-                       return 0;
-               return -1;
+       if (f2_sec > f1_sec) {
+               /* The final comparison makes sure that modify_window doesn't overflow a
+                * time_t, which would mean that f2_sec must be in the equality window. */
+               if (modify_window <= 0 || (f2_sec > f1_sec + modify_window && f1_sec + modify_window > f1_sec))
+                       return -1;
+       } else if (f1_sec > f2_sec) {
+               if (modify_window <= 0 || (f1_sec > f2_sec + modify_window && f2_sec + modify_window > f2_sec))
+                       return 1;
+       } else if (modify_window < 0) {
+               if (f2_nsec > f1_nsec)
+                       return -1;
+               else if (f1_nsec > f2_nsec)
+                       return 1;
        }
-       if (file1 - file2 <= modify_window)
-               return 0;
-       return 1;
+       return 0;
 }
 
-
 #ifdef __INSURE__XX
 #include <dlfcn.h>
 
@@ -1356,11 +1387,13 @@ int cmp_time(time_t file1, time_t file2)
 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
 {
        static int (*fn)();
-       int ret;
+       int ret, pid_int = getpid();
        char *cmd;
 
-       asprintf(&cmd, "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; gdb /proc/%d/exe %d'",
-               getpid(), getpid(), getpid());
+       if (asprintf(&cmd,
+           "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; "
+           "gdb /proc/%d/exe %d'", pid_int, pid_int, pid_int) < 0)
+               return -1;
 
        if (!fn) {
                static void *h;
@@ -1378,24 +1411,6 @@ int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
 }
 #endif
 
-#define MALLOC_MAX 0x40000000
-
-void *_new_array(unsigned long num, unsigned int size, int use_calloc)
-{
-       if (num >= MALLOC_MAX/size)
-               return NULL;
-       return use_calloc ? calloc(num, size) : malloc(num * size);
-}
-
-void *_realloc_array(void *ptr, unsigned int size, size_t num)
-{
-       if (num >= MALLOC_MAX/size)
-               return NULL;
-       if (!ptr)
-               return malloc(size * num);
-       return realloc(ptr, size * num);
-}
-
 /* Take a filename and filename length and return the most significant
  * filename suffix we can find.  This ignores suffixes such as "~",
  * ".bak", ".orig", ".~1~", etc. */
@@ -1628,6 +1643,14 @@ int flist_ndx_pop(flist_ndx_list *lp)
        return ndx;
 }
 
+/* Make sure there is room for one more item in the item list.  If there
+ * is not, expand the list as indicated by the value of "incr":
+ *  - if incr < 0 then increase the malloced size by -1 * incr
+ *  - if incr >= 0 then either make the malloced size equal to "incr"
+ *    or (if that's not large enough) double the malloced size
+ * After the size check, the list's count is incremented by 1 and a pointer
+ * to the "new" list item is returned.
+ */
 void *expand_item_list(item_list *lp, size_t item_size,
                       const char *desc, int incr)
 {
@@ -1638,10 +1661,12 @@ void *expand_item_list(item_list *lp, size_t item_size,
                if (incr < 0)
                        new_size += -incr; /* increase slowly */
                else if (new_size < (size_t)incr)
-                       new_size += incr;
-               else
+                       new_size = incr;
+               else if (new_size)
                        new_size *= 2;
-               if (new_size < lp->malloced)
+               else
+                       new_size = 1;
+               if (new_size <= lp->malloced)
                        overflow_exit("expand_item_list");
                /* Using _realloc_array() lets us pass the size, not a type. */
                new_ptr = _realloc_array(lp->items, item_size, new_size);
@@ -1658,3 +1683,11 @@ void *expand_item_list(item_list *lp, size_t item_size,
        }
        return (char*)lp->items + (lp->count++ * item_size);
 }
+
+/* This zeroing of memory won't be optimized away by the compiler. */
+void force_memzero(void *buf, size_t len)
+{
+    volatile uchar *z = buf;
+    while (len-- > 0)
+       *z++ = '\0';
+}