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