added the --safe-links option to disallow symlinks outside the
[rsync/rsync.git] / util.c
1 /* 
2    Copyright (C) Andrew Tridgell 1996
3    Copyright (C) Paul Mackerras 1996
4    
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.
9    
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.
14    
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.
18 */
19
20 /*
21   Utilities used in rsync 
22
23   tridge, June 1996
24   */
25 #include "rsync.h"
26
27 /****************************************************************************
28 Set a fd into nonblocking mode. Uses POSIX O_NONBLOCK if available,
29 else
30 if SYSV use O_NDELAY
31 if BSD use FNDELAY
32 ****************************************************************************/
33 int set_nonblocking(int fd)
34 {
35         int val;
36 #ifdef O_NONBLOCK
37 #define FLAG_TO_SET O_NONBLOCK
38 #else
39 #ifdef SYSV
40 #define FLAG_TO_SET O_NDELAY
41 #else /* BSD */
42 #define FLAG_TO_SET FNDELAY
43 #endif
44 #endif
45         
46         if((val = fcntl(fd, F_GETFL, 0)) == -1)
47                 return -1;
48         val |= FLAG_TO_SET;
49         return fcntl( fd, F_SETFL, val);
50 #undef FLAG_TO_SET
51 }
52
53
54 /* this is taken from CVS */
55 int piped_child(char **command,int *f_in,int *f_out)
56 {
57   int pid;
58   int to_child_pipe[2];
59   int from_child_pipe[2];
60
61   if (pipe(to_child_pipe) < 0 ||
62       pipe(from_child_pipe) < 0) {
63     rprintf(FERROR,"pipe: %s\n",strerror(errno));
64     exit_cleanup(1);
65   }
66
67
68   pid = do_fork();
69   if (pid < 0) {
70     rprintf(FERROR,"fork: %s\n",strerror(errno));
71     exit_cleanup(1);
72   }
73
74   if (pid == 0)
75     {
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));
82         exit_cleanup(1);
83       }
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]);
86       umask(orig_umask);
87       execvp(command[0], command);
88       rprintf(FERROR,"Failed to exec %s : %s\n",
89               command[0],strerror(errno));
90       exit_cleanup(1);
91     }
92
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));   
96     exit_cleanup(1);
97   }
98
99   *f_in = from_child_pipe[0];
100   *f_out = to_child_pipe[1];
101   
102   return pid;
103 }
104
105 int local_child(int argc, char **argv,int *f_in,int *f_out)
106 {
107         int pid;
108         int to_child_pipe[2];
109         int from_child_pipe[2];
110
111         if (pipe(to_child_pipe) < 0 ||
112             pipe(from_child_pipe) < 0) {
113                 rprintf(FERROR,"pipe: %s\n",strerror(errno));
114                 exit_cleanup(1);
115         }
116
117
118         pid = do_fork();
119         if (pid < 0) {
120                 rprintf(FERROR,"fork: %s\n",strerror(errno));
121                 exit_cleanup(1);
122         }
123
124         if (pid == 0) {
125                 extern int am_sender;
126                 extern int am_server;
127
128                 am_sender = !am_sender;
129                 am_server = 1;          
130
131                 if (dup2(to_child_pipe[0], STDIN_FILENO) < 0 ||
132                     close(to_child_pipe[1]) < 0 ||
133                     close(from_child_pipe[0]) < 0 ||
134                     dup2(from_child_pipe[1], STDOUT_FILENO) < 0) {
135                         rprintf(FERROR,"Failed to dup/close : %s\n",strerror(errno));
136                         exit_cleanup(1);
137                 }
138                 if (to_child_pipe[0] != STDIN_FILENO) close(to_child_pipe[0]);
139                 if (from_child_pipe[1] != STDOUT_FILENO) close(from_child_pipe[1]);
140                 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
141         }
142
143         if (close(from_child_pipe[1]) < 0 ||
144             close(to_child_pipe[0]) < 0) {
145                 rprintf(FERROR,"Failed to close : %s\n",strerror(errno));   
146                 exit_cleanup(1);
147         }
148
149         *f_in = from_child_pipe[0];
150         *f_out = to_child_pipe[1];
151   
152         return pid;
153 }
154
155
156
157 void out_of_memory(char *str)
158 {
159   rprintf(FERROR,"ERROR: out of memory in %s\n",str);
160   exit_cleanup(1);
161 }
162
163 void overflow(char *str)
164 {
165   rprintf(FERROR,"ERROR: buffer overflow in %s\n",str);
166   exit_cleanup(1);
167 }
168
169
170
171 int set_modtime(char *fname,time_t modtime)
172 {
173         extern int dry_run;
174         if (dry_run) return 0;
175         {
176 #ifdef HAVE_UTIMBUF
177                 struct utimbuf tbuf;  
178                 tbuf.actime = time(NULL);
179                 tbuf.modtime = modtime;
180                 return utime(fname,&tbuf);
181 #elif defined(HAVE_UTIME)
182                 time_t t[2];
183                 t[0] = time(NULL);
184                 t[1] = modtime;
185                 return utime(fname,t);
186 #else
187                 struct timeval t[2];
188                 t[0].tv_sec = time(NULL);
189                 t[0].tv_usec = 0;
190                 t[1].tv_sec = modtime;
191                 t[1].tv_usec = 0;
192                 return utimes(fname,t);
193 #endif
194         }
195 }
196
197
198 /****************************************************************************
199 create any necessary directories in fname. Unfortunately we don't know
200 what perms to give the directory when this is called so we need to rely
201 on the umask
202 ****************************************************************************/
203 int create_directory_path(char *fname)
204 {
205         extern int orig_umask;
206         char *p;
207
208         while (*fname == '/') fname++;
209         while (strncmp(fname,"./",2)==0) fname += 2;
210
211         p = fname;
212         while ((p=strchr(p,'/'))) {
213                 *p = 0;
214                 do_mkdir(fname,0777 & ~orig_umask); 
215                 *p = '/';
216                 p++;
217         }
218         return 0;
219 }
220
221
222 /* Write LEN bytes at PTR to descriptor DESC, retrying if interrupted.
223    Return LEN upon success, write's (negative) error code otherwise.  
224
225    derived from GNU C's cccp.c.
226 */
227 static int full_write(int desc, char *ptr, int len)
228 {
229         int total_written;
230         
231         total_written = 0;
232         while (len > 0) {
233                 int written = write (desc, ptr, len);
234                 if (written < 0)  {
235 #ifdef EINTR
236                         if (errno == EINTR)
237                                 continue;
238 #endif
239                         return written;
240                 }
241                 total_written += written;
242                 ptr += written;
243                 len -= written;
244         }
245         return total_written;
246 }
247
248 /* Read LEN bytes at PTR from descriptor DESC, retrying if interrupted.
249    Return the actual number of bytes read, zero for EOF, or negative
250    for an error.  
251
252    derived from GNU C's cccp.c. */
253 int safe_read(int desc, char *ptr, int len)
254 {
255         int n_chars;
256  
257         if (len <= 0)
258                 return len;
259  
260 #ifdef EINTR
261         do {
262                 n_chars = read(desc, ptr, len);
263         } while (n_chars < 0 && errno == EINTR);
264 #else
265         n_chars = read(desc, ptr, len);
266 #endif
267  
268         return n_chars;
269 }
270
271
272 /* copy a file - this is used in conjunction with the --temp-dir option */
273 int copy_file(char *source, char *dest, mode_t mode)
274 {
275         int ifd;
276         int ofd;
277         char buf[1024 * 8];
278         int len;   /* Number of bytes read into `buf'. */
279
280         ifd = open(source, O_RDONLY);
281         if (ifd == -1) {
282                 rprintf(FERROR,"open %s: %s\n",
283                         source,strerror(errno));
284                 return -1;
285         }
286
287         if (do_unlink(dest) && errno != ENOENT) {
288                 rprintf(FERROR,"unlink %s: %s\n",
289                         dest,strerror(errno));
290                 return -1;
291         }
292
293         ofd = do_open(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
294         if (ofd < 0) {
295                 rprintf(FERROR,"open %s: %s\n",
296                         dest,strerror(errno));
297                 close(ifd);
298                 return -1;
299         }
300
301         while ((len = safe_read(ifd, buf, sizeof(buf))) > 0) {
302                 if (full_write(ofd, buf, len) < 0) {
303                         rprintf(FERROR,"write %s: %s\n",
304                                 dest,strerror(errno));
305                         close(ifd);
306                         close(ofd);
307                         return -1;
308                 }
309         }
310
311         close(ifd);
312         close(ofd);
313
314         if (len < 0) {
315                 rprintf(FERROR,"read %s: %s\n",
316                         source,strerror(errno));
317                 return -1;
318         }
319
320         return 0;
321 }
322
323 /* sleep for a while via select */
324 void u_sleep(int usec)
325 {
326         struct timeval tv;
327
328         tv.tv_sec = 0;
329         tv.tv_usec = usec;
330         select(0, NULL, NULL, NULL, &tv);
331 }
332
333
334 static pid_t all_pids[10];
335 static int num_pids;
336
337 /* fork and record the pid of the child */
338 pid_t do_fork(void)
339 {
340         pid_t newpid = fork();
341         
342         if (newpid) {
343                 all_pids[num_pids++] = newpid;
344         }
345         return newpid;
346 }
347
348 /* kill all children */
349 void kill_all(int sig)
350 {
351         int i;
352         for (i=0;i<num_pids;i++) {
353                 if (all_pids[i] != getpid())
354                         kill(all_pids[i], sig);
355         }
356 }
357
358 /* like strncpy but does not 0 fill the buffer and always null 
359    terminates (thus it can use maxlen+1 space in d) */
360 void strlcpy(char *d, char *s, int maxlen)
361 {
362         int len = strlen(s);
363         if (len > maxlen) len = maxlen;
364         memcpy(d, s, len);
365         d[len] = 0;
366 }
367
368 /* like strncat but does not 0 fill the buffer and always null 
369    terminates (thus it can use maxlen+1 space in d) */
370 void strlcat(char *d, char *s, int maxlen)
371 {
372         int len1 = strlen(d);
373         int len2 = strlen(s);
374         if (len1+len2 > maxlen) {
375                 len2 = maxlen-len1;
376         }
377         if (len2 > 0) {
378                 memcpy(d+len1, s, len2);
379                 d[len1+len2] = 0;
380         }
381 }
382
383 /* turn a user name into a uid */
384 int name_to_uid(char *name, uid_t *uid)
385 {
386         struct passwd *pass;
387         if (!name || !*name) return 0;
388         pass = getpwnam(name);
389         if (pass) {
390                 *uid = pass->pw_uid;
391                 return 1;
392         }
393         return 0;
394 }
395
396 /* turn a group name into a gid */
397 int name_to_gid(char *name, gid_t *gid)
398 {
399         struct group *grp;
400         if (!name || !*name) return 0;
401         grp = getgrnam(name);
402         if (grp) {
403                 *gid = grp->gr_gid;
404                 return 1;
405         }
406         return 0;
407 }
408
409
410 /****************************************************************************
411 check if a process exists. 
412 ****************************************************************************/
413 int process_exists(int pid)
414 {
415         return(kill(pid,0) == 0 || errno != ESRCH);
416 }
417
418 /* lock a byte range in a open file */
419 int lock_range(int fd, int offset, int len)
420 {
421         struct flock lock;
422
423         lock.l_type = F_WRLCK;
424         lock.l_whence = SEEK_SET;
425         lock.l_start = offset;
426         lock.l_len = len;
427         lock.l_pid = 0;
428         
429         return fcntl(fd,F_SETLK,&lock) == 0;
430 }
431
432
433 static void glob_expand_one(char *s, char **argv, int *argc, int maxargs)
434 {
435 #ifndef HAVE_GLOB
436         if (!*s) s = ".";
437         argv[*argc] = strdup(s);
438         (*argc)++;
439         return;
440 #else
441         glob_t globbuf;
442         int i;
443
444         if (!*s) s = ".";
445
446         argv[*argc] = strdup(s);
447
448         memset(&globbuf, 0, sizeof(globbuf));
449         glob(argv[*argc], 0, NULL, &globbuf);
450         if (globbuf.gl_pathc == 0) {
451                 (*argc)++;
452                 globfree(&globbuf);
453                 return;
454         }
455         for (i=0; i<(maxargs - (*argc)) && i<globbuf.gl_pathc;i++) {
456                 if (i == 0) free(argv[*argc]);
457                 argv[(*argc) + i] = strdup(globbuf.gl_pathv[i]);
458                 if (!argv[(*argc) + i]) out_of_memory("glob_expand");
459         }
460         globfree(&globbuf);
461         (*argc) += i;
462 #endif
463 }
464
465 void glob_expand(char *base1, char **argv, int *argc, int maxargs)
466 {
467         char *s = argv[*argc];
468         char *p, *q;
469         char *base = base1;
470
471         if (!s || !*s) return;
472
473         if (strncmp(s, base, strlen(base)) == 0) {
474                 s += strlen(base);
475         }
476
477         s = strdup(s);
478         if (!s) out_of_memory("glob_expand");
479
480         base = (char *)malloc(strlen(base1)+3);
481         if (!base) out_of_memory("glob_expand");
482
483         sprintf(base," %s/", base1);
484
485         q = s;
486         while ((p = strstr(q,base)) && ((*argc) < maxargs)) {
487                 /* split it at this point */
488                 *p = 0;
489                 glob_expand_one(q, argv, argc, maxargs);
490                 q = p+strlen(base);
491         }
492
493         if (*q && (*argc < maxargs)) glob_expand_one(q, argv, argc, maxargs);
494
495         free(s);
496         free(base);
497 }
498
499 /*******************************************************************
500   convert a string to lower case
501 ********************************************************************/
502 void strlower(char *s)
503 {
504         while (*s) {
505                 if (isupper(*s)) *s = tolower(*s);
506                 s++;
507         }
508 }
509
510 /* this is like vsnprintf but the 'n' limit does not include
511    the terminating null. So if you have a 1024 byte buffer then
512    pass 1023 for n */
513 int vslprintf(char *str, int n, const char *format, va_list ap)
514 {
515 #ifdef HAVE_VSNPRINTF
516         int ret = vsnprintf(str, n, format, ap);
517         if (ret > n || ret < 0) {
518                 str[n] = 0;
519                 return -1;
520         }
521         str[ret] = 0;
522         return ret;
523 #else
524         static char *buf;
525         static int len=MAXPATHLEN*8;
526         int ret;
527
528         /* this code is NOT a proper vsnprintf() implementation. It
529            relies on the fact that all calls to slprintf() in rsync
530            pass strings which have already been checked to be less
531            than MAXPATHLEN in length and never more than 2 strings are
532            concatenated. This means the above buffer is absolutely
533            ample and can never be overflowed.
534
535            In the future we would like to replace this with a proper
536            vsnprintf() implementation but right now we need a solution
537            that is secure and portable. This is it.  */
538
539         if (!buf) {
540                 buf = malloc(len);
541                 if (!buf) {
542                         /* can't call debug or we would recurse */
543                         exit_cleanup(1);
544                 }
545         }
546
547         vsprintf(buf, format, ap);
548         ret = strlen(buf);
549         if (ret > n) {
550                 /* yikes! */
551                 exit_cleanup(1);
552         }
553         buf[ret] = 0;
554         
555         memcpy(str, buf, ret+1);
556
557         return ret;
558 #endif
559 }
560
561
562 /* like snprintf but always null terminates */
563 int slprintf(char *str, int n, char *format, ...)
564 {
565         va_list ap;  
566         int ret;
567
568         va_start(ap, format);
569         ret = vslprintf(str,n,format,ap);
570         va_end(ap);
571         return ret;
572 }
573
574
575 void *Realloc(void *p, int size)
576 {
577         if (!p) return (void *)malloc(size);
578         return (void *)realloc(p, size);
579 }
580
581
582 void clean_fname(char *name)
583 {
584         char *p;
585         int l;
586         int modified = 1;
587
588         if (!name) return;
589
590         while (modified) {
591                 modified = 0;
592
593                 if ((p=strstr(name,"/./"))) {
594                         modified = 1;
595                         while (*p) {
596                                 p[0] = p[2];
597                                 p++;
598                         }
599                 }
600
601                 if ((p=strstr(name,"//"))) {
602                         modified = 1;
603                         while (*p) {
604                                 p[0] = p[1];
605                                 p++;
606                         }
607                 }
608
609                 if (strncmp(p=name,"./",2) == 0) {      
610                         modified = 1;
611                         do {
612                                 p[0] = p[2];
613                         } while (*p++);
614                 }
615
616                 l = strlen(p=name);
617                 if (l > 1 && p[l-1] == '/') {
618                         modified = 1;
619                         p[l-1] = 0;
620                 }
621         }
622 }
623
624
625 static char curr_dir[MAXPATHLEN];
626
627 /* like chdir() but can be reversed with pop_dir() if save is set. It
628    is also much faster as it remembers where we have been */
629 char *push_dir(char *dir, int save)
630 {
631         char *ret = curr_dir;
632         static int initialised;
633
634         if (!initialised) {
635                 initialised = 1;
636                 getcwd(curr_dir, sizeof(curr_dir)-1);
637         }
638
639         if (chdir(dir)) return NULL;
640
641         if (save) {
642                 ret = strdup(curr_dir);
643         }
644
645         if (*dir == '/') {
646                 strlcpy(curr_dir, dir, sizeof(curr_dir)-1);
647         } else {
648                 strlcat(curr_dir,"/", sizeof(curr_dir)-1);
649                 strlcat(curr_dir,dir, sizeof(curr_dir)-1);
650         }
651
652         clean_fname(curr_dir);
653
654         return ret;
655 }
656
657 /* reverse a push_dir call */
658 int pop_dir(char *dir)
659 {
660         int ret;
661
662         ret = chdir(dir);
663         if (ret) {
664                 free(dir);
665                 return ret;
666         }
667
668         strlcpy(curr_dir, dir, sizeof(curr_dir)-1);
669
670         free(dir);
671
672         return 0;
673 }
674
675 /* we need to supply our own strcmp function for file list comparisons
676    to ensure that signed/unsigned usage is consistent between machines. */
677 int u_strcmp(const char *cs1, const char *cs2)
678 {
679         const uchar *s1 = (uchar *)cs1;
680         const uchar *s2 = (uchar *)cs2;
681
682         while (*s1 && *s2 && (*s1 == *s2)) {
683                 s1++; s2++;
684         }
685         
686         return (int)*s1 - (int)*s2;
687 }
688
689 static OFF_T last_ofs;
690
691 void end_progress(void)
692 {
693         extern int do_progress, am_server;
694
695         if (do_progress && !am_server) {
696                 rprintf(FINFO,"\n");
697         }
698         last_ofs = 0;
699 }
700
701 void show_progress(OFF_T ofs, OFF_T size)
702 {
703         extern int do_progress, am_server;
704
705         if (do_progress && !am_server) {
706                 if (ofs > last_ofs + 1000) {
707                         int pct = (int)((100.0*ofs)/size);
708                         rprintf(FINFO,"%.0f (%d%%)\r", (double)ofs, pct);
709                         last_ofs = ofs;
710                 }
711         }
712 }