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