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