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