2 Copyright (C) Andrew Tridgell 1996
3 Copyright (C) Paul Mackerras 1996
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 Utilities used in rsync
27 /****************************************************************************
28 Set a fd into nonblocking mode. Uses POSIX O_NONBLOCK if available,
32 ****************************************************************************/
33 int set_nonblocking(int fd)
37 #define FLAG_TO_SET O_NONBLOCK
40 #define FLAG_TO_SET O_NDELAY
42 #define FLAG_TO_SET FNDELAY
46 if((val = fcntl(fd, F_GETFL, 0)) == -1)
49 return fcntl( fd, F_SETFL, val);
54 /* this is taken from CVS */
55 int piped_child(char **command,int *f_in,int *f_out)
59 int from_child_pipe[2];
61 if (pipe(to_child_pipe) < 0 ||
62 pipe(from_child_pipe) < 0) {
63 rprintf(FERROR,"pipe: %s\n",strerror(errno));
70 rprintf(FERROR,"fork: %s\n",strerror(errno));
76 extern int orig_umask;
77 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
78 close(to_child_pipe[1]) < 0 ||
79 close(from_child_pipe[0]) < 0 ||
80 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
81 rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
84 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
85 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
87 execvp(command[0], command);
88 rprintf(FERROR,"Failed to exec %s : %s\n",
89 command[0],strerror(errno));
93 if (close(from_child_pipe[1]) < 0 ||
94 close(to_child_pipe[0]) < 0) {
95 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));
99 *f_in = from_child_pipe[0];
100 *f_out = to_child_pipe[1];
102 set_nonblocking(*f_in);
103 set_nonblocking(*f_out);
108 int local_child(int argc, char **argv,int *f_in,int *f_out)
111 int to_child_pipe[2];
112 int from_child_pipe[2];
114 if (pipe(to_child_pipe) < 0 ||
115 pipe(from_child_pipe) < 0) {
116 rprintf(FERROR,"pipe: %s\n",strerror(errno));
123 rprintf(FERROR,"fork: %s\n",strerror(errno));
128 extern int am_sender;
129 extern int am_server;
131 am_sender = !am_sender;
134 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
135 close(to_child_pipe[1]) < 0 ||
136 close(from_child_pipe[0]) < 0 ||
137 dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
138 rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
141 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
142 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
143 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
146 if (close(from_child_pipe[1]) < 0 ||
147 close(to_child_pipe[0]) < 0) {
148 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));
152 *f_in = from_child_pipe[0];
153 *f_out = to_child_pipe[1];
160 void out_of_memory(char *str)
162 rprintf(FERROR,"ERROR: out of memory in %s\n",str);
166 void overflow(char *str)
168 rprintf(FERROR,"ERROR: buffer overflow in %s\n",str);
174 int set_modtime(char *fname,time_t modtime)
177 if (dry_run) return 0;
181 tbuf.actime = time(NULL);
182 tbuf.modtime = modtime;
183 return utime(fname,&tbuf);
184 #elif defined(HAVE_UTIME)
188 return utime(fname,t);
191 t[0].tv_sec = time(NULL);
193 t[1].tv_sec = modtime;
195 return utimes(fname,t);
201 /****************************************************************************
202 create any necessary directories in fname. Unfortunately we don't know
203 what perms to give the directory when this is called so we need to rely
205 ****************************************************************************/
206 int create_directory_path(char *fname)
208 extern int orig_umask;
211 while (*fname == '/') fname++;
212 while (strncmp(fname,"./",2)==0) fname += 2;
215 while ((p=strchr(p,'/'))) {
217 do_mkdir(fname,0777 & ~orig_umask);
225 /* Write LEN bytes at PTR to descriptor DESC, retrying if interrupted.
226 Return LEN upon success, write's (negative) error code otherwise.
228 derived from GNU C's cccp.c.
230 static int full_write(int desc, char *ptr, int len)
236 int written = write (desc, ptr, len);
244 total_written += written;
248 return total_written;
251 /* Read LEN bytes at PTR from descriptor DESC, retrying if interrupted.
252 Return the actual number of bytes read, zero for EOF, or negative
255 derived from GNU C's cccp.c. */
256 static int safe_read(int desc, char *ptr, int len)
265 n_chars = read(desc, ptr, len);
266 } while (n_chars < 0 && errno == EINTR);
268 n_chars = read(desc, ptr, len);
275 /* copy a file - this is used in conjunction with the --temp-dir option */
276 int copy_file(char *source, char *dest, mode_t mode)
281 int len; /* Number of bytes read into `buf'. */
283 ifd = open(source, O_RDONLY);
285 rprintf(FERROR,"open %s: %s\n",
286 source,strerror(errno));
290 if (do_unlink(dest) && errno != ENOENT) {
291 rprintf(FERROR,"unlink %s: %s\n",
292 dest,strerror(errno));
296 ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
298 rprintf(FERROR,"open %s: %s\n",
299 dest,strerror(errno));
304 while ((len = safe_read(ifd, buf, sizeof(buf))) > 0) {
305 if (full_write(ofd, buf, len) < 0) {
306 rprintf(FERROR,"write %s: %s\n",
307 dest,strerror(errno));
318 rprintf(FERROR,"read %s: %s\n",
319 source,strerror(errno));
326 /* sleep for a while via select */
327 void u_sleep(int usec)
333 select(0, NULL, NULL, NULL, &tv);
337 static pid_t all_pids[10];
340 /* fork and record the pid of the child */
343 pid_t newpid = fork();
346 all_pids[num_pids++] = newpid;
351 /* kill all children */
352 void kill_all(int sig)
355 for (i=0;i<num_pids;i++) {
356 if (all_pids[i] != getpid())
357 kill(all_pids[i], sig);
361 /* like strncpy but does not 0 fill the buffer and always null
362 terminates (thus it can use maxlen+1 space in d) */
363 void strlcpy(char *d, char *s, int maxlen)
366 if (len > maxlen) len = maxlen;
371 /* like strncat but does not 0 fill the buffer and always null
372 terminates (thus it can use maxlen+1 space in d) */
373 void strlcat(char *d, char *s, int maxlen)
375 int len1 = strlen(d);
376 int len2 = strlen(s);
377 if (len1+len2 > maxlen) {
381 memcpy(d+len1, s, len2);
386 /* turn a user name into a uid */
387 int name_to_uid(char *name, uid_t *uid)
390 if (!name || !*name) return 0;
391 pass = getpwnam(name);
399 /* turn a group name into a gid */
400 int name_to_gid(char *name, gid_t *gid)
403 if (!name || !*name) return 0;
404 grp = getgrnam(name);
413 /* lock a byte range in a open file */
414 int lock_range(int fd, int offset, int len)
418 lock.l_type = F_WRLCK;
419 lock.l_whence = SEEK_SET;
420 lock.l_start = offset;
424 return fcntl(fd,F_SETLK,&lock) == 0;
428 static void glob_expand_one(char *s, char **argv, int *argc, int maxargs)
430 #if !(defined(HAVE_GLOB) && defined(HAVE_GLOB_H))
432 argv[*argc] = strdup(s);
441 argv[*argc] = strdup(s);
443 memset(&globbuf, 0, sizeof(globbuf));
444 glob(argv[*argc], 0, NULL, &globbuf);
445 if (globbuf.gl_pathc == 0) {
450 for (i=0; i<(maxargs - (*argc)) && i<globbuf.gl_pathc;i++) {
451 if (i == 0) free(argv[*argc]);
452 argv[(*argc) + i] = strdup(globbuf.gl_pathv[i]);
453 if (!argv[(*argc) + i]) out_of_memory("glob_expand");
460 void glob_expand(char *base1, char **argv, int *argc, int maxargs)
462 char *s = argv[*argc];
466 if (!s || !*s) return;
468 if (strncmp(s, base, strlen(base)) == 0) {
473 if (!s) out_of_memory("glob_expand");
475 base = (char *)malloc(strlen(base1)+3);
476 if (!base) out_of_memory("glob_expand");
478 sprintf(base," %s/", base1);
481 while ((p = strstr(q,base)) && ((*argc) < maxargs)) {
482 /* split it at this point */
484 glob_expand_one(q, argv, argc, maxargs);
488 if (*q && (*argc < maxargs)) glob_expand_one(q, argv, argc, maxargs);
494 /*******************************************************************
495 convert a string to lower case
496 ********************************************************************/
497 void strlower(char *s)
500 if (isupper(*s)) *s = tolower(*s);
505 /* this is like vsnprintf but the 'n' limit does not include
506 the terminating null. So if you have a 1024 byte buffer then
508 int vslprintf(char *str, int n, const char *format, va_list ap)
510 #ifdef HAVE_VSNPRINTF
511 int ret = vsnprintf(str, n, format, ap);
512 if (ret > n || ret < 0) {
520 static int len=MAXPATHLEN*8;
523 /* this code is NOT a proper vsnprintf() implementation. It
524 relies on the fact that all calls to slprintf() in rsync
525 pass strings which have already been checked to be less
526 than MAXPATHLEN in length and never more than 2 strings are
527 concatenated. This means the above buffer is absolutely
528 ample and can never be overflowed.
530 In the future we would like to replace this with a proper
531 vsnprintf() implementation but right now we need a solution
532 that is secure and portable. This is it. */
537 /* can't call debug or we would recurse */
542 vsprintf(buf, format, ap);
550 memcpy(str, buf, ret+1);
557 /* like snprintf but always null terminates */
558 int slprintf(char *str, int n, char *format, ...)
563 va_start(ap, format);
564 ret = vslprintf(str,n,format,ap);
570 void *Realloc(void *p, int size)
572 if (!p) return (void *)malloc(size);
573 return (void *)realloc(p, size);
577 void clean_fname(char *name)
588 if ((p=strstr(name,"/./"))) {
596 if ((p=strstr(name,"//"))) {
604 if (strncmp(p=name,"./",2) == 0) {
612 if (l > 1 && p[l-1] == '/') {
620 static char curr_dir[MAXPATHLEN];
622 /* like chdir() but can be reversed with pop_dir() if save is set. It
623 is also much faster as it remembers where we have been */
624 char *push_dir(char *dir, int save)
626 char *ret = curr_dir;
627 static int initialised;
631 getcwd(curr_dir, sizeof(curr_dir)-1);
634 if (chdir(dir)) return NULL;
637 ret = strdup(curr_dir);
641 strlcpy(curr_dir, dir, sizeof(curr_dir)-1);
643 strlcat(curr_dir,"/", sizeof(curr_dir)-1);
644 strlcat(curr_dir,dir, sizeof(curr_dir)-1);
647 clean_fname(curr_dir);
652 /* reverse a push_dir call */
653 int pop_dir(char *dir)
663 strlcpy(curr_dir, dir, sizeof(curr_dir)-1);
670 /* we need to supply our own strcmp function for file list comparisons
671 to ensure that signed/unsigned usage is consistent between machines. */
672 int u_strcmp(const char *cs1, const char *cs2)
674 const uchar *s1 = (uchar *)cs1;
675 const uchar *s2 = (uchar *)cs2;
677 while (*s1 && *s2 && (*s1 == *s2)) {
681 return (int)*s1 - (int)*s2;
684 static OFF_T last_ofs;
686 void end_progress(void)
688 extern int do_progress, am_server;
690 if (do_progress && !am_server) {
696 void show_progress(OFF_T ofs, OFF_T size)
698 extern int do_progress, am_server;
700 if (do_progress && !am_server) {
701 if (ofs > last_ofs + 1000) {
702 int pct = (int)((100.0*ofs)/size);
703 rprintf(FINFO,"%.0f (%d%%)\r", (double)ofs, pct);
709 /* determine if a symlink points outside the current directory tree */
710 int unsafe_symlink(char *dest, char *src)
715 /* all absolute and null symlinks are unsafe */
716 if (!dest || !(*dest) || (*dest == '/')) return 1;
719 if (!src) out_of_memory("unsafe_symlink");
721 /* find out what our safety margin is */
722 for (tok=strtok(src,"/"); tok; tok=strtok(NULL,"/")) {
723 if (strcmp(tok,"..") == 0) {
725 } else if (strcmp(tok,".") == 0) {
733 /* drop by one to account for the filename portion */
737 if (!dest) out_of_memory("unsafe_symlink");
739 for (tok=strtok(dest,"/"); tok; tok=strtok(NULL,"/")) {
740 if (strcmp(tok,"..") == 0) {
742 } else if (strcmp(tok,".") == 0) {
747 /* if at any point we go outside the current directory then
748 stop - it is unsafe */
749 if (depth < 0) break;
757 * Make path appear as if a chroot had occurred:
758 * 1. remove leading "/" (or replace with "." if at end)
759 * 2. remove leading ".." components
760 * 3. delete any other "<dir>/.." (recursively)
761 * Return a malloc'ed copy.
762 * Contributed by Dave Dykstra <dwd@bell-labs.com>
765 char *sanitize_path(char *p)
769 copy = (char *) malloc(strlen(p)+1);
772 if ((*p == '/') && (copyp == copy)) {
773 /* remove leading slash */
776 else if ((*p == '.') && (*(p+1) == '.') &&
777 ((*(p+2) == '/') || (*(p+2) == '\0'))) {
778 /* remove .. followed by slash or end */
781 /* backup the copy one level */
782 while ((--copyp != copy) && (*copyp == '/'))
783 /* skip trailing slashes */
785 while ((copyp != copy) && (*copyp != '/'))
786 /* skip back through slash */
790 /* copy one component */
793 if ((*p == '\0') || (*(p-1) == '/'))