1 /* -*- c-file-style: "linux" -*-
3 Copyright (C) 1996-2000 by Andrew Tridgell
4 Copyright (C) Paul Mackerras 1996
5 Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 * Utilities used in rsync
35 Set a fd into nonblocking mode
37 void set_nonblocking(int fd)
41 if((val = fcntl(fd, F_GETFL, 0)) == -1)
43 if (!(val & NONBLOCK_FLAG)) {
45 fcntl(fd, F_SETFL, val);
50 Set a fd into blocking mode
52 void set_blocking(int fd)
56 if((val = fcntl(fd, F_GETFL, 0)) == -1)
58 if (val & NONBLOCK_FLAG) {
59 val &= ~NONBLOCK_FLAG;
60 fcntl(fd, F_SETFL, val);
66 Create a file descriptor pair - like pipe() but use socketpair if
67 possible (because of blocking issues on pipes).
69 Always set non-blocking.
71 int fd_pair(int fd[2])
76 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
82 set_nonblocking(fd[0]);
83 set_nonblocking(fd[1]);
90 static void print_child_argv(char **cmd)
92 rprintf(FINFO, "opening connection using ");
94 /* Look for characters that ought to be quoted. This
95 * is not a great quoting algorithm, but it's
96 * sufficient for a log message. */
97 if (strspn(*cmd, "abcdefghijklmnopqrstuvwxyz"
98 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
100 ",.-_=+@/") != strlen(*cmd)) {
101 rprintf(FINFO, "\"%s\" ", *cmd);
103 rprintf(FINFO, "%s ", *cmd);
106 rprintf(FINFO, "\n");
111 * Create a child connected to use on stdin/stdout.
113 * This is derived from CVS code
115 * Note that in the child STDIN is set to blocking and STDOUT
116 * is set to non-blocking. This is necessary as rsh relies on stdin being blocking
117 * and ssh relies on stdout being non-blocking
119 * If blocking_io is set then use blocking io on both fds. That can be
120 * used to cope with badly broken rsh implementations like the one on
123 pid_t piped_child(char **command, int *f_in, int *f_out)
126 int to_child_pipe[2];
127 int from_child_pipe[2];
128 extern int blocking_io;
131 print_child_argv(command);
134 if (fd_pair(to_child_pipe) < 0 || fd_pair(from_child_pipe) < 0) {
135 rprintf(FERROR, "pipe: %s\n", strerror(errno));
136 exit_cleanup(RERR_IPC);
142 rprintf(FERROR, "fork: %s\n", strerror(errno));
143 exit_cleanup(RERR_IPC);
147 extern int orig_umask;
148 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
149 close(to_child_pipe[1]) < 0 ||
150 close(from_child_pipe[0]) < 0 ||
151 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
152 rprintf(FERROR, "Failed to dup/close : %s\n",
154 exit_cleanup(RERR_IPC);
156 if (to_child_pipe[0] != STDIN_FILENO)
157 close(to_child_pipe[0]);
158 if (from_child_pipe[1] != STDOUT_FILENO)
159 close(from_child_pipe[1]);
161 set_blocking(STDIN_FILENO);
163 set_blocking(STDOUT_FILENO);
165 execvp(command[0], command);
166 rprintf(FERROR, "Failed to exec %s : %s\n",
167 command[0], strerror(errno));
168 exit_cleanup(RERR_IPC);
171 if (close(from_child_pipe[1]) < 0 || close(to_child_pipe[0]) < 0) {
172 rprintf(FERROR, "Failed to close : %s\n", strerror(errno));
173 exit_cleanup(RERR_IPC);
176 *f_in = from_child_pipe[0];
177 *f_out = to_child_pipe[1];
182 pid_t local_child(int argc, char **argv,int *f_in,int *f_out,
183 int (*child_main)(int, char **))
186 int to_child_pipe[2];
187 int from_child_pipe[2];
188 extern int read_batch; /* dw */
190 if (fd_pair(to_child_pipe) < 0 ||
191 fd_pair(from_child_pipe) < 0) {
192 rprintf(FERROR,"pipe: %s\n",strerror(errno));
193 exit_cleanup(RERR_IPC);
199 rprintf(FERROR,"fork: %s\n",strerror(errno));
200 exit_cleanup(RERR_IPC);
204 extern int am_sender;
205 extern int am_server;
207 am_sender = read_batch ? 0 : !am_sender;
210 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
211 close(to_child_pipe[1]) < 0 ||
212 close(from_child_pipe[0]) < 0 ||
213 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
214 rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
215 exit_cleanup(RERR_IPC);
217 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
218 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
219 child_main(argc, argv);
222 if (close(from_child_pipe[1]) < 0 ||
223 close(to_child_pipe[0]) < 0) {
224 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));
225 exit_cleanup(RERR_IPC);
228 *f_in = from_child_pipe[0];
229 *f_out = to_child_pipe[1];
236 void out_of_memory(char *str)
238 rprintf(FERROR,"ERROR: out of memory in %s\n",str);
239 exit_cleanup(RERR_MALLOC);
242 void overflow(char *str)
244 rprintf(FERROR,"ERROR: buffer overflow in %s\n",str);
245 exit_cleanup(RERR_MALLOC);
250 int set_modtime(char *fname, time_t modtime)
257 rprintf(FINFO, "set modtime of %s to (%ld) %s",
258 fname, (long) modtime,
259 asctime(localtime(&modtime)));
265 tbuf.actime = time(NULL);
266 tbuf.modtime = modtime;
267 return utime(fname,&tbuf);
268 #elif defined(HAVE_UTIME)
272 return utime(fname,t);
275 t[0].tv_sec = time(NULL);
277 t[1].tv_sec = modtime;
279 return utimes(fname,t);
286 Create any necessary directories in fname. Unfortunately we don't know
287 what perms to give the directory when this is called so we need to rely
290 int create_directory_path(char *fname)
292 extern int orig_umask;
295 while (*fname == '/') fname++;
296 while (strncmp(fname,"./",2)==0) fname += 2;
299 while ((p=strchr(p,'/'))) {
301 do_mkdir(fname,0777 & ~orig_umask);
310 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
313 * @retval len upon success
315 * @retval <0 write's (negative) error code
317 * Derived from GNU C's cccp.c.
319 static int full_write(int desc, char *ptr, size_t len)
325 int written = write (desc, ptr, len);
333 total_written += written;
337 return total_written;
342 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
345 * @retval >0 the actual number of bytes read
349 * @retval <0 for an error.
351 * Derived from GNU C's cccp.c. */
352 static int safe_read(int desc, char *ptr, size_t len)
361 n_chars = read(desc, ptr, len);
362 } while (n_chars < 0 && errno == EINTR);
364 n_chars = read(desc, ptr, len);
373 * This is used in conjunction with the --temp-dir option */
374 int copy_file(char *source, char *dest, mode_t mode)
379 int len; /* Number of bytes read into `buf'. */
381 ifd = do_open(source, O_RDONLY, 0);
383 rprintf(FERROR,"open %s: %s\n",
384 source,strerror(errno));
388 if (robust_unlink(dest) && errno != ENOENT) {
389 rprintf(FERROR,"unlink %s: %s\n",
390 dest,strerror(errno));
394 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
396 rprintf(FERROR,"open %s: %s\n",
397 dest,strerror(errno));
402 while ((len = safe_read(ifd, buf, sizeof(buf))) > 0) {
403 if (full_write(ofd, buf, len) < 0) {
404 rprintf(FERROR,"write %s: %s\n",
405 dest,strerror(errno));
416 rprintf(FERROR,"read %s: %s\n",
417 source,strerror(errno));
424 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
425 #define MAX_RENAMES_DIGITS 3
426 #define MAX_RENAMES 1000
430 Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
431 rename to <path>/.rsyncNNN instead.
433 Note that successive rsync runs will shuffle the filenames around a
434 bit as long as the file is still busy; this is because this function
435 does not know if the unlink call is due to a new file coming in, or
436 --delete trying to remove old .rsyncNNN files, hence it renames it
439 int robust_unlink(char *fname)
442 return do_unlink(fname);
444 static int counter = 1;
446 char path[MAXPATHLEN];
448 rc = do_unlink(fname);
449 if ((rc == 0) || (errno != ETXTBSY))
452 strlcpy(path, fname, MAXPATHLEN);
455 while((path[--pos] != '/') && (pos >= 0))
458 strlcpy(&path[pos], ".rsync", MAXPATHLEN-pos);
459 pos += sizeof(".rsync")-1;
461 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
466 /* start where the last one left off to reduce chance of clashes */
469 sprintf(&path[pos], "%03d", counter);
470 if (++counter >= MAX_RENAMES)
472 } while (((rc = access(path, 0)) == 0) && (counter != start));
475 rprintf(FINFO,"renaming %s to %s because of text busy\n",
478 /* maybe we should return rename()'s exit status? Nah. */
479 if (do_rename(fname, path) != 0) {
487 int robust_rename(char *from, char *to)
490 return do_rename(from, to);
492 int rc = do_rename(from, to);
493 if ((rc == 0) || (errno != ETXTBSY))
495 if (robust_unlink(to) != 0)
497 return do_rename(from, to);
502 static pid_t all_pids[10];
505 /** Fork and record the pid of the child. **/
508 pid_t newpid = fork();
510 if (newpid != 0 && newpid != -1) {
511 all_pids[num_pids++] = newpid;
519 * @todo It would be kind of nice to make sure that they are actually
520 * all our children before we kill them, because their pids may have
521 * been recycled by some other process. Perhaps when we wait for a
522 * child, we should remove it from this array. Alternatively we could
523 * perhaps use process groups, but I think that would not work on
524 * ancient Unix versions that don't support them.
526 void kill_all(int sig)
530 for (i = 0; i < num_pids; i++) {
531 /* Let's just be a little careful where we
532 * point that gun, hey? See kill(2) for the
533 * magic caused by negative values. */
534 pid_t p = all_pids[i];
546 /** Turn a user name into a uid */
547 int name_to_uid(char *name, uid_t *uid)
550 if (!name || !*name) return 0;
551 pass = getpwnam(name);
559 /** Turn a group name into a gid */
560 int name_to_gid(char *name, gid_t *gid)
563 if (!name || !*name) return 0;
564 grp = getgrnam(name);
573 /** Lock a byte range in a open file */
574 int lock_range(int fd, int offset, int len)
578 lock.l_type = F_WRLCK;
579 lock.l_whence = SEEK_SET;
580 lock.l_start = offset;
584 return fcntl(fd,F_SETLK,&lock) == 0;
588 static void glob_expand_one(char *s, char **argv, int *argc, int maxargs)
590 #if !(defined(HAVE_GLOB) && defined(HAVE_GLOB_H))
592 argv[*argc] = strdup(s);
596 extern int sanitize_paths;
602 argv[*argc] = strdup(s);
603 if (sanitize_paths) {
604 sanitize_path(argv[*argc], NULL);
607 memset(&globbuf, 0, sizeof(globbuf));
608 glob(argv[*argc], 0, NULL, &globbuf);
609 if (globbuf.gl_pathc == 0) {
614 for (i=0; i<(maxargs - (*argc)) && i < (int) globbuf.gl_pathc;i++) {
615 if (i == 0) free(argv[*argc]);
616 argv[(*argc) + i] = strdup(globbuf.gl_pathv[i]);
617 if (!argv[(*argc) + i]) out_of_memory("glob_expand");
624 void glob_expand(char *base1, char **argv, int *argc, int maxargs)
626 char *s = argv[*argc];
630 if (!s || !*s) return;
632 if (strncmp(s, base, strlen(base)) == 0) {
637 if (!s) out_of_memory("glob_expand");
639 if (asprintf(&base," %s/", base1) <= 0) out_of_memory("glob_expand");
642 while ((p = strstr(q,base)) && ((*argc) < maxargs)) {
643 /* split it at this point */
645 glob_expand_one(q, argv, argc, maxargs);
649 if (*q && (*argc < maxargs)) glob_expand_one(q, argv, argc, maxargs);
656 * Convert a string to lower case
658 void strlower(char *s)
661 if (isupper(*s)) *s = tolower(*s);
666 void *Realloc(void *p, int size)
668 if (!p) return (void *)malloc(size);
669 return (void *)realloc(p, size);
673 void clean_fname(char *name)
684 if ((p=strstr(name,"/./"))) {
692 if ((p=strstr(name,"//"))) {
700 if (strncmp(p=name,"./",2) == 0) {
708 if (l > 1 && p[l-1] == '/') {
716 * Make path appear as if a chroot had occurred:
718 * 1. remove leading "/" (or replace with "." if at end)
719 * 2. remove leading ".." components (except those allowed by "reldir")
720 * 3. delete any other "<dir>/.." (recursively)
722 * Can only shrink paths, so sanitizes in place.
724 * While we're at it, remove double slashes and "." components like
725 * clean_fname does(), but DON'T remove a trailing slash because that
726 * is sometimes significant on command line arguments.
728 * If "reldir" is non-null, it is a sanitized directory that the path will be
729 * relative to, so allow as many ".." at the beginning of the path as
730 * there are components in reldir. This is used for symbolic link targets.
731 * If reldir is non-null and the path began with "/", to be completely like
732 * a chroot we should add in depth levels of ".." at the beginning of the
733 * path, but that would blow the assumption that the path doesn't grow and
734 * it is not likely to end up being a valid symlink anyway, so just do
735 * the normal removal of the leading "/" instead.
737 * Contributed by Dave Dykstra <dwd@bell-labs.com>
739 void sanitize_path(char *p, char *reldir)
748 if (*reldir++ == '/') {
756 /* remove leading slashes */
760 /* this loop iterates once per filename component in p.
761 * both p (and sanp if the original had a slash) should
762 * always be left pointing after a slash
764 if ((*p == '.') && ((*(p+1) == '/') || (*(p+1) == '\0'))) {
765 /* skip "." component */
766 while (*++p == '/') {
767 /* skip following slashes */
773 if ((*p == '.') && (*(p+1) == '.') &&
774 ((*(p+2) == '/') || (*(p+2) == '\0'))) {
775 /* ".." component followed by slash or end */
776 if ((depth > 0) && (sanp == start)) {
777 /* allow depth levels of .. at the beginning */
785 /* back up sanp one level */
786 --sanp; /* now pointing at slash */
787 while ((sanp > start) && (*(sanp - 1) != '/')) {
788 /* skip back up to slash */
796 /* copy one component through next slash */
798 if ((*p == '\0') || (*(p-1) == '/')) {
800 /* skip multiple slashes */
807 /* move the virtual beginning to leave the .. alone */
811 if ((sanp == start) && !allowdotdot) {
812 /* ended up with nothing, so put in "." component */
814 * note that the !allowdotdot doesn't prevent this from
815 * happening in all allowed ".." situations, but I didn't
816 * think it was worth putting in an extra variable to ensure
817 * it since an extra "." won't hurt in those situations.
825 static char curr_dir[MAXPATHLEN];
827 /** like chdir() but can be reversed with pop_dir() if save is set. It
828 is also much faster as it remembers where we have been */
829 char *push_dir(char *dir, int save)
831 char *ret = curr_dir;
832 static int initialised;
836 getcwd(curr_dir, sizeof(curr_dir)-1);
839 if (!dir) return NULL; /* this call was probably just to initialize */
841 if (chdir(dir)) return NULL;
844 ret = strdup(curr_dir);
848 strlcpy(curr_dir, dir, sizeof(curr_dir));
850 strlcat(curr_dir,"/", sizeof(curr_dir));
851 strlcat(curr_dir,dir, sizeof(curr_dir));
854 clean_fname(curr_dir);
859 /** Reverse a push_dir call */
860 int pop_dir(char *dir)
870 strlcpy(curr_dir, dir, sizeof(curr_dir));
877 /** We need to supply our own strcmp function for file list comparisons
878 to ensure that signed/unsigned usage is consistent between machines. */
879 int u_strcmp(const char *cs1, const char *cs2)
881 const uchar *s1 = (const uchar *)cs1;
882 const uchar *s2 = (const uchar *)cs2;
884 while (*s1 && *s2 && (*s1 == *s2)) {
888 return (int)*s1 - (int)*s2;
891 static OFF_T last_ofs;
892 static struct timeval print_time;
893 static struct timeval start_time;
894 static OFF_T start_ofs;
896 static unsigned long msdiff(struct timeval *t1, struct timeval *t2)
898 return (t2->tv_sec - t1->tv_sec) * 1000
899 + (t2->tv_usec - t1->tv_usec) / 1000;
904 * @param ofs Current position in file
905 * @param size Total size of file
906 * @param is_last True if this is the last time progress will be
907 * printed for this file, so we should output a newline. (Not
908 * necessarily the same as all bytes being received.)
910 static void rprint_progress(OFF_T ofs, OFF_T size, struct timeval *now,
913 int pct = (ofs == size) ? 100 : (int)((100.0*ofs)/size);
914 unsigned long diff = msdiff(&start_time, now);
915 double rate = diff ? (double) (ofs-start_ofs) * 1000.0 / diff / 1024.0 : 0;
917 /* If we've finished transferring this file, show the time taken;
918 * otherwise show expected time to complete. That's kind of
919 * inconsistent, but people can probably cope. Hopefully we'll
920 * get more consistent and complete progress reporting soon. --
922 double remain = is_last
923 ? (double) diff / 1000.0
924 : rate ? (double) (size-ofs) / rate / 1000.0 : 0.0;
925 int remain_h, remain_m, remain_s;
927 if (rate > 1024*1024) {
928 rate /= 1024.0 * 1024.0;
930 } else if (rate > 1024) {
937 remain_s = (int) remain % 60;
938 remain_m = (int) (remain / 60.0) % 60;
939 remain_h = (int) (remain / 3600.0);
941 rprintf(FINFO, "%12.0f %3d%% %7.2f%s %4d:%02d:%02d%s",
942 (double) ofs, pct, rate, units,
943 remain_h, remain_m, remain_s,
944 is_last ? "\n" : "\r");
947 void end_progress(OFF_T size)
949 extern int do_progress, am_server;
951 if (do_progress && !am_server) {
953 gettimeofday(&now, NULL);
954 rprint_progress(size, size, &now, True);
958 print_time.tv_sec = print_time.tv_usec = 0;
959 start_time.tv_sec = start_time.tv_usec = 0;
962 void show_progress(OFF_T ofs, OFF_T size)
964 extern int do_progress, am_server;
967 gettimeofday(&now, NULL);
969 if (!start_time.tv_sec && !start_time.tv_usec) {
970 start_time.tv_sec = now.tv_sec;
971 start_time.tv_usec = now.tv_usec;
977 && ofs > last_ofs + 1000
978 && msdiff(&print_time, &now) > 250) {
979 rprint_progress(ofs, size, &now, False);
981 print_time.tv_sec = now.tv_sec;
982 print_time.tv_usec = now.tv_usec;
988 * Determine if a symlink points outside the current directory tree.
989 * This is considered "unsafe" because e.g. when mirroring somebody
990 * else's machine it might allow them to establish a symlink to
991 * /etc/passwd, and then read it through a web server.
993 * @param dest Target of the symlink in question.
995 * @param src Top source directory currently applicable. Basically this
996 * is the first parameter to rsync in a simple invocation, but it's
997 * modified by flist.c in slightly complex ways.
999 * @retval True if unsafe
1000 * @retval False is unsafe
1002 int unsafe_symlink(char *dest, char *src)
1007 /* all absolute and null symlinks are unsafe */
1008 if (!dest || !(*dest) || (*dest == '/')) return 1;
1011 if (!src) out_of_memory("unsafe_symlink");
1013 /* find out what our safety margin is */
1014 for (tok=strtok(src,"/"); tok; tok=strtok(NULL,"/")) {
1015 if (strcmp(tok,"..") == 0) {
1017 } else if (strcmp(tok,".") == 0) {
1025 /* drop by one to account for the filename portion */
1028 dest = strdup(dest);
1029 if (!dest) out_of_memory("unsafe_symlink");
1031 for (tok=strtok(dest,"/"); tok; tok=strtok(NULL,"/")) {
1032 if (strcmp(tok,"..") == 0) {
1034 } else if (strcmp(tok,".") == 0) {
1039 /* if at any point we go outside the current directory then
1040 stop - it is unsafe */
1041 if (depth < 0) break;
1050 Return the date and time as a string
1052 char *timestring(time_t t)
1054 static char TimeBuf[200];
1055 struct tm *tm = localtime(&t);
1057 #ifdef HAVE_STRFTIME
1058 strftime(TimeBuf,sizeof(TimeBuf)-1,"%Y/%m/%d %T",tm);
1060 strlcpy(TimeBuf, asctime(tm), sizeof(TimeBuf));
1063 if (TimeBuf[strlen(TimeBuf)-1] == '\n') {
1064 TimeBuf[strlen(TimeBuf)-1] = 0;
1072 * Sleep for a specified number of milliseconds.
1074 * Always returns TRUE. (In the future it might return FALSE if
1080 struct timeval tval,t1,t2;
1082 gettimeofday(&t1, NULL);
1083 gettimeofday(&t2, NULL);
1086 tval.tv_sec = (t-tdiff)/1000;
1087 tval.tv_usec = 1000*((t-tdiff)%1000);
1090 select(0,NULL,NULL, NULL, &tval);
1092 gettimeofday(&t2, NULL);
1093 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1094 (t2.tv_usec - t1.tv_usec)/1000;
1102 * Determine if two file modification times are equivalent (either
1103 * exact or in the modification timestamp window established by
1106 * @retval 0 if the times should be treated as the same
1108 * @retval +1 if the first is later
1110 * @retval -1 if the 2nd is later
1112 int cmp_modtime(time_t file1, time_t file2)
1114 extern int modify_window;
1116 if (file2 > file1) {
1117 if (file2 - file1 <= modify_window) return 0;
1120 if (file1 - file2 <= modify_window) return 0;
1129 This routine is a trick to immediately catch errors when debugging
1130 with insure. A xterm with a gdb is popped up when insure catches
1131 a error. It is Linux specific.
1133 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1139 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'",
1140 getpid(), getpid(), getpid());
1144 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1145 fn = dlsym(h, "_Insure_trap_error");
1148 ret = fn(a1, a2, a3, a4, a5, a6);