Mention some mount options that can interfere with --link-dest.
[rsync/rsync.git] / util.c
... / ...
CommitLineData
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
26extern int dry_run;
27extern int module_id;
28extern int modify_window;
29extern int relative_paths;
30extern int human_readable;
31extern int preserve_xattrs;
32extern char *module_dir;
33extern unsigned int module_dirlen;
34extern mode_t orig_umask;
35extern char *partial_dir;
36extern struct filter_list_struct daemon_filter_list;
37
38int sanitize_paths = 0;
39
40char curr_dir[MAXPATHLEN];
41unsigned int curr_dir_len;
42int curr_dir_depth; /* This is only set for a sanitizing daemon. */
43
44/* Set a fd into nonblocking mode. */
45void 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. */
58void 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 */
76int 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
94void 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
113NORETURN 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
119NORETURN 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
125int 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(). */
175int 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. */
188int 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 */
221int 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. */
251static 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. */
272int 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 **/
366int 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. */
417int 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 -1;
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
453static pid_t all_pids[10];
454static int num_pids;
455
456/** Fork and record the pid of the child. **/
457pid_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 **/
477void 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 */
497int 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 */
509int 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 */
521int 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
538static inline void call_glob_match(const char *name, int len, int from_glob,
539 char *arg, int abpos, int fbpos);
540
541static struct glob_data {
542 char *arg_buf, *filt_buf, **argv;
543 int absize, fbsize, maxargs, argc;
544} glob;
545
546static 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
594static 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). */
646int 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. */
699void 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 **/
733void 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. */
746size_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. */
768size_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
794int 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 ".". */
815unsigned 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 ".". */
894char *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. */
974int 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 **/
1032char *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
1062static char partial_fname[MAXPATHLEN];
1063
1064char *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. */
1097int 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 return 0;
1116 statret = -1;
1117 }
1118 if (statret < 0 && do_mkdir(dir, 0700) < 0)
1119 return 0;
1120 } else
1121 do_rmdir(dir);
1122 *fn = '/';
1123
1124 return 1;
1125}
1126
1127/**
1128 * Determine if a symlink points outside the current directory tree.
1129 * This is considered "unsafe" because e.g. when mirroring somebody
1130 * else's machine it might allow them to establish a symlink to
1131 * /etc/passwd, and then read it through a web server.
1132 *
1133 * Null symlinks and absolute symlinks are always unsafe.
1134 *
1135 * Basically here we are concerned with symlinks whose target contains
1136 * "..", because this might cause us to walk back up out of the
1137 * transferred directory. We are not allowed to go back up and
1138 * reenter.
1139 *
1140 * @param dest Target of the symlink in question.
1141 *
1142 * @param src Top source directory currently applicable. Basically this
1143 * is the first parameter to rsync in a simple invocation, but it's
1144 * modified by flist.c in slightly complex ways.
1145 *
1146 * @retval True if unsafe
1147 * @retval False is unsafe
1148 *
1149 * @sa t_unsafe.c
1150 **/
1151int unsafe_symlink(const char *dest, const char *src)
1152{
1153 const char *name, *slash;
1154 int depth = 0;
1155
1156 /* all absolute and null symlinks are unsafe */
1157 if (!dest || !*dest || *dest == '/')
1158 return 1;
1159
1160 /* find out what our safety margin is */
1161 for (name = src; (slash = strchr(name, '/')) != 0; name = slash+1) {
1162 if (strncmp(name, "../", 3) == 0) {
1163 depth = 0;
1164 } else if (strncmp(name, "./", 2) == 0) {
1165 /* nothing */
1166 } else {
1167 depth++;
1168 }
1169 }
1170 if (strcmp(name, "..") == 0)
1171 depth = 0;
1172
1173 for (name = dest; (slash = strchr(name, '/')) != 0; name = slash+1) {
1174 if (strncmp(name, "../", 3) == 0) {
1175 /* if at any point we go outside the current directory
1176 then stop - it is unsafe */
1177 if (--depth < 0)
1178 return 1;
1179 } else if (strncmp(name, "./", 2) == 0) {
1180 /* nothing */
1181 } else {
1182 depth++;
1183 }
1184 }
1185 if (strcmp(name, "..") == 0)
1186 depth--;
1187
1188 return (depth < 0);
1189}
1190
1191/* Return the double number as a string. If the --human-readable option was
1192 * specified, we may output the number in K, M, or G units. We use a buffer
1193 * from big_num() to return our result. */
1194char *human_dnum(double dnum, int decimal_digits)
1195{
1196 char *buf = big_num(dnum, human_readable);
1197 int len = strlen(buf);
1198 if (isDigit(buf + len - 1)) {
1199 /* There's extra room in buf prior to the start of the num. */
1200 buf -= decimal_digits + 1;
1201 snprintf(buf, len + decimal_digits + 2, "%.*f", decimal_digits, dnum);
1202 }
1203 return buf;
1204}
1205
1206/* Return the date and time as a string. Some callers tweak returned buf. */
1207char *timestring(time_t t)
1208{
1209 static char TimeBuf[200];
1210 struct tm *tm = localtime(&t);
1211 char *p;
1212
1213#ifdef HAVE_STRFTIME
1214 strftime(TimeBuf, sizeof TimeBuf - 1, "%Y/%m/%d %H:%M:%S", tm);
1215#else
1216 strlcpy(TimeBuf, asctime(tm), sizeof TimeBuf);
1217#endif
1218
1219 if ((p = strchr(TimeBuf, '\n')) != NULL)
1220 *p = '\0';
1221
1222 return TimeBuf;
1223}
1224
1225/**
1226 * Sleep for a specified number of milliseconds.
1227 *
1228 * Always returns TRUE. (In the future it might return FALSE if
1229 * interrupted.)
1230 **/
1231int msleep(int t)
1232{
1233 int tdiff = 0;
1234 struct timeval tval, t1, t2;
1235
1236 gettimeofday(&t1, NULL);
1237
1238 while (tdiff < t) {
1239 tval.tv_sec = (t-tdiff)/1000;
1240 tval.tv_usec = 1000*((t-tdiff)%1000);
1241
1242 errno = 0;
1243 select(0,NULL,NULL, NULL, &tval);
1244
1245 gettimeofday(&t2, NULL);
1246 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1247 (t2.tv_usec - t1.tv_usec)/1000;
1248 }
1249
1250 return True;
1251}
1252
1253/* Determine if two time_t values are equivalent (either exact, or in
1254 * the modification timestamp window established by --modify-window).
1255 *
1256 * @retval 0 if the times should be treated as the same
1257 *
1258 * @retval +1 if the first is later
1259 *
1260 * @retval -1 if the 2nd is later
1261 **/
1262int cmp_time(time_t file1, time_t file2)
1263{
1264 if (file2 > file1) {
1265 if (file2 - file1 <= modify_window)
1266 return 0;
1267 return -1;
1268 }
1269 if (file1 - file2 <= modify_window)
1270 return 0;
1271 return 1;
1272}
1273
1274
1275#ifdef __INSURE__XX
1276#include <dlfcn.h>
1277
1278/**
1279 This routine is a trick to immediately catch errors when debugging
1280 with insure. A xterm with a gdb is popped up when insure catches
1281 a error. It is Linux specific.
1282**/
1283int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1284{
1285 static int (*fn)();
1286 int ret;
1287 char *cmd;
1288
1289 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'",
1290 getpid(), getpid(), getpid());
1291
1292 if (!fn) {
1293 static void *h;
1294 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1295 fn = dlsym(h, "_Insure_trap_error");
1296 }
1297
1298 ret = fn(a1, a2, a3, a4, a5, a6);
1299
1300 system(cmd);
1301
1302 free(cmd);
1303
1304 return ret;
1305}
1306#endif
1307
1308#define MALLOC_MAX 0x40000000
1309
1310void *_new_array(unsigned long num, unsigned int size, int use_calloc)
1311{
1312 if (num >= MALLOC_MAX/size)
1313 return NULL;
1314 return use_calloc ? calloc(num, size) : malloc(num * size);
1315}
1316
1317void *_realloc_array(void *ptr, unsigned int size, size_t num)
1318{
1319 if (num >= MALLOC_MAX/size)
1320 return NULL;
1321 if (!ptr)
1322 return malloc(size * num);
1323 return realloc(ptr, size * num);
1324}
1325
1326/* Take a filename and filename length and return the most significant
1327 * filename suffix we can find. This ignores suffixes such as "~",
1328 * ".bak", ".orig", ".~1~", etc. */
1329const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
1330{
1331 const char *suf, *s;
1332 BOOL had_tilde;
1333 int s_len;
1334
1335 /* One or more dots at the start aren't a suffix. */
1336 while (fn_len && *fn == '.') fn++, fn_len--;
1337
1338 /* Ignore the ~ in a "foo~" filename. */
1339 if (fn_len > 1 && fn[fn_len-1] == '~')
1340 fn_len--, had_tilde = True;
1341 else
1342 had_tilde = False;
1343
1344 /* Assume we don't find an suffix. */
1345 suf = "";
1346 *len_ptr = 0;
1347
1348 /* Find the last significant suffix. */
1349 for (s = fn + fn_len; fn_len > 1; ) {
1350 while (*--s != '.' && s != fn) {}
1351 if (s == fn)
1352 break;
1353 s_len = fn_len - (s - fn);
1354 fn_len = s - fn;
1355 if (s_len == 4) {
1356 if (strcmp(s+1, "bak") == 0
1357 || strcmp(s+1, "old") == 0)
1358 continue;
1359 } else if (s_len == 5) {
1360 if (strcmp(s+1, "orig") == 0)
1361 continue;
1362 } else if (s_len > 2 && had_tilde
1363 && s[1] == '~' && isDigit(s + 2))
1364 continue;
1365 *len_ptr = s_len;
1366 suf = s;
1367 if (s_len == 1)
1368 break;
1369 /* Determine if the suffix is all digits. */
1370 for (s++, s_len--; s_len > 0; s++, s_len--) {
1371 if (!isDigit(s))
1372 return suf;
1373 }
1374 /* An all-digit suffix may not be that signficant. */
1375 s = suf;
1376 }
1377
1378 return suf;
1379}
1380
1381/* This is an implementation of the Levenshtein distance algorithm. It
1382 * was implemented to avoid needing a two-dimensional matrix (to save
1383 * memory). It was also tweaked to try to factor in the ASCII distance
1384 * between changed characters as a minor distance quantity. The normal
1385 * Levenshtein units of distance (each signifying a single change between
1386 * the two strings) are defined as a "UNIT". */
1387
1388#define UNIT (1 << 16)
1389
1390uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
1391{
1392 uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
1393 int32 cost;
1394 int i1, i2;
1395
1396 if (!len1 || !len2) {
1397 if (!len1) {
1398 s1 = s2;
1399 len1 = len2;
1400 }
1401 for (i1 = 0, cost = 0; i1 < len1; i1++)
1402 cost += s1[i1];
1403 return (int32)len1 * UNIT + cost;
1404 }
1405
1406 for (i2 = 0; i2 < len2; i2++)
1407 a[i2] = (i2+1) * UNIT;
1408
1409 for (i1 = 0; i1 < len1; i1++) {
1410 diag = i1 * UNIT;
1411 above = (i1+1) * UNIT;
1412 for (i2 = 0; i2 < len2; i2++) {
1413 left = a[i2];
1414 if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
1415 if (cost < 0)
1416 cost = UNIT - cost;
1417 else
1418 cost = UNIT + cost;
1419 }
1420 diag_inc = diag + cost;
1421 left_inc = left + UNIT + *((uchar*)s1+i1);
1422 above_inc = above + UNIT + *((uchar*)s2+i2);
1423 a[i2] = above = left < above
1424 ? (left_inc < diag_inc ? left_inc : diag_inc)
1425 : (above_inc < diag_inc ? above_inc : diag_inc);
1426 diag = left;
1427 }
1428 }
1429
1430 return a[len2-1];
1431}
1432
1433#define BB_SLOT_SIZE (16*1024) /* Desired size in bytes */
1434#define BB_PER_SLOT_BITS (BB_SLOT_SIZE * 8) /* Number of bits per slot */
1435#define BB_PER_SLOT_INTS (BB_SLOT_SIZE / 4) /* Number of int32s per slot */
1436
1437struct bitbag {
1438 uint32 **bits;
1439 int slot_cnt;
1440};
1441
1442struct bitbag *bitbag_create(int max_ndx)
1443{
1444 struct bitbag *bb = new(struct bitbag);
1445 bb->slot_cnt = (max_ndx + BB_PER_SLOT_BITS - 1) / BB_PER_SLOT_BITS;
1446
1447 if (!(bb->bits = (uint32**)calloc(bb->slot_cnt, sizeof (uint32*))))
1448 out_of_memory("bitbag_create");
1449
1450 return bb;
1451}
1452
1453void bitbag_set_bit(struct bitbag *bb, int ndx)
1454{
1455 int slot = ndx / BB_PER_SLOT_BITS;
1456 ndx %= BB_PER_SLOT_BITS;
1457
1458 if (!bb->bits[slot]) {
1459 if (!(bb->bits[slot] = (uint32*)calloc(BB_PER_SLOT_INTS, 4)))
1460 out_of_memory("bitbag_set_bit");
1461 }
1462
1463 bb->bits[slot][ndx/32] |= 1u << (ndx % 32);
1464}
1465
1466#if 0 /* not needed yet */
1467void bitbag_clear_bit(struct bitbag *bb, int ndx)
1468{
1469 int slot = ndx / BB_PER_SLOT_BITS;
1470 ndx %= BB_PER_SLOT_BITS;
1471
1472 if (!bb->bits[slot])
1473 return;
1474
1475 bb->bits[slot][ndx/32] &= ~(1u << (ndx % 32));
1476}
1477
1478int bitbag_check_bit(struct bitbag *bb, int ndx)
1479{
1480 int slot = ndx / BB_PER_SLOT_BITS;
1481 ndx %= BB_PER_SLOT_BITS;
1482
1483 if (!bb->bits[slot])
1484 return 0;
1485
1486 return bb->bits[slot][ndx/32] & (1u << (ndx % 32)) ? 1 : 0;
1487}
1488#endif
1489
1490/* Call this with -1 to start checking from 0. Returns -1 at the end. */
1491int bitbag_next_bit(struct bitbag *bb, int after)
1492{
1493 uint32 bits, mask;
1494 int i, ndx = after + 1;
1495 int slot = ndx / BB_PER_SLOT_BITS;
1496 ndx %= BB_PER_SLOT_BITS;
1497
1498 mask = (1u << (ndx % 32)) - 1;
1499 for (i = ndx / 32; slot < bb->slot_cnt; slot++, i = mask = 0) {
1500 if (!bb->bits[slot])
1501 continue;
1502 for ( ; i < BB_PER_SLOT_INTS; i++, mask = 0) {
1503 if (!(bits = bb->bits[slot][i] & ~mask))
1504 continue;
1505 /* The xor magic figures out the lowest enabled bit in
1506 * bits, and the switch quickly computes log2(bit). */
1507 switch (bits ^ (bits & (bits-1))) {
1508#define LOG2(n) case 1u << n: return slot*BB_PER_SLOT_BITS + i*32 + n
1509 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
1510 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
1511 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
1512 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
1513 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
1514 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
1515 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
1516 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
1517 }
1518 return -1; /* impossible... */
1519 }
1520 }
1521
1522 return -1;
1523}
1524
1525void *expand_item_list(item_list *lp, size_t item_size,
1526 const char *desc, int incr)
1527{
1528 /* First time through, 0 <= 0, so list is expanded. */
1529 if (lp->malloced <= lp->count) {
1530 void *new_ptr;
1531 size_t new_size = lp->malloced;
1532 if (incr < 0)
1533 new_size += -incr; /* increase slowly */
1534 else if (new_size < (size_t)incr)
1535 new_size += incr;
1536 else
1537 new_size *= 2;
1538 if (new_size < lp->malloced)
1539 overflow_exit("expand_item_list");
1540 /* Using _realloc_array() lets us pass the size, not a type. */
1541 new_ptr = _realloc_array(lp->items, item_size, new_size);
1542 if (DEBUG_GTE(FLIST, 3)) {
1543 rprintf(FINFO, "[%s] expand %s to %s bytes, did%s move\n",
1544 who_am_i(), desc, big_num(new_size * item_size, 0),
1545 new_ptr == lp->items ? " not" : "");
1546 }
1547 if (!new_ptr)
1548 out_of_memory("expand_item_list");
1549
1550 lp->items = new_ptr;
1551 lp->malloced = new_size;
1552 }
1553 return (char*)lp->items + (lp->count++ * item_size);
1554}