A major overhaul of I/O routines, creating perform_io().
[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-2009 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 3 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, visit the http://fsf.org website.
21  */
22
23 #include "rsync.h"
24 #include "inums.h"
25 #include "io.h"
26 #if defined CONFIG_LOCALE && defined HAVE_LOCALE_H
27 #include <locale.h>
28 #endif
29
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_daemon;
36 extern int inc_recurse;
37 extern int blocking_io;
38 extern int always_checksum;
39 extern int remove_source_files;
40 extern int output_needs_newline;
41 extern int need_messages_from_generator;
42 extern int kluge_around_eof;
43 extern int got_xfer_error;
44 extern int msgs2stderr;
45 extern int module_id;
46 extern int copy_links;
47 extern int copy_dirlinks;
48 extern int copy_unsafe_links;
49 extern int keep_dirlinks;
50 extern int preserve_hard_links;
51 extern int protocol_version;
52 extern int file_total;
53 extern int recurse;
54 extern int xfer_dirs;
55 extern int protect_args;
56 extern int relative_paths;
57 extern int sanitize_paths;
58 extern int curr_dir_depth;
59 extern int curr_dir_len;
60 extern int module_id;
61 extern int rsync_port;
62 extern int whole_file;
63 extern int read_batch;
64 extern int write_batch;
65 extern int batch_fd;
66 extern int sock_f_in;
67 extern int sock_f_out;
68 extern int filesfrom_fd;
69 extern int connect_timeout;
70 extern int send_msgs_to_gen;
71 extern pid_t cleanup_child_pid;
72 extern size_t bwlimit_writemax;
73 extern unsigned int module_dirlen;
74 extern struct stats stats;
75 extern char *stdout_format;
76 extern char *logfile_format;
77 extern char *filesfrom_host;
78 extern char *partial_dir;
79 extern char *dest_option;
80 extern char *rsync_path;
81 extern char *shell_cmd;
82 extern char *batch_name;
83 extern char *password_file;
84 extern char *backup_dir;
85 extern char curr_dir[MAXPATHLEN];
86 extern char backup_dir_buf[MAXPATHLEN];
87 extern char *basis_dir[MAX_BASIS_DIRS+1];
88 extern struct file_list *first_flist;
89 extern filter_rule_list daemon_filter_list;
90
91 uid_t our_uid;
92 gid_t our_gid;
93 int am_generator = 0;
94 int local_server = 0;
95 int daemon_over_rsh = 0;
96 mode_t orig_umask = 0;
97 int batch_gen_fd = -1;
98 int sender_keeps_checksum = 0;
99
100 /* There's probably never more than at most 2 outstanding child processes,
101  * but set it higher, just in case. */
102 #define MAXCHILDPROCS 7
103
104 #ifdef HAVE_SIGACTION
105 # ifdef HAVE_SIGPROCMASK
106 #  define SIGACTMASK(n,h) SIGACTION(n,h), sigaddset(&sigmask,(n))
107 # else
108 #  define SIGACTMASK(n,h) SIGACTION(n,h)
109 # endif
110 static struct sigaction sigact;
111 #endif
112
113 struct pid_status {
114         pid_t pid;
115         int status;
116 } pid_stat_table[MAXCHILDPROCS];
117
118 static time_t starttime, endtime;
119 static int64 total_read, total_written;
120
121 static void show_malloc_stats(void);
122
123 /* Works like waitpid(), but if we already harvested the child pid in our
124  * remember_children(), we succeed instead of returning an error. */
125 pid_t wait_process(pid_t pid, int *status_ptr, int flags)
126 {
127         pid_t waited_pid;
128         
129         do {
130                 waited_pid = waitpid(pid, status_ptr, flags);
131         } while (waited_pid == -1 && errno == EINTR);
132
133         if (waited_pid == -1 && errno == ECHILD) {
134                 /* Status of requested child no longer available:  check to
135                  * see if it was processed by remember_children(). */
136                 int cnt;
137                 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
138                         if (pid == pid_stat_table[cnt].pid) {
139                                 *status_ptr = pid_stat_table[cnt].status;
140                                 pid_stat_table[cnt].pid = 0;
141                                 return pid;
142                         }
143                 }
144         }
145
146         return waited_pid;
147 }
148
149 /* Wait for a process to exit, calling io_flush while waiting. */
150 static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
151 {
152         pid_t waited_pid;
153         int status;
154
155         while ((waited_pid = wait_process(pid, &status, WNOHANG)) == 0) {
156                 msleep(20);
157                 io_flush(FULL_FLUSH);
158         }
159
160         /* TODO: If the child exited on a signal, then log an
161          * appropriate error message.  Perhaps we should also accept a
162          * message describing the purpose of the child.  Also indicate
163          * this to the caller so that they know something went wrong. */
164         if (waited_pid < 0) {
165                 rsyserr(FERROR, errno, "waitpid");
166                 *exit_code_ptr = RERR_WAITCHILD;
167         } else if (!WIFEXITED(status)) {
168 #ifdef WCOREDUMP
169                 if (WCOREDUMP(status))
170                         *exit_code_ptr = RERR_CRASHED;
171                 else
172 #endif
173                 if (WIFSIGNALED(status))
174                         *exit_code_ptr = RERR_TERMINATED;
175                 else
176                         *exit_code_ptr = RERR_WAITCHILD;
177         } else
178                 *exit_code_ptr = WEXITSTATUS(status);
179 }
180
181 void write_del_stats(int f)
182 {
183         if (read_batch)
184                 write_int(f, NDX_DEL_STATS);
185         else
186                 write_ndx(f, NDX_DEL_STATS);
187         write_varint(f, stats.deleted_files - stats.deleted_dirs
188                       - stats.deleted_symlinks - stats.deleted_devices
189                       - stats.deleted_specials);
190         write_varint(f, stats.deleted_dirs);
191         write_varint(f, stats.deleted_symlinks);
192         write_varint(f, stats.deleted_devices);
193         write_varint(f, stats.deleted_specials);
194 }
195
196 void read_del_stats(int f)
197 {
198         stats.deleted_files = read_varint(f);
199         stats.deleted_files += stats.deleted_dirs = read_varint(f);
200         stats.deleted_files += stats.deleted_symlinks = read_varint(f);
201         stats.deleted_files += stats.deleted_devices = read_varint(f);
202         stats.deleted_files += stats.deleted_specials = read_varint(f);
203 }
204
205 /* This function gets called from all 3 processes.  We want the client side
206  * to actually output the text, but the sender is the only process that has
207  * all the stats we need.  So, if we're a client sender, we do the report.
208  * If we're a server sender, we write the stats on the supplied fd.  If
209  * we're the client receiver we read the stats from the supplied fd and do
210  * the report.  All processes might also generate a set of debug stats, if
211  * the verbose level is high enough (this is the only thing that the
212  * generator process and the server receiver ever do here). */
213 static void handle_stats(int f)
214 {
215         endtime = time(NULL);
216
217         /* Cache two stats because the read/write code can change it. */
218         total_read = stats.total_read;
219         total_written = stats.total_written;
220
221         if (INFO_GTE(STATS, 3)) {
222                 /* These come out from every process */
223                 show_malloc_stats();
224                 show_flist_stats();
225         }
226
227         if (am_generator)
228                 return;
229
230         if (am_daemon) {
231                 if (f == -1 || !am_sender)
232                         return;
233         }
234
235         if (am_server) {
236                 if (am_sender) {
237                         write_varlong30(f, total_read, 3);
238                         write_varlong30(f, total_written, 3);
239                         write_varlong30(f, stats.total_size, 3);
240                         if (protocol_version >= 29) {
241                                 write_varlong30(f, stats.flist_buildtime, 3);
242                                 write_varlong30(f, stats.flist_xfertime, 3);
243                         }
244                 }
245                 return;
246         }
247
248         /* this is the client */
249
250         if (f < 0 && !am_sender) /* e.g. when we got an empty file list. */
251                 ;
252         else if (!am_sender) {
253                 /* Read the first two in opposite order because the meaning of
254                  * read/write swaps when switching from sender to receiver. */
255                 total_written = read_varlong30(f, 3);
256                 total_read = read_varlong30(f, 3);
257                 stats.total_size = read_varlong30(f, 3);
258                 if (protocol_version >= 29) {
259                         stats.flist_buildtime = read_varlong30(f, 3);
260                         stats.flist_xfertime = read_varlong30(f, 3);
261                 }
262         } else if (write_batch) {
263                 /* The --read-batch process is going to be a client
264                  * receiver, so we need to give it the stats. */
265                 write_varlong30(batch_fd, total_read, 3);
266                 write_varlong30(batch_fd, total_written, 3);
267                 write_varlong30(batch_fd, stats.total_size, 3);
268                 if (protocol_version >= 29) {
269                         write_varlong30(batch_fd, stats.flist_buildtime, 3);
270                         write_varlong30(batch_fd, stats.flist_xfertime, 3);
271                 }
272         }
273 }
274
275 static void output_itemized_counts(const char *prefix, int *counts)
276 {
277         static char *labels[] = { "reg", "dir", "link", "dev", "special" };
278         char buf[1024], *pre = " (";
279         int j, len = 0;
280         int total = counts[0];
281         if (total) {
282                 counts[0] -= counts[1] + counts[2] + counts[3] + counts[4];
283                 for (j = 0; j < 5; j++) {
284                         if (counts[j]) {
285                                 len += snprintf(buf+len, sizeof buf - len - 2,
286                                         "%s%s: %s",
287                                         pre, labels[j], comma_num(counts[j]));
288                                 pre = ", ";
289                         }
290                 }
291                 buf[len++] = ')';
292         }
293         buf[len] = '\0';
294         rprintf(FINFO, "%s: %s%s\n", prefix, comma_num(total), buf);
295 }
296
297 static void output_summary(void)
298 {
299         if (INFO_GTE(STATS, 2)) {
300                 rprintf(FCLIENT, "\n");
301                 output_itemized_counts("Number of files", &stats.num_files);
302                 if (protocol_version >= 29)
303                         output_itemized_counts("Number of created files", &stats.created_files);
304                 if (protocol_version >= 31)
305                         output_itemized_counts("Number of deleted files", &stats.deleted_files);
306                 rprintf(FINFO,"Number of regular files transferred: %s\n",
307                         comma_num(stats.xferred_files));
308                 rprintf(FINFO,"Total file size: %s bytes\n",
309                         human_num(stats.total_size));
310                 rprintf(FINFO,"Total transferred file size: %s bytes\n",
311                         human_num(stats.total_transferred_size));
312                 rprintf(FINFO,"Literal data: %s bytes\n",
313                         human_num(stats.literal_data));
314                 rprintf(FINFO,"Matched data: %s bytes\n",
315                         human_num(stats.matched_data));
316                 rprintf(FINFO,"File list size: %s\n",
317                         human_num(stats.flist_size));
318                 if (stats.flist_buildtime) {
319                         rprintf(FINFO,
320                                 "File list generation time: %s seconds\n",
321                                 comma_dnum((double)stats.flist_buildtime / 1000, 3));
322                         rprintf(FINFO,
323                                 "File list transfer time: %s seconds\n",
324                                 comma_dnum((double)stats.flist_xfertime / 1000, 3));
325                 }
326                 rprintf(FINFO,"Total bytes sent: %s\n",
327                         human_num(total_written));
328                 rprintf(FINFO,"Total bytes received: %s\n",
329                         human_num(total_read));
330         }
331
332         if (INFO_GTE(STATS, 1)) {
333                 rprintf(FCLIENT, "\n");
334                 rprintf(FINFO,
335                         "sent %s bytes  received %s bytes  %s bytes/sec\n",
336                         human_num(total_written), human_num(total_read),
337                         human_dnum((total_written + total_read)/(0.5 + (endtime - starttime)), 2));
338                 rprintf(FINFO, "total size is %s  speedup is %s%s\n",
339                         human_num(stats.total_size),
340                         comma_dnum((double)stats.total_size / (total_written+total_read), 2),
341                         write_batch < 0 ? " (BATCH ONLY)" : dry_run ? " (DRY RUN)" : "");
342         }
343
344         fflush(stdout);
345         fflush(stderr);
346 }
347
348
349 /**
350  * If our C library can get malloc statistics, then show them to FINFO
351  **/
352 static void show_malloc_stats(void)
353 {
354 #ifdef HAVE_MALLINFO
355         struct mallinfo mi;
356
357         mi = mallinfo();
358
359         rprintf(FCLIENT, "\n");
360         rprintf(FINFO, RSYNC_NAME "[%d] (%s%s%s) heap statistics:\n",
361                 getpid(), am_server ? "server " : "",
362                 am_daemon ? "daemon " : "", who_am_i());
363         rprintf(FINFO, "  arena:     %10ld   (bytes from sbrk)\n",
364                 (long)mi.arena);
365         rprintf(FINFO, "  ordblks:   %10ld   (chunks not in use)\n",
366                 (long)mi.ordblks);
367         rprintf(FINFO, "  smblks:    %10ld\n",
368                 (long)mi.smblks);
369         rprintf(FINFO, "  hblks:     %10ld   (chunks from mmap)\n",
370                 (long)mi.hblks);
371         rprintf(FINFO, "  hblkhd:    %10ld   (bytes from mmap)\n",
372                 (long)mi.hblkhd);
373         rprintf(FINFO, "  allmem:    %10ld   (bytes from sbrk + mmap)\n",
374                 (long)mi.arena + mi.hblkhd);
375         rprintf(FINFO, "  usmblks:   %10ld\n",
376                 (long)mi.usmblks);
377         rprintf(FINFO, "  fsmblks:   %10ld\n",
378                 (long)mi.fsmblks);
379         rprintf(FINFO, "  uordblks:  %10ld   (bytes used)\n",
380                 (long)mi.uordblks);
381         rprintf(FINFO, "  fordblks:  %10ld   (bytes free)\n",
382                 (long)mi.fordblks);
383         rprintf(FINFO, "  keepcost:  %10ld   (bytes in releasable chunk)\n",
384                 (long)mi.keepcost);
385 #endif /* HAVE_MALLINFO */
386 }
387
388
389 /* Start the remote shell.   cmd may be NULL to use the default. */
390 static pid_t do_cmd(char *cmd, char *machine, char *user, char **remote_argv, int remote_argc,
391                     int *f_in_p, int *f_out_p)
392 {
393         int i, argc = 0;
394         char *args[MAX_ARGS];
395         pid_t pid;
396         int dash_l_set = 0;
397
398         if (!read_batch && !local_server) {
399                 char *t, *f, in_quote = '\0';
400                 char *rsh_env = getenv(RSYNC_RSH_ENV);
401                 if (!cmd)
402                         cmd = rsh_env;
403                 if (!cmd)
404                         cmd = RSYNC_RSH;
405                 cmd = strdup(cmd); /* MEMORY LEAK */
406                 if (!cmd)
407                         goto oom;
408
409                 for (t = f = cmd; *f; f++) {
410                         if (*f == ' ')
411                                 continue;
412                         /* Comparison leaves rooms for server_options(). */
413                         if (argc >= MAX_ARGS - MAX_SERVER_ARGS)
414                                 goto arg_overflow;
415                         args[argc++] = t;
416                         while (*f != ' ' || in_quote) {
417                                 if (!*f) {
418                                         if (in_quote) {
419                                                 rprintf(FERROR,
420                                                     "Missing trailing-%c in remote-shell command.\n",
421                                                     in_quote);
422                                                 exit_cleanup(RERR_SYNTAX);
423                                         }
424                                         f--;
425                                         break;
426                                 }
427                                 if (*f == '\'' || *f == '"') {
428                                         if (!in_quote) {
429                                                 in_quote = *f++;
430                                                 continue;
431                                         }
432                                         if (*f == in_quote && *++f != in_quote) {
433                                                 in_quote = '\0';
434                                                 continue;
435                                         }
436                                 }
437                                 *t++ = *f++;
438                         }
439                         *t++ = '\0';
440                 }
441
442                 /* check to see if we've already been given '-l user' in
443                  * the remote-shell command */
444                 for (i = 0; i < argc-1; i++) {
445                         if (!strcmp(args[i], "-l") && args[i+1][0] != '-')
446                                 dash_l_set = 1;
447                 }
448
449 #ifdef HAVE_REMSH
450                 /* remsh (on HPUX) takes the arguments the other way around */
451                 args[argc++] = machine;
452                 if (user && !(daemon_over_rsh && dash_l_set)) {
453                         args[argc++] = "-l";
454                         args[argc++] = user;
455                 }
456 #else
457                 if (user && !(daemon_over_rsh && dash_l_set)) {
458                         args[argc++] = "-l";
459                         args[argc++] = user;
460                 }
461                 args[argc++] = machine;
462 #endif
463
464                 args[argc++] = rsync_path;
465
466                 if (blocking_io < 0) {
467                         char *cp;
468                         if ((cp = strrchr(cmd, '/')) != NULL)
469                                 cp++;
470                         else
471                                 cp = cmd;
472                         if (strcmp(cp, "rsh") == 0 || strcmp(cp, "remsh") == 0)
473                                 blocking_io = 1;
474                 }
475
476                 server_options(args,&argc);
477
478                 if (argc >= MAX_ARGS - 2)
479                         goto arg_overflow;
480         }
481
482         args[argc++] = ".";
483
484         if (!daemon_over_rsh) {
485                 while (remote_argc > 0) {
486                         if (argc >= MAX_ARGS - 1) {
487                           arg_overflow:
488                                 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
489                                 exit_cleanup(RERR_SYNTAX);
490                         }
491                         args[argc++] = *remote_argv++;
492                         remote_argc--;
493                 }
494         }
495
496         args[argc] = NULL;
497
498         if (DEBUG_GTE(CMD, 2)) {
499                 for (i = 0; i < argc; i++)
500                         rprintf(FCLIENT, "cmd[%d]=%s ", i, args[i]);
501                 rprintf(FCLIENT, "\n");
502         }
503
504         if (read_batch) {
505                 int from_gen_pipe[2];
506                 set_allow_inc_recurse();
507                 if (fd_pair(from_gen_pipe) < 0) {
508                         rsyserr(FERROR, errno, "pipe");
509                         exit_cleanup(RERR_IPC);
510                 }
511                 batch_gen_fd = from_gen_pipe[0];
512                 *f_out_p = from_gen_pipe[1];
513                 *f_in_p = batch_fd;
514                 pid = (pid_t)-1; /* no child pid */
515 #ifdef ICONV_CONST
516                 setup_iconv();
517 #endif
518         } else if (local_server) {
519                 /* If the user didn't request --[no-]whole-file, force
520                  * it on, but only if we're not batch processing. */
521                 if (whole_file < 0 && !write_batch)
522                         whole_file = 1;
523                 set_allow_inc_recurse();
524                 pid = local_child(argc, args, f_in_p, f_out_p, child_main);
525 #ifdef ICONV_CONST
526                 setup_iconv();
527 #endif
528         } else {
529                 pid = piped_child(args, f_in_p, f_out_p);
530 #ifdef ICONV_CONST
531                 setup_iconv();
532 #endif
533                 if (protect_args && !daemon_over_rsh)
534                         send_protected_args(*f_out_p, args);
535         }
536
537         return pid;
538
539   oom:
540         out_of_memory("do_cmd");
541         return 0; /* not reached */
542 }
543
544 /* The receiving side operates in one of two modes:
545  *
546  * 1. it receives any number of files into a destination directory,
547  * placing them according to their names in the file-list.
548  *
549  * 2. it receives a single file and saves it using the name in the
550  * destination path instead of its file-list name.  This requires a
551  * "local name" for writing out the destination file.
552  *
553  * So, our task is to figure out what mode/local-name we need.
554  * For mode 1, we change into the destination directory and return NULL.
555  * For mode 2, we change into the directory containing the destination
556  * file (if we aren't already there) and return the local-name. */
557 static char *get_local_name(struct file_list *flist, char *dest_path)
558 {
559         STRUCT_STAT st;
560         int statret;
561         char *cp;
562
563         if (DEBUG_GTE(RECV, 1)) {
564                 rprintf(FINFO, "get_local_name count=%d %s\n",
565                         file_total, NS(dest_path));
566         }
567
568         if (!dest_path || list_only)
569                 return NULL;
570
571         if (daemon_filter_list.head) {
572                 char *slash = strrchr(dest_path, '/');
573                 if (slash && (slash[1] == '\0' || (slash[1] == '.' && slash[2] == '\0')))
574                         *slash = '\0';
575                 else
576                         slash = NULL;
577                 if ((*dest_path != '.' || dest_path[1] != '\0')
578                  && (check_filter(&daemon_filter_list, FLOG, dest_path, 0) < 0
579                   || check_filter(&daemon_filter_list, FLOG, dest_path, 1) < 0)) {
580                         rprintf(FERROR, "skipping daemon-excluded destination \"%s\"\n",
581                                 dest_path);
582                         exit_cleanup(RERR_FILESELECT);
583                 }
584                 if (slash)
585                         *slash = '/';
586         }
587
588         /* See what currently exists at the destination. */
589         if ((statret = do_stat(dest_path, &st)) == 0) {
590                 /* If the destination is a dir, enter it and use mode 1. */
591                 if (S_ISDIR(st.st_mode)) {
592                         if (!change_dir(dest_path, CD_NORMAL)) {
593                                 rsyserr(FERROR, errno, "change_dir#1 %s failed",
594                                         full_fname(dest_path));
595                                 exit_cleanup(RERR_FILESELECT);
596                         }
597                         return NULL;
598                 }
599                 if (file_total > 1) {
600                         rprintf(FERROR,
601                                 "ERROR: destination must be a directory when"
602                                 " copying more than 1 file\n");
603                         exit_cleanup(RERR_FILESELECT);
604                 }
605                 if (file_total == 1 && S_ISDIR(flist->files[0]->mode)) {
606                         rprintf(FERROR,
607                                 "ERROR: cannot overwrite non-directory"
608                                 " with a directory\n");
609                         exit_cleanup(RERR_FILESELECT);
610                 }
611         } else if (errno != ENOENT) {
612                 /* If we don't know what's at the destination, fail. */
613                 rsyserr(FERROR, errno, "ERROR: cannot stat destination %s",
614                         full_fname(dest_path));
615                 exit_cleanup(RERR_FILESELECT);
616         }
617
618         cp = strrchr(dest_path, '/');
619
620         /* If we need a destination directory because the transfer is not
621          * of a single non-directory or the user has requested one via a
622          * destination path ending in a slash, create one and use mode 1. */
623         if (file_total > 1 || (cp && !cp[1])) {
624                 /* Lop off the final slash (if any). */
625                 if (cp && !cp[1])
626                         *cp = '\0';
627
628                 if (statret == 0) {
629                         rprintf(FERROR,
630                             "ERROR: destination path is not a directory\n");
631                         exit_cleanup(RERR_SYNTAX);
632                 }
633
634                 if (mkdir_defmode(dest_path) != 0) {
635                         rsyserr(FERROR, errno, "mkdir %s failed",
636                                 full_fname(dest_path));
637                         exit_cleanup(RERR_FILEIO);
638                 }
639
640                 if (flist->high >= flist->low
641                  && strcmp(flist->files[flist->low]->basename, ".") == 0)
642                         flist->files[0]->flags |= FLAG_DIR_CREATED;
643
644                 if (INFO_GTE(NAME, 1))
645                         rprintf(FINFO, "created directory %s\n", dest_path);
646
647                 if (dry_run) {
648                         /* Indicate that dest dir doesn't really exist. */
649                         dry_run++;
650                 }
651
652                 if (!change_dir(dest_path, dry_run > 1 ? CD_SKIP_CHDIR : CD_NORMAL)) {
653                         rsyserr(FERROR, errno, "change_dir#2 %s failed",
654                                 full_fname(dest_path));
655                         exit_cleanup(RERR_FILESELECT);
656                 }
657
658                 return NULL;
659         }
660
661         /* Otherwise, we are writing a single file, possibly on top of an
662          * existing non-directory.  Change to the item's parent directory
663          * (if it has a path component), return the basename of the
664          * destination file as the local name, and use mode 2. */
665         if (!cp)
666                 return dest_path;
667
668         if (cp == dest_path)
669                 dest_path = "/";
670
671         *cp = '\0';
672         if (!change_dir(dest_path, CD_NORMAL)) {
673                 rsyserr(FERROR, errno, "change_dir#3 %s failed",
674                         full_fname(dest_path));
675                 exit_cleanup(RERR_FILESELECT);
676         }
677         *cp = '/';
678
679         return cp + 1;
680 }
681
682 /* This function checks on our alternate-basis directories.  If we're in
683  * dry-run mode and the destination dir does not yet exist, we'll try to
684  * tweak any dest-relative paths to make them work for a dry-run (the
685  * destination dir must be in curr_dir[] when this function is called).
686  * We also warn about any arg that is non-existent or not a directory. */
687 static void check_alt_basis_dirs(void)
688 {
689         STRUCT_STAT st;
690         char **dir_p, *slash = strrchr(curr_dir, '/');
691
692         for (dir_p = basis_dir; *dir_p; dir_p++) {
693                 if (dry_run > 1 && **dir_p != '/') {
694                         int len = curr_dir_len + 1 + strlen(*dir_p) + 1;
695                         char *new = new_array(char, len);
696                         if (!new)
697                                 out_of_memory("check_alt_basis_dirs");
698                         if (slash && strncmp(*dir_p, "../", 3) == 0) {
699                             /* We want to remove only one leading "../" prefix for
700                              * the directory we couldn't create in dry-run mode:
701                              * this ensures that any other ".." references get
702                              * evaluated the same as they would for a live copy. */
703                             *slash = '\0';
704                             pathjoin(new, len, curr_dir, *dir_p + 3);
705                             *slash = '/';
706                         } else
707                             pathjoin(new, len, curr_dir, *dir_p);
708                         *dir_p = new;
709                 }
710                 if (do_stat(*dir_p, &st) < 0) {
711                         rprintf(FWARNING, "%s arg does not exist: %s\n",
712                                 dest_option, *dir_p);
713                 } else if (!S_ISDIR(st.st_mode)) {
714                         rprintf(FWARNING, "%s arg is not a dir: %s\n",
715                                 dest_option, *dir_p);
716                 }
717         }
718 }
719
720 /* This is only called by the sender. */
721 static void read_final_goodbye(int f_in, int f_out)
722 {
723         int i, iflags, xlen;
724         uchar fnamecmp_type;
725         char xname[MAXPATHLEN];
726
727         if (protocol_version < 29)
728                 i = read_int(f_in);
729         else {
730                 i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
731                 if (protocol_version >= 31 && i == NDX_DONE) {
732                         if (am_sender)
733                                 write_ndx(f_out, NDX_DONE);
734                         else {
735                                 if (batch_gen_fd >= 0) {
736                                         while (read_int(batch_gen_fd) != NDX_DEL_STATS) {}
737                                         read_del_stats(batch_gen_fd);
738                                 }
739                                 write_int(f_out, NDX_DONE);
740                         }
741                         i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
742                 }
743         }
744
745         if (i != NDX_DONE) {
746                 rprintf(FERROR, "Invalid packet at end of run (%d) [%s]\n",
747                         i, who_am_i());
748                 exit_cleanup(RERR_PROTOCOL);
749         }
750 }
751
752 static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
753 {
754         struct file_list *flist;
755         char *dir = argv[0];
756
757         if (DEBUG_GTE(SEND, 1)) {
758                 rprintf(FINFO, "server_sender starting pid=%ld\n",
759                         (long)getpid());
760         }
761
762         if (am_daemon && lp_write_only(module_id)) {
763                 rprintf(FERROR, "ERROR: module is write only\n");
764                 exit_cleanup(RERR_SYNTAX);
765                 return;
766         }
767         if (am_daemon && lp_read_only(module_id) && remove_source_files) {
768                 rprintf(FERROR,
769                     "ERROR: --remove-%s-files cannot be used with a read-only module\n",
770                     remove_source_files == 1 ? "source" : "sent");
771                 exit_cleanup(RERR_SYNTAX);
772                 return;
773         }
774
775         if (!relative_paths) {
776                 if (!change_dir(dir, CD_NORMAL)) {
777                         rsyserr(FERROR, errno, "change_dir#3 %s failed",
778                                 full_fname(dir));
779                         exit_cleanup(RERR_FILESELECT);
780                 }
781         }
782         argc--;
783         argv++;
784
785         if (argc == 0 && (recurse || xfer_dirs || list_only)) {
786                 argc = 1;
787                 argv--;
788                 argv[0] = ".";
789         }
790
791         flist = send_file_list(f_out,argc,argv);
792         if (!flist || flist->used == 0)
793                 exit_cleanup(0);
794
795         io_start_buffering_in(f_in);
796
797         send_files(f_in, f_out);
798         io_flush(FULL_FLUSH);
799         handle_stats(f_out);
800         if (protocol_version >= 24)
801                 read_final_goodbye(f_in, f_out);
802         io_flush(FULL_FLUSH);
803         exit_cleanup(0);
804 }
805
806
807 static int do_recv(int f_in, int f_out, char *local_name)
808 {
809         int pid;
810         int exit_code = 0;
811         int error_pipe[2];
812
813         /* The receiving side mustn't obey this, or an existing symlink that
814          * points to an identical file won't be replaced by the referent. */
815         copy_links = copy_dirlinks = copy_unsafe_links = 0;
816
817 #ifdef SUPPORT_HARD_LINKS
818         if (preserve_hard_links && !inc_recurse)
819                 match_hard_links(first_flist);
820 #endif
821
822         if (fd_pair(error_pipe) < 0) {
823                 rsyserr(FERROR, errno, "pipe failed in do_recv");
824                 exit_cleanup(RERR_IPC);
825         }
826
827         if (backup_dir) {
828                 int ret = make_path(backup_dir_buf, MKP_DROP_NAME); /* drops trailing slash */
829                 if (ret < 0)
830                         exit_cleanup(RERR_SYNTAX);
831                 if (ret)
832                         rprintf(FINFO, "Created backup_dir %s\n", backup_dir_buf);
833                 else if (INFO_GTE(BACKUP, 1))
834                         rprintf(FINFO, "backup_dir is %s\n", backup_dir_buf);
835         }
836
837         io_flush(FULL_FLUSH);
838
839         if ((pid = do_fork()) == -1) {
840                 rsyserr(FERROR, errno, "fork failed in do_recv");
841                 exit_cleanup(RERR_IPC);
842         }
843
844         if (pid == 0) {
845                 send_msgs_to_gen = am_server;
846
847                 close(error_pipe[0]);
848
849                 /* We can't let two processes write to the socket at one time. */
850                 io_end_multiplex_out(False);
851                 if (f_in != f_out)
852                         close(f_out);
853                 sock_f_out = -1;
854                 f_out = error_pipe[1];
855
856                 bwlimit_writemax = 0; /* receiver doesn't need to do this */
857
858                 if (read_batch)
859                         io_start_buffering_in(f_in);
860                 io_start_multiplex_out(f_out);
861
862                 recv_files(f_in, f_out, local_name);
863                 io_flush(FULL_FLUSH);
864                 handle_stats(f_in);
865
866                 if (output_needs_newline) {
867                         fputc('\n', stdout);
868                         output_needs_newline = 0;
869                 }
870
871                 write_int(f_out, NDX_DONE);
872                 send_msg(MSG_STATS, (char*)&stats.total_read, sizeof stats.total_read, 0);
873                 io_flush(FULL_FLUSH);
874
875                 /* Handle any keep-alive packets from the post-processing work
876                  * that the generator does. */
877                 if (protocol_version >= 29) {
878                         kluge_around_eof = -1;
879
880                         /* This should only get stopped via a USR2 signal. */
881                         read_final_goodbye(f_in, f_out);
882
883                         rprintf(FERROR, "Invalid packet at end of run [%s]\n",
884                                 who_am_i());
885                         exit_cleanup(RERR_PROTOCOL);
886                 }
887
888                 /* Finally, we go to sleep until our parent kills us with a
889                  * USR2 signal.  We sleep for a short time, as on some OSes
890                  * a signal won't interrupt a sleep! */
891                 while (1)
892                         msleep(20);
893         }
894
895         am_generator = 1;
896
897         io_end_multiplex_in(False);
898         if (write_batch && !am_server)
899                 stop_write_batch();
900
901         close(error_pipe[1]);
902         if (f_in != f_out)
903                 close(f_in);
904         sock_f_in = -1;
905         f_in = error_pipe[0];
906
907         io_start_buffering_out(f_out);
908         io_start_multiplex_in(f_in);
909
910 #ifdef SUPPORT_HARD_LINKS
911         if (preserve_hard_links && inc_recurse) {
912                 struct file_list *flist;
913                 for (flist = first_flist; flist; flist = flist->next)
914                         match_hard_links(flist);
915         }
916 #endif
917
918         generate_files(f_out, local_name);
919
920         handle_stats(-1);
921         io_flush(FULL_FLUSH);
922         if (protocol_version >= 24) {
923                 /* send a final goodbye message */
924                 write_ndx(f_out, NDX_DONE);
925         }
926         io_flush(FULL_FLUSH);
927
928         kill(pid, SIGUSR2);
929         wait_process_with_flush(pid, &exit_code);
930         return exit_code;
931 }
932
933 static void do_server_recv(int f_in, int f_out, int argc, char *argv[])
934 {
935         int exit_code;
936         struct file_list *flist;
937         char *local_name = NULL;
938         int negated_levels;
939
940         if (filesfrom_fd >= 0 && !msgs2stderr && protocol_version < 31) {
941                 /* We can't mix messages with files-from data on the socket,
942                  * so temporarily turn off info/debug messages. */
943                 negate_output_levels();
944                 negated_levels = 1;
945         } else
946                 negated_levels = 0;
947
948         if (DEBUG_GTE(RECV, 1)) {
949                 rprintf(FINFO, "server_recv(%d) starting pid=%ld\n",
950                         argc, (long)getpid());
951         }
952
953         if (am_daemon && lp_read_only(module_id)) {
954                 rprintf(FERROR,"ERROR: module is read only\n");
955                 exit_cleanup(RERR_SYNTAX);
956                 return;
957         }
958
959         if (argc > 0) {
960                 char *dir = argv[0];
961                 argc--;
962                 argv++;
963                 if (!am_daemon && !change_dir(dir, CD_NORMAL)) {
964                         rsyserr(FERROR, errno, "change_dir#4 %s failed",
965                                 full_fname(dir));
966                         exit_cleanup(RERR_FILESELECT);
967                 }
968         }
969
970         if (protocol_version >= 30)
971                 io_start_multiplex_in(f_in);
972         else
973                 io_start_buffering_in(f_in);
974         recv_filter_list(f_in);
975
976         if (filesfrom_fd >= 0) {
977                 /* We need to send the files-from names to the sender at the
978                  * same time that we receive the file-list from them, so we
979                  * need the IO routines to automatically write out the names
980                  * onto our f_out socket as we read the file-list.  This
981                  * avoids both deadlock and extra delays/buffers. */
982                 start_filesfrom_forwarding(filesfrom_fd);
983                 filesfrom_fd = -1;
984         }
985
986         flist = recv_file_list(f_in);
987         if (!flist) {
988                 rprintf(FERROR,"server_recv: recv_file_list error\n");
989                 exit_cleanup(RERR_FILESELECT);
990         }
991         if (inc_recurse && file_total == 1)
992                 recv_additional_file_list(f_in);
993
994         if (negated_levels)
995                 negate_output_levels();
996
997         if (argc > 0)
998                 local_name = get_local_name(flist,argv[0]);
999
1000         /* Now that we know what our destination directory turned out to be,
1001          * we can sanitize the --link-/copy-/compare-dest args correctly. */
1002         if (sanitize_paths) {
1003                 char **dir_p;
1004                 for (dir_p = basis_dir; *dir_p; dir_p++)
1005                         *dir_p = sanitize_path(NULL, *dir_p, NULL, curr_dir_depth, SP_DEFAULT);
1006                 if (partial_dir)
1007                         partial_dir = sanitize_path(NULL, partial_dir, NULL, curr_dir_depth, SP_DEFAULT);
1008         }
1009         check_alt_basis_dirs();
1010
1011         if (daemon_filter_list.head) {
1012                 char **dir_p;
1013                 filter_rule_list *elp = &daemon_filter_list;
1014
1015                 for (dir_p = basis_dir; *dir_p; dir_p++) {
1016                         char *dir = *dir_p;
1017                         if (*dir == '/')
1018                                 dir += module_dirlen;
1019                         if (check_filter(elp, FLOG, dir, 1) < 0)
1020                                 goto options_rejected;
1021                 }
1022                 if (partial_dir && *partial_dir == '/'
1023                  && check_filter(elp, FLOG, partial_dir + module_dirlen, 1) < 0) {
1024                     options_rejected:
1025                         rprintf(FERROR,
1026                                 "Your options have been rejected by the server.\n");
1027                         exit_cleanup(RERR_SYNTAX);
1028                 }
1029         }
1030
1031         exit_code = do_recv(f_in, f_out, local_name);
1032         exit_cleanup(exit_code);
1033 }
1034
1035
1036 int child_main(int argc, char *argv[])
1037 {
1038         start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1039         return 0;
1040 }
1041
1042
1043 void start_server(int f_in, int f_out, int argc, char *argv[])
1044 {
1045         set_nonblocking(f_in);
1046         set_nonblocking(f_out);
1047
1048         io_set_sock_fds(f_in, f_out);
1049         setup_protocol(f_out, f_in);
1050
1051         if (protocol_version >= 23)
1052                 io_start_multiplex_out(f_out);
1053
1054         if (am_sender) {
1055                 keep_dirlinks = 0; /* Must be disabled on the sender. */
1056                 if (need_messages_from_generator)
1057                         io_start_multiplex_in(f_in);
1058                 recv_filter_list(f_in);
1059                 do_server_sender(f_in, f_out, argc, argv);
1060         } else
1061                 do_server_recv(f_in, f_out, argc, argv);
1062         exit_cleanup(0);
1063 }
1064
1065 /* This is called once the connection has been negotiated.  It is used
1066  * for rsyncd, remote-shell, and local connections. */
1067 int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
1068 {
1069         struct file_list *flist = NULL;
1070         int exit_code = 0, exit_code2 = 0;
1071         char *local_name = NULL;
1072
1073         cleanup_child_pid = pid;
1074         if (!read_batch) {
1075                 set_nonblocking(f_in);
1076                 set_nonblocking(f_out);
1077         }
1078
1079         io_set_sock_fds(f_in, f_out);
1080         setup_protocol(f_out,f_in);
1081
1082         /* We set our stderr file handle to blocking because ssh might have
1083          * set it to non-blocking.  This can be particularly troublesome if
1084          * stderr is a clone of stdout, because ssh would have set our stdout
1085          * to non-blocking at the same time (which can easily cause us to lose
1086          * output from our print statements).  This kluge shouldn't cause ssh
1087          * any problems for how we use it.  Note also that we delayed setting
1088          * this until after the above protocol setup so that we know for sure
1089          * that ssh is done twiddling its file descriptors.  */
1090         set_blocking(STDERR_FILENO);
1091
1092         if (am_sender) {
1093                 keep_dirlinks = 0; /* Must be disabled on the sender. */
1094
1095                 if (always_checksum
1096                  && (log_format_has(stdout_format, 'C')
1097                   || log_format_has(logfile_format, 'C')))
1098                         sender_keeps_checksum = 1;
1099
1100                 if (protocol_version >= 30)
1101                         io_start_multiplex_out(f_out);
1102                 else
1103                         io_start_buffering_out(f_out);
1104                 if (protocol_version >= 31 || (!filesfrom_host && protocol_version >= 23))
1105                         io_start_multiplex_in(f_in);
1106                 send_filter_list(f_out);
1107                 if (filesfrom_host)
1108                         filesfrom_fd = f_in;
1109
1110                 if (write_batch && !am_server)
1111                         start_write_batch(f_out);
1112                 flist = send_file_list(f_out, argc, argv);
1113                 if (DEBUG_GTE(FLIST, 3))
1114                         rprintf(FINFO,"file list sent\n");
1115
1116                 if (protocol_version < 31 && filesfrom_host && protocol_version >= 23)
1117                         io_start_multiplex_in(f_in);
1118
1119                 io_flush(NORMAL_FLUSH);
1120                 send_files(f_in, f_out);
1121                 io_flush(FULL_FLUSH);
1122                 handle_stats(-1);
1123                 if (protocol_version >= 24)
1124                         read_final_goodbye(f_in, f_out);
1125                 if (pid != -1) {
1126                         if (DEBUG_GTE(EXIT, 2))
1127                                 rprintf(FINFO,"client_run waiting on %d\n", (int) pid);
1128                         io_flush(FULL_FLUSH);
1129                         wait_process_with_flush(pid, &exit_code);
1130                 }
1131                 output_summary();
1132                 io_flush(FULL_FLUSH);
1133                 exit_cleanup(exit_code);
1134         }
1135
1136         if (!read_batch) {
1137                 if (protocol_version >= 23)
1138                         io_start_multiplex_in(f_in);
1139                 if (need_messages_from_generator)
1140                         io_start_multiplex_out(f_out);
1141         }
1142
1143         send_filter_list(read_batch ? -1 : f_out);
1144
1145         if (filesfrom_fd >= 0) {
1146                 start_filesfrom_forwarding(filesfrom_fd);
1147                 filesfrom_fd = -1;
1148         }
1149
1150         if (write_batch && !am_server)
1151                 start_write_batch(f_in);
1152         flist = recv_file_list(f_in);
1153         if (inc_recurse && file_total == 1)
1154                 recv_additional_file_list(f_in);
1155
1156         if (flist && flist->used > 0) {
1157                 local_name = get_local_name(flist, argv[0]);
1158
1159                 check_alt_basis_dirs();
1160
1161                 exit_code2 = do_recv(f_in, f_out, local_name);
1162         } else {
1163                 handle_stats(-1);
1164                 output_summary();
1165         }
1166
1167         if (pid != -1) {
1168                 if (DEBUG_GTE(RECV, 1))
1169                         rprintf(FINFO,"client_run2 waiting on %d\n", (int) pid);
1170                 io_flush(FULL_FLUSH);
1171                 wait_process_with_flush(pid, &exit_code);
1172         }
1173
1174         return MAX(exit_code, exit_code2);
1175 }
1176
1177 static int copy_argv(char *argv[])
1178 {
1179         int i;
1180
1181         for (i = 0; argv[i]; i++) {
1182                 if (!(argv[i] = strdup(argv[i]))) {
1183                         rprintf (FERROR, "out of memory at %s(%d)\n",
1184                                  __FILE__, __LINE__);
1185                         return RERR_MALLOC;
1186                 }
1187         }
1188
1189         return 0;
1190 }
1191
1192
1193 /* Start a client for either type of remote connection.  Work out
1194  * whether the arguments request a remote shell or rsyncd connection,
1195  * and call the appropriate connection function, then run_client.
1196  *
1197  * Calls either start_socket_client (for sockets) or do_cmd and
1198  * client_run (for ssh). */
1199 static int start_client(int argc, char *argv[])
1200 {
1201         char *p, *shell_machine = NULL, *shell_user = NULL;
1202         char **remote_argv;
1203         int remote_argc;
1204         int f_in, f_out;
1205         int ret;
1206         pid_t pid;
1207
1208         /* Don't clobber argv[] so that ps(1) can still show the right
1209          * command line. */
1210         if ((ret = copy_argv(argv)) != 0)
1211                 return ret;
1212
1213         if (!read_batch) { /* for read_batch, NO source is specified */
1214                 char *path = check_for_hostspec(argv[0], &shell_machine, &rsync_port);
1215                 if (path) { /* source is remote */
1216                         char *dummy_host;
1217                         int dummy_port = 0;
1218                         *argv = path;
1219                         remote_argv = argv;
1220                         remote_argc = argc;
1221                         argv += argc - 1;
1222                         if (argc == 1 || **argv == ':')
1223                                 argc = 0; /* no dest arg */
1224                         else if (check_for_hostspec(*argv, &dummy_host, &dummy_port)) {
1225                                 rprintf(FERROR,
1226                                         "The source and destination cannot both be remote.\n");
1227                                 exit_cleanup(RERR_SYNTAX);
1228                         } else {
1229                                 remote_argc--; /* don't count dest */
1230                                 argc = 1;
1231                         }
1232                         if (filesfrom_host && *filesfrom_host
1233                             && strcmp(filesfrom_host, shell_machine) != 0) {
1234                                 rprintf(FERROR,
1235                                         "--files-from hostname is not the same as the transfer hostname\n");
1236                                 exit_cleanup(RERR_SYNTAX);
1237                         }
1238                         am_sender = 0;
1239                         if (rsync_port)
1240                                 daemon_over_rsh = shell_cmd ? 1 : -1;
1241                 } else { /* source is local, check dest arg */
1242                         am_sender = 1;
1243
1244                         if (argc > 1) {
1245                                 p = argv[--argc];
1246                                 remote_argv = argv + argc;
1247                         } else {
1248                                 static char *dotarg[1] = { "." };
1249                                 p = dotarg[0];
1250                                 remote_argv = dotarg;
1251                         }
1252                         remote_argc = 1;
1253
1254                         path = check_for_hostspec(p, &shell_machine, &rsync_port);
1255                         if (path && filesfrom_host && *filesfrom_host
1256                             && strcmp(filesfrom_host, shell_machine) != 0) {
1257                                 rprintf(FERROR,
1258                                         "--files-from hostname is not the same as the transfer hostname\n");
1259                                 exit_cleanup(RERR_SYNTAX);
1260                         }
1261                         if (!path) { /* no hostspec found, so src & dest are local */
1262                                 local_server = 1;
1263                                 if (filesfrom_host) {
1264                                         rprintf(FERROR,
1265                                                 "--files-from cannot be remote when the transfer is local\n");
1266                                         exit_cleanup(RERR_SYNTAX);
1267                                 }
1268                                 shell_machine = NULL;
1269                         } else { /* hostspec was found, so dest is remote */
1270                                 argv[argc] = path;
1271                                 if (rsync_port)
1272                                         daemon_over_rsh = shell_cmd ? 1 : -1;
1273                         }
1274                 }
1275         } else {  /* read_batch */
1276                 local_server = 1;
1277                 if (check_for_hostspec(argv[argc-1], &shell_machine, &rsync_port)) {
1278                         rprintf(FERROR, "remote destination is not allowed with --read-batch\n");
1279                         exit_cleanup(RERR_SYNTAX);
1280                 }
1281                 remote_argv = argv += argc - 1;
1282                 remote_argc = argc = 1;
1283         }
1284
1285         if (am_sender) {
1286                 char *dummy_host;
1287                 int dummy_port = rsync_port;
1288                 int i;
1289                 /* For local source, extra source args must not have hostspec. */
1290                 for (i = 1; i < argc; i++) {
1291                         if (check_for_hostspec(argv[i], &dummy_host, &dummy_port)) {
1292                                 rprintf(FERROR, "Unexpected remote arg: %s\n", argv[i]);
1293                                 exit_cleanup(RERR_SYNTAX);
1294                         }
1295                 }
1296         } else {
1297                 char *dummy_host;
1298                 int dummy_port = rsync_port;
1299                 int i;
1300                 /* For remote source, any extra source args must have either
1301                  * the same hostname or an empty hostname. */
1302                 for (i = 1; i < remote_argc; i++) {
1303                         char *arg = check_for_hostspec(remote_argv[i], &dummy_host, &dummy_port);
1304                         if (!arg) {
1305                                 rprintf(FERROR, "Unexpected local arg: %s\n", remote_argv[i]);
1306                                 rprintf(FERROR, "If arg is a remote file/dir, prefix it with a colon (:).\n");
1307                                 exit_cleanup(RERR_SYNTAX);
1308                         }
1309                         if (*dummy_host && strcmp(dummy_host, shell_machine) != 0) {
1310                                 rprintf(FERROR, "All source args must come from the same machine.\n");
1311                                 exit_cleanup(RERR_SYNTAX);
1312                         }
1313                         if (rsync_port != dummy_port) {
1314                                 if (!rsync_port || !dummy_port)
1315                                         rprintf(FERROR, "All source args must use the same hostspec format.\n");
1316                                 else
1317                                         rprintf(FERROR, "All source args must use the same port number.\n");
1318                                 exit_cleanup(RERR_SYNTAX);
1319                         }
1320                         remote_argv[i] = arg;
1321                 }
1322         }
1323
1324         if (daemon_over_rsh < 0)
1325                 return start_socket_client(shell_machine, remote_argc, remote_argv, argc, argv);
1326
1327         if (password_file && !daemon_over_rsh) {
1328                 rprintf(FERROR, "The --password-file option may only be "
1329                                 "used when accessing an rsync daemon.\n");
1330                 exit_cleanup(RERR_SYNTAX);
1331         }
1332
1333         if (connect_timeout) {
1334                 rprintf(FERROR, "The --contimeout option may only be "
1335                                 "used when connecting to an rsync daemon.\n");
1336                 exit_cleanup(RERR_SYNTAX);
1337         }
1338
1339         if (shell_machine) {
1340                 p = strrchr(shell_machine,'@');
1341                 if (p) {
1342                         *p = 0;
1343                         shell_user = shell_machine;
1344                         shell_machine = p+1;
1345                 }
1346         }
1347
1348         if (DEBUG_GTE(CMD, 2)) {
1349                 rprintf(FINFO,"cmd=%s machine=%s user=%s path=%s\n",
1350                         NS(shell_cmd), NS(shell_machine), NS(shell_user),
1351                         remote_argv ? NS(remote_argv[0]) : "");
1352         }
1353
1354         pid = do_cmd(shell_cmd, shell_machine, shell_user, remote_argv, remote_argc,
1355                      &f_in, &f_out);
1356
1357         /* if we're running an rsync server on the remote host over a
1358          * remote shell command, we need to do the RSYNCD protocol first */
1359         if (daemon_over_rsh) {
1360                 int tmpret;
1361                 tmpret = start_inband_exchange(f_in, f_out, shell_user, remote_argc, remote_argv);
1362                 if (tmpret < 0)
1363                         return tmpret;
1364         }
1365
1366         ret = client_run(f_in, f_out, pid, argc, argv);
1367
1368         fflush(stdout);
1369         fflush(stderr);
1370
1371         return ret;
1372 }
1373
1374
1375 static RETSIGTYPE sigusr1_handler(UNUSED(int val))
1376 {
1377         exit_cleanup(RERR_SIGNAL1);
1378 }
1379
1380 static RETSIGTYPE sigusr2_handler(UNUSED(int val))
1381 {
1382         if (!am_server)
1383                 output_summary();
1384         close_all();
1385         if (got_xfer_error)
1386                 _exit(RERR_PARTIAL);
1387         _exit(0);
1388 }
1389
1390 RETSIGTYPE remember_children(UNUSED(int val))
1391 {
1392 #ifdef WNOHANG
1393         int cnt, status;
1394         pid_t pid;
1395         /* An empty waitpid() loop was put here by Tridge and we could never
1396          * get him to explain why he put it in, so rather than taking it
1397          * out we're instead saving the child exit statuses for later use.
1398          * The waitpid() loop presumably eliminates all possibility of leaving
1399          * zombie children, maybe that's why he did it. */
1400         while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1401                 /* save the child's exit status */
1402                 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
1403                         if (pid_stat_table[cnt].pid == 0) {
1404                                 pid_stat_table[cnt].pid = pid;
1405                                 pid_stat_table[cnt].status = status;
1406                                 break;
1407                         }
1408                 }
1409         }
1410 #endif
1411 #ifndef HAVE_SIGACTION
1412         signal(SIGCHLD, remember_children);
1413 #endif
1414 }
1415
1416
1417 /**
1418  * This routine catches signals and tries to send them to gdb.
1419  *
1420  * Because it's called from inside a signal handler it ought not to
1421  * use too many library routines.
1422  *
1423  * @todo Perhaps use "screen -X" instead/as well, to help people
1424  * debugging without easy access to X.  Perhaps use an environment
1425  * variable, or just call a script?
1426  *
1427  * @todo The /proc/ magic probably only works on Linux (and
1428  * Solaris?)  Can we be more portable?
1429  **/
1430 #ifdef MAINTAINER_MODE
1431 const char *get_panic_action(void)
1432 {
1433         const char *cmd_fmt = getenv("RSYNC_PANIC_ACTION");
1434
1435         if (cmd_fmt)
1436                 return cmd_fmt;
1437         else
1438                 return "xterm -display :0 -T Panic -n Panic "
1439                         "-e gdb /proc/%d/exe %d";
1440 }
1441
1442
1443 /**
1444  * Handle a fatal signal by launching a debugger, controlled by $RSYNC_PANIC_ACTION.
1445  *
1446  * This signal handler is only installed if we were configured with
1447  * --enable-maintainer-mode.  Perhaps it should always be on and we
1448  * should just look at the environment variable, but I'm a bit leery
1449  * of a signal sending us into a busy loop.
1450  **/
1451 static RETSIGTYPE rsync_panic_handler(UNUSED(int whatsig))
1452 {
1453         char cmd_buf[300];
1454         int ret;
1455
1456         snprintf(cmd_buf, sizeof cmd_buf, get_panic_action(),
1457                  getpid(), getpid());
1458
1459         /* Unless we failed to execute gdb, we allow the process to
1460          * continue.  I'm not sure if that's right. */
1461         ret = system(cmd_buf);
1462         if (ret)
1463                 _exit(ret);
1464 }
1465 #endif
1466
1467
1468 int main(int argc,char *argv[])
1469 {
1470         int ret;
1471         int orig_argc = argc;
1472         char **orig_argv = argv;
1473 #ifdef HAVE_SIGACTION
1474 # ifdef HAVE_SIGPROCMASK
1475         sigset_t sigmask;
1476
1477         sigemptyset(&sigmask);
1478 # endif
1479         sigact.sa_flags = SA_NOCLDSTOP;
1480 #endif
1481         SIGACTMASK(SIGUSR1, sigusr1_handler);
1482         SIGACTMASK(SIGUSR2, sigusr2_handler);
1483         SIGACTMASK(SIGCHLD, remember_children);
1484 #ifdef MAINTAINER_MODE
1485         SIGACTMASK(SIGSEGV, rsync_panic_handler);
1486         SIGACTMASK(SIGFPE, rsync_panic_handler);
1487         SIGACTMASK(SIGABRT, rsync_panic_handler);
1488         SIGACTMASK(SIGBUS, rsync_panic_handler);
1489 #endif
1490
1491         starttime = time(NULL);
1492         our_uid = MY_UID();
1493         our_gid = MY_GID();
1494         am_root = our_uid == 0;
1495
1496         memset(&stats, 0, sizeof(stats));
1497
1498         if (argc < 2) {
1499                 usage(FERROR);
1500                 exit_cleanup(RERR_SYNTAX);
1501         }
1502
1503         /* we set a 0 umask so that correct file permissions can be
1504          * carried across */
1505         orig_umask = umask(0);
1506
1507 #if defined CONFIG_LOCALE && defined HAVE_SETLOCALE
1508         setlocale(LC_CTYPE, "");
1509 #endif
1510
1511         if (!parse_arguments(&argc, (const char ***) &argv)) {
1512                 /* FIXME: We ought to call the same error-handling
1513                  * code here, rather than relying on getopt. */
1514                 option_error();
1515                 exit_cleanup(RERR_SYNTAX);
1516         }
1517
1518         SIGACTMASK(SIGINT, sig_int);
1519         SIGACTMASK(SIGHUP, sig_int);
1520         SIGACTMASK(SIGTERM, sig_int);
1521 #if defined HAVE_SIGACTION && HAVE_SIGPROCMASK
1522         sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
1523 #endif
1524
1525         /* Ignore SIGPIPE; we consistently check error codes and will
1526          * see the EPIPE. */
1527         SIGACTION(SIGPIPE, SIG_IGN);
1528 #ifdef SIGXFSZ
1529         SIGACTION(SIGXFSZ, SIG_IGN);
1530 #endif
1531
1532         /* Initialize change_dir() here because on some old systems getcwd
1533          * (implemented by forking "pwd" and reading its output) doesn't
1534          * work when there are other child processes.  Also, on all systems
1535          * that implement getcwd that way "pwd" can't be found after chroot. */
1536         change_dir(NULL, CD_NORMAL);
1537
1538         init_flist();
1539
1540         if ((write_batch || read_batch) && !am_server) {
1541                 if (write_batch)
1542                         write_batch_shell_file(orig_argc, orig_argv, argc);
1543
1544                 if (read_batch && strcmp(batch_name, "-") == 0)
1545                         batch_fd = STDIN_FILENO;
1546                 else {
1547                         batch_fd = do_open(batch_name,
1548                                    write_batch ? O_WRONLY | O_CREAT | O_TRUNC
1549                                    : O_RDONLY, S_IRUSR | S_IWUSR);
1550                 }
1551                 if (batch_fd < 0) {
1552                         rsyserr(FERROR, errno, "Batch file %s open error",
1553                                 full_fname(batch_name));
1554                         exit_cleanup(RERR_FILEIO);
1555                 }
1556                 if (read_batch)
1557                         read_stream_flags(batch_fd);
1558                 else
1559                         write_stream_flags(batch_fd);
1560         }
1561         if (write_batch < 0)
1562                 dry_run = 1;
1563
1564         if (am_server) {
1565 #ifdef ICONV_CONST
1566                 setup_iconv();
1567 #endif
1568         } else if (am_daemon)
1569                 return daemon_main();
1570
1571         if (am_server && protect_args) {
1572                 char buf[MAXPATHLEN];
1573                 protect_args = 2;
1574                 read_args(STDIN_FILENO, NULL, buf, sizeof buf, 1, &argv, &argc, NULL);
1575                 if (!parse_arguments(&argc, (const char ***) &argv)) {
1576                         option_error();
1577                         exit_cleanup(RERR_SYNTAX);
1578                 }
1579         }
1580
1581         if (argc < 1) {
1582                 usage(FERROR);
1583                 exit_cleanup(RERR_SYNTAX);
1584         }
1585
1586         if (am_server) {
1587                 set_nonblocking(STDIN_FILENO);
1588                 set_nonblocking(STDOUT_FILENO);
1589                 if (am_daemon)
1590                         return start_daemon(STDIN_FILENO, STDOUT_FILENO);
1591                 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1592         }
1593
1594         ret = start_client(argc, argv);
1595         if (ret == -1)
1596                 exit_cleanup(RERR_STARTCLIENT);
1597         else
1598                 exit_cleanup(ret);
1599
1600         return ret;
1601 }