Avoid negotiating a "none" choice by default
[rsync.git] / main.c
blobb41a39435d261424b4c02c16904411f41d5ad864
1 /*
2 * The startup routines, including main(), for rsync.
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-2020 Wayne Davison
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.
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.
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.
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 #include <popt.h>
31 extern int dry_run;
32 extern int list_only;
33 extern int io_timeout;
34 extern int am_root;
35 extern int am_server;
36 extern int am_sender;
37 extern int am_daemon;
38 extern int inc_recurse;
39 extern int blocking_io;
40 extern int always_checksum;
41 extern int remove_source_files;
42 extern int output_needs_newline;
43 extern int called_from_signal_handler;
44 extern int need_messages_from_generator;
45 extern int kluge_around_eof;
46 extern int got_xfer_error;
47 extern int msgs2stderr;
48 extern int module_id;
49 extern int read_only;
50 extern int copy_links;
51 extern int copy_dirlinks;
52 extern int copy_unsafe_links;
53 extern int keep_dirlinks;
54 extern int preserve_hard_links;
55 extern int protocol_version;
56 extern int file_total;
57 extern int recurse;
58 extern int xfer_dirs;
59 extern int protect_args;
60 extern int relative_paths;
61 extern int sanitize_paths;
62 extern int curr_dir_depth;
63 extern int curr_dir_len;
64 extern int module_id;
65 extern int rsync_port;
66 extern int whole_file;
67 extern int read_batch;
68 extern int write_batch;
69 extern int batch_fd;
70 extern int sock_f_in;
71 extern int sock_f_out;
72 extern int filesfrom_fd;
73 extern int connect_timeout;
74 extern int send_msgs_to_gen;
75 extern dev_t filesystem_dev;
76 extern pid_t cleanup_child_pid;
77 extern size_t bwlimit_writemax;
78 extern unsigned int module_dirlen;
79 extern BOOL flist_receiving_enabled;
80 extern BOOL want_progress_now;
81 extern BOOL shutting_down;
82 extern int backup_dir_len;
83 extern int basis_dir_cnt;
84 extern int default_af_hint;
85 extern struct stats stats;
86 extern char *stdout_format;
87 extern char *logfile_format;
88 extern char *filesfrom_host;
89 extern char *partial_dir;
90 extern char *rsync_path;
91 extern char *shell_cmd;
92 extern char *password_file;
93 extern char *backup_dir;
94 extern char *copy_as;
95 extern char curr_dir[MAXPATHLEN];
96 extern char backup_dir_buf[MAXPATHLEN];
97 extern char *basis_dir[MAX_BASIS_DIRS+1];
98 extern struct file_list *first_flist;
99 extern filter_rule_list daemon_filter_list;
101 uid_t our_uid;
102 gid_t our_gid;
103 int am_receiver = 0; /* Only set to 1 after the receiver/generator fork. */
104 int am_generator = 0; /* Only set to 1 after the receiver/generator fork. */
105 int local_server = 0;
106 int daemon_over_rsh = 0;
107 mode_t orig_umask = 0;
108 int batch_gen_fd = -1;
109 int sender_keeps_checksum = 0;
110 int raw_argc, cooked_argc;
111 char **raw_argv, **cooked_argv;
113 /* There's probably never more than at most 2 outstanding child processes,
114 * but set it higher, just in case. */
115 #define MAXCHILDPROCS 7
117 #ifdef HAVE_SIGACTION
118 # ifdef HAVE_SIGPROCMASK
119 # define SIGACTMASK(n,h) SIGACTION(n,h), sigaddset(&sigmask,(n))
120 # else
121 # define SIGACTMASK(n,h) SIGACTION(n,h)
122 # endif
123 static struct sigaction sigact;
124 #endif
126 struct pid_status {
127 pid_t pid;
128 int status;
129 } pid_stat_table[MAXCHILDPROCS];
131 static time_t starttime, endtime;
132 static int64 total_read, total_written;
134 static void show_malloc_stats(void);
136 /* Works like waitpid(), but if we already harvested the child pid in our
137 * remember_children(), we succeed instead of returning an error. */
138 pid_t wait_process(pid_t pid, int *status_ptr, int flags)
140 pid_t waited_pid;
142 do {
143 waited_pid = waitpid(pid, status_ptr, flags);
144 } while (waited_pid == -1 && errno == EINTR);
146 if (waited_pid == -1 && errno == ECHILD) {
147 /* Status of requested child no longer available: check to
148 * see if it was processed by remember_children(). */
149 int cnt;
150 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
151 if (pid == pid_stat_table[cnt].pid) {
152 *status_ptr = pid_stat_table[cnt].status;
153 pid_stat_table[cnt].pid = 0;
154 return pid;
159 return waited_pid;
162 int shell_exec(const char *cmd)
164 char *shell = getenv("RSYNC_SHELL");
165 int status;
166 pid_t pid;
168 if (!shell)
169 return system(cmd);
171 if ((pid = fork()) < 0)
172 return -1;
174 if (pid == 0) {
175 execlp(shell, shell, "-c", cmd, NULL);
176 _exit(1);
179 int ret = wait_process(pid, &status, 0);
180 return ret < 0 ? -1 : status;
183 /* Wait for a process to exit, calling io_flush while waiting. */
184 static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
186 pid_t waited_pid;
187 int status;
189 while ((waited_pid = wait_process(pid, &status, WNOHANG)) == 0) {
190 msleep(20);
191 io_flush(FULL_FLUSH);
194 /* TODO: If the child exited on a signal, then log an
195 * appropriate error message. Perhaps we should also accept a
196 * message describing the purpose of the child. Also indicate
197 * this to the caller so that they know something went wrong. */
198 if (waited_pid < 0) {
199 rsyserr(FERROR, errno, "waitpid");
200 *exit_code_ptr = RERR_WAITCHILD;
201 } else if (!WIFEXITED(status)) {
202 #ifdef WCOREDUMP
203 if (WCOREDUMP(status))
204 *exit_code_ptr = RERR_CRASHED;
205 else
206 #endif
207 if (WIFSIGNALED(status))
208 *exit_code_ptr = RERR_TERMINATED;
209 else
210 *exit_code_ptr = RERR_WAITCHILD;
211 } else
212 *exit_code_ptr = WEXITSTATUS(status);
215 void write_del_stats(int f)
217 if (read_batch)
218 write_int(f, NDX_DEL_STATS);
219 else
220 write_ndx(f, NDX_DEL_STATS);
221 write_varint(f, stats.deleted_files - stats.deleted_dirs
222 - stats.deleted_symlinks - stats.deleted_devices
223 - stats.deleted_specials);
224 write_varint(f, stats.deleted_dirs);
225 write_varint(f, stats.deleted_symlinks);
226 write_varint(f, stats.deleted_devices);
227 write_varint(f, stats.deleted_specials);
230 void read_del_stats(int f)
232 stats.deleted_files = read_varint(f);
233 stats.deleted_files += stats.deleted_dirs = read_varint(f);
234 stats.deleted_files += stats.deleted_symlinks = read_varint(f);
235 stats.deleted_files += stats.deleted_devices = read_varint(f);
236 stats.deleted_files += stats.deleted_specials = read_varint(f);
239 static void become_copy_as_user()
241 char *gname;
242 uid_t uid;
243 gid_t gid;
245 if (!copy_as)
246 return;
248 if (DEBUG_GTE(CMD, 2))
249 rprintf(FINFO, "[%s] copy_as=%s\n", who_am_i(), copy_as);
251 if ((gname = strchr(copy_as, ':')) != NULL)
252 *gname++ = '\0';
254 if (!user_to_uid(copy_as, &uid, True)) {
255 rprintf(FERROR, "Invalid copy-as user: %s\n", copy_as);
256 exit_cleanup(RERR_SYNTAX);
259 if (gname) {
260 if (!group_to_gid(gname, &gid, True)) {
261 rprintf(FERROR, "Invalid copy-as group: %s\n", gname);
262 exit_cleanup(RERR_SYNTAX);
264 } else {
265 struct passwd *pw;
266 if ((pw = getpwuid(uid)) == NULL) {
267 rsyserr(FERROR, errno, "getpwuid failed");
268 exit_cleanup(RERR_SYNTAX);
270 gid = pw->pw_gid;
273 if (setgid(gid) < 0) {
274 rsyserr(FERROR, errno, "setgid failed");
275 exit_cleanup(RERR_SYNTAX);
277 #ifdef HAVE_SETGROUPS
278 if (setgroups(1, &gid)) {
279 rsyserr(FERROR, errno, "setgroups failed");
280 exit_cleanup(RERR_SYNTAX);
282 #endif
283 #ifdef HAVE_INITGROUPS
284 if (!gname && initgroups(copy_as, gid) < 0) {
285 rsyserr(FERROR, errno, "initgroups failed");
286 exit_cleanup(RERR_SYNTAX);
288 #endif
290 if (setuid(uid) < 0
291 #ifdef HAVE_SETEUID
292 || seteuid(uid) < 0
293 #endif
295 rsyserr(FERROR, errno, "setuid failed");
296 exit_cleanup(RERR_SYNTAX);
299 our_uid = MY_UID();
300 our_gid = MY_GID();
301 am_root = (our_uid == 0);
303 if (gname)
304 gname[-1] = ':';
307 /* This function gets called from all 3 processes. We want the client side
308 * to actually output the text, but the sender is the only process that has
309 * all the stats we need. So, if we're a client sender, we do the report.
310 * If we're a server sender, we write the stats on the supplied fd. If
311 * we're the client receiver we read the stats from the supplied fd and do
312 * the report. All processes might also generate a set of debug stats, if
313 * the verbose level is high enough (this is the only thing that the
314 * generator process and the server receiver ever do here). */
315 static void handle_stats(int f)
317 endtime = time(NULL);
319 /* Cache two stats because the read/write code can change it. */
320 total_read = stats.total_read;
321 total_written = stats.total_written;
323 if (INFO_GTE(STATS, 3)) {
324 /* These come out from every process */
325 show_malloc_stats();
326 show_flist_stats();
329 if (am_generator)
330 return;
332 if (am_daemon) {
333 if (f == -1 || !am_sender)
334 return;
337 if (am_server) {
338 if (am_sender) {
339 write_varlong30(f, total_read, 3);
340 write_varlong30(f, total_written, 3);
341 write_varlong30(f, stats.total_size, 3);
342 if (protocol_version >= 29) {
343 write_varlong30(f, stats.flist_buildtime, 3);
344 write_varlong30(f, stats.flist_xfertime, 3);
347 return;
350 /* this is the client */
352 if (f < 0 && !am_sender) /* e.g. when we got an empty file list. */
354 else if (!am_sender) {
355 /* Read the first two in opposite order because the meaning of
356 * read/write swaps when switching from sender to receiver. */
357 total_written = read_varlong30(f, 3);
358 total_read = read_varlong30(f, 3);
359 stats.total_size = read_varlong30(f, 3);
360 if (protocol_version >= 29) {
361 stats.flist_buildtime = read_varlong30(f, 3);
362 stats.flist_xfertime = read_varlong30(f, 3);
364 } else if (write_batch) {
365 /* The --read-batch process is going to be a client
366 * receiver, so we need to give it the stats. */
367 write_varlong30(batch_fd, total_read, 3);
368 write_varlong30(batch_fd, total_written, 3);
369 write_varlong30(batch_fd, stats.total_size, 3);
370 if (protocol_version >= 29) {
371 write_varlong30(batch_fd, stats.flist_buildtime, 3);
372 write_varlong30(batch_fd, stats.flist_xfertime, 3);
377 static void output_itemized_counts(const char *prefix, int *counts)
379 static char *labels[] = { "reg", "dir", "link", "dev", "special" };
380 char buf[1024], *pre = " (";
381 int j, len = 0;
382 int total = counts[0];
383 if (total) {
384 counts[0] -= counts[1] + counts[2] + counts[3] + counts[4];
385 for (j = 0; j < 5; j++) {
386 if (counts[j]) {
387 len += snprintf(buf+len, sizeof buf - len - 2,
388 "%s%s: %s",
389 pre, labels[j], comma_num(counts[j]));
390 pre = ", ";
393 buf[len++] = ')';
395 buf[len] = '\0';
396 rprintf(FINFO, "%s: %s%s\n", prefix, comma_num(total), buf);
399 static const char *bytes_per_sec_human_dnum(void)
401 if (starttime == (time_t)-1 || endtime == (time_t)-1)
402 return "UNKNOWN";
403 return human_dnum((total_written + total_read) / (0.5 + (endtime - starttime)), 2);
406 static void output_summary(void)
408 if (INFO_GTE(STATS, 2)) {
409 rprintf(FCLIENT, "\n");
410 output_itemized_counts("Number of files", &stats.num_files);
411 if (protocol_version >= 29)
412 output_itemized_counts("Number of created files", &stats.created_files);
413 if (protocol_version >= 31)
414 output_itemized_counts("Number of deleted files", &stats.deleted_files);
415 rprintf(FINFO,"Number of regular files transferred: %s\n",
416 comma_num(stats.xferred_files));
417 rprintf(FINFO,"Total file size: %s bytes\n",
418 human_num(stats.total_size));
419 rprintf(FINFO,"Total transferred file size: %s bytes\n",
420 human_num(stats.total_transferred_size));
421 rprintf(FINFO,"Literal data: %s bytes\n",
422 human_num(stats.literal_data));
423 rprintf(FINFO,"Matched data: %s bytes\n",
424 human_num(stats.matched_data));
425 rprintf(FINFO,"File list size: %s\n",
426 human_num(stats.flist_size));
427 if (stats.flist_buildtime) {
428 rprintf(FINFO,
429 "File list generation time: %s seconds\n",
430 comma_dnum((double)stats.flist_buildtime / 1000, 3));
431 rprintf(FINFO,
432 "File list transfer time: %s seconds\n",
433 comma_dnum((double)stats.flist_xfertime / 1000, 3));
435 rprintf(FINFO,"Total bytes sent: %s\n",
436 human_num(total_written));
437 rprintf(FINFO,"Total bytes received: %s\n",
438 human_num(total_read));
441 if (INFO_GTE(STATS, 1)) {
442 rprintf(FCLIENT, "\n");
443 rprintf(FINFO,
444 "sent %s bytes received %s bytes %s bytes/sec\n",
445 human_num(total_written), human_num(total_read),
446 bytes_per_sec_human_dnum());
447 rprintf(FINFO, "total size is %s speedup is %s%s\n",
448 human_num(stats.total_size),
449 comma_dnum((double)stats.total_size / (total_written+total_read), 2),
450 write_batch < 0 ? " (BATCH ONLY)" : dry_run ? " (DRY RUN)" : "");
453 fflush(stdout);
454 fflush(stderr);
459 * If our C library can get malloc statistics, then show them to FINFO
461 static void show_malloc_stats(void)
463 #ifdef HAVE_MALLINFO
464 struct mallinfo mi;
466 mi = mallinfo();
468 rprintf(FCLIENT, "\n");
469 rprintf(FINFO, RSYNC_NAME "[%d] (%s%s%s) heap statistics:\n",
470 (int)getpid(), am_server ? "server " : "",
471 am_daemon ? "daemon " : "", who_am_i());
472 rprintf(FINFO, " arena: %10ld (bytes from sbrk)\n",
473 (long)mi.arena);
474 rprintf(FINFO, " ordblks: %10ld (chunks not in use)\n",
475 (long)mi.ordblks);
476 rprintf(FINFO, " smblks: %10ld\n",
477 (long)mi.smblks);
478 rprintf(FINFO, " hblks: %10ld (chunks from mmap)\n",
479 (long)mi.hblks);
480 rprintf(FINFO, " hblkhd: %10ld (bytes from mmap)\n",
481 (long)mi.hblkhd);
482 rprintf(FINFO, " allmem: %10ld (bytes from sbrk + mmap)\n",
483 (long)mi.arena + mi.hblkhd);
484 rprintf(FINFO, " usmblks: %10ld\n",
485 (long)mi.usmblks);
486 rprintf(FINFO, " fsmblks: %10ld\n",
487 (long)mi.fsmblks);
488 rprintf(FINFO, " uordblks: %10ld (bytes used)\n",
489 (long)mi.uordblks);
490 rprintf(FINFO, " fordblks: %10ld (bytes free)\n",
491 (long)mi.fordblks);
492 rprintf(FINFO, " keepcost: %10ld (bytes in releasable chunk)\n",
493 (long)mi.keepcost);
494 #endif /* HAVE_MALLINFO */
498 /* Start the remote shell. cmd may be NULL to use the default. */
499 static pid_t do_cmd(char *cmd, char *machine, char *user, char **remote_argv, int remote_argc,
500 int *f_in_p, int *f_out_p)
502 int i, argc = 0;
503 char *args[MAX_ARGS], *need_to_free = NULL;
504 pid_t pid;
505 int dash_l_set = 0;
507 if (!read_batch && !local_server) {
508 char *t, *f, in_quote = '\0';
509 char *rsh_env = getenv(RSYNC_RSH_ENV);
510 if (!cmd)
511 cmd = rsh_env;
512 if (!cmd)
513 cmd = RSYNC_RSH;
514 cmd = need_to_free = strdup(cmd);
515 if (!cmd)
516 goto oom;
518 for (t = f = cmd; *f; f++) {
519 if (*f == ' ')
520 continue;
521 /* Comparison leaves rooms for server_options(). */
522 if (argc >= MAX_ARGS - MAX_SERVER_ARGS)
523 goto arg_overflow;
524 args[argc++] = t;
525 while (*f != ' ' || in_quote) {
526 if (!*f) {
527 if (in_quote) {
528 rprintf(FERROR,
529 "Missing trailing-%c in remote-shell command.\n",
530 in_quote);
531 exit_cleanup(RERR_SYNTAX);
533 f--;
534 break;
536 if (*f == '\'' || *f == '"') {
537 if (!in_quote) {
538 in_quote = *f++;
539 continue;
541 if (*f == in_quote && *++f != in_quote) {
542 in_quote = '\0';
543 continue;
546 *t++ = *f++;
548 *t++ = '\0';
551 /* NOTE: must preserve t == start of command name until the end of the args handling! */
552 if ((t = strrchr(cmd, '/')) != NULL)
553 t++;
554 else
555 t = cmd;
557 /* Check to see if we've already been given '-l user' in the remote-shell command. */
558 for (i = 0; i < argc-1; i++) {
559 if (!strcmp(args[i], "-l") && args[i+1][0] != '-')
560 dash_l_set = 1;
563 #ifdef HAVE_REMSH
564 /* remsh (on HPUX) takes the arguments the other way around */
565 args[argc++] = machine;
566 if (user && !(daemon_over_rsh && dash_l_set)) {
567 args[argc++] = "-l";
568 args[argc++] = user;
570 #else
571 if (user && !(daemon_over_rsh && dash_l_set)) {
572 args[argc++] = "-l";
573 args[argc++] = user;
575 #ifdef AF_INET
576 if (default_af_hint == AF_INET && strcmp(t, "ssh") == 0)
577 args[argc++] = "-4"; /* we're using ssh so we can add a -4 option */
578 #endif
579 #ifdef AF_INET6
580 if (default_af_hint == AF_INET6 && strcmp(t, "ssh") == 0)
581 args[argc++] = "-6"; /* we're using ssh so we can add a -6 option */
582 #endif
583 args[argc++] = machine;
584 #endif
586 args[argc++] = rsync_path;
588 if (blocking_io < 0 && (strcmp(t, "rsh") == 0 || strcmp(t, "remsh") == 0))
589 blocking_io = 1;
591 server_options(args, &argc);
593 if (argc >= MAX_ARGS - 2)
594 goto arg_overflow;
597 args[argc++] = ".";
599 if (!daemon_over_rsh) {
600 while (remote_argc > 0) {
601 if (argc >= MAX_ARGS - 1) {
602 arg_overflow:
603 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
604 exit_cleanup(RERR_SYNTAX);
606 if (**remote_argv == '-') {
607 if (asprintf(args + argc++, "./%s", *remote_argv++) < 0)
608 out_of_memory("do_cmd");
609 } else
610 args[argc++] = *remote_argv++;
611 remote_argc--;
615 args[argc] = NULL;
617 if (DEBUG_GTE(CMD, 2)) {
618 for (i = 0; i < argc; i++)
619 rprintf(FCLIENT, "cmd[%d]=%s ", i, args[i]);
620 rprintf(FCLIENT, "\n");
623 if (read_batch) {
624 int from_gen_pipe[2];
625 set_allow_inc_recurse();
626 if (fd_pair(from_gen_pipe) < 0) {
627 rsyserr(FERROR, errno, "pipe");
628 exit_cleanup(RERR_IPC);
630 batch_gen_fd = from_gen_pipe[0];
631 *f_out_p = from_gen_pipe[1];
632 *f_in_p = batch_fd;
633 pid = (pid_t)-1; /* no child pid */
634 #ifdef ICONV_CONST
635 setup_iconv();
636 #endif
637 } else if (local_server) {
638 /* If the user didn't request --[no-]whole-file, force
639 * it on, but only if we're not batch processing. */
640 if (whole_file < 0 && !write_batch)
641 whole_file = 1;
642 set_allow_inc_recurse();
643 pid = local_child(argc, args, f_in_p, f_out_p, child_main);
644 #ifdef ICONV_CONST
645 setup_iconv();
646 #endif
647 } else {
648 pid = piped_child(args, f_in_p, f_out_p);
649 #ifdef ICONV_CONST
650 setup_iconv();
651 #endif
652 if (protect_args && !daemon_over_rsh)
653 send_protected_args(*f_out_p, args);
656 if (need_to_free)
657 free(need_to_free);
659 return pid;
661 oom:
662 out_of_memory("do_cmd");
663 return 0; /* not reached */
666 /* The receiving side operates in one of two modes:
668 * 1. it receives any number of files into a destination directory,
669 * placing them according to their names in the file-list.
671 * 2. it receives a single file and saves it using the name in the
672 * destination path instead of its file-list name. This requires a
673 * "local name" for writing out the destination file.
675 * So, our task is to figure out what mode/local-name we need.
676 * For mode 1, we change into the destination directory and return NULL.
677 * For mode 2, we change into the directory containing the destination
678 * file (if we aren't already there) and return the local-name. */
679 static char *get_local_name(struct file_list *flist, char *dest_path)
681 STRUCT_STAT st;
682 int statret;
683 char *cp;
685 if (DEBUG_GTE(RECV, 1)) {
686 rprintf(FINFO, "get_local_name count=%d %s\n",
687 file_total, NS(dest_path));
690 if (!dest_path || list_only)
691 return NULL;
693 /* Treat an empty string as a copy into the current directory. */
694 if (!*dest_path)
695 dest_path = ".";
697 if (daemon_filter_list.head) {
698 char *slash = strrchr(dest_path, '/');
699 if (slash && (slash[1] == '\0' || (slash[1] == '.' && slash[2] == '\0')))
700 *slash = '\0';
701 else
702 slash = NULL;
703 if ((*dest_path != '.' || dest_path[1] != '\0')
704 && (check_filter(&daemon_filter_list, FLOG, dest_path, 0) < 0
705 || check_filter(&daemon_filter_list, FLOG, dest_path, 1) < 0)) {
706 rprintf(FERROR, "ERROR: daemon has excluded destination \"%s\"\n",
707 dest_path);
708 exit_cleanup(RERR_FILESELECT);
710 if (slash)
711 *slash = '/';
714 /* See what currently exists at the destination. */
715 if ((statret = do_stat(dest_path, &st)) == 0) {
716 /* If the destination is a dir, enter it and use mode 1. */
717 if (S_ISDIR(st.st_mode)) {
718 if (!change_dir(dest_path, CD_NORMAL)) {
719 rsyserr(FERROR, errno, "change_dir#1 %s failed",
720 full_fname(dest_path));
721 exit_cleanup(RERR_FILESELECT);
723 filesystem_dev = st.st_dev; /* ensures --force works right w/-x */
724 return NULL;
726 if (file_total > 1) {
727 rprintf(FERROR,
728 "ERROR: destination must be a directory when"
729 " copying more than 1 file\n");
730 exit_cleanup(RERR_FILESELECT);
732 if (file_total == 1 && S_ISDIR(flist->files[0]->mode)) {
733 rprintf(FERROR,
734 "ERROR: cannot overwrite non-directory"
735 " with a directory\n");
736 exit_cleanup(RERR_FILESELECT);
738 } else if (errno != ENOENT) {
739 /* If we don't know what's at the destination, fail. */
740 rsyserr(FERROR, errno, "ERROR: cannot stat destination %s",
741 full_fname(dest_path));
742 exit_cleanup(RERR_FILESELECT);
745 cp = strrchr(dest_path, '/');
747 /* If we need a destination directory because the transfer is not
748 * of a single non-directory or the user has requested one via a
749 * destination path ending in a slash, create one and use mode 1. */
750 if (file_total > 1 || (cp && !cp[1])) {
751 /* Lop off the final slash (if any). */
752 if (cp && !cp[1])
753 *cp = '\0';
755 if (statret == 0) {
756 rprintf(FERROR, "ERROR: destination path is not a directory\n");
757 exit_cleanup(RERR_SYNTAX);
760 if (do_mkdir(dest_path, ACCESSPERMS) != 0) {
761 rsyserr(FERROR, errno, "mkdir %s failed",
762 full_fname(dest_path));
763 exit_cleanup(RERR_FILEIO);
766 if (flist->high >= flist->low
767 && strcmp(flist->files[flist->low]->basename, ".") == 0)
768 flist->files[0]->flags |= FLAG_DIR_CREATED;
770 if (INFO_GTE(NAME, 1))
771 rprintf(FINFO, "created directory %s\n", dest_path);
773 if (dry_run) {
774 /* Indicate that dest dir doesn't really exist. */
775 dry_run++;
778 if (!change_dir(dest_path, dry_run > 1 ? CD_SKIP_CHDIR : CD_NORMAL)) {
779 rsyserr(FERROR, errno, "change_dir#2 %s failed",
780 full_fname(dest_path));
781 exit_cleanup(RERR_FILESELECT);
784 return NULL;
787 /* Otherwise, we are writing a single file, possibly on top of an
788 * existing non-directory. Change to the item's parent directory
789 * (if it has a path component), return the basename of the
790 * destination file as the local name, and use mode 2. */
791 if (!cp)
792 return dest_path;
794 if (cp == dest_path)
795 dest_path = "/";
797 *cp = '\0';
798 if (!change_dir(dest_path, CD_NORMAL)) {
799 rsyserr(FERROR, errno, "change_dir#3 %s failed",
800 full_fname(dest_path));
801 exit_cleanup(RERR_FILESELECT);
803 *cp = '/';
805 return cp + 1;
808 /* This function checks on our alternate-basis directories. If we're in
809 * dry-run mode and the destination dir does not yet exist, we'll try to
810 * tweak any dest-relative paths to make them work for a dry-run (the
811 * destination dir must be in curr_dir[] when this function is called).
812 * We also warn about any arg that is non-existent or not a directory. */
813 static void check_alt_basis_dirs(void)
815 STRUCT_STAT st;
816 char *slash = strrchr(curr_dir, '/');
817 int j;
819 for (j = 0; j < basis_dir_cnt; j++) {
820 char *bdir = basis_dir[j];
821 int bd_len = strlen(bdir);
822 if (bd_len > 1 && bdir[bd_len-1] == '/')
823 bdir[--bd_len] = '\0';
824 if (dry_run > 1 && *bdir != '/') {
825 int len = curr_dir_len + 1 + bd_len + 1;
826 char *new = new_array(char, len);
827 if (!new)
828 out_of_memory("check_alt_basis_dirs");
829 if (slash && strncmp(bdir, "../", 3) == 0) {
830 /* We want to remove only one leading "../" prefix for
831 * the directory we couldn't create in dry-run mode:
832 * this ensures that any other ".." references get
833 * evaluated the same as they would for a live copy. */
834 *slash = '\0';
835 pathjoin(new, len, curr_dir, bdir + 3);
836 *slash = '/';
837 } else
838 pathjoin(new, len, curr_dir, bdir);
839 basis_dir[j] = bdir = new;
841 if (do_stat(bdir, &st) < 0)
842 rprintf(FWARNING, "%s arg does not exist: %s\n", alt_dest_opt(0), bdir);
843 else if (!S_ISDIR(st.st_mode))
844 rprintf(FWARNING, "%s arg is not a dir: %s\n", alt_dest_opt(0), bdir);
848 /* This is only called by the sender. */
849 static void read_final_goodbye(int f_in, int f_out)
851 int i, iflags, xlen;
852 uchar fnamecmp_type;
853 char xname[MAXPATHLEN];
855 shutting_down = True;
857 if (protocol_version < 29)
858 i = read_int(f_in);
859 else {
860 i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
861 if (protocol_version >= 31 && i == NDX_DONE) {
862 if (am_sender)
863 write_ndx(f_out, NDX_DONE);
864 else {
865 if (batch_gen_fd >= 0) {
866 while (read_int(batch_gen_fd) != NDX_DEL_STATS) {}
867 read_del_stats(batch_gen_fd);
869 write_int(f_out, NDX_DONE);
871 i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
875 if (i != NDX_DONE) {
876 rprintf(FERROR, "Invalid packet at end of run (%d) [%s]\n",
877 i, who_am_i());
878 exit_cleanup(RERR_PROTOCOL);
882 static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
884 struct file_list *flist;
885 char *dir;
887 if (DEBUG_GTE(SEND, 1))
888 rprintf(FINFO, "server_sender starting pid=%d\n", (int)getpid());
890 if (am_daemon && lp_write_only(module_id)) {
891 rprintf(FERROR, "ERROR: module is write only\n");
892 exit_cleanup(RERR_SYNTAX);
894 if (am_daemon && read_only && remove_source_files) {
895 rprintf(FERROR,
896 "ERROR: --remove-%s-files cannot be used with a read-only module\n",
897 remove_source_files == 1 ? "source" : "sent");
898 exit_cleanup(RERR_SYNTAX);
900 if (argc < 1) {
901 rprintf(FERROR, "ERROR: do_server_sender called without args\n");
902 exit_cleanup(RERR_SYNTAX);
905 become_copy_as_user();
907 dir = argv[0];
908 if (!relative_paths) {
909 if (!change_dir(dir, CD_NORMAL)) {
910 rsyserr(FERROR, errno, "change_dir#3 %s failed",
911 full_fname(dir));
912 exit_cleanup(RERR_FILESELECT);
915 argc--;
916 argv++;
918 if (argc == 0 && (recurse || xfer_dirs || list_only)) {
919 argc = 1;
920 argv--;
921 argv[0] = ".";
924 flist = send_file_list(f_out,argc,argv);
925 if (!flist || flist->used == 0) {
926 /* Make sure input buffering is off so we can't hang in noop_io_until_death(). */
927 io_end_buffering_in(0);
928 /* TODO: we should really exit in a more controlled manner. */
929 exit_cleanup(0);
932 io_start_buffering_in(f_in);
934 send_files(f_in, f_out);
935 io_flush(FULL_FLUSH);
936 handle_stats(f_out);
937 if (protocol_version >= 24)
938 read_final_goodbye(f_in, f_out);
939 io_flush(FULL_FLUSH);
940 exit_cleanup(0);
944 static int do_recv(int f_in, int f_out, char *local_name)
946 int pid;
947 int exit_code = 0;
948 int error_pipe[2];
950 /* The receiving side mustn't obey this, or an existing symlink that
951 * points to an identical file won't be replaced by the referent. */
952 copy_links = copy_dirlinks = copy_unsafe_links = 0;
954 #ifdef SUPPORT_HARD_LINKS
955 if (preserve_hard_links && !inc_recurse)
956 match_hard_links(first_flist);
957 #endif
959 if (fd_pair(error_pipe) < 0) {
960 rsyserr(FERROR, errno, "pipe failed in do_recv");
961 exit_cleanup(RERR_IPC);
964 if (backup_dir) {
965 STRUCT_STAT st;
966 int ret;
967 if (backup_dir_len > 1)
968 backup_dir_buf[backup_dir_len-1] = '\0';
969 ret = do_stat(backup_dir_buf, &st);
970 if (ret != 0 || !S_ISDIR(st.st_mode)) {
971 if (ret == 0) {
972 rprintf(FERROR, "The backup-dir is not a directory: %s\n", backup_dir_buf);
973 exit_cleanup(RERR_SYNTAX);
975 if (errno != ENOENT) {
976 rprintf(FERROR, "Failed to stat %s: %s\n", backup_dir_buf, strerror(errno));
977 exit_cleanup(RERR_FILEIO);
979 if (INFO_GTE(BACKUP, 1))
980 rprintf(FINFO, "(new) backup_dir is %s\n", backup_dir_buf);
981 } else if (INFO_GTE(BACKUP, 1))
982 rprintf(FINFO, "backup_dir is %s\n", backup_dir_buf);
983 if (backup_dir_len > 1)
984 backup_dir_buf[backup_dir_len-1] = '/';
987 io_flush(FULL_FLUSH);
989 if ((pid = do_fork()) == -1) {
990 rsyserr(FERROR, errno, "fork failed in do_recv");
991 exit_cleanup(RERR_IPC);
994 if (pid == 0) {
995 am_receiver = 1;
996 send_msgs_to_gen = am_server;
998 close(error_pipe[0]);
1000 /* We can't let two processes write to the socket at one time. */
1001 io_end_multiplex_out(MPLX_SWITCHING);
1002 if (f_in != f_out)
1003 close(f_out);
1004 sock_f_out = -1;
1005 f_out = error_pipe[1];
1007 bwlimit_writemax = 0; /* receiver doesn't need to do this */
1009 if (read_batch)
1010 io_start_buffering_in(f_in);
1011 io_start_multiplex_out(f_out);
1013 recv_files(f_in, f_out, local_name);
1014 io_flush(FULL_FLUSH);
1015 handle_stats(f_in);
1017 if (output_needs_newline) {
1018 fputc('\n', stdout);
1019 output_needs_newline = 0;
1022 write_int(f_out, NDX_DONE);
1023 send_msg(MSG_STATS, (char*)&stats.total_read, sizeof stats.total_read, 0);
1024 io_flush(FULL_FLUSH);
1026 /* Handle any keep-alive packets from the post-processing work
1027 * that the generator does. */
1028 if (protocol_version >= 29) {
1029 kluge_around_eof = -1;
1031 /* This should only get stopped via a USR2 signal. */
1032 read_final_goodbye(f_in, f_out);
1034 rprintf(FERROR, "Invalid packet at end of run [%s]\n",
1035 who_am_i());
1036 exit_cleanup(RERR_PROTOCOL);
1039 /* Finally, we go to sleep until our parent kills us with a
1040 * USR2 signal. We sleep for a short time, as on some OSes
1041 * a signal won't interrupt a sleep! */
1042 while (1)
1043 msleep(20);
1046 am_generator = 1;
1047 flist_receiving_enabled = True;
1049 io_end_multiplex_in(MPLX_SWITCHING);
1050 if (write_batch && !am_server)
1051 stop_write_batch();
1053 close(error_pipe[1]);
1054 if (f_in != f_out)
1055 close(f_in);
1056 sock_f_in = -1;
1057 f_in = error_pipe[0];
1059 io_start_buffering_out(f_out);
1060 io_start_multiplex_in(f_in);
1062 #ifdef SUPPORT_HARD_LINKS
1063 if (preserve_hard_links && inc_recurse) {
1064 struct file_list *flist;
1065 for (flist = first_flist; flist; flist = flist->next)
1066 match_hard_links(flist);
1068 #endif
1070 generate_files(f_out, local_name);
1072 handle_stats(-1);
1073 io_flush(FULL_FLUSH);
1074 shutting_down = True;
1075 if (protocol_version >= 24) {
1076 /* send a final goodbye message */
1077 write_ndx(f_out, NDX_DONE);
1079 io_flush(FULL_FLUSH);
1081 kill(pid, SIGUSR2);
1082 wait_process_with_flush(pid, &exit_code);
1083 return exit_code;
1086 static void do_server_recv(int f_in, int f_out, int argc, char *argv[])
1088 int exit_code;
1089 struct file_list *flist;
1090 char *local_name = NULL;
1091 int negated_levels;
1093 if (filesfrom_fd >= 0 && !msgs2stderr && protocol_version < 31) {
1094 /* We can't mix messages with files-from data on the socket,
1095 * so temporarily turn off info/debug messages. */
1096 negate_output_levels();
1097 negated_levels = 1;
1098 } else
1099 negated_levels = 0;
1101 if (DEBUG_GTE(RECV, 1))
1102 rprintf(FINFO, "server_recv(%d) starting pid=%d\n", argc, (int)getpid());
1104 if (am_daemon && read_only) {
1105 rprintf(FERROR,"ERROR: module is read only\n");
1106 exit_cleanup(RERR_SYNTAX);
1107 return;
1110 become_copy_as_user();
1112 if (argc > 0) {
1113 char *dir = argv[0];
1114 argc--;
1115 argv++;
1116 if (!am_daemon && !change_dir(dir, CD_NORMAL)) {
1117 rsyserr(FERROR, errno, "change_dir#4 %s failed",
1118 full_fname(dir));
1119 exit_cleanup(RERR_FILESELECT);
1123 if (protocol_version >= 30)
1124 io_start_multiplex_in(f_in);
1125 else
1126 io_start_buffering_in(f_in);
1127 recv_filter_list(f_in);
1129 if (filesfrom_fd >= 0) {
1130 /* We need to send the files-from names to the sender at the
1131 * same time that we receive the file-list from them, so we
1132 * need the IO routines to automatically write out the names
1133 * onto our f_out socket as we read the file-list. This
1134 * avoids both deadlock and extra delays/buffers. */
1135 start_filesfrom_forwarding(filesfrom_fd);
1136 filesfrom_fd = -1;
1139 flist = recv_file_list(f_in, -1);
1140 if (!flist) {
1141 rprintf(FERROR,"server_recv: recv_file_list error\n");
1142 exit_cleanup(RERR_FILESELECT);
1144 if (inc_recurse && file_total == 1)
1145 recv_additional_file_list(f_in);
1147 if (negated_levels)
1148 negate_output_levels();
1150 if (argc > 0)
1151 local_name = get_local_name(flist,argv[0]);
1153 /* Now that we know what our destination directory turned out to be,
1154 * we can sanitize the --link-/copy-/compare-dest args correctly. */
1155 if (sanitize_paths) {
1156 char **dir_p;
1157 for (dir_p = basis_dir; *dir_p; dir_p++)
1158 *dir_p = sanitize_path(NULL, *dir_p, NULL, curr_dir_depth, SP_DEFAULT);
1159 if (partial_dir)
1160 partial_dir = sanitize_path(NULL, partial_dir, NULL, curr_dir_depth, SP_DEFAULT);
1162 check_alt_basis_dirs();
1164 if (daemon_filter_list.head) {
1165 char **dir_p;
1166 filter_rule_list *elp = &daemon_filter_list;
1168 for (dir_p = basis_dir; *dir_p; dir_p++) {
1169 char *dir = *dir_p;
1170 if (*dir == '/')
1171 dir += module_dirlen;
1172 if (check_filter(elp, FLOG, dir, 1) < 0)
1173 goto options_rejected;
1175 if (partial_dir && *partial_dir == '/'
1176 && check_filter(elp, FLOG, partial_dir + module_dirlen, 1) < 0) {
1177 options_rejected:
1178 rprintf(FERROR, "Your options have been rejected by the server.\n");
1179 exit_cleanup(RERR_SYNTAX);
1183 exit_code = do_recv(f_in, f_out, local_name);
1184 exit_cleanup(exit_code);
1188 int child_main(int argc, char *argv[])
1190 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1191 return 0;
1195 void start_server(int f_in, int f_out, int argc, char *argv[])
1197 set_nonblocking(f_in);
1198 set_nonblocking(f_out);
1200 io_set_sock_fds(f_in, f_out);
1201 setup_protocol(f_out, f_in);
1203 if (protocol_version >= 23)
1204 io_start_multiplex_out(f_out);
1205 if (am_daemon && io_timeout && protocol_version >= 31)
1206 send_msg_int(MSG_IO_TIMEOUT, io_timeout);
1208 if (am_sender) {
1209 keep_dirlinks = 0; /* Must be disabled on the sender. */
1210 if (need_messages_from_generator)
1211 io_start_multiplex_in(f_in);
1212 else
1213 io_start_buffering_in(f_in);
1214 recv_filter_list(f_in);
1215 do_server_sender(f_in, f_out, argc, argv);
1216 } else
1217 do_server_recv(f_in, f_out, argc, argv);
1218 exit_cleanup(0);
1221 /* This is called once the connection has been negotiated. It is used
1222 * for rsyncd, remote-shell, and local connections. */
1223 int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
1225 struct file_list *flist = NULL;
1226 int exit_code = 0, exit_code2 = 0;
1227 char *local_name = NULL;
1229 cleanup_child_pid = pid;
1230 if (!read_batch) {
1231 set_nonblocking(f_in);
1232 set_nonblocking(f_out);
1235 io_set_sock_fds(f_in, f_out);
1236 setup_protocol(f_out,f_in);
1238 /* We set our stderr file handle to blocking because ssh might have
1239 * set it to non-blocking. This can be particularly troublesome if
1240 * stderr is a clone of stdout, because ssh would have set our stdout
1241 * to non-blocking at the same time (which can easily cause us to lose
1242 * output from our print statements). This kluge shouldn't cause ssh
1243 * any problems for how we use it. Note also that we delayed setting
1244 * this until after the above protocol setup so that we know for sure
1245 * that ssh is done twiddling its file descriptors. */
1246 set_blocking(STDERR_FILENO);
1248 if (am_sender) {
1249 keep_dirlinks = 0; /* Must be disabled on the sender. */
1251 if (always_checksum
1252 && (log_format_has(stdout_format, 'C')
1253 || log_format_has(logfile_format, 'C')))
1254 sender_keeps_checksum = 1;
1256 if (protocol_version >= 30)
1257 io_start_multiplex_out(f_out);
1258 else
1259 io_start_buffering_out(f_out);
1260 if (protocol_version >= 31 || (!filesfrom_host && protocol_version >= 23))
1261 io_start_multiplex_in(f_in);
1262 else
1263 io_start_buffering_in(f_in);
1264 send_filter_list(f_out);
1265 if (filesfrom_host)
1266 filesfrom_fd = f_in;
1268 if (write_batch && !am_server)
1269 start_write_batch(f_out);
1271 become_copy_as_user();
1273 flist = send_file_list(f_out, argc, argv);
1274 if (DEBUG_GTE(FLIST, 3))
1275 rprintf(FINFO,"file list sent\n");
1277 if (protocol_version < 31 && filesfrom_host && protocol_version >= 23)
1278 io_start_multiplex_in(f_in);
1280 io_flush(NORMAL_FLUSH);
1281 send_files(f_in, f_out);
1282 io_flush(FULL_FLUSH);
1283 handle_stats(-1);
1284 if (protocol_version >= 24)
1285 read_final_goodbye(f_in, f_out);
1286 if (pid != -1) {
1287 if (DEBUG_GTE(EXIT, 2))
1288 rprintf(FINFO,"client_run waiting on %d\n", (int) pid);
1289 io_flush(FULL_FLUSH);
1290 wait_process_with_flush(pid, &exit_code);
1292 output_summary();
1293 io_flush(FULL_FLUSH);
1294 exit_cleanup(exit_code);
1297 if (!read_batch) {
1298 if (protocol_version >= 23)
1299 io_start_multiplex_in(f_in);
1300 if (need_messages_from_generator)
1301 io_start_multiplex_out(f_out);
1302 else
1303 io_start_buffering_out(f_out);
1306 become_copy_as_user();
1308 send_filter_list(read_batch ? -1 : f_out);
1310 if (filesfrom_fd >= 0) {
1311 start_filesfrom_forwarding(filesfrom_fd);
1312 filesfrom_fd = -1;
1315 if (write_batch && !am_server)
1316 start_write_batch(f_in);
1317 flist = recv_file_list(f_in, -1);
1318 if (inc_recurse && file_total == 1)
1319 recv_additional_file_list(f_in);
1321 if (flist && flist->used > 0) {
1322 local_name = get_local_name(flist, argv[0]);
1324 check_alt_basis_dirs();
1326 exit_code2 = do_recv(f_in, f_out, local_name);
1327 } else {
1328 handle_stats(-1);
1329 output_summary();
1332 if (pid != -1) {
1333 if (DEBUG_GTE(RECV, 1))
1334 rprintf(FINFO,"client_run2 waiting on %d\n", (int) pid);
1335 io_flush(FULL_FLUSH);
1336 wait_process_with_flush(pid, &exit_code);
1339 return MAX(exit_code, exit_code2);
1342 static int copy_argv(char *argv[])
1344 int i;
1346 for (i = 0; argv[i]; i++) {
1347 if (!(argv[i] = strdup(argv[i]))) {
1348 rprintf (FERROR, "out of memory at %s(%d)\n",
1349 __FILE__, __LINE__);
1350 return RERR_MALLOC;
1354 return 0;
1358 /* Start a client for either type of remote connection. Work out
1359 * whether the arguments request a remote shell or rsyncd connection,
1360 * and call the appropriate connection function, then run_client.
1362 * Calls either start_socket_client (for sockets) or do_cmd and
1363 * client_run (for ssh). */
1364 static int start_client(int argc, char *argv[])
1366 char *p, *shell_machine = NULL, *shell_user = NULL;
1367 char **remote_argv;
1368 int remote_argc, env_port = rsync_port;
1369 int f_in, f_out;
1370 int ret;
1371 pid_t pid;
1373 /* Don't clobber argv[] so that ps(1) can still show the right
1374 * command line. */
1375 if ((ret = copy_argv(argv)) != 0)
1376 return ret;
1378 if (!read_batch) { /* for read_batch, NO source is specified */
1379 char *path = check_for_hostspec(argv[0], &shell_machine, &rsync_port);
1380 if (path) { /* source is remote */
1381 char *dummy_host;
1382 int dummy_port = 0;
1383 *argv = path;
1384 remote_argv = argv;
1385 remote_argc = argc;
1386 argv += argc - 1;
1387 if (argc == 1 || **argv == ':')
1388 argc = 0; /* no dest arg */
1389 else if (check_for_hostspec(*argv, &dummy_host, &dummy_port)) {
1390 rprintf(FERROR,
1391 "The source and destination cannot both be remote.\n");
1392 exit_cleanup(RERR_SYNTAX);
1393 } else {
1394 remote_argc--; /* don't count dest */
1395 argc = 1;
1397 if (filesfrom_host && *filesfrom_host && strcmp(filesfrom_host, shell_machine) != 0) {
1398 rprintf(FERROR,
1399 "--files-from hostname is not the same as the transfer hostname\n");
1400 exit_cleanup(RERR_SYNTAX);
1402 am_sender = 0;
1403 if (rsync_port)
1404 daemon_over_rsh = shell_cmd ? 1 : -1;
1405 } else { /* source is local, check dest arg */
1406 am_sender = 1;
1408 if (argc > 1) {
1409 p = argv[--argc];
1410 remote_argv = argv + argc;
1411 } else {
1412 static char *dotarg[1] = { "." };
1413 p = dotarg[0];
1414 remote_argv = dotarg;
1416 remote_argc = 1;
1418 path = check_for_hostspec(p, &shell_machine, &rsync_port);
1419 if (path && filesfrom_host && *filesfrom_host && strcmp(filesfrom_host, shell_machine) != 0) {
1420 rprintf(FERROR,
1421 "--files-from hostname is not the same as the transfer hostname\n");
1422 exit_cleanup(RERR_SYNTAX);
1424 if (!path) { /* no hostspec found, so src & dest are local */
1425 local_server = 1;
1426 if (filesfrom_host) {
1427 rprintf(FERROR,
1428 "--files-from cannot be remote when the transfer is local\n");
1429 exit_cleanup(RERR_SYNTAX);
1431 shell_machine = NULL;
1432 rsync_port = 0;
1433 } else { /* hostspec was found, so dest is remote */
1434 argv[argc] = path;
1435 if (rsync_port)
1436 daemon_over_rsh = shell_cmd ? 1 : -1;
1439 } else { /* read_batch */
1440 local_server = 1;
1441 if (check_for_hostspec(argv[argc-1], &shell_machine, &rsync_port)) {
1442 rprintf(FERROR, "remote destination is not allowed with --read-batch\n");
1443 exit_cleanup(RERR_SYNTAX);
1445 remote_argv = argv += argc - 1;
1446 remote_argc = argc = 1;
1447 rsync_port = 0;
1450 if (!rsync_port && remote_argc && !**remote_argv) /* Turn an empty arg into a dot dir. */
1451 *remote_argv = ".";
1453 if (am_sender) {
1454 char *dummy_host;
1455 int dummy_port = rsync_port;
1456 int i;
1457 /* For local source, extra source args must not have hostspec. */
1458 for (i = 1; i < argc; i++) {
1459 if (check_for_hostspec(argv[i], &dummy_host, &dummy_port)) {
1460 rprintf(FERROR, "Unexpected remote arg: %s\n", argv[i]);
1461 exit_cleanup(RERR_SYNTAX);
1464 } else {
1465 char *dummy_host;
1466 int dummy_port = rsync_port;
1467 int i;
1468 /* For remote source, any extra source args must have either
1469 * the same hostname or an empty hostname. */
1470 for (i = 1; i < remote_argc; i++) {
1471 char *arg = check_for_hostspec(remote_argv[i], &dummy_host, &dummy_port);
1472 if (!arg) {
1473 rprintf(FERROR, "Unexpected local arg: %s\n", remote_argv[i]);
1474 rprintf(FERROR, "If arg is a remote file/dir, prefix it with a colon (:).\n");
1475 exit_cleanup(RERR_SYNTAX);
1477 if (*dummy_host && strcmp(dummy_host, shell_machine) != 0) {
1478 rprintf(FERROR, "All source args must come from the same machine.\n");
1479 exit_cleanup(RERR_SYNTAX);
1481 if (rsync_port != dummy_port) {
1482 if (!rsync_port || !dummy_port)
1483 rprintf(FERROR, "All source args must use the same hostspec format.\n");
1484 else
1485 rprintf(FERROR, "All source args must use the same port number.\n");
1486 exit_cleanup(RERR_SYNTAX);
1488 if (!rsync_port && !*arg) /* Turn an empty arg into a dot dir. */
1489 arg = ".";
1490 remote_argv[i] = arg;
1494 if (rsync_port < 0)
1495 rsync_port = RSYNC_PORT;
1496 else
1497 env_port = rsync_port;
1499 if (daemon_over_rsh < 0)
1500 return start_socket_client(shell_machine, remote_argc, remote_argv, argc, argv);
1502 if (password_file && !daemon_over_rsh) {
1503 rprintf(FERROR, "The --password-file option may only be "
1504 "used when accessing an rsync daemon.\n");
1505 exit_cleanup(RERR_SYNTAX);
1508 if (connect_timeout) {
1509 rprintf(FERROR, "The --contimeout option may only be "
1510 "used when connecting to an rsync daemon.\n");
1511 exit_cleanup(RERR_SYNTAX);
1514 if (shell_machine) {
1515 p = strrchr(shell_machine,'@');
1516 if (p) {
1517 *p = 0;
1518 shell_user = shell_machine;
1519 shell_machine = p+1;
1523 if (DEBUG_GTE(CMD, 2)) {
1524 rprintf(FINFO,"cmd=%s machine=%s user=%s path=%s\n",
1525 NS(shell_cmd), NS(shell_machine), NS(shell_user),
1526 NS(remote_argv[0]));
1529 #ifdef HAVE_PUTENV
1530 if (daemon_over_rsh)
1531 set_env_num("RSYNC_PORT", env_port);
1532 #endif
1534 pid = do_cmd(shell_cmd, shell_machine, shell_user, remote_argv, remote_argc, &f_in, &f_out);
1536 /* if we're running an rsync server on the remote host over a
1537 * remote shell command, we need to do the RSYNCD protocol first */
1538 if (daemon_over_rsh) {
1539 int tmpret;
1540 tmpret = start_inband_exchange(f_in, f_out, shell_user, remote_argc, remote_argv);
1541 if (tmpret < 0)
1542 return tmpret;
1545 ret = client_run(f_in, f_out, pid, argc, argv);
1547 fflush(stdout);
1548 fflush(stderr);
1550 return ret;
1554 static void sigusr1_handler(UNUSED(int val))
1556 called_from_signal_handler = 1;
1557 exit_cleanup(RERR_SIGNAL1);
1560 static void sigusr2_handler(UNUSED(int val))
1562 if (!am_server)
1563 output_summary();
1564 close_all();
1565 if (got_xfer_error)
1566 _exit(RERR_PARTIAL);
1567 _exit(0);
1570 static void siginfo_handler(UNUSED(int val))
1572 if (!am_server && !INFO_GTE(PROGRESS, 1))
1573 want_progress_now = True;
1576 void remember_children(UNUSED(int val))
1578 #ifdef WNOHANG
1579 int cnt, status;
1580 pid_t pid;
1581 /* An empty waitpid() loop was put here by Tridge and we could never
1582 * get him to explain why he put it in, so rather than taking it
1583 * out we're instead saving the child exit statuses for later use.
1584 * The waitpid() loop presumably eliminates all possibility of leaving
1585 * zombie children, maybe that's why he did it. */
1586 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1587 /* save the child's exit status */
1588 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
1589 if (pid_stat_table[cnt].pid == 0) {
1590 pid_stat_table[cnt].pid = pid;
1591 pid_stat_table[cnt].status = status;
1592 break;
1596 #endif
1597 #ifndef HAVE_SIGACTION
1598 signal(SIGCHLD, remember_children);
1599 #endif
1604 * This routine catches signals and tries to send them to gdb.
1606 * Because it's called from inside a signal handler it ought not to
1607 * use too many library routines.
1609 * @todo Perhaps use "screen -X" instead/as well, to help people
1610 * debugging without easy access to X. Perhaps use an environment
1611 * variable, or just call a script?
1613 * @todo The /proc/ magic probably only works on Linux (and
1614 * Solaris?) Can we be more portable?
1616 #ifdef MAINTAINER_MODE
1617 const char *get_panic_action(void)
1619 const char *cmd_fmt = getenv("RSYNC_PANIC_ACTION");
1621 if (cmd_fmt)
1622 return cmd_fmt;
1623 return "xterm -display :0 -T Panic -n Panic -e gdb /proc/%d/exe %d";
1628 * Handle a fatal signal by launching a debugger, controlled by $RSYNC_PANIC_ACTION.
1630 * This signal handler is only installed if we were configured with
1631 * --enable-maintainer-mode. Perhaps it should always be on and we
1632 * should just look at the environment variable, but I'm a bit leery
1633 * of a signal sending us into a busy loop.
1635 static void rsync_panic_handler(UNUSED(int whatsig))
1637 char cmd_buf[300];
1638 int ret, pid_int = getpid();
1640 snprintf(cmd_buf, sizeof cmd_buf, get_panic_action(), pid_int, pid_int);
1642 /* Unless we failed to execute gdb, we allow the process to
1643 * continue. I'm not sure if that's right. */
1644 ret = shell_exec(cmd_buf);
1645 if (ret)
1646 _exit(ret);
1648 #endif
1651 int main(int argc,char *argv[])
1653 int ret;
1655 raw_argc = argc;
1656 raw_argv = argv;
1658 #ifdef HAVE_SIGACTION
1659 # ifdef HAVE_SIGPROCMASK
1660 sigset_t sigmask;
1662 sigemptyset(&sigmask);
1663 # endif
1664 sigact.sa_flags = SA_NOCLDSTOP;
1665 #endif
1666 SIGACTMASK(SIGUSR1, sigusr1_handler);
1667 SIGACTMASK(SIGUSR2, sigusr2_handler);
1668 SIGACTMASK(SIGCHLD, remember_children);
1669 #ifdef MAINTAINER_MODE
1670 SIGACTMASK(SIGSEGV, rsync_panic_handler);
1671 SIGACTMASK(SIGFPE, rsync_panic_handler);
1672 SIGACTMASK(SIGABRT, rsync_panic_handler);
1673 SIGACTMASK(SIGBUS, rsync_panic_handler);
1674 #endif
1675 #ifdef SIGINFO
1676 SIGACTMASK(SIGINFO, siginfo_handler);
1677 #endif
1678 #ifdef SIGVTALRM
1679 SIGACTMASK(SIGVTALRM, siginfo_handler);
1680 #endif
1682 starttime = time(NULL);
1683 our_uid = MY_UID();
1684 our_gid = MY_GID();
1685 am_root = our_uid == 0;
1687 memset(&stats, 0, sizeof(stats));
1689 /* Even a non-daemon runs needs the default config values to be set, e.g.
1690 * lp_dont_compress() is queried when no --skip-compress option is set. */
1691 reset_daemon_vars();
1693 if (argc < 2) {
1694 usage(FERROR);
1695 exit_cleanup(RERR_SYNTAX);
1698 /* Get the umask for use in permission calculations. We no longer set
1699 * it to zero; that is ugly and pointless now that all the callers that
1700 * relied on it have been reeducated to work with default ACLs. */
1701 umask(orig_umask = umask(0));
1703 #if defined CONFIG_LOCALE && defined HAVE_SETLOCALE
1704 setlocale(LC_CTYPE, "");
1705 #endif
1707 if (!parse_arguments(&argc, (const char ***) &argv)) {
1708 option_error();
1709 exit_cleanup(RERR_SYNTAX);
1711 if (write_batch
1712 && poptDupArgv(argc, (const char **)argv, &cooked_argc, (const char ***)&cooked_argv) != 0)
1713 out_of_memory("main");
1715 SIGACTMASK(SIGINT, sig_int);
1716 SIGACTMASK(SIGHUP, sig_int);
1717 SIGACTMASK(SIGTERM, sig_int);
1718 #if defined HAVE_SIGACTION && HAVE_SIGPROCMASK
1719 sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
1720 #endif
1722 /* Ignore SIGPIPE; we consistently check error codes and will
1723 * see the EPIPE. */
1724 SIGACTION(SIGPIPE, SIG_IGN);
1725 #ifdef SIGXFSZ
1726 SIGACTION(SIGXFSZ, SIG_IGN);
1727 #endif
1729 /* Initialize change_dir() here because on some old systems getcwd
1730 * (implemented by forking "pwd" and reading its output) doesn't
1731 * work when there are other child processes. Also, on all systems
1732 * that implement getcwd that way "pwd" can't be found after chroot. */
1733 change_dir(NULL, CD_NORMAL);
1735 if ((write_batch || read_batch) && !am_server) {
1736 open_batch_files(); /* sets batch_fd */
1737 if (read_batch)
1738 read_stream_flags(batch_fd);
1739 else
1740 write_stream_flags(batch_fd);
1742 if (write_batch < 0)
1743 dry_run = 1;
1745 if (am_server) {
1746 #ifdef ICONV_CONST
1747 setup_iconv();
1748 #endif
1749 } else if (am_daemon)
1750 return daemon_main();
1752 if (am_server && protect_args) {
1753 char buf[MAXPATHLEN];
1754 protect_args = 2;
1755 read_args(STDIN_FILENO, NULL, buf, sizeof buf, 1, &argv, &argc, NULL);
1756 if (!parse_arguments(&argc, (const char ***) &argv)) {
1757 option_error();
1758 exit_cleanup(RERR_SYNTAX);
1762 if (argc < 1) {
1763 usage(FERROR);
1764 exit_cleanup(RERR_SYNTAX);
1767 if (am_server) {
1768 set_nonblocking(STDIN_FILENO);
1769 set_nonblocking(STDOUT_FILENO);
1770 if (am_daemon)
1771 return start_daemon(STDIN_FILENO, STDOUT_FILENO);
1772 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1775 ret = start_client(argc, argv);
1776 if (ret == -1)
1777 exit_cleanup(RERR_STARTCLIENT);
1778 else
1779 exit_cleanup(ret);
1781 return ret;