Remove `<a name=...>` tags.
[rsync.git] / util1.c
1 /*
2  * Utility routines used in rsync.
3  *
4  * Copyright (C) 1996-2000 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2003-2022 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 #include "rsync.h"
24 #include "ifuncs.h"
25 #include "itypes.h"
26 #include "inums.h"
27
28 extern int dry_run;
29 extern int module_id;
30 extern int do_fsync;
31 extern int protect_args;
32 extern int modify_window;
33 extern int relative_paths;
34 extern int preserve_mtimes;
35 extern int preserve_xattrs;
36 extern int omit_link_times;
37 extern int preallocate_files;
38 extern char *module_dir;
39 extern unsigned int module_dirlen;
40 extern char *partial_dir;
41 extern filter_rule_list daemon_filter_list;
42
43 int sanitize_paths = 0;
44
45 char curr_dir[MAXPATHLEN];
46 unsigned int curr_dir_len;
47 int curr_dir_depth; /* This is only set for a sanitizing daemon. */
48
49 /* Set a fd into nonblocking mode. */
50 void set_nonblocking(int fd)
51 {
52         int val;
53
54         if ((val = fcntl(fd, F_GETFL)) == -1)
55                 return;
56         if (!(val & NONBLOCK_FLAG)) {
57                 val |= NONBLOCK_FLAG;
58                 fcntl(fd, F_SETFL, val);
59         }
60 }
61
62 /* Set a fd into blocking mode. */
63 void set_blocking(int fd)
64 {
65         int val;
66
67         if ((val = fcntl(fd, F_GETFL)) == -1)
68                 return;
69         if (val & NONBLOCK_FLAG) {
70                 val &= ~NONBLOCK_FLAG;
71                 fcntl(fd, F_SETFL, val);
72         }
73 }
74
75 /**
76  * Create a file descriptor pair - like pipe() but use socketpair if
77  * possible (because of blocking issues on pipes).
78  *
79  * Always set non-blocking.
80  */
81 int fd_pair(int fd[2])
82 {
83         int ret;
84
85 #ifdef HAVE_SOCKETPAIR
86         ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
87 #else
88         ret = pipe(fd);
89 #endif
90
91         if (ret == 0) {
92                 set_nonblocking(fd[0]);
93                 set_nonblocking(fd[1]);
94         }
95
96         return ret;
97 }
98
99 void print_child_argv(const char *prefix, char **cmd)
100 {
101         int cnt = 0;
102         rprintf(FCLIENT, "%s ", prefix);
103         for (; *cmd; cmd++) {
104                 /* Look for characters that ought to be quoted.  This
105                 * is not a great quoting algorithm, but it's
106                 * sufficient for a log message. */
107                 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
108                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
109                            "0123456789"
110                            ",.-_=+@/") != strlen(*cmd)) {
111                         rprintf(FCLIENT, "\"%s\" ", *cmd);
112                 } else {
113                         rprintf(FCLIENT, "%s ", *cmd);
114                 }
115                 cnt++;
116         }
117         rprintf(FCLIENT, " (%d args)\n", cnt);
118 }
119
120 /* This returns 0 for success, 1 for a symlink if symlink time-setting
121  * is not possible, or -1 for any other error. */
122 int set_times(const char *fname, STRUCT_STAT *stp)
123 {
124         static int switch_step = 0;
125
126         if (DEBUG_GTE(TIME, 1)) {
127                 rprintf(FINFO,
128                         "set modtime, atime of %s to (%ld) %s, (%ld) %s\n",
129                         fname, (long)stp->st_mtime,
130                         timestring(stp->st_mtime), (long)stp->st_atime, timestring(stp->st_atime));
131         }
132
133         switch (switch_step) {
134 #ifdef HAVE_SETATTRLIST
135 #include "case_N.h"
136                 if (do_setattrlist_times(fname, stp) == 0)
137                         break;
138                 if (errno != ENOSYS)
139                         return -1;
140                 switch_step++;
141 #endif
142
143 #ifdef HAVE_UTIMENSAT
144 #include "case_N.h"
145                 if (do_utimensat(fname, stp) == 0)
146                         break;
147                 if (errno != ENOSYS)
148                         return -1;
149                 switch_step++;
150 #endif
151
152 #ifdef HAVE_LUTIMES
153 #include "case_N.h"
154                 if (do_lutimes(fname, stp) == 0)
155                         break;
156                 if (errno != ENOSYS)
157                         return -1;
158                 switch_step++;
159 #endif
160
161 #include "case_N.h"
162                 switch_step++;
163                 if (!omit_link_times) {
164                         omit_link_times = 1;
165                         if (S_ISLNK(stp->st_mode))
166                                 return 1;
167                 }
168
169 #include "case_N.h"
170 #ifdef HAVE_UTIMES
171                 if (do_utimes(fname, stp) == 0)
172                         break;
173 #else
174                 if (do_utime(fname, stp) == 0)
175                         break;
176 #endif
177
178                 return -1;
179         }
180
181         return 0;
182 }
183
184 /* Create any necessary directories in fname.  Any missing directories are
185  * created with default permissions.  Returns < 0 on error, or the number
186  * of directories created. */
187 int make_path(char *fname, int flags)
188 {
189         char *end, *p;
190         int ret = 0;
191
192         if (flags & MKP_SKIP_SLASH) {
193                 while (*fname == '/')
194                         fname++;
195         }
196
197         while (*fname == '.' && fname[1] == '/')
198                 fname += 2;
199
200         if (flags & MKP_DROP_NAME) {
201                 end = strrchr(fname, '/');
202                 if (!end || end == fname)
203                         return 0;
204                 *end = '\0';
205         } else
206                 end = fname + strlen(fname);
207
208         /* Try to find an existing dir, starting from the deepest dir. */
209         for (p = end; ; ) {
210                 if (dry_run) {
211                         STRUCT_STAT st;
212                         if (do_stat(fname, &st) == 0) {
213                                 if (S_ISDIR(st.st_mode))
214                                         errno = EEXIST;
215                                 else
216                                         errno = ENOTDIR;
217                         }
218                 } else if (do_mkdir(fname, ACCESSPERMS) == 0) {
219                         ret++;
220                         break;
221                 }
222
223                 if (errno != ENOENT) {
224                         STRUCT_STAT st;
225                         if (errno != EEXIST || (do_stat(fname, &st) == 0 && !S_ISDIR(st.st_mode)))
226                                 ret = -ret - 1;
227                         break;
228                 }
229                 while (1) {
230                         if (p == fname) {
231                                 /* We got a relative path that doesn't exist, so assume that '.'
232                                  * is there and just break out and create the whole thing. */
233                                 p = NULL;
234                                 goto double_break;
235                         }
236                         if (*--p == '/') {
237                                 if (p == fname) {
238                                         /* We reached the "/" dir, which we assume is there. */
239                                         goto double_break;
240                                 }
241                                 *p = '\0';
242                                 break;
243                         }
244                 }
245         }
246   double_break:
247
248         /* Make all the dirs that we didn't find on the way here. */
249         while (p != end) {
250                 if (p)
251                         *p = '/';
252                 else
253                         p = fname;
254                 p += strlen(p);
255                 if (ret < 0) /* Skip mkdir on error, but keep restoring the path. */
256                         continue;
257                 if (do_mkdir(fname, ACCESSPERMS) < 0)
258                         ret = -ret - 1;
259                 else
260                         ret++;
261         }
262
263         if (flags & MKP_DROP_NAME)
264                 *end = '/';
265
266         return ret;
267 }
268
269 /**
270  * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
271  * interrupted.
272  *
273  * @retval len upon success
274  *
275  * @retval <0 write's (negative) error code
276  *
277  * Derived from GNU C's cccp.c.
278  */
279 int full_write(int desc, const char *ptr, size_t len)
280 {
281         int total_written;
282
283         total_written = 0;
284         while (len > 0) {
285                 int written = write(desc, ptr, len);
286                 if (written < 0)  {
287                         if (errno == EINTR)
288                                 continue;
289                         return written;
290                 }
291                 total_written += written;
292                 ptr += written;
293                 len -= written;
294         }
295         return total_written;
296 }
297
298 /**
299  * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
300  * interrupted.
301  *
302  * @retval >0 the actual number of bytes read
303  *
304  * @retval 0 for EOF
305  *
306  * @retval <0 for an error.
307  *
308  * Derived from GNU C's cccp.c. */
309 static int safe_read(int desc, char *ptr, size_t len)
310 {
311         int n_chars;
312
313         if (len == 0)
314                 return len;
315
316         do {
317                 n_chars = read(desc, ptr, len);
318         } while (n_chars < 0 && errno == EINTR);
319
320         return n_chars;
321 }
322
323 /* Copy a file.  If ofd < 0, copy_file unlinks and opens the "dest" file.
324  * Otherwise, it just writes to and closes the provided file descriptor.
325  * In either case, if --xattrs are being preserved, the dest file will
326  * have its xattrs set from the source file.
327  *
328  * This is used in conjunction with the --temp-dir, --backup, and
329  * --copy-dest options. */
330 int copy_file(const char *source, const char *dest, int ofd, mode_t mode)
331 {
332         int ifd;
333         char buf[1024 * 8];
334         int len;   /* Number of bytes read into `buf'. */
335         OFF_T prealloc_len = 0, offset = 0;
336
337         if ((ifd = do_open(source, O_RDONLY, 0)) < 0) {
338                 int save_errno = errno;
339                 rsyserr(FERROR_XFER, errno, "open %s", full_fname(source));
340                 errno = save_errno;
341                 return -1;
342         }
343
344         if (ofd < 0) {
345                 if (robust_unlink(dest) && errno != ENOENT) {
346                         int save_errno = errno;
347                         rsyserr(FERROR_XFER, errno, "unlink %s", full_fname(dest));
348                         close(ifd);
349                         errno = save_errno;
350                         return -1;
351                 }
352
353 #ifdef SUPPORT_XATTRS
354                 if (preserve_xattrs)
355                         mode |= S_IWUSR;
356 #endif
357                 mode &= INITACCESSPERMS;
358                 if ((ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode)) < 0) {
359                         int save_errno = errno;
360                         rsyserr(FERROR_XFER, save_errno, "open %s", full_fname(dest));
361                         close(ifd);
362                         errno = save_errno;
363                         return -1;
364                 }
365         }
366
367 #ifdef SUPPORT_PREALLOCATION
368         if (preallocate_files) {
369                 STRUCT_STAT srcst;
370
371                 /* Try to preallocate enough space for file's eventual length.  Can
372                  * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
373                 if (do_fstat(ifd, &srcst) < 0)
374                         rsyserr(FWARNING, errno, "fstat %s", full_fname(source));
375                 else if (srcst.st_size > 0) {
376                         prealloc_len = do_fallocate(ofd, 0, srcst.st_size);
377                         if (prealloc_len < 0)
378                                 rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest));
379                 }
380         }
381 #endif
382
383         while ((len = safe_read(ifd, buf, sizeof buf)) > 0) {
384                 if (full_write(ofd, buf, len) < 0) {
385                         int save_errno = errno;
386                         rsyserr(FERROR_XFER, errno, "write %s", full_fname(dest));
387                         close(ifd);
388                         close(ofd);
389                         errno = save_errno;
390                         return -1;
391                 }
392                 offset += len;
393         }
394
395         if (len < 0) {
396                 int save_errno = errno;
397                 rsyserr(FERROR_XFER, errno, "read %s", full_fname(source));
398                 close(ifd);
399                 close(ofd);
400                 errno = save_errno;
401                 return -1;
402         }
403
404         if (close(ifd) < 0) {
405                 rsyserr(FWARNING, errno, "close failed on %s",
406                         full_fname(source));
407         }
408
409         /* Source file might have shrunk since we fstatted it.
410          * Cut off any extra preallocated zeros from dest file. */
411         if (offset < prealloc_len) {
412 #ifdef HAVE_FTRUNCATE
413                 /* If we fail to truncate, the dest file may be wrong, so we
414                  * must trigger the "partial transfer" error. */
415                 if (do_ftruncate(ofd, offset) < 0)
416                         rsyserr(FERROR_XFER, errno, "ftruncate %s", full_fname(dest));
417 #else
418                 rprintf(FERROR_XFER, "no ftruncate for over-long pre-alloc: %s", full_fname(dest));
419 #endif
420         }
421
422         if (do_fsync && fsync(ofd) < 0) {
423                 int save_errno = errno;
424                 rsyserr(FERROR, errno, "fsync failed on %s", full_fname(dest));
425                 close(ofd);
426                 errno = save_errno;
427                 return -1;
428         }
429
430         if (close(ofd) < 0) {
431                 int save_errno = errno;
432                 rsyserr(FERROR_XFER, errno, "close failed on %s", full_fname(dest));
433                 errno = save_errno;
434                 return -1;
435         }
436
437 #ifdef SUPPORT_XATTRS
438         if (preserve_xattrs)
439                 copy_xattrs(source, dest);
440 #endif
441
442         return 0;
443 }
444
445 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
446 #define MAX_RENAMES_DIGITS 3
447 #define MAX_RENAMES 1000
448
449 /**
450  * Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
451  * rename to <path>/.rsyncNNN instead.
452  *
453  * Note that successive rsync runs will shuffle the filenames around a
454  * bit as long as the file is still busy; this is because this function
455  * does not know if the unlink call is due to a new file coming in, or
456  * --delete trying to remove old .rsyncNNN files, hence it renames it
457  * each time.
458  **/
459 int robust_unlink(const char *fname)
460 {
461 #ifndef ETXTBSY
462         return do_unlink(fname);
463 #else
464         static int counter = 1;
465         int rc, pos, start;
466         char path[MAXPATHLEN];
467
468         rc = do_unlink(fname);
469         if (rc == 0 || errno != ETXTBSY)
470                 return rc;
471
472         if ((pos = strlcpy(path, fname, MAXPATHLEN)) >= MAXPATHLEN)
473                 pos = MAXPATHLEN - 1;
474
475         while (pos > 0 && path[pos-1] != '/')
476                 pos--;
477         pos += strlcpy(path+pos, ".rsync", MAXPATHLEN-pos);
478
479         if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
480                 errno = ETXTBSY;
481                 return -1;
482         }
483
484         /* start where the last one left off to reduce chance of clashes */
485         start = counter;
486         do {
487                 snprintf(&path[pos], MAX_RENAMES_DIGITS+1, "%03d", counter);
488                 if (++counter >= MAX_RENAMES)
489                         counter = 1;
490         } while ((rc = access(path, 0)) == 0 && counter != start);
491
492         if (INFO_GTE(MISC, 1)) {
493                 rprintf(FWARNING, "renaming %s to %s because of text busy\n",
494                         fname, path);
495         }
496
497         /* maybe we should return rename()'s exit status? Nah. */
498         if (do_rename(fname, path) != 0) {
499                 errno = ETXTBSY;
500                 return -1;
501         }
502         return 0;
503 #endif
504 }
505
506 /* Returns 0 on successful rename, 1 if we successfully copied the file
507  * across filesystems, -2 if copy_file() failed, and -1 on other errors.
508  * If partialptr is not NULL and we need to do a copy, copy the file into
509  * the active partial-dir instead of over the destination file. */
510 int robust_rename(const char *from, const char *to, const char *partialptr,
511                   int mode)
512 {
513         int tries = 4;
514
515         /* A resumed in-place partial-dir transfer might call us with from and
516          * to pointing to the same buf if the transfer failed yet again. */
517         if (from == to)
518                 return 0;
519
520         while (tries--) {
521                 if (do_rename(from, to) == 0)
522                         return 0;
523
524                 switch (errno) {
525 #ifdef ETXTBSY
526                 case ETXTBSY:
527                         if (robust_unlink(to) != 0) {
528                                 errno = ETXTBSY;
529                                 return -1;
530                         }
531                         errno = ETXTBSY;
532                         break;
533 #endif
534                 case EXDEV:
535                         if (partialptr) {
536                                 if (!handle_partial_dir(partialptr,PDIR_CREATE))
537                                         return -2;
538                                 to = partialptr;
539                         }
540                         if (copy_file(from, to, -1, mode) != 0)
541                                 return -2;
542                         do_unlink(from);
543                         return 1;
544                 default:
545                         return -1;
546                 }
547         }
548         return -1;
549 }
550
551 static pid_t all_pids[10];
552 static int num_pids;
553
554 /** Fork and record the pid of the child. **/
555 pid_t do_fork(void)
556 {
557         pid_t newpid = fork();
558
559         if (newpid != 0  &&  newpid != -1) {
560                 all_pids[num_pids++] = newpid;
561         }
562         return newpid;
563 }
564
565 /**
566  * Kill all children.
567  *
568  * @todo It would be kind of nice to make sure that they are actually
569  * all our children before we kill them, because their pids may have
570  * been recycled by some other process.  Perhaps when we wait for a
571  * child, we should remove it from this array.  Alternatively we could
572  * perhaps use process groups, but I think that would not work on
573  * ancient Unix versions that don't support them.
574  **/
575 void kill_all(int sig)
576 {
577         int i;
578
579         for (i = 0; i < num_pids; i++) {
580                 /* Let's just be a little careful where we
581                  * point that gun, hey?  See kill(2) for the
582                  * magic caused by negative values. */
583                 pid_t p = all_pids[i];
584
585                 if (p == getpid())
586                         continue;
587                 if (p <= 0)
588                         continue;
589
590                 kill(p, sig);
591         }
592 }
593
594 /** Lock a byte range in a open file */
595 int lock_range(int fd, int offset, int len)
596 {
597         struct flock lock;
598
599         lock.l_type = F_WRLCK;
600         lock.l_whence = SEEK_SET;
601         lock.l_start = offset;
602         lock.l_len = len;
603         lock.l_pid = 0;
604
605         return fcntl(fd,F_SETLK,&lock) == 0;
606 }
607
608 #define ENSURE_MEMSPACE(buf, type, sz, req) \
609         do { if ((req) > sz) buf = realloc_array(buf, type, sz = MAX(sz * 2, req)); } while(0)
610
611 static inline void call_glob_match(const char *name, int len, int from_glob,
612                                    char *arg, int abpos, int fbpos);
613
614 static struct glob_data {
615         char *arg_buf, *filt_buf, **argv;
616         int absize, fbsize, maxargs, argc;
617 } glob;
618
619 static void glob_match(char *arg, int abpos, int fbpos)
620 {
621         int len;
622         char *slash;
623
624         while (*arg == '.' && arg[1] == '/') {
625                 if (fbpos < 0) {
626                         ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, glob.absize);
627                         memcpy(glob.filt_buf, glob.arg_buf, abpos + 1);
628                         fbpos = abpos;
629                 }
630                 ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + 3);
631                 glob.arg_buf[abpos++] = *arg++;
632                 glob.arg_buf[abpos++] = *arg++;
633                 glob.arg_buf[abpos] = '\0';
634         }
635         if ((slash = strchr(arg, '/')) != NULL) {
636                 *slash = '\0';
637                 len = slash - arg;
638         } else
639                 len = strlen(arg);
640         if (strpbrk(arg, "*?[")) {
641                 struct dirent *di;
642                 DIR *d;
643
644                 if (!(d = opendir(abpos ? glob.arg_buf : ".")))
645                         return;
646                 while ((di = readdir(d)) != NULL) {
647                         char *dname = d_name(di);
648                         if (dname[0] == '.' && (dname[1] == '\0'
649                           || (dname[1] == '.' && dname[2] == '\0')))
650                                 continue;
651                         if (!wildmatch(arg, dname))
652                                 continue;
653                         call_glob_match(dname, strlen(dname), 1,
654                                         slash ? arg + len + 1 : NULL,
655                                         abpos, fbpos);
656                 }
657                 closedir(d);
658         } else {
659                 call_glob_match(arg, len, 0,
660                                 slash ? arg + len + 1 : NULL,
661                                 abpos, fbpos);
662         }
663         if (slash)
664                 *slash = '/';
665 }
666
667 static inline void call_glob_match(const char *name, int len, int from_glob,
668                                    char *arg, int abpos, int fbpos)
669 {
670         char *use_buf;
671
672         ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, abpos + len + 2);
673         memcpy(glob.arg_buf + abpos, name, len);
674         abpos += len;
675         glob.arg_buf[abpos] = '\0';
676
677         if (fbpos >= 0) {
678                 ENSURE_MEMSPACE(glob.filt_buf, char, glob.fbsize, fbpos + len + 2);
679                 memcpy(glob.filt_buf + fbpos, name, len);
680                 fbpos += len;
681                 glob.filt_buf[fbpos] = '\0';
682                 use_buf = glob.filt_buf;
683         } else
684                 use_buf = glob.arg_buf;
685
686         if (from_glob || (arg && len)) {
687                 STRUCT_STAT st;
688                 int is_dir;
689
690                 if (do_stat(glob.arg_buf, &st) != 0)
691                         return;
692                 is_dir = S_ISDIR(st.st_mode) != 0;
693                 if (arg && !is_dir)
694                         return;
695
696                 if (daemon_filter_list.head
697                  && check_filter(&daemon_filter_list, FLOG, use_buf, is_dir) < 0)
698                         return;
699         }
700
701         if (arg) {
702                 glob.arg_buf[abpos++] = '/';
703                 glob.arg_buf[abpos] = '\0';
704                 if (fbpos >= 0) {
705                         glob.filt_buf[fbpos++] = '/';
706                         glob.filt_buf[fbpos] = '\0';
707                 }
708                 glob_match(arg, abpos, fbpos);
709         } else {
710                 ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
711                 glob.argv[glob.argc++] = strdup(glob.arg_buf);
712         }
713 }
714
715 /* This routine performs wild-card expansion of the pathname in "arg".  Any
716  * daemon-excluded files/dirs will not be matched by the wildcards.  Returns 0
717  * if a wild-card string is the only returned item (due to matching nothing). */
718 int glob_expand(const char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
719 {
720         int ret, save_argc;
721         char *s;
722
723         if (!arg) {
724                 if (glob.filt_buf)
725                         free(glob.filt_buf);
726                 free(glob.arg_buf);
727                 memset(&glob, 0, sizeof glob);
728                 return -1;
729         }
730
731         if (sanitize_paths)
732                 s = sanitize_path(NULL, arg, "", 0, SP_KEEP_DOT_DIRS);
733         else {
734                 s = strdup(arg);
735                 clean_fname(s, CFN_KEEP_DOT_DIRS | CFN_KEEP_TRAILING_SLASH | CFN_COLLAPSE_DOT_DOT_DIRS);
736         }
737
738         ENSURE_MEMSPACE(glob.arg_buf, char, glob.absize, MAXPATHLEN);
739         *glob.arg_buf = '\0';
740
741         glob.argc = save_argc = *argc_p;
742         glob.argv = *argv_p;
743         glob.maxargs = *maxargs_p;
744
745         ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, 100);
746
747         glob_match(s, 0, -1);
748
749         /* The arg didn't match anything, so add the failed arg to the list. */
750         if (glob.argc == save_argc) {
751                 ENSURE_MEMSPACE(glob.argv, char *, glob.maxargs, glob.argc + 1);
752                 glob.argv[glob.argc++] = s;
753                 ret = 0;
754         } else {
755                 free(s);
756                 ret = 1;
757         }
758
759         *maxargs_p = glob.maxargs;
760         *argv_p = glob.argv;
761         *argc_p = glob.argc;
762
763         return ret;
764 }
765
766 /* This routine is only used in daemon mode. */
767 void glob_expand_module(char *base1, char *arg, char ***argv_p, int *argc_p, int *maxargs_p)
768 {
769         char *p, *s;
770         char *base = base1;
771         int base_len = strlen(base);
772
773         if (!arg || !*arg)
774                 return;
775
776         if (strncmp(arg, base, base_len) == 0)
777                 arg += base_len;
778
779         if (protect_args) {
780                 glob_expand(arg, argv_p, argc_p, maxargs_p);
781                 return;
782         }
783
784         arg = strdup(arg);
785
786         if (asprintf(&base," %s/", base1) < 0)
787                 out_of_memory("glob_expand_module");
788         base_len++;
789
790         for (s = arg; *s; s = p + base_len) {
791                 if ((p = strstr(s, base)) != NULL)
792                         *p = '\0'; /* split it at this point */
793                 glob_expand(s, argv_p, argc_p, maxargs_p);
794                 if (!p)
795                         break;
796         }
797
798         free(arg);
799         free(base);
800 }
801
802 /**
803  * Convert a string to lower case
804  **/
805 void strlower(char *s)
806 {
807         while (*s) {
808                 if (isUpper(s))
809                         *s = toLower(s);
810                 s++;
811         }
812 }
813
814 /**
815  * Split a string into tokens based (usually) on whitespace & commas.  If the
816  * string starts with a comma (after skipping any leading whitespace), then
817  * splitting is done only on commas. No empty tokens are ever returned. */
818 char *conf_strtok(char *str)
819 {
820         static int commas_only = 0;
821
822         if (str) {
823                 while (isSpace(str)) str++;
824                 if (*str == ',') {
825                         commas_only = 1;
826                         str++;
827                 } else
828                         commas_only = 0;
829         }
830
831         while (commas_only) {
832                 char *end, *tok = strtok(str, ",");
833                 if (!tok)
834                         return NULL;
835                 /* Trim just leading and trailing whitespace. */
836                 while (isSpace(tok))
837                         tok++;
838                 end = tok + strlen(tok);
839                 while (end > tok && isSpace(end-1))
840                         *--end = '\0';
841                 if (*tok)
842                         return tok;
843                 str = NULL;
844         }
845
846         return strtok(str, " ,\t\r\n");
847 }
848
849 /* Join strings p1 & p2 into "dest" with a guaranteed '/' between them.  (If
850  * p1 ends with a '/', no extra '/' is inserted.)  Returns the length of both
851  * strings + 1 (if '/' was inserted), regardless of whether the null-terminated
852  * string fits into destsize. */
853 size_t pathjoin(char *dest, size_t destsize, const char *p1, const char *p2)
854 {
855         size_t len = strlcpy(dest, p1, destsize);
856         if (len < destsize - 1) {
857                 if (!len || dest[len-1] != '/')
858                         dest[len++] = '/';
859                 if (len < destsize - 1)
860                         len += strlcpy(dest + len, p2, destsize - len);
861                 else {
862                         dest[len] = '\0';
863                         len += strlen(p2);
864                 }
865         }
866         else
867                 len += strlen(p2) + 1; /* Assume we'd insert a '/'. */
868         return len;
869 }
870
871 /* Join any number of strings together, putting them in "dest".  The return
872  * value is the length of all the strings, regardless of whether the null-
873  * terminated whole fits in destsize.  Your list of string pointers must end
874  * with a NULL to indicate the end of the list. */
875 size_t stringjoin(char *dest, size_t destsize, ...)
876 {
877         va_list ap;
878         size_t len, ret = 0;
879         const char *src;
880
881         va_start(ap, destsize);
882         while (1) {
883                 if (!(src = va_arg(ap, const char *)))
884                         break;
885                 len = strlen(src);
886                 ret += len;
887                 if (destsize > 1) {
888                         if (len >= destsize)
889                                 len = destsize - 1;
890                         memcpy(dest, src, len);
891                         destsize -= len;
892                         dest += len;
893                 }
894         }
895         *dest = '\0';
896         va_end(ap);
897
898         return ret;
899 }
900
901 int count_dir_elements(const char *p)
902 {
903         int cnt = 0, new_component = 1;
904         while (*p) {
905                 if (*p++ == '/')
906                         new_component = (*p != '.' || (p[1] != '/' && p[1] != '\0'));
907                 else if (new_component) {
908                         new_component = 0;
909                         cnt++;
910                 }
911         }
912         return cnt;
913 }
914
915 /* Turns multiple adjacent slashes into a single slash (possible exception:
916  * the preserving of two leading slashes at the start), drops all leading or
917  * interior "." elements unless CFN_KEEP_DOT_DIRS is flagged.  Will also drop
918  * a trailing '.' after a '/' if CFN_DROP_TRAILING_DOT_DIR is flagged, removes
919  * a trailing slash (perhaps after removing the aforementioned dot) unless
920  * CFN_KEEP_TRAILING_SLASH is flagged, and will also collapse ".." elements
921  * (except at the start) if CFN_COLLAPSE_DOT_DOT_DIRS is flagged.  If the
922  * resulting name would be empty, returns ".". */
923 int clean_fname(char *name, int flags)
924 {
925         char *limit = name - 1, *t = name, *f = name;
926         int anchored;
927
928         if (!name)
929                 return 0;
930
931 #define DOT_IS_DOT_DOT_DIR(bp) (bp[1] == '.' && (bp[2] == '/' || !bp[2]))
932
933         if ((anchored = *f == '/') != 0) {
934                 *t++ = *f++;
935 #ifdef __CYGWIN__
936                 /* If there are exactly 2 slashes at the start, preserve
937                  * them.  Would break daemon excludes unless the paths are
938                  * really treated differently, so used this sparingly. */
939                 if (*f == '/' && f[1] != '/')
940                         *t++ = *f++;
941 #endif
942         } else if (flags & CFN_KEEP_DOT_DIRS && *f == '.' && f[1] == '/') {
943                 *t++ = *f++;
944                 *t++ = *f++;
945         } else if (flags & CFN_REFUSE_DOT_DOT_DIRS && *f == '.' && DOT_IS_DOT_DOT_DIR(f))
946                 return -1;
947         while (*f) {
948                 /* discard extra slashes */
949                 if (*f == '/') {
950                         f++;
951                         continue;
952                 }
953                 if (*f == '.') {
954                         /* discard interior "." dirs */
955                         if (f[1] == '/' && !(flags & CFN_KEEP_DOT_DIRS)) {
956                                 f += 2;
957                                 continue;
958                         }
959                         if (f[1] == '\0' && flags & CFN_DROP_TRAILING_DOT_DIR)
960                                 break;
961                         /* collapse ".." dirs */
962                         if (flags & (CFN_COLLAPSE_DOT_DOT_DIRS|CFN_REFUSE_DOT_DOT_DIRS) && DOT_IS_DOT_DOT_DIR(f)) {
963                                 char *s = t - 1;
964                                 if (flags & CFN_REFUSE_DOT_DOT_DIRS)
965                                         return -1;
966                                 if (s == name && anchored) {
967                                         f += 2;
968                                         continue;
969                                 }
970                                 while (s > limit && *--s != '/') {}
971                                 if (s != t - 1 && (s < name || *s == '/')) {
972                                         t = s + 1;
973                                         f += 2;
974                                         continue;
975                                 }
976                                 limit = t + 2;
977                         }
978                 }
979                 while (*f && (*t++ = *f++) != '/') {}
980         }
981
982         if (t > name+anchored && t[-1] == '/' && !(flags & CFN_KEEP_TRAILING_SLASH))
983                 t--;
984         if (t == name)
985                 *t++ = '.';
986         *t = '\0';
987
988 #undef DOT_IS_DOT_DOT_DIR
989
990         return t - name;
991 }
992
993 /* Make path appear as if a chroot had occurred.  This handles a leading
994  * "/" (either removing it or expanding it) and any leading or embedded
995  * ".." components that attempt to escape past the module's top dir.
996  *
997  * If dest is NULL, a buffer is allocated to hold the result.  It is legal
998  * to call with the dest and the path (p) pointing to the same buffer, but
999  * rootdir will be ignored to avoid expansion of the string.
1000  *
1001  * The rootdir string contains a value to use in place of a leading slash.
1002  * Specify NULL to get the default of "module_dir".
1003  *
1004  * The depth var is a count of how many '..'s to allow at the start of the
1005  * path.
1006  *
1007  * We also clean the path in a manner similar to clean_fname() but with a
1008  * few differences:
1009  *
1010  * Turns multiple adjacent slashes into a single slash, gets rid of "." dir
1011  * elements (INCLUDING a trailing dot dir), PRESERVES a trailing slash, and
1012  * ALWAYS collapses ".." elements (except for those at the start of the
1013  * string up to "depth" deep).  If the resulting name would be empty,
1014  * change it into a ".". */
1015 char *sanitize_path(char *dest, const char *p, const char *rootdir, int depth, int flags)
1016 {
1017         char *start, *sanp;
1018         int rlen = 0, drop_dot_dirs = !relative_paths || !(flags & SP_KEEP_DOT_DIRS);
1019
1020         if (dest != p) {
1021                 int plen = strlen(p); /* the path len INCLUDING any separating slash */
1022                 if (*p == '/') {
1023                         if (!rootdir)
1024                                 rootdir = module_dir;
1025                         rlen = strlen(rootdir);
1026                         depth = 0;
1027                         p++;
1028                 }
1029                 if (!dest)
1030                         dest = new_array(char, MAX(rlen + plen + 1, 2));
1031                 else if (rlen + plen + 1 >= MAXPATHLEN)
1032                         return NULL;
1033                 if (rlen) { /* only true if p previously started with a slash */
1034                         memcpy(dest, rootdir, rlen);
1035                         if (rlen > 1) /* a rootdir of len 1 is "/", so this avoids a 2nd slash */
1036                                 dest[rlen++] = '/';
1037                 }
1038         }
1039
1040         if (drop_dot_dirs) {
1041                 while (*p == '.' && p[1] == '/')
1042                         p += 2;
1043         }
1044
1045         start = sanp = dest + rlen;
1046         /* This loop iterates once per filename component in p, pointing at
1047          * the start of the name (past any prior slash) for each iteration. */
1048         while (*p) {
1049                 /* discard leading or extra slashes */
1050                 if (*p == '/') {
1051                         p++;
1052                         continue;
1053                 }
1054                 if (drop_dot_dirs) {
1055                         if (*p == '.' && (p[1] == '/' || p[1] == '\0')) {
1056                                 /* skip "." component */
1057                                 p++;
1058                                 continue;
1059                         }
1060                 }
1061                 if (*p == '.' && p[1] == '.' && (p[2] == '/' || p[2] == '\0')) {
1062                         /* ".." component followed by slash or end */
1063                         if (depth <= 0 || sanp != start) {
1064                                 p += 2;
1065                                 if (sanp != start) {
1066                                         /* back up sanp one level */
1067                                         --sanp; /* now pointing at slash */
1068                                         while (sanp > start && sanp[-1] != '/')
1069                                                 sanp--;
1070                                 }
1071                                 continue;
1072                         }
1073                         /* allow depth levels of .. at the beginning */
1074                         depth--;
1075                         /* move the virtual beginning to leave the .. alone */
1076                         start = sanp + 3;
1077                 }
1078                 /* copy one component through next slash */
1079                 while (*p && (*sanp++ = *p++) != '/') {}
1080         }
1081         if (sanp == dest) {
1082                 /* ended up with nothing, so put in "." component */
1083                 *sanp++ = '.';
1084         }
1085         *sanp = '\0';
1086
1087         return dest;
1088 }
1089
1090 /* Like chdir(), but it keeps track of the current directory (in the
1091  * global "curr_dir"), and ensures that the path size doesn't overflow.
1092  * Also cleans the path using the clean_fname() function. */
1093 int change_dir(const char *dir, int set_path_only)
1094 {
1095         static int initialised, skipped_chdir;
1096         unsigned int len;
1097
1098         if (!initialised) {
1099                 initialised = 1;
1100                 if (getcwd(curr_dir, sizeof curr_dir - 1) == NULL) {
1101                         rsyserr(FERROR, errno, "getcwd()");
1102                         exit_cleanup(RERR_FILESELECT);
1103                 }
1104                 curr_dir_len = strlen(curr_dir);
1105         }
1106
1107         if (!dir)       /* this call was probably just to initialize */
1108                 return 0;
1109
1110         len = strlen(dir);
1111         if (len == 1 && *dir == '.' && (!skipped_chdir || set_path_only))
1112                 return 1;
1113
1114         if (*dir == '/') {
1115                 if (len >= sizeof curr_dir) {
1116                         errno = ENAMETOOLONG;
1117                         return 0;
1118                 }
1119                 if (!set_path_only && chdir(dir))
1120                         return 0;
1121                 skipped_chdir = set_path_only;
1122                 memcpy(curr_dir, dir, len + 1);
1123         } else {
1124                 unsigned int save_dir_len = curr_dir_len;
1125                 if (curr_dir_len + 1 + len >= sizeof curr_dir) {
1126                         errno = ENAMETOOLONG;
1127                         return 0;
1128                 }
1129                 if (!(curr_dir_len && curr_dir[curr_dir_len-1] == '/'))
1130                         curr_dir[curr_dir_len++] = '/';
1131                 memcpy(curr_dir + curr_dir_len, dir, len + 1);
1132
1133                 if (!set_path_only && chdir(curr_dir)) {
1134                         curr_dir_len = save_dir_len;
1135                         curr_dir[curr_dir_len] = '\0';
1136                         return 0;
1137                 }
1138                 skipped_chdir = set_path_only;
1139         }
1140
1141         curr_dir_len = clean_fname(curr_dir, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
1142         if (sanitize_paths) {
1143                 if (module_dirlen > curr_dir_len)
1144                         module_dirlen = curr_dir_len;
1145                 curr_dir_depth = count_dir_elements(curr_dir + module_dirlen);
1146         }
1147
1148         if (DEBUG_GTE(CHDIR, 1) && !set_path_only)
1149                 rprintf(FINFO, "[%s] change_dir(%s)\n", who_am_i(), curr_dir);
1150
1151         return 1;
1152 }
1153
1154 /* This will make a relative path absolute and clean it up via clean_fname().
1155  * Returns the string, which might be newly allocated, or NULL on error. */
1156 char *normalize_path(char *path, BOOL force_newbuf, unsigned int *len_ptr)
1157 {
1158         unsigned int len;
1159
1160         if (*path != '/') { /* Make path absolute. */
1161                 int len = strlen(path);
1162                 if (curr_dir_len + 1 + len >= sizeof curr_dir)
1163                         return NULL;
1164                 curr_dir[curr_dir_len] = '/';
1165                 memcpy(curr_dir + curr_dir_len + 1, path, len + 1);
1166                 path = strdup(curr_dir);
1167                 curr_dir[curr_dir_len] = '\0';
1168         } else if (force_newbuf)
1169                 path = strdup(path);
1170
1171         len = clean_fname(path, CFN_COLLAPSE_DOT_DOT_DIRS | CFN_DROP_TRAILING_DOT_DIR);
1172
1173         if (len_ptr)
1174                 *len_ptr = len;
1175
1176         return path;
1177 }
1178
1179 /**
1180  * Return a quoted string with the full pathname of the indicated filename.
1181  * The string " (in MODNAME)" may also be appended.  The returned pointer
1182  * remains valid until the next time full_fname() is called.
1183  **/
1184 char *full_fname(const char *fn)
1185 {
1186         static char *result = NULL;
1187         char *m1, *m2, *m3;
1188         char *p1, *p2;
1189
1190         if (result)
1191                 free(result);
1192
1193         if (*fn == '/')
1194                 p1 = p2 = "";
1195         else {
1196                 p1 = curr_dir + module_dirlen;
1197                 for (p2 = p1; *p2 == '/'; p2++) {}
1198                 if (*p2)
1199                         p2 = "/";
1200         }
1201         if (module_id >= 0) {
1202                 m1 = " (in ";
1203                 m2 = lp_name(module_id);
1204                 m3 = ")";
1205         } else
1206                 m1 = m2 = m3 = "";
1207
1208         if (asprintf(&result, "\"%s%s%s\"%s%s%s", p1, p2, fn, m1, m2, m3) < 0)
1209                 out_of_memory("full_fname");
1210
1211         return result;
1212 }
1213
1214 static char partial_fname[MAXPATHLEN];
1215
1216 char *partial_dir_fname(const char *fname)
1217 {
1218         char *t = partial_fname;
1219         int sz = sizeof partial_fname;
1220         const char *fn;
1221
1222         if ((fn = strrchr(fname, '/')) != NULL) {
1223                 fn++;
1224                 if (*partial_dir != '/') {
1225                         int len = fn - fname;
1226                         strncpy(t, fname, len); /* safe */
1227                         t += len;
1228                         sz -= len;
1229                 }
1230         } else
1231                 fn = fname;
1232         if ((int)pathjoin(t, sz, partial_dir, fn) >= sz)
1233                 return NULL;
1234         if (daemon_filter_list.head) {
1235                 t = strrchr(partial_fname, '/');
1236                 *t = '\0';
1237                 if (check_filter(&daemon_filter_list, FLOG, partial_fname, 1) < 0)
1238                         return NULL;
1239                 *t = '/';
1240                 if (check_filter(&daemon_filter_list, FLOG, partial_fname, 0) < 0)
1241                         return NULL;
1242         }
1243
1244         return partial_fname;
1245 }
1246
1247 /* If no --partial-dir option was specified, we don't need to do anything
1248  * (the partial-dir is essentially '.'), so just return success. */
1249 int handle_partial_dir(const char *fname, int create)
1250 {
1251         char *fn, *dir;
1252
1253         if (fname != partial_fname)
1254                 return 1;
1255         if (!create && *partial_dir == '/')
1256                 return 1;
1257         if (!(fn = strrchr(partial_fname, '/')))
1258                 return 1;
1259
1260         *fn = '\0';
1261         dir = partial_fname;
1262         if (create) {
1263                 STRUCT_STAT st;
1264                 int statret = do_lstat(dir, &st);
1265                 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1266                         if (do_unlink(dir) < 0) {
1267                                 *fn = '/';
1268                                 return 0;
1269                         }
1270                         statret = -1;
1271                 }
1272                 if (statret < 0 && do_mkdir(dir, 0700) < 0) {
1273                         *fn = '/';
1274                         return 0;
1275                 }
1276         } else
1277                 do_rmdir(dir);
1278         *fn = '/';
1279
1280         return 1;
1281 }
1282
1283 /* Determine if a symlink points outside the current directory tree.
1284  * This is considered "unsafe" because e.g. when mirroring somebody
1285  * else's machine it might allow them to establish a symlink to
1286  * /etc/passwd, and then read it through a web server.
1287  *
1288  * Returns 1 if unsafe, 0 if safe.
1289  *
1290  * Null symlinks and absolute symlinks are always unsafe.
1291  *
1292  * Basically here we are concerned with symlinks whose target contains
1293  * "..", because this might cause us to walk back up out of the
1294  * transferred directory.  We are not allowed to go back up and
1295  * reenter.
1296  *
1297  * "dest" is the target of the symlink in question.
1298  *
1299  * "src" is the top source directory currently applicable at the level
1300  * of the referenced symlink.  This is usually the symlink's full path
1301  * (including its name), as referenced from the root of the transfer. */
1302 int unsafe_symlink(const char *dest, const char *src)
1303 {
1304         const char *name, *slash;
1305         int depth = 0;
1306
1307         /* all absolute and null symlinks are unsafe */
1308         if (!dest || !*dest || *dest == '/')
1309                 return 1;
1310
1311         /* find out what our safety margin is */
1312         for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1313                 /* ".." segment starts the count over.  "." segment is ignored. */
1314                 if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
1315                         if (name[1] == '.')
1316                                 depth = 0;
1317                 } else
1318                         depth++;
1319                 while (slash[1] == '/') slash++; /* just in case src isn't clean */
1320         }
1321         if (*name == '.' && name[1] == '.' && name[2] == '\0')
1322                 depth = 0;
1323
1324         for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1325                 if (*name == '.' && (name[1] == '/' || (name[1] == '.' && name[2] == '/'))) {
1326                         if (name[1] == '.') {
1327                                 /* if at any point we go outside the current directory
1328                                    then stop - it is unsafe */
1329                                 if (--depth < 0)
1330                                         return 1;
1331                         }
1332                 } else
1333                         depth++;
1334                 while (slash[1] == '/') slash++;
1335         }
1336         if (*name == '.' && name[1] == '.' && name[2] == '\0')
1337                 depth--;
1338
1339         return depth < 0;
1340 }
1341
1342 /* Return the date and time as a string.  Some callers tweak returned buf. */
1343 char *timestring(time_t t)
1344 {
1345         static int ndx = 0;
1346         static char buffers[4][20]; /* We support 4 simultaneous timestring results. */
1347         char *TimeBuf = buffers[ndx = (ndx + 1) % 4];
1348         struct tm *tm = localtime(&t);
1349         int len = snprintf(TimeBuf, sizeof buffers[0], "%4d/%02d/%02d %02d:%02d:%02d",
1350                  (int)tm->tm_year + 1900, (int)tm->tm_mon + 1, (int)tm->tm_mday,
1351                  (int)tm->tm_hour, (int)tm->tm_min, (int)tm->tm_sec);
1352         assert(len > 0); /* Silence gcc warning */
1353
1354         return TimeBuf;
1355 }
1356
1357 /* Determine if two time_t values are equivalent (either exact, or in
1358  * the modification timestamp window established by --modify-window).
1359  * Returns 1 if the times the "same", or 0 if they are different. */
1360 int same_time(time_t f1_sec, unsigned long f1_nsec, time_t f2_sec, unsigned long f2_nsec)
1361 {
1362         if (modify_window == 0)
1363                 return f1_sec == f2_sec;
1364         if (modify_window < 0)
1365                 return f1_sec == f2_sec && f1_nsec == f2_nsec;
1366         /* The nanoseconds do not figure into these checks -- time windows don't care about that. */
1367         if (f2_sec > f1_sec)
1368                 return f2_sec - f1_sec <= modify_window;
1369         return f1_sec - f2_sec <= modify_window;
1370 }
1371
1372 #ifdef __INSURE__XX
1373 #include <dlfcn.h>
1374
1375 /**
1376    This routine is a trick to immediately catch errors when debugging
1377    with insure. A xterm with a gdb is popped up when insure catches
1378    a error. It is Linux specific.
1379 **/
1380 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1381 {
1382         static int (*fn)();
1383         int ret, pid_int = getpid();
1384         char *cmd;
1385
1386         if (asprintf(&cmd,
1387             "/usr/X11R6/bin/xterm -display :0 -T Panic -n Panic -e /bin/sh -c 'cat /tmp/ierrs.*.%d ; "
1388             "gdb /proc/%d/exe %d'", pid_int, pid_int, pid_int) < 0)
1389                 return -1;
1390
1391         if (!fn) {
1392                 static void *h;
1393                 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1394                 fn = dlsym(h, "_Insure_trap_error");
1395         }
1396
1397         ret = fn(a1, a2, a3, a4, a5, a6);
1398
1399         system(cmd);
1400
1401         free(cmd);
1402
1403         return ret;
1404 }
1405 #endif
1406
1407 /* Take a filename and filename length and return the most significant
1408  * filename suffix we can find.  This ignores suffixes such as "~",
1409  * ".bak", ".orig", ".~1~", etc. */
1410 const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1411 {
1412         const char *suf, *s;
1413         BOOL had_tilde;
1414         int s_len;
1415
1416         /* One or more dots at the start aren't a suffix. */
1417         while (fn_len && *fn == '.') fn++, fn_len--;
1418
1419         /* Ignore the ~ in a "foo~" filename. */
1420         if (fn_len > 1 && fn[fn_len-1] == '~')
1421                 fn_len--, had_tilde = True;
1422         else
1423                 had_tilde = False;
1424
1425         /* Assume we don't find an suffix. */
1426         suf = "";
1427         *len_ptr = 0;
1428
1429         /* Find the last significant suffix. */
1430         for (s = fn + fn_len; fn_len > 1; ) {
1431                 while (*--s != '.' && s != fn) {}
1432                 if (s == fn)
1433                         break;
1434                 s_len = fn_len - (s - fn);
1435                 fn_len = s - fn;
1436                 if (s_len == 4) {
1437                         if (strcmp(s+1, "bak") == 0
1438                          || strcmp(s+1, "old") == 0)
1439                                 continue;
1440                 } else if (s_len == 5) {
1441                         if (strcmp(s+1, "orig") == 0)
1442                                 continue;
1443                 } else if (s_len > 2 && had_tilde && s[1] == '~' && isDigit(s + 2))
1444                         continue;
1445                 *len_ptr = s_len;
1446                 suf = s;
1447                 if (s_len == 1)
1448                         break;
1449                 /* Determine if the suffix is all digits. */
1450                 for (s++, s_len--; s_len > 0; s++, s_len--) {
1451                         if (!isDigit(s))
1452                                 return suf;
1453                 }
1454                 /* An all-digit suffix may not be that significant. */
1455                 s = suf;
1456         }
1457
1458         return suf;
1459 }
1460
1461 /* This is an implementation of the Levenshtein distance algorithm.  It
1462  * was implemented to avoid needing a two-dimensional matrix (to save
1463  * memory).  It was also tweaked to try to factor in the ASCII distance
1464  * between changed characters as a minor distance quantity.  The normal
1465  * Levenshtein units of distance (each signifying a single change between
1466  * the two strings) are defined as a "UNIT". */
1467
1468 #define UNIT (1 << 16)
1469
1470 uint32 fuzzy_distance(const char *s1, unsigned len1, const char *s2, unsigned len2)
1471 {
1472         uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1473         int32 cost;
1474         unsigned i1, i2;
1475
1476         if (!len1 || !len2) {
1477                 if (!len1) {
1478                         s1 = s2;
1479                         len1 = len2;
1480                 }
1481                 for (i1 = 0, cost = 0; i1 < len1; i1++)
1482                         cost += s1[i1];
1483                 return (int32)len1 * UNIT + cost;
1484         }
1485
1486         for (i2 = 0; i2 < len2; i2++)
1487                 a[i2] = (i2+1) * UNIT;
1488
1489         for (i1 = 0; i1 < len1; i1++) {
1490                 diag = i1 * UNIT;
1491                 above = (i1+1) * UNIT;
1492                 for (i2 = 0; i2 < len2; i2++) {
1493                         left = a[i2];
1494                         if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1495                                 if (cost < 0)
1496                                         cost = UNIT - cost;
1497                                 else
1498                                         cost = UNIT + cost;
1499                         }
1500                         diag_inc = diag + cost;
1501                         left_inc = left + UNIT + *((uchar*)s1+i1);
1502                         above_inc = above + UNIT + *((uchar*)s2+i2);
1503                         a[i2] = above = left < above
1504                               ? (left_inc < diag_inc ? left_inc : diag_inc)
1505                               : (above_inc < diag_inc ? above_inc : diag_inc);
1506                         diag = left;
1507                 }
1508         }
1509
1510         return a[len2-1];
1511 }
1512
1513 #define BB_SLOT_SIZE     (16*1024)          /* Desired size in bytes */
1514 #define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1515 #define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1516
1517 struct bitbag {
1518         uint32 **bits;
1519         int slot_cnt;
1520 };
1521
1522 struct bitbag *bitbag_create(int max_ndx)
1523 {
1524         struct bitbag *bb = new(struct bitbag);
1525         bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1526
1527         bb->bits = new_array0(uint32*, bb->slot_cnt);
1528
1529         return bb;
1530 }
1531
1532 void bitbag_set_bit(struct bitbag *bb, int ndx)
1533 {
1534         int slot = ndx / BB_PER_SLOT_BITS;
1535         ndx %= BB_PER_SLOT_BITS;
1536
1537         if (!bb->bits[slot])
1538                 bb->bits[slot] = new_array0(uint32, BB_PER_SLOT_INTS);
1539
1540         bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1541 }
1542
1543 #if 0 /* not needed yet */
1544 void bitbag_clear_bit(struct bitbag *bb, int ndx)
1545 {
1546         int slot = ndx / BB_PER_SLOT_BITS;
1547         ndx %= BB_PER_SLOT_BITS;
1548
1549         if (!bb->bits[slot])
1550                 return;
1551
1552         bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1553 }
1554
1555 int bitbag_check_bit(struct bitbag *bb, int ndx)
1556 {
1557         int slot = ndx / BB_PER_SLOT_BITS;
1558         ndx %= BB_PER_SLOT_BITS;
1559
1560         if (!bb->bits[slot])
1561                 return 0;
1562
1563         return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1564 }
1565 #endif
1566
1567 /* Call this with -1 to start checking from 0.  Returns -1 at the end. */
1568 int bitbag_next_bit(struct bitbag *bb, int after)
1569 {
1570         uint32 bits, mask;
1571         int i, ndx = after + 1;
1572         int slot = ndx / BB_PER_SLOT_BITS;
1573         ndx %= BB_PER_SLOT_BITS;
1574
1575         mask = (1u << (ndx % 32)) - 1;
1576         for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1577                 if (!bb->bits[slot])
1578                         continue;
1579                 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1580                         if (!(bits = bb->bits[slot][i] & ~mask))
1581                                 continue;
1582                         /* The xor magic figures out the lowest enabled bit in
1583                          * bits, and the switch quickly computes log2(bit). */
1584                         switch (bits ^ (bits & (bits-1))) {
1585 #define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1586                             LOG2(0);  LOG2(1);  LOG2(2);  LOG2(3);
1587                             LOG2(4);  LOG2(5);  LOG2(6);  LOG2(7);
1588                             LOG2(8);  LOG2(9);  LOG2(10); LOG2(11);
1589                             LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1590                             LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1591                             LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1592                             LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1593                             LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1594                         }
1595                         return -1; /* impossible... */
1596                 }
1597         }
1598
1599         return -1;
1600 }
1601
1602 void flist_ndx_push(flist_ndx_list *lp, int ndx)
1603 {
1604         struct flist_ndx_item *item;
1605
1606         item = new(struct flist_ndx_item);
1607         item->next = NULL;
1608         item->ndx = ndx;
1609         if (lp->tail)
1610                 lp->tail->next = item;
1611         else
1612                 lp->head = item;
1613         lp->tail = item;
1614 }
1615
1616 int flist_ndx_pop(flist_ndx_list *lp)
1617 {
1618         struct flist_ndx_item *next;
1619         int ndx;
1620
1621         if (!lp->head)
1622                 return -1;
1623
1624         ndx = lp->head->ndx;
1625         next = lp->head->next;
1626         free(lp->head);
1627         lp->head = next;
1628         if (!next)
1629                 lp->tail = NULL;
1630
1631         return ndx;
1632 }
1633
1634 /* Make sure there is room for one more item in the item list.  If there
1635  * is not, expand the list as indicated by the value of "incr":
1636  *  - if incr < 0 then increase the malloced size by -1 * incr
1637  *  - if incr >= 0 then either make the malloced size equal to "incr"
1638  *    or (if that's not large enough) double the malloced size
1639  * After the size check, the list's count is incremented by 1 and a pointer
1640  * to the "new" list item is returned.
1641  */
1642 void *expand_item_list(item_list *lp, size_t item_size, const char *desc, int incr)
1643 {
1644         /* First time through, 0 <= 0, so list is expanded. */
1645         if (lp->malloced <= lp->count) {
1646                 void *new_ptr;
1647                 size_t expand_size;
1648                 if (incr < 0)
1649                         expand_size = -incr; /* increase slowly */
1650                 else if (lp->malloced < (size_t)incr)
1651                         expand_size = incr - lp->malloced;
1652                 else if (lp->malloced)
1653                         expand_size = lp->malloced; /* double in size */
1654                 else
1655                         expand_size = 1;
1656                 if (SIZE_MAX/item_size - expand_size < lp->malloced)
1657                         overflow_exit("expand_item_list");
1658                 expand_size += lp->malloced;
1659                 new_ptr = realloc_buf(lp->items, expand_size * item_size);
1660                 if (DEBUG_GTE(FLIST, 3)) {
1661                         rprintf(FINFO, "[%s] expand %s to %s bytes, did%s move\n",
1662                                 who_am_i(), desc, big_num(expand_size * item_size),
1663                                 new_ptr == lp->items ? " not" : "");
1664                 }
1665
1666                 lp->items = new_ptr;
1667                 lp->malloced = expand_size;
1668         }
1669         return (char*)lp->items + (lp->count++ * item_size);
1670 }
1671
1672 /* This zeroing of memory won't be optimized away by the compiler. */
1673 void force_memzero(void *buf, size_t len)
1674 {
1675         volatile uchar *z = buf;
1676         while (len-- > 0)
1677                 *z++ = '\0';
1678 }