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)
185 int to_child_pipe[2];
186 int from_child_pipe[2];
187 extern int read_batch; /* dw */
189 if (fd_pair(to_child_pipe) < 0 ||
190 fd_pair(from_child_pipe) < 0) {
191 rprintf(FERROR,"pipe: %s\n",strerror(errno));
192 exit_cleanup(RERR_IPC);
198 rprintf(FERROR,"fork: %s\n",strerror(errno));
199 exit_cleanup(RERR_IPC);
203 extern int am_sender;
204 extern int am_server;
206 am_sender = read_batch ? 0 : !am_sender;
209 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
210 close(to_child_pipe[1]) < 0 ||
211 close(from_child_pipe[0]) < 0 ||
212 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
213 rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
214 exit_cleanup(RERR_IPC);
216 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
217 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
218 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
221 if (close(from_child_pipe[1]) < 0 ||
222 close(to_child_pipe[0]) < 0) {
223 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));
224 exit_cleanup(RERR_IPC);
227 *f_in = from_child_pipe[0];
228 *f_out = to_child_pipe[1];
235 void out_of_memory(char *str)
237 rprintf(FERROR,"ERROR: out of memory in %s\n",str);
238 exit_cleanup(RERR_MALLOC);
241 void overflow(char *str)
243 rprintf(FERROR,"ERROR: buffer overflow in %s\n",str);
244 exit_cleanup(RERR_MALLOC);
249 int set_modtime(char *fname, time_t modtime)
256 rprintf(FINFO, "set modtime of %s to (%ld) %s",
257 fname, (long) modtime,
258 asctime(localtime(&modtime)));
264 tbuf.actime = time(NULL);
265 tbuf.modtime = modtime;
266 return utime(fname,&tbuf);
267 #elif defined(HAVE_UTIME)
271 return utime(fname,t);
274 t[0].tv_sec = time(NULL);
276 t[1].tv_sec = modtime;
278 return utimes(fname,t);
285 Create any necessary directories in fname. Unfortunately we don't know
286 what perms to give the directory when this is called so we need to rely
289 int create_directory_path(char *fname)
291 extern int orig_umask;
294 while (*fname == '/') fname++;
295 while (strncmp(fname,"./",2)==0) fname += 2;
298 while ((p=strchr(p,'/'))) {
300 do_mkdir(fname,0777 & ~orig_umask);
309 * Write @p len bytes at @p ptr to descriptor @p desc, retrying if
312 * @retval len upon success
314 * @retval <0 write's (negative) error code
316 * Derived from GNU C's cccp.c.
318 static int full_write(int desc, char *ptr, size_t len)
324 int written = write (desc, ptr, len);
332 total_written += written;
336 return total_written;
341 * Read @p len bytes at @p ptr from descriptor @p desc, retrying if
344 * @retval >0 the actual number of bytes read
348 * @retval <0 for an error.
350 * Derived from GNU C's cccp.c. */
351 static int safe_read(int desc, char *ptr, size_t len)
360 n_chars = read(desc, ptr, len);
361 } while (n_chars < 0 && errno == EINTR);
363 n_chars = read(desc, ptr, len);
372 * This is used in conjunction with the --temp-dir option */
373 int copy_file(char *source, char *dest, mode_t mode)
378 int len; /* Number of bytes read into `buf'. */
380 ifd = do_open(source, O_RDONLY, 0);
382 rprintf(FERROR,"open %s: %s\n",
383 source,strerror(errno));
387 if (robust_unlink(dest) && errno != ENOENT) {
388 rprintf(FERROR,"unlink %s: %s\n",
389 dest,strerror(errno));
393 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
395 rprintf(FERROR,"open %s: %s\n",
396 dest,strerror(errno));
401 while ((len = safe_read(ifd, buf, sizeof(buf))) > 0) {
402 if (full_write(ofd, buf, len) < 0) {
403 rprintf(FERROR,"write %s: %s\n",
404 dest,strerror(errno));
415 rprintf(FERROR,"read %s: %s\n",
416 source,strerror(errno));
423 /* MAX_RENAMES should be 10**MAX_RENAMES_DIGITS */
424 #define MAX_RENAMES_DIGITS 3
425 #define MAX_RENAMES 1000
429 Robust unlink: some OS'es (HPUX) refuse to unlink busy files, so
430 rename to <path>/.rsyncNNN instead.
432 Note that successive rsync runs will shuffle the filenames around a
433 bit as long as the file is still busy; this is because this function
434 does not know if the unlink call is due to a new file coming in, or
435 --delete trying to remove old .rsyncNNN files, hence it renames it
438 int robust_unlink(char *fname)
441 return do_unlink(fname);
443 static int counter = 1;
445 char path[MAXPATHLEN];
447 rc = do_unlink(fname);
448 if ((rc == 0) || (errno != ETXTBSY))
451 strlcpy(path, fname, MAXPATHLEN);
454 while((path[--pos] != '/') && (pos >= 0))
457 strlcpy(&path[pos], ".rsync", MAXPATHLEN-pos);
458 pos += sizeof(".rsync")-1;
460 if (pos > (MAXPATHLEN-MAX_RENAMES_DIGITS-1)) {
465 /* start where the last one left off to reduce chance of clashes */
468 sprintf(&path[pos], "%03d", counter);
469 if (++counter >= MAX_RENAMES)
471 } while (((rc = access(path, 0)) == 0) && (counter != start));
474 rprintf(FINFO,"renaming %s to %s because of text busy\n",
477 /* maybe we should return rename()'s exit status? Nah. */
478 if (do_rename(fname, path) != 0) {
486 int robust_rename(char *from, char *to)
489 return do_rename(from, to);
491 int rc = do_rename(from, to);
492 if ((rc == 0) || (errno != ETXTBSY))
494 if (robust_unlink(to) != 0)
496 return do_rename(from, to);
501 static pid_t all_pids[10];
504 /** Fork and record the pid of the child. **/
507 pid_t newpid = fork();
509 if (newpid != 0 && newpid != -1) {
510 all_pids[num_pids++] = newpid;
518 * @todo It would be kind of nice to make sure that they are actually
519 * all our children before we kill them, because their pids may have
520 * been recycled by some other process. Perhaps when we wait for a
521 * child, we should remove it from this array. Alternatively we could
522 * perhaps use process groups, but I think that would not work on
523 * ancient Unix versions that don't support them.
525 void kill_all(int sig)
529 for (i = 0; i < num_pids; i++) {
530 /* Let's just be a little careful where we
531 * point that gun, hey? See kill(2) for the
532 * magic caused by negative values. */
533 pid_t p = all_pids[i];
545 /** Turn a user name into a uid */
546 int name_to_uid(char *name, uid_t *uid)
549 if (!name || !*name) return 0;
550 pass = getpwnam(name);
558 /** Turn a group name into a gid */
559 int name_to_gid(char *name, gid_t *gid)
562 if (!name || !*name) return 0;
563 grp = getgrnam(name);
572 /** Lock a byte range in a open file */
573 int lock_range(int fd, int offset, int len)
577 lock.l_type = F_WRLCK;
578 lock.l_whence = SEEK_SET;
579 lock.l_start = offset;
583 return fcntl(fd,F_SETLK,&lock) == 0;
587 static void glob_expand_one(char *s, char **argv, int *argc, int maxargs)
589 #if !(defined(HAVE_GLOB) && defined(HAVE_GLOB_H))
591 argv[*argc] = strdup(s);
595 extern int sanitize_paths;
601 argv[*argc] = strdup(s);
602 if (sanitize_paths) {
603 sanitize_path(argv[*argc], NULL);
606 memset(&globbuf, 0, sizeof(globbuf));
607 glob(argv[*argc], 0, NULL, &globbuf);
608 if (globbuf.gl_pathc == 0) {
613 for (i=0; i<(maxargs - (*argc)) && i < (int) globbuf.gl_pathc;i++) {
614 if (i == 0) free(argv[*argc]);
615 argv[(*argc) + i] = strdup(globbuf.gl_pathv[i]);
616 if (!argv[(*argc) + i]) out_of_memory("glob_expand");
623 void glob_expand(char *base1, char **argv, int *argc, int maxargs)
625 char *s = argv[*argc];
629 if (!s || !*s) return;
631 if (strncmp(s, base, strlen(base)) == 0) {
636 if (!s) out_of_memory("glob_expand");
638 if (asprintf(&base," %s/", base1) <= 0) out_of_memory("glob_expand");
641 while ((p = strstr(q,base)) && ((*argc) < maxargs)) {
642 /* split it at this point */
644 glob_expand_one(q, argv, argc, maxargs);
648 if (*q && (*argc < maxargs)) glob_expand_one(q, argv, argc, maxargs);
655 * Convert a string to lower case
657 void strlower(char *s)
660 if (isupper(*s)) *s = tolower(*s);
665 void *Realloc(void *p, int size)
667 if (!p) return (void *)malloc(size);
668 return (void *)realloc(p, size);
672 void clean_fname(char *name)
683 if ((p=strstr(name,"/./"))) {
691 if ((p=strstr(name,"//"))) {
699 if (strncmp(p=name,"./",2) == 0) {
707 if (l > 1 && p[l-1] == '/') {
715 * Make path appear as if a chroot had occurred:
717 * 1. remove leading "/" (or replace with "." if at end)
718 * 2. remove leading ".." components (except those allowed by "reldir")
719 * 3. delete any other "<dir>/.." (recursively)
721 * Can only shrink paths, so sanitizes in place.
723 * While we're at it, remove double slashes and "." components like
724 * clean_fname does(), but DON'T remove a trailing slash because that
725 * is sometimes significant on command line arguments.
727 * If "reldir" is non-null, it is a sanitized directory that the path will be
728 * relative to, so allow as many ".." at the beginning of the path as
729 * there are components in reldir. This is used for symbolic link targets.
730 * If reldir is non-null and the path began with "/", to be completely like
731 * a chroot we should add in depth levels of ".." at the beginning of the
732 * path, but that would blow the assumption that the path doesn't grow and
733 * it is not likely to end up being a valid symlink anyway, so just do
734 * the normal removal of the leading "/" instead.
736 * Contributed by Dave Dykstra <dwd@bell-labs.com>
738 void sanitize_path(char *p, char *reldir)
747 if (*reldir++ == '/') {
755 /* remove leading slashes */
759 /* this loop iterates once per filename component in p.
760 * both p (and sanp if the original had a slash) should
761 * always be left pointing after a slash
763 if ((*p == '.') && ((*(p+1) == '/') || (*(p+1) == '\0'))) {
764 /* skip "." component */
765 while (*++p == '/') {
766 /* skip following slashes */
772 if ((*p == '.') && (*(p+1) == '.') &&
773 ((*(p+2) == '/') || (*(p+2) == '\0'))) {
774 /* ".." component followed by slash or end */
775 if ((depth > 0) && (sanp == start)) {
776 /* allow depth levels of .. at the beginning */
784 /* back up sanp one level */
785 --sanp; /* now pointing at slash */
786 while ((sanp > start) && (*(sanp - 1) != '/')) {
787 /* skip back up to slash */
795 /* copy one component through next slash */
797 if ((*p == '\0') || (*(p-1) == '/')) {
799 /* skip multiple slashes */
806 /* move the virtual beginning to leave the .. alone */
810 if ((sanp == start) && !allowdotdot) {
811 /* ended up with nothing, so put in "." component */
813 * note that the !allowdotdot doesn't prevent this from
814 * happening in all allowed ".." situations, but I didn't
815 * think it was worth putting in an extra variable to ensure
816 * it since an extra "." won't hurt in those situations.
824 static char curr_dir[MAXPATHLEN];
826 /** like chdir() but can be reversed with pop_dir() if save is set. It
827 is also much faster as it remembers where we have been */
828 char *push_dir(char *dir, int save)
830 char *ret = curr_dir;
831 static int initialised;
835 getcwd(curr_dir, sizeof(curr_dir)-1);
838 if (!dir) return NULL; /* this call was probably just to initialize */
840 if (chdir(dir)) return NULL;
843 ret = strdup(curr_dir);
847 strlcpy(curr_dir, dir, sizeof(curr_dir));
849 strlcat(curr_dir,"/", sizeof(curr_dir));
850 strlcat(curr_dir,dir, sizeof(curr_dir));
853 clean_fname(curr_dir);
858 /** Reverse a push_dir call */
859 int pop_dir(char *dir)
869 strlcpy(curr_dir, dir, sizeof(curr_dir));
876 /** We need to supply our own strcmp function for file list comparisons
877 to ensure that signed/unsigned usage is consistent between machines. */
878 int u_strcmp(const char *cs1, const char *cs2)
880 const uchar *s1 = (const uchar *)cs1;
881 const uchar *s2 = (const uchar *)cs2;
883 while (*s1 && *s2 && (*s1 == *s2)) {
887 return (int)*s1 - (int)*s2;
890 static OFF_T last_ofs;
891 static struct timeval print_time;
892 static struct timeval start_time;
893 static OFF_T start_ofs;
895 static unsigned long msdiff(struct timeval *t1, struct timeval *t2)
897 return (t2->tv_sec - t1->tv_sec) * 1000
898 + (t2->tv_usec - t1->tv_usec) / 1000;
903 * @param ofs Current position in file
904 * @param size Total size of file
905 * @param is_last True if this is the last time progress will be
906 * printed for this file, so we should output a newline. (Not
907 * necessarily the same as all bytes being received.)
909 static void rprint_progress(OFF_T ofs, OFF_T size, struct timeval *now,
912 int pct = (ofs == size) ? 100 : (int)((100.0*ofs)/size);
913 unsigned long diff = msdiff(&start_time, now);
914 double rate = diff ? (double) (ofs-start_ofs) * 1000.0 / diff / 1024.0 : 0;
916 /* If we've finished transferring this file, show the time taken;
917 * otherwise show expected time to complete. That's kind of
918 * inconsistent, but people can probably cope. Hopefully we'll
919 * get more consistent and complete progress reporting soon. --
921 double remain = is_last
922 ? (double) diff / 1000.0
923 : rate ? (double) (size-ofs) / rate / 1000.0 : 0.0;
924 int remain_h, remain_m, remain_s;
926 if (rate > 1024*1024) {
927 rate /= 1024.0 * 1024.0;
929 } else if (rate > 1024) {
936 remain_s = (int) remain % 60;
937 remain_m = (int) (remain / 60.0) % 60;
938 remain_h = (int) (remain / 3600.0);
940 rprintf(FINFO, "%12.0f %3d%% %7.2f%s %4d:%02d:%02d%s",
941 (double) ofs, pct, rate, units,
942 remain_h, remain_m, remain_s,
943 is_last ? "\n" : "\r");
946 void end_progress(OFF_T size)
948 extern int do_progress, am_server;
950 if (do_progress && !am_server) {
952 gettimeofday(&now, NULL);
953 rprint_progress(size, size, &now, True);
957 print_time.tv_sec = print_time.tv_usec = 0;
958 start_time.tv_sec = start_time.tv_usec = 0;
961 void show_progress(OFF_T ofs, OFF_T size)
963 extern int do_progress, am_server;
966 gettimeofday(&now, NULL);
968 if (!start_time.tv_sec && !start_time.tv_usec) {
969 start_time.tv_sec = now.tv_sec;
970 start_time.tv_usec = now.tv_usec;
976 && ofs > last_ofs + 1000
977 && msdiff(&print_time, &now) > 250) {
978 rprint_progress(ofs, size, &now, False);
980 print_time.tv_sec = now.tv_sec;
981 print_time.tv_usec = now.tv_usec;
987 * Determine if a symlink points outside the current directory tree.
989 int unsafe_symlink(char *dest, char *src)
994 /* all absolute and null symlinks are unsafe */
995 if (!dest || !(*dest) || (*dest == '/')) return 1;
998 if (!src) out_of_memory("unsafe_symlink");
1000 /* find out what our safety margin is */
1001 for (tok=strtok(src,"/"); tok; tok=strtok(NULL,"/")) {
1002 if (strcmp(tok,"..") == 0) {
1004 } else if (strcmp(tok,".") == 0) {
1012 /* drop by one to account for the filename portion */
1015 dest = strdup(dest);
1016 if (!dest) out_of_memory("unsafe_symlink");
1018 for (tok=strtok(dest,"/"); tok; tok=strtok(NULL,"/")) {
1019 if (strcmp(tok,"..") == 0) {
1021 } else if (strcmp(tok,".") == 0) {
1026 /* if at any point we go outside the current directory then
1027 stop - it is unsafe */
1028 if (depth < 0) break;
1037 Return the date and time as a string
1039 char *timestring(time_t t)
1041 static char TimeBuf[200];
1042 struct tm *tm = localtime(&t);
1044 #ifdef HAVE_STRFTIME
1045 strftime(TimeBuf,sizeof(TimeBuf)-1,"%Y/%m/%d %T",tm);
1047 strlcpy(TimeBuf, asctime(tm), sizeof(TimeBuf));
1050 if (TimeBuf[strlen(TimeBuf)-1] == '\n') {
1051 TimeBuf[strlen(TimeBuf)-1] = 0;
1059 * Sleep for a specified number of milliseconds.
1061 * Always returns TRUE. (In the future it might return FALSE if
1067 struct timeval tval,t1,t2;
1069 gettimeofday(&t1, NULL);
1070 gettimeofday(&t2, NULL);
1073 tval.tv_sec = (t-tdiff)/1000;
1074 tval.tv_usec = 1000*((t-tdiff)%1000);
1077 select(0,NULL,NULL, NULL, &tval);
1079 gettimeofday(&t2, NULL);
1080 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
1081 (t2.tv_usec - t1.tv_usec)/1000;
1089 * Determine if two file modification times are equivalent (either
1090 * exact or in the modification timestamp window established by
1093 * @retval 0 if the times should be treated as the same
1095 * @retval +1 if the first is later
1097 * @retval -1 if the 2nd is later
1099 int cmp_modtime(time_t file1, time_t file2)
1101 extern int modify_window;
1103 if (file2 > file1) {
1104 if (file2 - file1 <= modify_window) return 0;
1107 if (file1 - file2 <= modify_window) return 0;
1116 This routine is a trick to immediately catch errors when debugging
1117 with insure. A xterm with a gdb is popped up when insure catches
1118 a error. It is Linux specific.
1120 int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
1126 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'",
1127 getpid(), getpid(), getpid());
1131 h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
1132 fn = dlsym(h, "_Insure_trap_error");
1135 ret = fn(a1, a2, a3, a4, a5, a6);