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