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