We sanitize the --*-dest args here so they can be relative to the
[rsync/rsync.git] / main.c
1 /*
2  * The startup routines, including main(), for rsync.
3  *
4  * Copyright (C) 1996-2001 Andrew Tridgell <tridge@samba.org>
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 #if defined CONFIG_LOCALE && defined HAVE_LOCALE_H
26 #include <locale.h>
27 #endif
28
29 extern int verbose;
30 extern int dry_run;
31 extern int list_only;
32 extern int am_root;
33 extern int am_server;
34 extern int am_sender;
35 extern int am_generator;
36 extern int am_daemon;
37 extern int blocking_io;
38 extern int remove_sent_files;
39 extern int daemon_over_rsh;
40 extern int need_messages_from_generator;
41 extern int kluge_around_eof;
42 extern int do_stats;
43 extern int log_got_error;
44 extern int module_id;
45 extern int copy_links;
46 extern int copy_dirlinks;
47 extern int keep_dirlinks;
48 extern int preserve_hard_links;
49 extern int protocol_version;
50 extern int recurse;
51 extern int relative_paths;
52 extern int sanitize_paths;
53 extern int module_id;
54 extern int rsync_port;
55 extern int whole_file;
56 extern int read_batch;
57 extern int write_batch;
58 extern int batch_fd;
59 extern int batch_gen_fd;
60 extern int filesfrom_fd;
61 extern pid_t cleanup_child_pid;
62 extern struct stats stats;
63 extern char *filesfrom_host;
64 extern char *basis_dir[];
65 extern char *rsync_path;
66 extern char *shell_cmd;
67 extern char *batch_name;
68
69 extern char curr_dir[MAXPATHLEN];
70
71 int local_server = 0;
72 mode_t orig_umask = 0;
73 struct file_list *the_file_list;
74
75 /* There's probably never more than at most 2 outstanding child processes,
76  * but set it higher, just in case. */
77 #define MAXCHILDPROCS 7
78
79 #ifdef HAVE_SIGACTION
80 # ifdef HAVE_SIGPROCMASK
81 #  define SIGACTMASK(n,h) SIGACTION(n,h), sigaddset(&sigmask,(n))
82 # else
83 #  define SIGACTMASK(n,h) SIGACTION(n,h)
84 # endif
85 static struct sigaction sigact;
86 #endif
87
88 struct pid_status {
89         pid_t pid;
90         int status;
91 } pid_stat_table[MAXCHILDPROCS];
92
93 static time_t starttime, endtime;
94 static int64 total_read, total_written;
95
96 static void show_malloc_stats(void);
97
98 /* Works like waitpid(), but if we already harvested the child pid in our
99  * remember_children(), we succeed instead of returning an error. */
100 pid_t wait_process(pid_t pid, int *status_ptr, int flags)
101 {
102         pid_t waited_pid = waitpid(pid, status_ptr, flags);
103
104         if (waited_pid == -1 && errno == ECHILD) {
105                 /* Status of requested child no longer available:  check to
106                  * see if it was processed by remember_children(). */
107                 int cnt;
108                 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
109                         if (pid == pid_stat_table[cnt].pid) {
110                                 *status_ptr = pid_stat_table[cnt].status;
111                                 pid_stat_table[cnt].pid = 0;
112                                 return pid;
113                         }
114                 }
115         }
116
117         return waited_pid;
118 }
119
120 /* Wait for a process to exit, calling io_flush while waiting. */
121 static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
122 {
123         pid_t waited_pid;
124         int status;
125
126         while ((waited_pid = wait_process(pid, &status, WNOHANG)) == 0) {
127                 msleep(20);
128                 io_flush(FULL_FLUSH);
129         }
130
131         /* TODO: If the child exited on a signal, then log an
132          * appropriate error message.  Perhaps we should also accept a
133          * message describing the purpose of the child.  Also indicate
134          * this to the caller so that they know something went wrong. */
135         if (waited_pid < 0) {
136                 rsyserr(FERROR, errno, "waitpid");
137                 *exit_code_ptr = RERR_WAITCHILD;
138         } else if (!WIFEXITED(status)) {
139 #ifdef WCOREDUMP
140                 if (WCOREDUMP(status))
141                         *exit_code_ptr = RERR_CRASHED;
142                 else
143 #endif
144                 if (WIFSIGNALED(status))
145                         *exit_code_ptr = RERR_TERMINATED;
146                 else
147                         *exit_code_ptr = RERR_WAITCHILD;
148         } else
149                 *exit_code_ptr = WEXITSTATUS(status);
150 }
151
152 /* This function gets called from all 3 processes.  We want the client side
153  * to actually output the text, but the sender is the only process that has
154  * all the stats we need.  So, if we're a client sender, we do the report.
155  * If we're a server sender, we write the stats on the supplied fd.  If
156  * we're the client receiver we read the stats from the supplied fd and do
157  * the report.  All processes might also generate a set of debug stats, if
158  * the verbose level is high enough (this is the only thing that the
159  * generator process and the server receiver ever do here). */
160 static void handle_stats(int f)
161 {
162         endtime = time(NULL);
163
164         /* Cache two stats because the read/write code can change it. */
165         total_read = stats.total_read;
166         total_written = stats.total_written;
167
168         if (do_stats && verbose > 1) {
169                 /* These come out from every process */
170                 show_malloc_stats();
171                 show_flist_stats();
172         }
173
174         if (am_generator)
175                 return;
176
177         if (am_daemon) {
178                 log_exit(0, __FILE__, __LINE__);
179                 if (f == -1 || !am_sender)
180                         return;
181         }
182
183         if (am_server) {
184                 if (am_sender) {
185                         write_longint(f, total_read);
186                         write_longint(f, total_written);
187                         write_longint(f, stats.total_size);
188                         if (protocol_version >= 29) {
189                                 write_longint(f, stats.flist_buildtime);
190                                 write_longint(f, stats.flist_xfertime);
191                         }
192                 }
193                 return;
194         }
195
196         /* this is the client */
197
198         if (f < 0 && !am_sender) /* e.g. when we got an empty file list. */
199                 ;
200         else if (!am_sender) {
201                 /* Read the first two in opposite order because the meaning of
202                  * read/write swaps when switching from sender to receiver. */
203                 total_written = read_longint(f);
204                 total_read = read_longint(f);
205                 stats.total_size = read_longint(f);
206                 if (protocol_version >= 29) {
207                         stats.flist_buildtime = read_longint(f);
208                         stats.flist_xfertime = read_longint(f);
209                 }
210         } else if (write_batch) {
211                 /* The --read-batch process is going to be a client
212                  * receiver, so we need to give it the stats. */
213                 write_longint(batch_fd, total_read);
214                 write_longint(batch_fd, total_written);
215                 write_longint(batch_fd, stats.total_size);
216                 if (protocol_version >= 29) {
217                         write_longint(batch_fd, stats.flist_buildtime);
218                         write_longint(batch_fd, stats.flist_xfertime);
219                 }
220         }
221 }
222
223 static void output_summary(void)
224 {
225         if (do_stats) {
226                 rprintf(FINFO,"\nNumber of files: %d\n", stats.num_files);
227                 rprintf(FINFO,"Number of files transferred: %d\n",
228                         stats.num_transferred_files);
229                 rprintf(FINFO,"Total file size: %s bytes\n",
230                         human_num(stats.total_size));
231                 rprintf(FINFO,"Total transferred file size: %s bytes\n",
232                         human_num(stats.total_transferred_size));
233                 rprintf(FINFO,"Literal data: %s bytes\n",
234                         human_num(stats.literal_data));
235                 rprintf(FINFO,"Matched data: %s bytes\n",
236                         human_num(stats.matched_data));
237                 rprintf(FINFO,"File list size: %d\n", stats.flist_size);
238                 if (stats.flist_buildtime) {
239                         rprintf(FINFO,
240                                 "File list generation time: %.3f seconds\n",
241                                 (double)stats.flist_buildtime / 1000);
242                         rprintf(FINFO,
243                                 "File list transfer time: %.3f seconds\n",
244                                 (double)stats.flist_xfertime / 1000);
245                 }
246                 rprintf(FINFO,"Total bytes sent: %s\n",
247                         human_num(total_written));
248                 rprintf(FINFO,"Total bytes received: %s\n",
249                         human_num(total_read));
250         }
251
252         if (verbose || do_stats) {
253                 rprintf(FINFO,
254                         "\nsent %s bytes  received %s bytes  %s bytes/sec\n",
255                         human_num(total_written), human_num(total_read),
256                         human_dnum((total_written + total_read)/(0.5 + (endtime - starttime)), 2));
257                 rprintf(FINFO, "total size is %s  speedup is %.2f\n",
258                         human_num(stats.total_size),
259                         (double)stats.total_size / (total_written+total_read));
260         }
261
262         fflush(stdout);
263         fflush(stderr);
264 }
265
266
267 /**
268  * If our C library can get malloc statistics, then show them to FINFO
269  **/
270 static void show_malloc_stats(void)
271 {
272 #ifdef HAVE_MALLINFO
273         struct mallinfo mi;
274
275         mi = mallinfo();
276
277         rprintf(FINFO, "\n" RSYNC_NAME "[%d] (%s%s%s) heap statistics:\n",
278                 getpid(), am_server ? "server " : "",
279                 am_daemon ? "daemon " : "", who_am_i());
280         rprintf(FINFO, "  arena:     %10ld   (bytes from sbrk)\n",
281                 (long)mi.arena);
282         rprintf(FINFO, "  ordblks:   %10ld   (chunks not in use)\n",
283                 (long)mi.ordblks);
284         rprintf(FINFO, "  smblks:    %10ld\n",
285                 (long)mi.smblks);
286         rprintf(FINFO, "  hblks:     %10ld   (chunks from mmap)\n",
287                 (long)mi.hblks);
288         rprintf(FINFO, "  hblkhd:    %10ld   (bytes from mmap)\n",
289                 (long)mi.hblkhd);
290         rprintf(FINFO, "  allmem:    %10ld   (bytes from sbrk + mmap)\n",
291                 (long)mi.arena + mi.hblkhd);
292         rprintf(FINFO, "  usmblks:   %10ld\n",
293                 (long)mi.usmblks);
294         rprintf(FINFO, "  fsmblks:   %10ld\n",
295                 (long)mi.fsmblks);
296         rprintf(FINFO, "  uordblks:  %10ld   (bytes used)\n",
297                 (long)mi.uordblks);
298         rprintf(FINFO, "  fordblks:  %10ld   (bytes free)\n",
299                 (long)mi.fordblks);
300         rprintf(FINFO, "  keepcost:  %10ld   (bytes in releasable chunk)\n",
301                 (long)mi.keepcost);
302 #endif /* HAVE_MALLINFO */
303 }
304
305
306 /* Start the remote shell.   cmd may be NULL to use the default. */
307 static pid_t do_cmd(char *cmd, char *machine, char *user, char *path,
308                     int *f_in, int *f_out)
309 {
310         int i, argc = 0;
311         char *args[MAX_ARGS];
312         pid_t ret;
313         char *dir = NULL;
314         int dash_l_set = 0;
315
316         if (!read_batch && !local_server) {
317                 char *t, *f, in_quote = '\0';
318                 char *rsh_env = getenv(RSYNC_RSH_ENV);
319                 if (!cmd)
320                         cmd = rsh_env;
321                 if (!cmd)
322                         cmd = RSYNC_RSH;
323                 cmd = strdup(cmd);
324                 if (!cmd)
325                         goto oom;
326
327                 for (t = f = cmd; *f; f++) {
328                         if (*f == ' ')
329                                 continue;
330                         /* Comparison leaves rooms for server_options(). */
331                         if (argc >= MAX_ARGS - MAX_SERVER_ARGS) {
332                                 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
333                                 exit_cleanup(RERR_SYNTAX);
334                         }
335                         args[argc++] = t;
336                         while (*f != ' ' || in_quote) {
337                                 if (!*f) {
338                                         if (in_quote) {
339                                                 rprintf(FERROR,
340                                                     "Missing trailing-%c in remote-shell command.\n",
341                                                     in_quote);
342                                                 exit_cleanup(RERR_SYNTAX);
343                                         }
344                                         f--;
345                                         break;
346                                 }
347                                 if (*f == '\'' || *f == '"') {
348                                         if (!in_quote) {
349                                                 in_quote = *f++;
350                                                 continue;
351                                         }
352                                         if (*f == in_quote && *++f != in_quote) {
353                                                 in_quote = '\0';
354                                                 continue;
355                                         }
356                                 }
357                                 *t++ = *f++;
358                         }
359                         *t++ = '\0';
360                 }
361
362                 /* check to see if we've already been given '-l user' in
363                  * the remote-shell command */
364                 for (i = 0; i < argc-1; i++) {
365                         if (!strcmp(args[i], "-l") && args[i+1][0] != '-')
366                                 dash_l_set = 1;
367                 }
368
369 #ifdef HAVE_REMSH
370                 /* remsh (on HPUX) takes the arguments the other way around */
371                 args[argc++] = machine;
372                 if (user && !(daemon_over_rsh && dash_l_set)) {
373                         args[argc++] = "-l";
374                         args[argc++] = user;
375                 }
376 #else
377                 if (user && !(daemon_over_rsh && dash_l_set)) {
378                         args[argc++] = "-l";
379                         args[argc++] = user;
380                 }
381                 args[argc++] = machine;
382 #endif
383
384                 args[argc++] = rsync_path;
385
386                 if (blocking_io < 0) {
387                         char *cp;
388                         if ((cp = strrchr(cmd, '/')) != NULL)
389                                 cp++;
390                         else
391                                 cp = cmd;
392                         if (strcmp(cp, "rsh") == 0 || strcmp(cp, "remsh") == 0)
393                                 blocking_io = 1;
394                 }
395
396                 server_options(args,&argc);
397
398                 if (argc >= MAX_ARGS - 2) {
399                         rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
400                         exit_cleanup(RERR_SYNTAX);
401                 }
402         }
403
404         args[argc++] = ".";
405
406         if (!daemon_over_rsh && path && *path)
407                 args[argc++] = path;
408
409         args[argc] = NULL;
410
411         if (verbose > 3) {
412                 for (i = 0; i < argc; i++)
413                         rprintf(FINFO, "cmd[%d]=%s ", i, args[i]);
414                 rprintf(FINFO, "\n");
415         }
416
417         if (read_batch) {
418                 int from_gen_pipe[2];
419                 if (fd_pair(from_gen_pipe) < 0) {
420                         rsyserr(FERROR, errno, "pipe");
421                         exit_cleanup(RERR_IPC);
422                 }
423                 batch_gen_fd = from_gen_pipe[0];
424                 *f_out = from_gen_pipe[1];
425                 *f_in = batch_fd;
426                 ret = -1; /* no child pid */
427         } else if (local_server) {
428                 /* If the user didn't request --[no-]whole-file, force
429                  * it on, but only if we're not batch processing. */
430                 if (whole_file < 0 && !write_batch)
431                         whole_file = 1;
432                 ret = local_child(argc, args, f_in, f_out, child_main);
433         } else
434                 ret = piped_child(args,f_in,f_out);
435
436         if (dir)
437                 free(dir);
438
439         return ret;
440
441   oom:
442         out_of_memory("do_cmd");
443         return 0; /* not reached */
444 }
445
446 /* The receiving side operates in one of two modes:
447  *
448  * 1. it receives any number of files into a destination directory,
449  * placing them according to their names in the file-list.
450  *
451  * 2. it receives a single file and saves it using the name in the
452  * destination path instead of its file-list name.  This requires a
453  * "local name" for writing out the destination file.
454  *
455  * So, our task is to figure out what mode/local-name we need and return
456  * either a NULL for mode 1, or the local-name for mode 2.  We also
457  * change directory if there are any path components in dest_path. */
458 static char *get_local_name(struct file_list *flist, char *dest_path)
459 {
460         STRUCT_STAT st;
461         char *cp;
462
463         if (verbose > 2) {
464                 rprintf(FINFO, "get_local_name count=%d %s\n",
465                         flist->count, NS(dest_path));
466         }
467
468         if (!dest_path || list_only)
469                 return NULL;
470
471         /* If the destination path refers to an existing directory, enter
472          * it and use mode 1.  If there is something other than a directory
473          * at the destination path, we must be transferring one file
474          * (anything at the destination will be overwritten). */
475         if (do_stat(dest_path, &st) == 0) {
476                 if (S_ISDIR(st.st_mode)) {
477                         if (!push_dir(dest_path)) {
478                                 rsyserr(FERROR, errno, "push_dir#1 %s failed",
479                                         full_fname(dest_path));
480                                 exit_cleanup(RERR_FILESELECT);
481                         }
482                         return NULL;
483                 }
484                 if (flist->count > 1) {
485                         rprintf(FERROR,
486                                 "ERROR: destination must be a directory when"
487                                 " copying more than 1 file\n");
488                         exit_cleanup(RERR_FILESELECT);
489                 }
490                 /* Caution: flist->count could be 0! */
491                 if (flist->count == 1 && S_ISDIR(flist->files[0]->mode)) {
492                         rprintf(FERROR,
493                                 "ERROR: cannot overwrite non-directory"
494                                 " with a directory\n");
495                         exit_cleanup(RERR_FILESELECT);
496                 }
497         } else if (errno != ENOENT) {
498                 rsyserr(FERROR, errno, "cannot stat destination %s",
499                         full_fname(dest_path));
500                 exit_cleanup(RERR_FILESELECT);
501         }
502
503         cp = strrchr(dest_path, '/');
504
505         /* If the destination path ends in a slash or we are transferring
506          * multiple files, create a directory at the destination path,
507          * enter the new directory, and use mode 1. */
508         if (flist->count > 1 || (cp && !cp[1])) {
509                 /* Lop off the final slash (if any). */
510                 if (cp && !cp[1])
511                         *cp = '\0';
512
513                 if (mkdir_defmode(dest_path) != 0) {
514                         rsyserr(FERROR, errno, "mkdir %s failed",
515                                 full_fname(dest_path));
516                         exit_cleanup(RERR_FILEIO);
517                 }
518
519                 if (verbose)
520                         rprintf(FINFO, "created directory %s\n", dest_path);
521
522                 if (dry_run) {
523                         /* Indicate that the destination directory doesn't
524                          * really exist and return mode 1. */
525                         dry_run++;
526                         return NULL;
527                 }
528
529                 if (!push_dir(dest_path)) {
530                         rsyserr(FERROR, errno, "push_dir#2 %s failed",
531                                 full_fname(dest_path));
532                         exit_cleanup(RERR_FILESELECT);
533                 }
534
535                 return NULL;
536         }
537
538         /* Otherwise, we are writing a single file, possibly on top of an
539          * existing non-directory.  Change to the item's parent directory
540          * (if it has a path component), return the basename of the
541          * destination file as the local name, and use mode 2. */
542         if (!cp)
543                 return dest_path;
544
545         if (cp == dest_path)
546                 dest_path = "/";
547
548         *cp = '\0';
549         if (!push_dir(dest_path)) {
550                 rsyserr(FERROR, errno, "push_dir#3 %s failed",
551                         full_fname(dest_path));
552                 exit_cleanup(RERR_FILESELECT);
553         }
554         *cp = '/';
555
556         return cp + 1;
557 }
558
559
560 /* This is only called by the sender. */
561 static void read_final_goodbye(int f_in, int f_out)
562 {
563         int i;
564
565         if (protocol_version < 29)
566                 i = read_int(f_in);
567         else {
568                 while ((i = read_int(f_in)) == the_file_list->count
569                     && read_shortint(f_in) == ITEM_IS_NEW) {
570                         /* Forward the keep-alive (no-op) to the receiver. */
571                         write_int(f_out, the_file_list->count);
572                         write_shortint(f_out, ITEM_IS_NEW);
573                 }
574         }
575
576         if (i != -1) {
577                 rprintf(FERROR, "Invalid packet at end of run (%d) [%s]\n",
578                         i, who_am_i());
579                 exit_cleanup(RERR_PROTOCOL);
580         }
581 }
582
583
584 static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
585 {
586         struct file_list *flist;
587         char *dir = argv[0];
588
589         if (verbose > 2) {
590                 rprintf(FINFO, "server_sender starting pid=%ld\n",
591                         (long)getpid());
592         }
593
594         if (am_daemon && lp_write_only(module_id)) {
595                 rprintf(FERROR, "ERROR: module is write only\n");
596                 exit_cleanup(RERR_SYNTAX);
597                 return;
598         }
599         if (am_daemon && lp_read_only(module_id) && remove_sent_files) {
600                 rprintf(FERROR,
601                     "ERROR: --remove-sent-files cannot be used with a read-only module\n");
602                 exit_cleanup(RERR_SYNTAX);
603                 return;
604         }
605
606         if (!relative_paths && !push_dir(dir)) {
607                 rsyserr(FERROR, errno, "push_dir#3 %s failed",
608                         full_fname(dir));
609                 exit_cleanup(RERR_FILESELECT);
610         }
611         argc--;
612         argv++;
613
614         if (argc == 0 && (recurse || list_only)) {
615                 argc = 1;
616                 argv--;
617                 argv[0] = ".";
618         }
619
620         flist = send_file_list(f_out,argc,argv);
621         if (!flist || flist->count == 0) {
622                 exit_cleanup(0);
623         }
624         the_file_list = flist;
625
626         io_start_buffering_in();
627         io_start_buffering_out();
628
629         send_files(flist,f_out,f_in);
630         io_flush(FULL_FLUSH);
631         handle_stats(f_out);
632         if (protocol_version >= 24)
633                 read_final_goodbye(f_in, f_out);
634         io_flush(FULL_FLUSH);
635         exit_cleanup(0);
636 }
637
638
639 static int do_recv(int f_in,int f_out,struct file_list *flist,char *local_name)
640 {
641         int pid;
642         int exit_code = 0;
643         int error_pipe[2];
644
645         /* The receiving side mustn't obey this, or an existing symlink that
646          * points to an identical file won't be replaced by the referent. */
647         copy_links = copy_dirlinks = 0;
648
649         if (preserve_hard_links)
650                 init_hard_links();
651
652         if (fd_pair(error_pipe) < 0) {
653                 rsyserr(FERROR, errno, "pipe failed in do_recv");
654                 exit_cleanup(RERR_IPC);
655         }
656
657         io_flush(NORMAL_FLUSH);
658
659         if ((pid = do_fork()) == -1) {
660                 rsyserr(FERROR, errno, "fork failed in do_recv");
661                 exit_cleanup(RERR_IPC);
662         }
663
664         if (pid == 0) {
665                 close(error_pipe[0]);
666                 if (f_in != f_out)
667                         close(f_out);
668
669                 /* we can't let two processes write to the socket at one time */
670                 close_multiplexing_out();
671
672                 /* set place to send errors */
673                 set_msg_fd_out(error_pipe[1]);
674
675                 recv_files(f_in, flist, local_name);
676                 io_flush(FULL_FLUSH);
677                 handle_stats(f_in);
678
679                 send_msg(MSG_DONE, "", 0);
680                 io_flush(FULL_FLUSH);
681
682                 /* Handle any keep-alive packets from the post-processing work
683                  * that the generator does. */
684                 if (protocol_version >= 29) {
685                         kluge_around_eof = -1;
686
687                         /* This should only get stopped via a USR2 signal. */
688                         while (read_int(f_in) == flist->count
689                             && read_shortint(f_in) == ITEM_IS_NEW) {}
690
691                         rprintf(FERROR, "Invalid packet at end of run [%s]\n",
692                                 who_am_i());
693                         exit_cleanup(RERR_PROTOCOL);
694                 }
695
696                 /* Finally, we go to sleep until our parent kills us with a
697                  * USR2 signal.  We sleep for a short time, as on some OSes
698                  * a signal won't interrupt a sleep! */
699                 while (1)
700                         msleep(20);
701         }
702
703         am_generator = 1;
704         close_multiplexing_in();
705         if (write_batch && !am_server)
706                 stop_write_batch();
707
708         close(error_pipe[1]);
709         if (f_in != f_out)
710                 close(f_in);
711
712         io_start_buffering_out();
713
714         set_msg_fd_in(error_pipe[0]);
715
716         generate_files(f_out, flist, local_name);
717
718         handle_stats(-1);
719         io_flush(FULL_FLUSH);
720         if (protocol_version >= 24) {
721                 /* send a final goodbye message */
722                 write_int(f_out, -1);
723         }
724         io_flush(FULL_FLUSH);
725
726         set_msg_fd_in(-1);
727         kill(pid, SIGUSR2);
728         wait_process_with_flush(pid, &exit_code);
729         return exit_code;
730 }
731
732
733 static void do_server_recv(int f_in, int f_out, int argc,char *argv[])
734 {
735         int exit_code;
736         struct file_list *flist;
737         char *local_name = NULL;
738         char *dir = NULL;
739         int save_verbose = verbose;
740
741         if (filesfrom_fd >= 0) {
742                 /* We can't mix messages with files-from data on the socket,
743                  * so temporarily turn off verbose messages. */
744                 verbose = 0;
745         }
746
747         if (verbose > 2) {
748                 rprintf(FINFO, "server_recv(%d) starting pid=%ld\n",
749                         argc, (long)getpid());
750         }
751
752         if (am_daemon && lp_read_only(module_id)) {
753                 rprintf(FERROR,"ERROR: module is read only\n");
754                 exit_cleanup(RERR_SYNTAX);
755                 return;
756         }
757
758         if (argc > 0) {
759                 dir = argv[0];
760                 argc--;
761                 argv++;
762                 if (!am_daemon && !push_dir(dir)) {
763                         rsyserr(FERROR, errno, "push_dir#4 %s failed",
764                                 full_fname(dir));
765                         exit_cleanup(RERR_FILESELECT);
766                 }
767         }
768
769         io_start_buffering_in();
770         recv_filter_list(f_in);
771
772         if (filesfrom_fd >= 0) {
773                 /* We need to send the files-from names to the sender at the
774                  * same time that we receive the file-list from them, so we
775                  * need the IO routines to automatically write out the names
776                  * onto our f_out socket as we read the file-list.  This
777                  * avoids both deadlock and extra delays/buffers. */
778                 io_set_filesfrom_fds(filesfrom_fd, f_out);
779                 filesfrom_fd = -1;
780         }
781
782         flist = recv_file_list(f_in);
783         verbose = save_verbose;
784         if (!flist) {
785                 rprintf(FERROR,"server_recv: recv_file_list error\n");
786                 exit_cleanup(RERR_FILESELECT);
787         }
788         the_file_list = flist;
789
790         if (argc > 0)
791                 local_name = get_local_name(flist,argv[0]);
792
793         /* Now that we know what our destination directory turned out to be,
794          * we can sanitize the --link-/copy-/compare-dest args correctly. */
795         if (sanitize_paths) {
796                 char *dest_path = curr_dir + strlen(lp_path(module_id));
797                 int dest_depth = count_dir_elements(dest_path);
798                 char **dir;
799                 for (dir = basis_dir; *dir; dir++)
800                         *dir = sanitize_path(NULL, *dir, NULL, dest_depth);
801         }
802
803         exit_code = do_recv(f_in,f_out,flist,local_name);
804         exit_cleanup(exit_code);
805 }
806
807
808 int child_main(int argc, char *argv[])
809 {
810         start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
811         return 0;
812 }
813
814
815 void start_server(int f_in, int f_out, int argc, char *argv[])
816 {
817         set_nonblocking(f_in);
818         set_nonblocking(f_out);
819
820         io_set_sock_fds(f_in, f_out);
821         setup_protocol(f_out, f_in);
822 #if defined HAVE_ICONV_OPEN && defined HAVE_ICONV_H
823         setup_iconv();
824 #endif
825
826         if (protocol_version >= 23)
827                 io_start_multiplex_out();
828
829         if (am_sender) {
830                 keep_dirlinks = 0; /* Must be disabled on the sender. */
831                 if (need_messages_from_generator)
832                         io_start_multiplex_in();
833
834                 recv_filter_list(f_in);
835                 do_server_sender(f_in, f_out, argc, argv);
836         } else {
837                 do_server_recv(f_in, f_out, argc, argv);
838         }
839         exit_cleanup(0);
840 }
841
842
843 /*
844  * This is called once the connection has been negotiated.  It is used
845  * for rsyncd, remote-shell, and local connections.
846  */
847 int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
848 {
849         struct file_list *flist = NULL;
850         int exit_code = 0, exit_code2 = 0;
851         char *local_name = NULL;
852
853         cleanup_child_pid = pid;
854         if (!read_batch) {
855                 set_nonblocking(f_in);
856                 set_nonblocking(f_out);
857         }
858
859         io_set_sock_fds(f_in, f_out);
860         setup_protocol(f_out,f_in);
861 #if defined HAVE_ICONV_OPEN && defined HAVE_ICONV_H
862         setup_iconv();
863 #endif
864
865         if (protocol_version >= 23 && !read_batch)
866                 io_start_multiplex_in();
867
868         /* We set our stderr file handle to blocking because ssh might have
869          * set it to non-blocking.  This can be particularly troublesome if
870          * stderr is a clone of stdout, because ssh would have set our stdout
871          * to non-blocking at the same time (which can easily cause us to lose
872          * output from our print statements).  This kluge shouldn't cause ssh
873          * any problems for how we use it.  Note also that we delayed setting
874          * this until after the above protocol setup so that we know for sure
875          * that ssh is done twiddling its file descriptors.  */
876         set_blocking(STDERR_FILENO);
877
878         if (am_sender) {
879                 keep_dirlinks = 0; /* Must be disabled on the sender. */
880                 io_start_buffering_out();
881                 if (!filesfrom_host)
882                         set_msg_fd_in(f_in);
883                 send_filter_list(f_out);
884                 if (filesfrom_host)
885                         filesfrom_fd = f_in;
886
887                 if (write_batch && !am_server)
888                         start_write_batch(f_out);
889                 flist = send_file_list(f_out, argc, argv);
890                 set_msg_fd_in(-1);
891                 if (verbose > 3)
892                         rprintf(FINFO,"file list sent\n");
893                 the_file_list = flist;
894
895                 io_flush(NORMAL_FLUSH);
896                 send_files(flist,f_out,f_in);
897                 io_flush(FULL_FLUSH);
898                 handle_stats(-1);
899                 if (protocol_version >= 24)
900                         read_final_goodbye(f_in, f_out);
901                 if (pid != -1) {
902                         if (verbose > 3)
903                                 rprintf(FINFO,"client_run waiting on %d\n", (int) pid);
904                         io_flush(FULL_FLUSH);
905                         wait_process_with_flush(pid, &exit_code);
906                 }
907                 output_summary();
908                 io_flush(FULL_FLUSH);
909                 exit_cleanup(exit_code);
910         }
911
912         if (need_messages_from_generator && !read_batch)
913                 io_start_multiplex_out();
914
915         if (argc == 0)
916                 list_only |= 1;
917
918         send_filter_list(read_batch ? -1 : f_out);
919
920         if (filesfrom_fd >= 0) {
921                 io_set_filesfrom_fds(filesfrom_fd, f_out);
922                 filesfrom_fd = -1;
923         }
924
925         if (write_batch && !am_server)
926                 start_write_batch(f_in);
927         flist = recv_file_list(f_in);
928         the_file_list = flist;
929
930         if (flist && flist->count > 0) {
931                 local_name = get_local_name(flist, argv[0]);
932
933                 exit_code2 = do_recv(f_in, f_out, flist, local_name);
934         } else {
935                 handle_stats(-1);
936                 output_summary();
937         }
938
939         if (pid != -1) {
940                 if (verbose > 3)
941                         rprintf(FINFO,"client_run2 waiting on %d\n", (int) pid);
942                 io_flush(FULL_FLUSH);
943                 wait_process_with_flush(pid, &exit_code);
944         }
945
946         return MAX(exit_code, exit_code2);
947 }
948
949 static int copy_argv (char *argv[])
950 {
951         int i;
952
953         for (i = 0; argv[i]; i++) {
954                 if (!(argv[i] = strdup(argv[i]))) {
955                         rprintf (FERROR, "out of memory at %s(%d)\n",
956                                  __FILE__, __LINE__);
957                         return RERR_MALLOC;
958                 }
959         }
960
961         return 0;
962 }
963
964
965 /**
966  * Start a client for either type of remote connection.  Work out
967  * whether the arguments request a remote shell or rsyncd connection,
968  * and call the appropriate connection function, then run_client.
969  *
970  * Calls either start_socket_client (for sockets) or do_cmd and
971  * client_run (for ssh).
972  **/
973 static int start_client(int argc, char *argv[])
974 {
975         char *p;
976         char *shell_machine = NULL;
977         char *shell_path = NULL;
978         char *shell_user = NULL;
979         int ret;
980         pid_t pid;
981         int f_in,f_out;
982         int rc;
983
984         /* Don't clobber argv[] so that ps(1) can still show the right
985          * command line. */
986         if ((rc = copy_argv(argv)))
987                 return rc;
988
989         if (!read_batch) { /* for read_batch, NO source is specified */
990                 shell_path = check_for_hostspec(argv[0], &shell_machine, &rsync_port);
991                 if (shell_path) { /* source is remote */
992                         char *dummy1;
993                         int dummy2;
994                         if (--argc
995                          && check_for_hostspec(argv[argc], &dummy1, &dummy2)) {
996                                 rprintf(FERROR,
997                                         "The source and destination cannot both be remote.\n");
998                                 exit_cleanup(RERR_SYNTAX);
999                         }
1000                         argv++;
1001                         if (filesfrom_host && *filesfrom_host
1002                             && strcmp(filesfrom_host, shell_machine) != 0) {
1003                                 rprintf(FERROR,
1004                                         "--files-from hostname is not the same as the transfer hostname\n");
1005                                 exit_cleanup(RERR_SYNTAX);
1006                         }
1007                         if (rsync_port) {
1008                                 if (!shell_cmd) {
1009                                         return start_socket_client(shell_machine,
1010                                                                    shell_path,
1011                                                                    argc, argv);
1012                                 }
1013                                 daemon_over_rsh = 1;
1014                         }
1015
1016                         am_sender = 0;
1017                 } else { /* source is local, check dest arg */
1018                         am_sender = 1;
1019
1020                         if (argc > 1)
1021                                 p = argv[--argc];
1022                         else {
1023                                 p = ".";
1024                                 list_only = 1;
1025                         }
1026
1027                         shell_path = check_for_hostspec(p, &shell_machine, &rsync_port);
1028                         if (shell_path && filesfrom_host && *filesfrom_host
1029                             && strcmp(filesfrom_host, shell_machine) != 0) {
1030                                 rprintf(FERROR,
1031                                         "--files-from hostname is not the same as the transfer hostname\n");
1032                                 exit_cleanup(RERR_SYNTAX);
1033                         }
1034                         if (!shell_path) { /* no hostspec found, so src & dest are local */
1035                                 local_server = 1;
1036                                 if (filesfrom_host) {
1037                                         rprintf(FERROR,
1038                                                 "--files-from cannot be remote when the transfer is local\n");
1039                                         exit_cleanup(RERR_SYNTAX);
1040                                 }
1041                                 shell_machine = NULL;
1042                                 shell_path = p;
1043                         } else if (rsync_port) {
1044                                 if (!shell_cmd) {
1045                                         return start_socket_client(shell_machine,
1046                                                                    shell_path,
1047                                                                    argc, argv);
1048                                 }
1049                                 daemon_over_rsh = 1;
1050                         }
1051                 }
1052         } else {  /* read_batch */
1053                 local_server = 1;
1054                 shell_path = argv[argc-1];
1055                 if (check_for_hostspec(shell_path, &shell_machine, &rsync_port)) {
1056                         rprintf(FERROR, "remote destination is not allowed with --read-batch\n");
1057                         exit_cleanup(RERR_SYNTAX);
1058                 }
1059         }
1060
1061         if (shell_machine) {
1062                 p = strrchr(shell_machine,'@');
1063                 if (p) {
1064                         *p = 0;
1065                         shell_user = shell_machine;
1066                         shell_machine = p+1;
1067                 }
1068         }
1069
1070         if (verbose > 3) {
1071                 rprintf(FINFO,"cmd=%s machine=%s user=%s path=%s\n",
1072                         shell_cmd ? shell_cmd : "",
1073                         shell_machine ? shell_machine : "",
1074                         shell_user ? shell_user : "",
1075                         shell_path ? shell_path : "");
1076         }
1077
1078         /* for remote source, only single dest arg can remain ... */
1079         if (!am_sender && argc > 1) {
1080                 usage(FERROR);
1081                 exit_cleanup(RERR_SYNTAX);
1082         }
1083
1084         /* ... or no dest at all */
1085         if (!am_sender && argc == 0)
1086                 list_only |= 1;
1087
1088         pid = do_cmd(shell_cmd,shell_machine,shell_user,shell_path,
1089                      &f_in,&f_out);
1090
1091         /* if we're running an rsync server on the remote host over a
1092          * remote shell command, we need to do the RSYNCD protocol first */
1093         if (daemon_over_rsh) {
1094                 int tmpret;
1095                 tmpret = start_inband_exchange(shell_user, shell_path,
1096                                                f_in, f_out, argc);
1097                 if (tmpret < 0)
1098                         return tmpret;
1099         }
1100
1101         ret = client_run(f_in, f_out, pid, argc, argv);
1102
1103         fflush(stdout);
1104         fflush(stderr);
1105
1106         return ret;
1107 }
1108
1109
1110 static RETSIGTYPE sigusr1_handler(UNUSED(int val))
1111 {
1112         exit_cleanup(RERR_SIGNAL1);
1113 }
1114
1115 static RETSIGTYPE sigusr2_handler(UNUSED(int val))
1116 {
1117         if (!am_server)
1118                 output_summary();
1119         close_all();
1120         if (log_got_error)
1121                 _exit(RERR_PARTIAL);
1122         _exit(0);
1123 }
1124
1125 RETSIGTYPE remember_children(UNUSED(int val))
1126 {
1127 #ifdef WNOHANG
1128         int cnt, status;
1129         pid_t pid;
1130         /* An empty waitpid() loop was put here by Tridge and we could never
1131          * get him to explain why he put it in, so rather than taking it
1132          * out we're instead saving the child exit statuses for later use.
1133          * The waitpid() loop presumably eliminates all possibility of leaving
1134          * zombie children, maybe that's why he did it. */
1135         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1136                 /* save the child's exit status */
1137                 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
1138                         if (pid_stat_table[cnt].pid == 0) {
1139                                 pid_stat_table[cnt].pid = pid;
1140                                 pid_stat_table[cnt].status = status;
1141                                 break;
1142                         }
1143                 }
1144         }
1145 #endif
1146 #ifndef HAVE_SIGACTION
1147         signal(SIGCHLD, remember_children);
1148 #endif
1149 }
1150
1151
1152 /**
1153  * This routine catches signals and tries to send them to gdb.
1154  *
1155  * Because it's called from inside a signal handler it ought not to
1156  * use too many library routines.
1157  *
1158  * @todo Perhaps use "screen -X" instead/as well, to help people
1159  * debugging without easy access to X.  Perhaps use an environment
1160  * variable, or just call a script?
1161  *
1162  * @todo The /proc/ magic probably only works on Linux (and
1163  * Solaris?)  Can we be more portable?
1164  **/
1165 #ifdef MAINTAINER_MODE
1166 const char *get_panic_action(void)
1167 {
1168         const char *cmd_fmt = getenv("RSYNC_PANIC_ACTION");
1169
1170         if (cmd_fmt)
1171                 return cmd_fmt;
1172         else
1173                 return "xterm -display :0 -T Panic -n Panic "
1174                         "-e gdb /proc/%d/exe %d";
1175 }
1176
1177
1178 /**
1179  * Handle a fatal signal by launching a debugger, controlled by $RSYNC_PANIC_ACTION.
1180  *
1181  * This signal handler is only installed if we were configured with
1182  * --enable-maintainer-mode.  Perhaps it should always be on and we
1183  * should just look at the environment variable, but I'm a bit leery
1184  * of a signal sending us into a busy loop.
1185  **/
1186 static RETSIGTYPE rsync_panic_handler(UNUSED(int whatsig))
1187 {
1188         char cmd_buf[300];
1189         int ret;
1190
1191         sprintf(cmd_buf, get_panic_action(),
1192                 getpid(), getpid());
1193
1194         /* Unless we failed to execute gdb, we allow the process to
1195          * continue.  I'm not sure if that's right. */
1196         ret = system(cmd_buf);
1197         if (ret)
1198                 _exit(ret);
1199 }
1200 #endif
1201
1202
1203 int main(int argc,char *argv[])
1204 {
1205         int ret;
1206         int orig_argc = argc;
1207         char **orig_argv = argv;
1208 #ifdef HAVE_SIGACTION
1209 # ifdef HAVE_SIGPROCMASK
1210         sigset_t sigmask;
1211
1212         sigemptyset(&sigmask);
1213 # endif
1214         sigact.sa_flags = SA_NOCLDSTOP;
1215 #endif
1216         SIGACTMASK(SIGUSR1, sigusr1_handler);
1217         SIGACTMASK(SIGUSR2, sigusr2_handler);
1218         SIGACTMASK(SIGCHLD, remember_children);
1219 #ifdef MAINTAINER_MODE
1220         SIGACTMASK(SIGSEGV, rsync_panic_handler);
1221         SIGACTMASK(SIGFPE, rsync_panic_handler);
1222         SIGACTMASK(SIGABRT, rsync_panic_handler);
1223         SIGACTMASK(SIGBUS, rsync_panic_handler);
1224 #endif
1225
1226         starttime = time(NULL);
1227         am_root = (MY_UID() == 0);
1228
1229         memset(&stats, 0, sizeof(stats));
1230
1231         if (argc < 2) {
1232                 usage(FERROR);
1233                 exit_cleanup(RERR_SYNTAX);
1234         }
1235
1236         /* we set a 0 umask so that correct file permissions can be
1237          * carried across */
1238         orig_umask = umask(0);
1239
1240 #if defined CONFIG_LOCALE && defined HAVE_SETLOCALE
1241         setlocale(LC_CTYPE, "");
1242 #endif
1243
1244         if (!parse_arguments(&argc, (const char ***) &argv, 1)) {
1245                 /* FIXME: We ought to call the same error-handling
1246                  * code here, rather than relying on getopt. */
1247                 option_error();
1248                 exit_cleanup(RERR_SYNTAX);
1249         }
1250
1251         SIGACTMASK(SIGINT, sig_int);
1252         SIGACTMASK(SIGHUP, sig_int);
1253         SIGACTMASK(SIGTERM, sig_int);
1254 #if defined HAVE_SIGACTION && HAVE_SIGPROCMASK
1255         sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
1256 #endif
1257
1258         /* Ignore SIGPIPE; we consistently check error codes and will
1259          * see the EPIPE. */
1260         SIGACTION(SIGPIPE, SIG_IGN);
1261 #ifdef SIGXFSZ
1262         SIGACTION(SIGXFSZ, SIG_IGN);
1263 #endif
1264
1265         /* Initialize push_dir here because on some old systems getcwd
1266          * (implemented by forking "pwd" and reading its output) doesn't
1267          * work when there are other child processes.  Also, on all systems
1268          * that implement getcwd that way "pwd" can't be found after chroot. */
1269         push_dir(NULL);
1270
1271         init_flist();
1272
1273         if ((write_batch || read_batch) && !am_server) {
1274                 if (write_batch)
1275                         write_batch_shell_file(orig_argc, orig_argv, argc);
1276
1277                 if (read_batch && strcmp(batch_name, "-") == 0)
1278                         batch_fd = STDIN_FILENO;
1279                 else {
1280                         batch_fd = do_open(batch_name,
1281                                    write_batch ? O_WRONLY | O_CREAT | O_TRUNC
1282                                    : O_RDONLY, S_IRUSR | S_IWUSR);
1283                 }
1284                 if (batch_fd < 0) {
1285                         rsyserr(FERROR, errno, "Batch file %s open error",
1286                                 full_fname(batch_name));
1287                         exit_cleanup(RERR_FILEIO);
1288                 }
1289                 if (read_batch)
1290                         read_stream_flags(batch_fd);
1291         }
1292         if (write_batch < 0)
1293                 dry_run = 1;
1294
1295         if (am_daemon && !am_server)
1296                 return daemon_main();
1297
1298         if (argc < 1) {
1299                 usage(FERROR);
1300                 exit_cleanup(RERR_SYNTAX);
1301         }
1302
1303         if (am_server) {
1304                 set_nonblocking(STDIN_FILENO);
1305                 set_nonblocking(STDOUT_FILENO);
1306                 if (am_daemon)
1307                         return start_daemon(STDIN_FILENO, STDOUT_FILENO);
1308                 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1309         }
1310
1311         ret = start_client(argc, argv);
1312         if (ret == -1)
1313                 exit_cleanup(RERR_STARTCLIENT);
1314         else
1315                 exit_cleanup(ret);
1316
1317         return ret;
1318 }