Fix `md2man --test` on a fresh checkout.
[rsync.git] / util.c
diff --git a/util.c b/util.c
index bd537ae9bfa6d2151422a42ee72520b99da294b9..84dcac52ca9ebf89e7ab09d0f123c8a0878bea51 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-2014 Wayne Davison
+ * Copyright (C) 2003-2020 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
@@ -117,52 +117,59 @@ void print_child_argv(const char *prefix, char **cmd)
 
 /* This returns 0 for success, 1 for a symlink if symlink time-setting
  * is not possible, or -1 for any other error. */
-int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
+int set_times(const char *fname, STRUCT_STAT *stp)
 {
        static int switch_step = 0;
 
        if (DEBUG_GTE(TIME, 1)) {
-               rprintf(FINFO, "set modtime of %s to (%ld) %s",
-                       fname, (long)modtime,
-                       asctime(localtime(&modtime)));
+               rprintf(FINFO,
+                       "set modtime, atime of %s to (%ld) %s, (%ld) %s\n",
+                       fname, (long)stp->st_mtime,
+                       timestring(stp->st_mtime), (long)stp->st_atime, timestring(stp->st_atime));
        }
 
        switch (switch_step) {
+#ifdef HAVE_SETATTRLIST
+#include "case_N.h"
+               if (do_setattrlist_times(fname, stp) == 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)
+               if (do_utimensat(fname, stp) == 0)
                        break;
                if (errno != ENOSYS)
                        return -1;
                switch_step++;
-               /* FALLTHROUGH */
 #endif
 
 #ifdef HAVE_LUTIMES
 #include "case_N.h"
-               if (do_lutimes(fname, modtime, mod_nsec) == 0)
+               if (do_lutimes(fname, stp) == 0)
                        break;
                if (errno != ENOSYS)
                        return -1;
                switch_step++;
-               /* FALLTHROUGH */
 #endif
 
 #include "case_N.h"
                switch_step++;
                if (preserve_times & PRESERVE_LINK_TIMES) {
                        preserve_times &= ~PRESERVE_LINK_TIMES;
-                       if (S_ISLNK(mode))
+                       if (S_ISLNK(stp->st_mode))
                                return 1;
                }
-               /* FALLTHROUGH */
 
 #include "case_N.h"
 #ifdef HAVE_UTIMES
-               if (do_utimes(fname, modtime, mod_nsec) == 0)
+               if (do_utimes(fname, stp) == 0)
                        break;
 #else
-               if (do_utime(fname, modtime, mod_nsec) == 0)
+               if (do_utime(fname, stp) == 0)
                        break;
 #endif
 
@@ -190,7 +197,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
@@ -210,8 +217,10 @@ int make_path(char *fname, int flags)
                        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;
                }
@@ -321,9 +330,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;
@@ -336,6 +343,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;
                }
@@ -363,11 +371,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));
                }
        }
@@ -382,9 +387,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) {
@@ -401,15 +404,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;
@@ -497,6 +498,11 @@ int robust_rename(const char *from, const char *to, const char *partialptr,
 {
        int tries = 4;
 
+       /* A resumed in-place partial-dir transfer might call us with from and
+        * to pointing to the same buf if the transfer failed yet again. */
+       if (from == to)
+               return 0;
+
        while (tries--) {
                if (do_rename(from, to) == 0)
                        return 0;
@@ -716,9 +722,7 @@ int glob_expand(const char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
                s = strdup(arg);
                if (!s)
                        out_of_memory("glob_expand");
-               clean_fname(s, CFN_KEEP_DOT_DIRS
-                            | CFN_KEEP_TRAILING_SLASH
-                            | CFN_COLLAPSE_DOT_DOT_DIRS);
+               clean_fname(s, CFN_KEEP_DOT_DIRS | CFN_KEEP_TRAILING_SLASH | CFN_COLLAPSE_DOT_DOT_DIRS);
        }
 
        ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, MAXPATHLEN);
@@ -798,6 +802,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
@@ -964,14 +1003,13 @@ int clean_fname(char *name, int flags)
  * ALWAYS collapses ".." elements (except for those at the start of the
  * string up to "depth" deep).  If the resulting name would be empty,
  * change it into a ".". */
-char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth,
-                   int flags)
+char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth, int flags)
 {
        char *start, *sanp;
        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;
@@ -982,11 +1020,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++] = '/';
                }
        }
@@ -1075,6 +1113,7 @@ int change_dir(const char *dir, int set_path_only)
                skipped_chdir = set_path_only;
                memcpy(curr_dir, dir, len + 1);
        } else {
+               unsigned int save_dir_len = curr_dir_len;
                if (curr_dir_len + 1 + len >= sizeof curr_dir) {
                        errno = ENAMETOOLONG;
                        return 0;
@@ -1084,6 +1123,7 @@ int change_dir(const char *dir, int set_path_only)
                memcpy(curr_dir + curr_dir_len, dir, len + 1);
 
                if (!set_path_only && chdir(curr_dir)) {
+                       curr_dir_len = save_dir_len;
                        curr_dir[curr_dir_len] = '\0';
                        return 0;
                }
@@ -1297,44 +1337,33 @@ int unsafe_symlink(const char *dest, const char *src)
 /* Return the date and time as a string.  Some callers tweak returned buf. */
 char *timestring(time_t t)
 {
-       static char TimeBuf[200];
+       static int ndx = 0;
+       static char buffers[4][20]; /* We support 4 simultaneous timestring results. */
+       char *TimeBuf = buffers[ndx = (ndx + 1) % 4];
        struct tm *tm = localtime(&t);
-       char *p;
-
-#ifdef HAVE_STRFTIME
-       strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
-#else
-       strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
-#endif
-
-       if ((p = strchr(TimeBuf, '\n')) != NULL)
-               *p = '\0';
+       int len = snprintf(TimeBuf, sizeof buffers[0], "%4d/%02d/%02d %02d:%02d:%02d",
+                (int)tm->tm_year + 1900, (int)tm->tm_mon + 1, (int)tm->tm_mday,
+                (int)tm->tm_hour, (int)tm->tm_min, (int)tm->tm_sec);
+       assert(len > 0); /* Silence gcc warning */
 
        return TimeBuf;
 }
 
 /* Determine if two time_t values are equivalent (either exact, or in
  * the modification timestamp window established by --modify-window).
- *
- * @retval 0 if the times should be treated as the same
- *
- * @retval +1 if the first is later
- *
- * @retval -1 if the 2nd is later
- **/
-int cmp_time(time_t file1, time_t file2)
+ * Returns 1 if the times the "same", or 0 if they are different. */
+int same_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 (file1 - file2 <= modify_window)
-               return 0;
-       return 1;
+       if (modify_window == 0)
+               return f1_sec == f2_sec;
+       if (modify_window < 0)
+               return f1_sec == f2_sec && f1_nsec == f2_nsec;
+       /* The nano seconds doesn't figure into these checks -- time windows don't care about that. */
+       if (f2_sec > f1_sec)
+               return f2_sec - f1_sec <= modify_window;
+       return f1_sec - f2_sec <= modify_window;
 }
 
-
 #ifdef __INSURE__XX
 #include <dlfcn.h>
 
@@ -1406,8 +1435,7 @@ const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
                } else if (s_len == 5) {
                        if (strcmp(s+1, "orig") == 0)
                                continue;
-               } else if (s_len > 2 && had_tilde
-                   && s[1] == '~' && isDigit(s + 2))
+               } else if (s_len > 2 && had_tilde && s[1] == '~' && isDigit(s + 2))
                        continue;
                *len_ptr = s_len;
                suf = s;
@@ -1418,7 +1446,7 @@ const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
                        if (!isDigit(s))
                                return suf;
                }
-               /* An all-digit suffix may not be that signficant. */
+               /* An all-digit suffix may not be that significant. */
                s = suf;
        }
 
@@ -1482,8 +1510,8 @@ uint32 fuzzy_distance(const char *s1, unsigned len1, const char *s2, unsigned le
 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
 
 struct bitbag {
-    uint32 **bits;
-    int slot_cnt;
+       uint32 **bits;
+       int slot_cnt;
 };
 
 struct bitbag *bitbag_create(int max_ndx)
@@ -1602,8 +1630,15 @@ int flist_ndx_pop(flist_ndx_list *lp)
        return ndx;
 }
 
-void *expand_item_list(item_list *lp, size_t item_size,
-                      const char *desc, int incr)
+/* 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)
 {
        /* First time through, 0 <= 0, so list is expanded. */
        if (lp->malloced <= lp->count) {
@@ -1612,10 +1647,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);
@@ -1632,3 +1669,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';
+}