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