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