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