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