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