Debian Codegraph @

main.c

raw symbols SCIP
1 /*
2 * The startup routines, including main(), for rsync.
3 *
4 * Copyright (C) 1996-2001 Andrew Tridgell <[email protected]>
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <[email protected]>
7 * Copyright (C) 2003-2022 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 "ifuncs.h"
26 #include "io.h"
27 #if defined CONFIG_LOCALE && defined HAVE_LOCALE_H
28 #include <locale.h>
29 #endif
30 #include <popt.h>
31 #ifdef __TANDEM
32 #include <floss.h(floss_execlp)>
33 #endif
34 #ifdef HAVE_SYS_RESOURCE_H
35 #include <sys/resource.h>
36 #endif
37
38 extern int dry_run;
39 extern int list_only;
40 extern int io_timeout;
41 extern int am_root;
42 extern int am_server;
43 extern int am_sender;
44 extern int am_daemon;
45 extern int inc_recurse;
46 extern int blocking_io;
47 extern int always_checksum;
48 extern int remove_source_files;
49 extern int output_needs_newline;
50 extern int called_from_signal_handler;
51 extern int need_messages_from_generator;
52 extern int kluge_around_eof;
53 extern int got_xfer_error;
54 extern volatile sig_atomic_t got_sigusr2;
55 extern int old_style_args;
56 extern int msgs2stderr;
57 extern int module_id;
58 extern int read_only;
59 extern int copy_links;
60 extern int copy_dirlinks;
61 extern int copy_unsafe_links;
62 extern int keep_dirlinks;
63 extern int preserve_hard_links;
64 extern int protocol_version;
65 extern int mkpath_dest_arg;
66 extern int file_total;
67 extern int recurse;
68 extern int xfer_dirs;
69 extern int protect_args;
70 extern int relative_paths;
71 extern int sanitize_paths;
72 extern int curr_dir_depth;
73 extern unsigned int curr_dir_len;
74 extern int module_id;
75 extern int rsync_port;
76 extern int whole_file;
77 extern int read_batch;
78 extern int write_batch;
79 extern int batch_fd;
80 extern int sock_f_in;
81 extern int sock_f_out;
82 extern int filesfrom_fd;
83 extern int connect_timeout;
84 extern int send_msgs_to_gen;
85 extern dev_t filesystem_dev;
86 extern pid_t cleanup_child_pid;
87 extern size_t bwlimit_writemax;
88 extern unsigned int module_dirlen;
89 extern BOOL flist_receiving_enabled;
90 extern BOOL want_progress_now;
91 extern BOOL shutting_down;
92 extern int backup_dir_len;
93 extern int basis_dir_cnt;
94 extern int default_af_hint;
95 extern int stdout_format_has_i;
96 extern int trust_sender_filter;
97 extern int trust_sender_args;
98 extern struct stats stats;
99 extern char *stdout_format;
100 extern char *logfile_format;
101 extern char *filesfrom_host;
102 extern char *partial_dir;
103 extern char *rsync_path;
104 extern char *shell_cmd;
105 extern char *password_file;
106 extern char *backup_dir;
107 extern char *copy_as;
108 extern char *tmpdir;
109 extern char curr_dir[MAXPATHLEN];
110 extern char backup_dir_buf[MAXPATHLEN];
111 extern char *basis_dir[MAX_BASIS_DIRS+1];
112 extern struct file_list *first_flist;
113 extern filter_rule_list daemon_filter_list, implied_filter_list;
114
115 uid_t our_uid;
116 gid_t our_gid;
117 int am_receiver = 0; /* Only set to 1 after the receiver/generator fork. */
118 int am_generator = 0; /* Only set to 1 after the receiver/generator fork. */
119 int local_server = 0;
120 int daemon_connection = 0; /* 0 = no daemon, 1 = daemon via remote shell, -1 = daemon via socket */
121 mode_t orig_umask = 0;
122 int batch_gen_fd = -1;
123 int sender_keeps_checksum = 0;
124 int raw_argc, cooked_argc;
125 char **raw_argv, **cooked_argv;
126
127 /* There's probably never more than at most 2 outstanding child processes,
128 * but set it higher, just in case. */
129 #define MAXCHILDPROCS 7
130
131 #ifdef HAVE_SIGACTION
132 # ifdef HAVE_SIGPROCMASK
133 # define SIGACTMASK(n,h) SIGACTION(n,h), sigaddset(&sigmask,(n))
134 # else
135 # define SIGACTMASK(n,h) SIGACTION(n,h)
136 # endif
137 static struct sigaction sigact;
138 #endif
139
140 struct pid_status {
141 pid_t pid;
142 int status;
143 } pid_stat_table[MAXCHILDPROCS];
144
145 static time_t starttime, endtime;
146 static int64 total_read, total_written;
147
148 static void show_malloc_stats(void);
149
150 /* Works like waitpid(), but if we already harvested the child pid in our
151 * remember_children(), we succeed instead of returning an error. */
152 pid_t wait_process(pid_t pid, int *status_ptr, int flags)
153 {
154 pid_t waited_pid;
155
156 do {
157 waited_pid = waitpid(pid, status_ptr, flags);
158 } while (waited_pid == -1 && errno == EINTR);
159
160 if (waited_pid == -1 && errno == ECHILD) {
161 /* Status of requested child no longer available: check to
162 * see if it was processed by remember_children(). */
163 int cnt;
164 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
165 if (pid == pid_stat_table[cnt].pid) {
166 *status_ptr = pid_stat_table[cnt].status;
167 pid_stat_table[cnt].pid = 0;
168 return pid;
169 }
170 }
171 }
172
173 return waited_pid;
174 }
175
176 int shell_exec(const char *cmd)
177 {
178 char *shell = getenv("RSYNC_SHELL");
179 int status;
180 pid_t pid;
181
182 if (!shell)
183 return system(cmd);
184
185 if ((pid = fork()) < 0)
186 return -1;
187
188 if (pid == 0) {
189 execlp(shell, shell, "-c", cmd, NULL);
190 _exit(1);
191 }
192
193 int ret = wait_process(pid, &status, 0);
194 return ret < 0 ? -1 : status;
195 }
196
197 /* Wait for a process to exit, calling io_flush while waiting. */
198 static void wait_process_with_flush(pid_t pid, int *exit_code_ptr)
199 {
200 pid_t waited_pid;
201 int status;
202
203 while ((waited_pid = wait_process(pid, &status, WNOHANG)) == 0) {
204 msleep(20);
205 io_flush(FULL_FLUSH);
206 }
207
208 /* TODO: If the child exited on a signal, then log an
209 * appropriate error message. Perhaps we should also accept a
210 * message describing the purpose of the child. Also indicate
211 * this to the caller so that they know something went wrong. */
212 if (waited_pid < 0) {
213 rsyserr(FERROR, errno, "waitpid");
214 *exit_code_ptr = RERR_WAITCHILD;
215 } else if (!WIFEXITED(status)) {
216 #ifdef WCOREDUMP
217 if (WCOREDUMP(status))
218 *exit_code_ptr = RERR_CRASHED;
219 else
220 #endif
221 if (WIFSIGNALED(status))
222 *exit_code_ptr = RERR_TERMINATED;
223 else
224 *exit_code_ptr = RERR_WAITCHILD;
225 } else
226 *exit_code_ptr = WEXITSTATUS(status);
227 }
228
229 void write_del_stats(int f)
230 {
231 if (read_batch)
232 write_int(f, NDX_DEL_STATS);
233 else
234 write_ndx(f, NDX_DEL_STATS);
235 write_varint(f, stats.deleted_files - stats.deleted_dirs
236 - stats.deleted_symlinks - stats.deleted_devices
237 - stats.deleted_specials);
238 write_varint(f, stats.deleted_dirs);
239 write_varint(f, stats.deleted_symlinks);
240 write_varint(f, stats.deleted_devices);
241 write_varint(f, stats.deleted_specials);
242 }
243
244 void read_del_stats(int f)
245 {
246 stats.deleted_files = read_varint_bounded(f, 0, MAX_WIRE_DEL_STAT, "deleted_files");
247 stats.deleted_files += stats.deleted_dirs = read_varint_bounded(f, 0, MAX_WIRE_DEL_STAT, "deleted_dirs");
248 stats.deleted_files += stats.deleted_symlinks = read_varint_bounded(f, 0, MAX_WIRE_DEL_STAT, "deleted_symlinks");
249 stats.deleted_files += stats.deleted_devices = read_varint_bounded(f, 0, MAX_WIRE_DEL_STAT, "deleted_devices");
250 stats.deleted_files += stats.deleted_specials = read_varint_bounded(f, 0, MAX_WIRE_DEL_STAT, "deleted_specials");
251 }
252
253 static void become_copy_as_user()
254 {
255 char *gname;
256 uid_t uid;
257 gid_t gid;
258
259 if (!copy_as)
260 return;
261
262 if (DEBUG_GTE(CMD, 2))
263 rprintf(FINFO, "[%s] copy_as=%s\n", who_am_i(), copy_as);
264
265 if ((gname = strchr(copy_as, ':')) != NULL)
266 *gname++ = '\0';
267
268 if (!user_to_uid(copy_as, &uid, True)) {
269 rprintf(FERROR, "Invalid copy-as user: %s\n", copy_as);
270 exit_cleanup(RERR_SYNTAX);
271 }
272
273 if (gname) {
274 if (!group_to_gid(gname, &gid, True)) {
275 rprintf(FERROR, "Invalid copy-as group: %s\n", gname);
276 exit_cleanup(RERR_SYNTAX);
277 }
278 } else {
279 struct passwd *pw;
280 if ((pw = getpwuid(uid)) == NULL) {
281 rsyserr(FERROR, errno, "getpwuid failed");
282 exit_cleanup(RERR_SYNTAX);
283 }
284 gid = pw->pw_gid;
285 }
286
287 if (setgid(gid) < 0) {
288 rsyserr(FERROR, errno, "setgid failed");
289 exit_cleanup(RERR_SYNTAX);
290 }
291 #ifdef HAVE_SETGROUPS
292 if (setgroups(1, &gid)) {
293 rsyserr(FERROR, errno, "setgroups failed");
294 exit_cleanup(RERR_SYNTAX);
295 }
296 #endif
297 #ifdef HAVE_INITGROUPS
298 if (!gname && initgroups(copy_as, gid) < 0) {
299 rsyserr(FERROR, errno, "initgroups failed");
300 exit_cleanup(RERR_SYNTAX);
301 }
302 #endif
303
304 if (setuid(uid) < 0
305 #ifdef HAVE_SETEUID
306 || seteuid(uid) < 0
307 #endif
308 ) {
309 rsyserr(FERROR, errno, "setuid failed");
310 exit_cleanup(RERR_SYNTAX);
311 }
312
313 our_uid = MY_UID();
314 our_gid = MY_GID();
315 am_root = (our_uid == ROOT_UID);
316
317 if (gname)
318 gname[-1] = ':';
319 }
320
321 /* This function gets called from all 3 processes. We want the client side
322 * to actually output the text, but the sender is the only process that has
323 * all the stats we need. So, if we're a client sender, we do the report.
324 * If we're a server sender, we write the stats on the supplied fd. If
325 * we're the client receiver we read the stats from the supplied fd and do
326 * the report. All processes might also generate a set of debug stats, if
327 * the verbose level is high enough (this is the only thing that the
328 * generator process and the server receiver ever do here). */
329 static void handle_stats(int f)
330 {
331 endtime = time(NULL);
332
333 /* Cache two stats because the read/write code can change it. */
334 total_read = stats.total_read;
335 total_written = stats.total_written;
336
337 if (INFO_GTE(STATS, 3)) {
338 /* These come out from every process */
339 show_malloc_stats();
340 show_flist_stats();
341 }
342
343 if (am_generator)
344 return;
345
346 if (am_daemon) {
347 if (f == -1 || !am_sender)
348 return;
349 }
350
351 if (am_server) {
352 if (am_sender) {
353 write_varlong30(f, total_read, 3);
354 write_varlong30(f, total_written, 3);
355 write_varlong30(f, stats.total_size, 3);
356 if (protocol_version >= 29) {
357 write_varlong30(f, stats.flist_buildtime, 3);
358 write_varlong30(f, stats.flist_xfertime, 3);
359 }
360 }
361 return;
362 }
363
364 /* this is the client */
365
366 if (f < 0 && !am_sender) /* e.g. when we got an empty file list. */
367 ;
368 else if (!am_sender) {
369 /* Read the first two in opposite order because the meaning of
370 * read/write swaps when switching from sender to receiver. */
371 total_written = read_varlong30(f, 3);
372 total_read = read_varlong30(f, 3);
373 stats.total_size = read_varlong30(f, 3);
374 if (protocol_version >= 29) {
375 stats.flist_buildtime = read_varlong30(f, 3);
376 stats.flist_xfertime = read_varlong30(f, 3);
377 }
378 } else if (write_batch) {
379 /* The --read-batch process is going to be a client
380 * receiver, so we need to give it the stats. */
381 write_varlong30(batch_fd, total_read, 3);
382 write_varlong30(batch_fd, total_written, 3);
383 write_varlong30(batch_fd, stats.total_size, 3);
384 if (protocol_version >= 29) {
385 write_varlong30(batch_fd, stats.flist_buildtime, 3);
386 write_varlong30(batch_fd, stats.flist_xfertime, 3);
387 }
388 }
389 }
390
391 static void output_itemized_counts(const char *prefix, int *counts)
392 {
393 static char *const labels[] = { "reg", "dir", "link", "dev", "special" };
394 char buf[1024], *pre = " (";
395 int j, len = 0;
396 int total = counts[0];
397 if (total) {
398 counts[0] -= counts[1] + counts[2] + counts[3] + counts[4];
399 for (j = 0; j < 5; j++) {
400 if (counts[j]) {
401 /* snprintf can return more than its size arg
402 * on truncation; keep len <= sizeof buf - 2 so
403 * the closing ')' and trailing NUL always
404 * have room and the next iteration's
405 * sizeof buf - len - 2 cannot underflow. */
406 if (len >= (int)sizeof buf - 2)
407 break;
408 len += snprintf(buf+len, sizeof buf - len - 2,
409 "%s%s: %s",
410 pre, labels[j], comma_num(counts[j]));
411 if (len > (int)sizeof buf - 2)
412 len = (int)sizeof buf - 2;
413 pre = ", ";
414 }
415 }
416 buf[len++] = ')';
417 }
418 buf[len] = '\0';
419 rprintf(FINFO, "%s: %s%s\n", prefix, comma_num(total), buf);
420 }
421
422 static const char *bytes_per_sec_human_dnum(void)
423 {
424 if (starttime == (time_t)-1 || endtime == (time_t)-1)
425 return "UNKNOWN";
426 return human_dnum((total_written + total_read) / (0.5 + (endtime - starttime)), 2);
427 }
428
429 static void output_summary(void)
430 {
431 if (INFO_GTE(STATS, 2)) {
432 rprintf(FCLIENT, "\n");
433 output_itemized_counts("Number of files", &stats.num_files);
434 if (protocol_version >= 29)
435 output_itemized_counts("Number of created files", &stats.created_files);
436 if (protocol_version >= 31)
437 output_itemized_counts("Number of deleted files", &stats.deleted_files);
438 rprintf(FINFO,"Number of regular files transferred: %s\n",
439 comma_num(stats.xferred_files));
440 rprintf(FINFO,"Total file size: %s bytes\n",
441 human_num(stats.total_size));
442 rprintf(FINFO,"Total transferred file size: %s bytes\n",
443 human_num(stats.total_transferred_size));
444 rprintf(FINFO,"Literal data: %s bytes\n",
445 human_num(stats.literal_data));
446 rprintf(FINFO,"Matched data: %s bytes\n",
447 human_num(stats.matched_data));
448 rprintf(FINFO,"File list size: %s\n",
449 human_num(stats.flist_size));
450 if (stats.flist_buildtime) {
451 rprintf(FINFO,
452 "File list generation time: %s seconds\n",
453 comma_dnum((double)stats.flist_buildtime / 1000, 3));
454 rprintf(FINFO,
455 "File list transfer time: %s seconds\n",
456 comma_dnum((double)stats.flist_xfertime / 1000, 3));
457 }
458 rprintf(FINFO,"Total bytes sent: %s\n",
459 human_num(total_written));
460 rprintf(FINFO,"Total bytes received: %s\n",
461 human_num(total_read));
462 }
463
464 if (INFO_GTE(STATS, 1)) {
465 rprintf(FCLIENT, "\n");
466 rprintf(FINFO,
467 "sent %s bytes received %s bytes %s bytes/sec\n",
468 human_num(total_written), human_num(total_read),
469 bytes_per_sec_human_dnum());
470 rprintf(FINFO, "total size is %s speedup is %s%s\n",
471 human_num(stats.total_size),
472 comma_dnum((double)stats.total_size / (total_written+total_read), 2),
473 write_batch < 0 ? " (BATCH ONLY)" : dry_run ? " (DRY RUN)" : "");
474 }
475
476 fflush(stdout);
477 fflush(stderr);
478 }
479
480
481 /**
482 * If our C library can get malloc statistics, then show them to FINFO
483 **/
484 static void show_malloc_stats(void)
485 {
486 #ifdef MEM_ALLOC_INFO
487 struct MEM_ALLOC_INFO mi = MEM_ALLOC_INFO(); /* mallinfo or mallinfo2 */
488
489 rprintf(FCLIENT, "\n");
490 rprintf(FINFO, RSYNC_NAME "[%d] (%s%s%s) heap statistics:\n",
491 (int)getpid(), am_server ? "server " : "",
492 am_daemon ? "daemon " : "", who_am_i());
493
494 #define PRINT_ALLOC_NUM(title, descr, num) \
495 rprintf(FINFO, " %-11s%10" SIZE_T_FMT_MOD "d (" descr ")\n", \
496 title ":", (SIZE_T_FMT_CAST)(num));
497
498 PRINT_ALLOC_NUM("arena", "bytes from sbrk", mi.arena);
499 PRINT_ALLOC_NUM("ordblks", "chunks not in use", mi.ordblks);
500 PRINT_ALLOC_NUM("smblks", "free fastbin blocks", mi.smblks);
501 PRINT_ALLOC_NUM("hblks", "chunks from mmap", mi.hblks);
502 PRINT_ALLOC_NUM("hblkhd", "bytes from mmap", mi.hblkhd);
503 PRINT_ALLOC_NUM("allmem", "bytes from sbrk + mmap", mi.arena + mi.hblkhd);
504 PRINT_ALLOC_NUM("usmblks", "always 0", mi.usmblks);
505 PRINT_ALLOC_NUM("fsmblks", "bytes in freed fastbin blocks", mi.fsmblks);
506 PRINT_ALLOC_NUM("uordblks", "bytes used", mi.uordblks);
507 PRINT_ALLOC_NUM("fordblks", "bytes free", mi.fordblks);
508 PRINT_ALLOC_NUM("keepcost", "bytes in releasable chunk", mi.keepcost);
509
510 #undef PRINT_ALLOC_NUM
511
512 #endif /* MEM_ALLOC_INFO */
513 }
514
515
516 /* Start the remote shell. cmd may be NULL to use the default. */
517 static pid_t do_cmd(char *cmd, char *machine, char *user, char **remote_argv, int remote_argc,
518 int *f_in_p, int *f_out_p)
519 {
520 int i, argc = 0;
521 char *args[MAX_ARGS], *need_to_free = NULL;
522 pid_t pid;
523 int dash_l_set = 0;
524
525 if (!read_batch && !local_server) {
526 char *t, *f, in_quote = '\0';
527 char *rsh_env = getenv(RSYNC_RSH_ENV);
528 if (!cmd)
529 cmd = rsh_env;
530 if (!cmd)
531 cmd = RSYNC_RSH;
532 cmd = need_to_free = strdup(cmd);
533
534 for (t = f = cmd; *f; f++) {
535 if (*f == ' ')
536 continue;
537 /* Comparison leaves rooms for server_options(). */
538 if (argc >= MAX_ARGS - MAX_SERVER_ARGS)
539 goto arg_overflow;
540 args[argc++] = t;
541 while (*f != ' ' || in_quote) {
542 if (!*f) {
543 if (in_quote) {
544 rprintf(FERROR,
545 "Missing trailing-%c in remote-shell command.\n",
546 in_quote);
547 exit_cleanup(RERR_SYNTAX);
548 }
549 f--;
550 break;
551 }
552 if (*f == '\'' || *f == '"') {
553 if (!in_quote) {
554 in_quote = *f++;
555 continue;
556 }
557 if (*f == in_quote && *++f != in_quote) {
558 in_quote = '\0';
559 continue;
560 }
561 }
562 *t++ = *f++;
563 }
564 *t++ = '\0';
565 }
566
567 /* NOTE: must preserve t == start of command name until the end of the args handling! */
568 if ((t = strrchr(cmd, '/')) != NULL)
569 t++;
570 else
571 t = cmd;
572
573 /* Check to see if we've already been given '-l user' in the remote-shell command. */
574 for (i = 0; i < argc-1; i++) {
575 if (!strcmp(args[i], "-l") && args[i+1][0] != '-')
576 dash_l_set = 1;
577 }
578
579 #ifdef HAVE_REMSH
580 /* remsh (on HPUX) takes the arguments the other way around */
581 args[argc++] = machine;
582 if (user && !(daemon_connection && dash_l_set)) {
583 args[argc++] = "-l";
584 args[argc++] = user;
585 }
586 #else
587 if (user && !(daemon_connection && dash_l_set)) {
588 args[argc++] = "-l";
589 args[argc++] = user;
590 }
591 #ifdef AF_INET
592 if (default_af_hint == AF_INET && strcmp(t, "ssh") == 0)
593 args[argc++] = "-4"; /* we're using ssh so we can add a -4 option */
594 #endif
595 #ifdef AF_INET6
596 if (default_af_hint == AF_INET6 && strcmp(t, "ssh") == 0)
597 args[argc++] = "-6"; /* we're using ssh so we can add a -6 option */
598 #endif
599 args[argc++] = machine;
600 #endif
601
602 args[argc++] = rsync_path;
603
604 if (blocking_io < 0 && (strcmp(t, "rsh") == 0 || strcmp(t, "remsh") == 0))
605 blocking_io = 1;
606
607 if (daemon_connection > 0) {
608 args[argc++] = "--server";
609 args[argc++] = "--daemon";
610 } else
611 server_options(args, &argc);
612
613 if (argc >= MAX_ARGS - 2)
614 goto arg_overflow;
615 }
616
617 args[argc++] = ".";
618
619 if (!daemon_connection) {
620 while (remote_argc > 0) {
621 if (argc >= MAX_ARGS - 1) {
622 arg_overflow:
623 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
624 exit_cleanup(RERR_SYNTAX);
625 }
626 args[argc++] = safe_arg(NULL, *remote_argv++);
627 remote_argc--;
628 }
629 }
630
631 args[argc] = NULL;
632
633 if (DEBUG_GTE(CMD, 2)) {
634 for (i = 0; i < argc; i++)
635 rprintf(FCLIENT, "cmd[%d]=%s ", i, args[i]);
636 rprintf(FCLIENT, "\n");
637 }
638
639 if (read_batch) {
640 int from_gen_pipe[2];
641 set_allow_inc_recurse();
642 if (fd_pair(from_gen_pipe) < 0) {
643 rsyserr(FERROR, errno, "pipe");
644 exit_cleanup(RERR_IPC);
645 }
646 batch_gen_fd = from_gen_pipe[0];
647 *f_out_p = from_gen_pipe[1];
648 *f_in_p = batch_fd;
649 pid = (pid_t)-1; /* no child pid */
650 #ifdef ICONV_CONST
651 setup_iconv();
652 #endif
653 } else if (local_server) {
654 /* If the user didn't request --[no-]whole-file, force
655 * it on, but only if we're not batch processing. */
656 if (whole_file < 0 && !write_batch)
657 whole_file = 1;
658 set_allow_inc_recurse();
659 pid = local_child(argc, args, f_in_p, f_out_p, child_main);
660 #ifdef ICONV_CONST
661 setup_iconv();
662 #endif
663 } else {
664 pid = piped_child(args, f_in_p, f_out_p);
665 #ifdef ICONV_CONST
666 setup_iconv();
667 #endif
668 if (protect_args && !daemon_connection)
669 send_protected_args(*f_out_p, args);
670 }
671
672 if (need_to_free)
673 free(need_to_free);
674
675 return pid;
676 }
677
678 /* Older versions turn an empty string as a reference to the current directory.
679 * We now treat this as an error unless --old-args was used. */
680 static char *dot_dir_or_error()
681 {
682 if (old_style_args || am_server)
683 return ".";
684 rprintf(FERROR, "Empty destination arg specified (use \".\" or see --old-args).\n");
685 exit_cleanup(RERR_SYNTAX);
686 }
687
688 /* The receiving side operates in one of two modes:
689 *
690 * 1. it receives any number of files into a destination directory,
691 * placing them according to their names in the file-list.
692 *
693 * 2. it receives a single file and saves it using the name in the
694 * destination path instead of its file-list name. This requires a
695 * "local name" for writing out the destination file.
696 *
697 * So, our task is to figure out what mode/local-name we need.
698 * For mode 1, we change into the destination directory and return NULL.
699 * For mode 2, we change into the directory containing the destination
700 * file (if we aren't already there) and return the local-name. */
701 static char *get_local_name(struct file_list *flist, char *dest_path)
702 {
703 STRUCT_STAT st;
704 int statret, trailing_slash;
705 char *cp;
706
707 if (DEBUG_GTE(RECV, 1)) {
708 rprintf(FINFO, "get_local_name count=%d %s\n",
709 file_total, NS(dest_path));
710 }
711
712 if (!dest_path || list_only)
713 return NULL;
714
715 if (!*dest_path)
716 dest_path = dot_dir_or_error();
717
718 if (daemon_filter_list.head) {
719 /* Collapse ".." for the NAME-based daemon filter check so a "../excluded"
720 * destination is matched by name, as stock rsync does on its sanitized
721 * arg. Done on a copy: the daemon exclude/filter is name-based (a symlink
722 * whose own name is not excluded is still followed -- see rsyncd.conf(5)
723 * "munge symlinks"), and the real dest_path is left for the resolver. */
724 char cleaned[MAXPATHLEN], *slash;
725 if (!sanitize_path(cleaned, dest_path, NULL, 0, SP_KEEP_DOT_DIRS))
726 strlcpy(cleaned, dest_path, sizeof cleaned);
727 slash = strrchr(cleaned, '/');
728 if (slash && (slash[1] == '\0' || (slash[1] == '.' && slash[2] == '\0')))
729 *slash = '\0';
730 if ((*cleaned != '.' || cleaned[1] != '\0')
731 && (check_filter(&daemon_filter_list, FLOG, cleaned, 0) < 0
732 || check_filter(&daemon_filter_list, FLOG, cleaned, 1) < 0)) {
733 rprintf(FERROR, "ERROR: daemon has excluded destination \"%s\"\n",
734 dest_path);
735 exit_cleanup(RERR_FILESELECT);
736 }
737 }
738
739 /* See what currently exists at the destination. */
740 statret = do_stat(dest_path, &st);
741 cp = strrchr(dest_path, '/');
742 trailing_slash = cp && !cp[1];
743
744 if (mkpath_dest_arg && statret < 0 && (cp || file_total > 1)) {
745 int save_errno = errno;
746 int ret = make_path(dest_path, file_total > 1 && !trailing_slash ? 0 : MKP_DROP_NAME);
747 if (ret < 0)
748 goto mkdir_error;
749 if (ret && (INFO_GTE(NAME, 1) || stdout_format_has_i)) {
750 if (cp && (file_total == 1 || trailing_slash))
751 *cp = '\0';
752 rprintf(FINFO, "created %d director%s for %s\n", ret, ret == 1 ? "y" : "ies", dest_path);
753 if (cp && (file_total == 1 || trailing_slash))
754 *cp = '/';
755 }
756 if (ret)
757 statret = do_stat(dest_path, &st);
758 else
759 errno = save_errno;
760 }
761
762 if (statret == 0) {
763 /* If the destination is a dir, enter it and use mode 1. */
764 if (S_ISDIR(st.st_mode)) {
765 if (!change_dir(dest_path, CD_NORMAL)) {
766 rsyserr(FERROR, errno, "change_dir#1 %s failed",
767 full_fname(dest_path));
768 exit_cleanup(RERR_FILESELECT);
769 }
770 filesystem_dev = st.st_dev; /* ensures --force works right w/-x */
771 return NULL;
772 }
773 if (file_total > 1) {
774 rprintf(FERROR,
775 "ERROR: destination must be a directory when"
776 " copying more than 1 file\n");
777 exit_cleanup(RERR_FILESELECT);
778 }
779 if (file_total == 1 && S_ISDIR(flist->files[0]->mode)) {
780 rprintf(FERROR,
781 "ERROR: cannot overwrite non-directory"
782 " with a directory\n");
783 exit_cleanup(RERR_FILESELECT);
784 }
785 } else if (errno != ENOENT) {
786 /* If we don't know what's at the destination, fail. */
787 rsyserr(FERROR, errno, "ERROR: cannot stat destination %s",
788 full_fname(dest_path));
789 exit_cleanup(RERR_FILESELECT);
790 }
791
792 /* If we need a destination directory because the transfer is not
793 * of a single non-directory or the user has requested one via a
794 * destination path ending in a slash, create one and use mode 1. */
795 if (file_total > 1 || trailing_slash) {
796 if (trailing_slash)
797 *cp = '\0'; /* Lop off the final slash (if any). */
798
799 if (statret == 0) {
800 rprintf(FERROR, "ERROR: destination path is not a directory\n");
801 exit_cleanup(RERR_SYNTAX);
802 }
803
804 if (do_mkdir(dest_path, ACCESSPERMS) != 0) {
805 mkdir_error:
806 rsyserr(FERROR, errno, "mkdir %s failed",
807 full_fname(dest_path));
808 exit_cleanup(RERR_FILEIO);
809 }
810
811 if (flist->high >= flist->low
812 && strcmp(flist->files[flist->low]->basename, ".") == 0)
813 flist->files[0]->flags |= FLAG_DIR_CREATED;
814
815 if (INFO_GTE(NAME, 1) || stdout_format_has_i)
816 rprintf(FINFO, "created directory %s\n", dest_path);
817
818 if (dry_run) {
819 /* Indicate that dest dir doesn't really exist. */
820 dry_run++;
821 }
822
823 if (!change_dir(dest_path, dry_run > 1 ? CD_SKIP_CHDIR : CD_NORMAL)) {
824 rsyserr(FERROR, errno, "change_dir#2 %s failed",
825 full_fname(dest_path));
826 exit_cleanup(RERR_FILESELECT);
827 }
828
829 return NULL;
830 }
831
832 /* Otherwise, we are writing a single file, possibly on top of an
833 * existing non-directory. Change to the item's parent directory
834 * (if it has a path component), return the basename of the
835 * destination file as the local name, and use mode 2. */
836 if (!cp)
837 return dest_path;
838
839 if (cp == dest_path)
840 dest_path = "/";
841
842 *cp = '\0';
843 if (dry_run && mkpath_dest_arg && do_stat(dest_path, &st) < 0) {
844 /* --mkpath would have created this parent dir, but a dry run did
845 * not, so don't chdir into it; flag the destination as not yet
846 * present (as the dir-creation path above does) so the generator
847 * doesn't try to compare against the missing tree (#880). Only
848 * the missing-parent case is touched, so an ordinary file-to-file
849 * dry run still itemizes against an existing destination. */
850 dry_run++;
851 change_dir(dest_path, CD_SKIP_CHDIR);
852 } else if (!change_dir(dest_path, CD_NORMAL)) {
853 rsyserr(FERROR, errno, "change_dir#3 %s failed",
854 full_fname(dest_path));
855 exit_cleanup(RERR_FILESELECT);
856 }
857 *cp = '/';
858
859 return cp + 1;
860 }
861
862 /* This function checks on our alternate-basis directories. If we're in
863 * dry-run mode and the destination dir does not yet exist, we'll try to
864 * tweak any dest-relative paths to make them work for a dry-run (the
865 * destination dir must be in curr_dir[] when this function is called).
866 * We also warn about any arg that is non-existent or not a directory. */
867 static void check_alt_basis_dirs(void)
868 {
869 STRUCT_STAT st;
870 char *slash = strrchr(curr_dir, '/');
871 int j;
872
873 for (j = 0; j < basis_dir_cnt; j++) {
874 char *bdir = basis_dir[j];
875 assert(bdir != NULL); /* option-supplied root; never NULL */
876 int bd_len = strlen(bdir);
877 if (bd_len > 1 && bdir[bd_len-1] == '/')
878 bdir[--bd_len] = '\0';
879 /* Make a relative --link-dest/--copy-dest/--compare-dest absolute
880 * (vs the destination curr_dir). These are operator-trusted roots, so
881 * an absolute path makes the do_*_at() wrappers use plain resolution
882 * rather than reject an operator '..' outside the dest tree (e.g.
883 * --copy-dest=../to). Skipped when sanitize_paths already confined
884 * them; the dry_run>1 case keeps its leading-"../"-strip. */
885 if (*bdir != '/' && (dry_run > 1 || !sanitize_paths)) {
886 int len = curr_dir_len + 1 + bd_len + 1;
887 char *new = new_array(char, len);
888 if (dry_run > 1 && slash && strncmp(bdir, "../", 3) == 0) {
889 /* We want to remove only one leading "../" prefix for
890 * the directory we couldn't create in dry-run mode:
891 * this ensures that any other ".." references get
892 * evaluated the same as they would for a live copy. */
893 *slash = '\0';
894 pathjoin(new, len, curr_dir, bdir + 3);
895 *slash = '/';
896 } else
897 pathjoin(new, len, curr_dir, bdir);
898 basis_dir[j] = bdir = new;
899 }
900 if (do_stat(bdir, &st) < 0)
901 rprintf(FWARNING, "%s arg does not exist: %s\n", alt_dest_opt(0), bdir);
902 else if (!S_ISDIR(st.st_mode))
903 rprintf(FWARNING, "%s arg is not a dir: %s\n", alt_dest_opt(0), bdir);
904 }
905 }
906
907 /* This is only called by the sender. */
908 static void read_final_goodbye(int f_in, int f_out)
909 {
910 int i, iflags, xlen;
911 uchar fnamecmp_type;
912 char xname[MAXPATHLEN];
913
914 shutting_down = True;
915
916 if (protocol_version < 29)
917 i = read_int(f_in);
918 else {
919 i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
920 if (protocol_version >= 31 && i == NDX_DONE) {
921 if (am_sender)
922 write_ndx(f_out, NDX_DONE);
923 else {
924 if (batch_gen_fd >= 0) {
925 while (read_int(batch_gen_fd) != NDX_DEL_STATS) {}
926 read_del_stats(batch_gen_fd);
927 }
928 write_int(f_out, NDX_DONE);
929 }
930 i = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type, xname, &xlen);
931 }
932 }
933
934 if (i != NDX_DONE) {
935 rprintf(FERROR, "Invalid packet at end of run (%d) [%s]\n",
936 i, who_am_i());
937 exit_cleanup(RERR_PROTOCOL);
938 }
939 }
940
941 static void do_server_sender(int f_in, int f_out, int argc, char *argv[])
942 {
943 struct file_list *flist;
944 char *dir;
945
946 if (DEBUG_GTE(SEND, 1))
947 rprintf(FINFO, "server_sender starting pid=%d\n", (int)getpid());
948
949 if (am_daemon && lp_write_only(module_id)) {
950 rprintf(FERROR, "ERROR: module is write only\n");
951 exit_cleanup(RERR_SYNTAX);
952 }
953 if (am_daemon && read_only && remove_source_files) {
954 rprintf(FERROR,
955 "ERROR: --remove-%s-files cannot be used with a read-only module\n",
956 remove_source_files == 1 ? "source" : "sent");
957 exit_cleanup(RERR_SYNTAX);
958 }
959 if (argc < 1) {
960 rprintf(FERROR, "ERROR: do_server_sender called without args\n");
961 exit_cleanup(RERR_SYNTAX);
962 }
963
964 become_copy_as_user();
965
966 dir = argv[0];
967 if (!relative_paths) {
968 if (!change_dir(dir, CD_NORMAL)) {
969 rsyserr(FERROR, errno, "change_dir#3 %s failed",
970 full_fname(dir));
971 exit_cleanup(RERR_FILESELECT);
972 }
973 }
974 argc--;
975 argv++;
976
977 if (argc == 0 && (recurse || xfer_dirs || list_only)) {
978 argc = 1;
979 argv--;
980 argv[0] = ".";
981 }
982
983 flist = send_file_list(f_out,argc,argv);
984 if (!flist || flist->used == 0) {
985 /* Make sure input buffering is off so we can't hang in noop_io_until_death(). */
986 io_end_buffering_in(0);
987 /* TODO: we should really exit in a more controlled manner. */
988 exit_cleanup(0);
989 }
990
991 io_start_buffering_in(f_in);
992
993 send_files(f_in, f_out);
994 io_flush(FULL_FLUSH);
995 handle_stats(f_out);
996 if (protocol_version >= 24)
997 read_final_goodbye(f_in, f_out);
998 io_flush(FULL_FLUSH);
999 exit_cleanup(0);
1000 }
1001
1002
1003 static int do_recv(int f_in, int f_out, char *local_name)
1004 {
1005 int pid;
1006 int exit_code = 0;
1007 int error_pipe[2];
1008
1009 /* The receiving side mustn't obey this, or an existing symlink that
1010 * points to an identical file won't be replaced by the referent. */
1011 copy_links = copy_dirlinks = copy_unsafe_links = 0;
1012
1013 #ifdef SUPPORT_HARD_LINKS
1014 if (preserve_hard_links && !inc_recurse)
1015 match_hard_links(first_flist);
1016 #endif
1017
1018 if (fd_pair(error_pipe) < 0) {
1019 rsyserr(FERROR, errno, "pipe failed in do_recv");
1020 exit_cleanup(RERR_IPC);
1021 }
1022
1023 if (backup_dir) {
1024 STRUCT_STAT st;
1025 int ret;
1026 if (backup_dir_len > 1)
1027 backup_dir_buf[backup_dir_len-1] = '\0';
1028 ret = do_stat(backup_dir_buf, &st);
1029 if (ret != 0 || !S_ISDIR(st.st_mode)) {
1030 if (ret == 0) {
1031 rprintf(FERROR, "The backup-dir is not a directory: %s\n", backup_dir_buf);
1032 exit_cleanup(RERR_SYNTAX);
1033 }
1034 if (errno != ENOENT) {
1035 rprintf(FERROR, "Failed to stat %s: %s\n", backup_dir_buf, strerror(errno));
1036 exit_cleanup(RERR_FILEIO);
1037 }
1038 if (INFO_GTE(BACKUP, 1))
1039 rprintf(FINFO, "(new) backup_dir is %s\n", backup_dir_buf);
1040 } else if (INFO_GTE(BACKUP, 1))
1041 rprintf(FINFO, "backup_dir is %s\n", backup_dir_buf);
1042 if (backup_dir_len > 1)
1043 backup_dir_buf[backup_dir_len-1] = '/';
1044 }
1045
1046 if (tmpdir) {
1047 STRUCT_STAT st;
1048 int ret = do_stat(tmpdir, &st);
1049 if (ret < 0 || !S_ISDIR(st.st_mode)) {
1050 if (ret == 0) {
1051 rprintf(FERROR, "The temp-dir is not a directory: %s\n", tmpdir);
1052 exit_cleanup(RERR_SYNTAX);
1053 }
1054 if (errno == ENOENT) {
1055 rprintf(FERROR, "The temp-dir does not exist: %s\n", tmpdir);
1056 exit_cleanup(RERR_SYNTAX);
1057 }
1058 rprintf(FERROR, "Failed to stat temp-dir %s: %s\n", tmpdir, strerror(errno));
1059 exit_cleanup(RERR_FILEIO);
1060 }
1061 }
1062
1063 io_flush(FULL_FLUSH);
1064
1065 if ((pid = do_fork()) == -1) {
1066 rsyserr(FERROR, errno, "fork failed in do_recv");
1067 exit_cleanup(RERR_IPC);
1068 }
1069
1070 if (pid == 0) {
1071 am_receiver = 1;
1072 send_msgs_to_gen = am_server;
1073
1074 close(error_pipe[0]);
1075
1076 /* We can't let two processes write to the socket at one time. */
1077 io_end_multiplex_out(MPLX_SWITCHING);
1078 if (f_in != f_out)
1079 close(f_out);
1080 sock_f_out = -1;
1081 f_out = error_pipe[1];
1082
1083 bwlimit_writemax = 0; /* receiver doesn't need to do this */
1084
1085 if (read_batch)
1086 io_start_buffering_in(f_in);
1087 io_start_multiplex_out(f_out);
1088
1089 recv_files(f_in, f_out, local_name);
1090 io_flush(FULL_FLUSH);
1091 handle_stats(f_in);
1092
1093 if (output_needs_newline) {
1094 fputc('\n', stdout);
1095 output_needs_newline = 0;
1096 }
1097
1098 write_int(f_out, NDX_DONE);
1099 send_msg(MSG_STATS, (char*)&stats.total_read, sizeof stats.total_read, 0);
1100 io_flush(FULL_FLUSH);
1101
1102 /* Handle any keep-alive packets from the post-processing work
1103 * that the generator does. */
1104 if (protocol_version >= 29) {
1105 kluge_around_eof = -1;
1106
1107 /* This should only get stopped via a USR2 signal. */
1108 read_final_goodbye(f_in, f_out);
1109
1110 rprintf(FERROR, "Invalid packet at end of run [%s]\n",
1111 who_am_i());
1112 exit_cleanup(RERR_PROTOCOL);
1113 }
1114
1115 /* Finally, we go to sleep until our parent tells us to wrap up
1116 * with a USR2 signal. We sleep for a short time, as on some OSes
1117 * a signal won't interrupt a sleep, then act on the flag the
1118 * (async-signal-safe) handler set. */
1119 while (!got_sigusr2)
1120 msleep(20);
1121 receive_sigusr2();
1122 }
1123
1124 am_generator = 1;
1125 implied_filter_list.head = implied_filter_list.tail = NULL;
1126 flist_receiving_enabled = True;
1127
1128 io_end_multiplex_in(MPLX_SWITCHING);
1129 if (write_batch && !am_server)
1130 stop_write_batch();
1131
1132 close(error_pipe[1]);
1133 if (f_in != f_out)
1134 close(f_in);
1135 sock_f_in = -1;
1136 f_in = error_pipe[0];
1137
1138 io_start_buffering_out(f_out);
1139 io_start_multiplex_in(f_in);
1140
1141 #ifdef SUPPORT_HARD_LINKS
1142 if (preserve_hard_links && inc_recurse) {
1143 struct file_list *flist;
1144 for (flist = first_flist; flist; flist = flist->next)
1145 match_hard_links(flist);
1146 }
1147 #endif
1148
1149 generate_files(f_out, local_name);
1150
1151 handle_stats(-1);
1152 io_flush(FULL_FLUSH);
1153 shutting_down = True;
1154 if (protocol_version >= 24) {
1155 /* send a final goodbye message */
1156 write_ndx(f_out, NDX_DONE);
1157 }
1158 io_flush(FULL_FLUSH);
1159
1160 kill(pid, SIGUSR2);
1161 wait_process_with_flush(pid, &exit_code);
1162 return exit_code;
1163 }
1164
1165 static void do_server_recv(int f_in, int f_out, int argc, char *argv[])
1166 {
1167 int exit_code;
1168 struct file_list *flist;
1169 char *local_name = NULL;
1170 int negated_levels;
1171
1172 if (filesfrom_fd >= 0 && msgs2stderr != 1 && protocol_version < 31) {
1173 /* We can't mix messages with files-from data on the socket,
1174 * so temporarily turn off info/debug messages. */
1175 negate_output_levels();
1176 negated_levels = 1;
1177 } else
1178 negated_levels = 0;
1179
1180 if (DEBUG_GTE(RECV, 1))
1181 rprintf(FINFO, "server_recv(%d) starting pid=%d\n", argc, (int)getpid());
1182
1183 if (am_daemon && read_only) {
1184 rprintf(FERROR,"ERROR: module is read only\n");
1185 exit_cleanup(RERR_SYNTAX);
1186 return;
1187 }
1188
1189 become_copy_as_user();
1190
1191 if (argc > 0) {
1192 char *dir = argv[0];
1193 argc--;
1194 argv++;
1195 if (!am_daemon && !change_dir(dir, CD_NORMAL)) {
1196 rsyserr(FERROR, errno, "change_dir#4 %s failed",
1197 full_fname(dir));
1198 exit_cleanup(RERR_FILESELECT);
1199 }
1200 }
1201
1202 if (protocol_version >= 30)
1203 io_start_multiplex_in(f_in);
1204 else
1205 io_start_buffering_in(f_in);
1206 recv_filter_list(f_in);
1207
1208 if (filesfrom_fd >= 0) {
1209 /* We need to send the files-from names to the sender at the
1210 * same time that we receive the file-list from them, so we
1211 * need the IO routines to automatically write out the names
1212 * onto our f_out socket as we read the file-list. This
1213 * avoids both deadlock and extra delays/buffers. */
1214 start_filesfrom_forwarding(filesfrom_fd);
1215 filesfrom_fd = -1;
1216 }
1217
1218 flist = recv_file_list(f_in, -1);
1219 if (!flist) {
1220 rprintf(FERROR,"server_recv: recv_file_list error\n");
1221 exit_cleanup(RERR_FILESELECT);
1222 }
1223 if (inc_recurse && file_total == 1)
1224 recv_additional_file_list(f_in);
1225
1226 if (negated_levels)
1227 negate_output_levels();
1228
1229 if (argc > 0)
1230 local_name = get_local_name(flist,argv[0]);
1231
1232 /* Now that we know what our destination directory turned out to be,
1233 * we can sanitize the --link-/copy-/compare-dest args correctly. */
1234 if (sanitize_paths) {
1235 char **dir_p;
1236 for (dir_p = basis_dir; *dir_p; dir_p++)
1237 *dir_p = sanitize_path(NULL, *dir_p, NULL, curr_dir_depth, SP_DEFAULT);
1238 if (partial_dir)
1239 partial_dir = sanitize_path(NULL, partial_dir, NULL, curr_dir_depth, SP_DEFAULT);
1240 }
1241 check_alt_basis_dirs();
1242
1243 if (daemon_filter_list.head) {
1244 char **dir_p;
1245 filter_rule_list *elp = &daemon_filter_list;
1246
1247 /* Collapse ".." and strip the module-dir prefix to get the module-relative
1248 * name, but keep a leading "/" for a "path = /" module (module_dirlen <= 1)
1249 * so an absolute (module-rooted) filter rule still matches. */
1250 char clean[MAXPATHLEN], *dir;
1251 for (dir_p = basis_dir; *dir_p; dir_p++) {
1252 if (!sanitize_path(clean, *dir_p, "/", 0, SP_DEFAULT))
1253 strlcpy(clean, *dir_p, sizeof clean);
1254 dir = clean + (*clean == '/' && module_dirlen > 1 ? module_dirlen : 0);
1255 if (check_filter(elp, FLOG, dir, 1) < 0)
1256 goto options_rejected;
1257 }
1258 if (partial_dir && *partial_dir == '/') {
1259 if (!sanitize_path(clean, partial_dir, "/", 0, SP_DEFAULT))
1260 strlcpy(clean, partial_dir, sizeof clean);
1261 dir = clean + (*clean == '/' && module_dirlen > 1 ? module_dirlen : 0);
1262 if (check_filter(elp, FLOG, dir, 1) < 0)
1263 goto options_rejected;
1264 }
1265 if (0) {
1266 options_rejected:
1267 rprintf(FERROR, "Your options have been rejected by the server.\n");
1268 exit_cleanup(RERR_SYNTAX);
1269 }
1270 }
1271
1272 exit_code = do_recv(f_in, f_out, local_name);
1273 exit_cleanup(exit_code);
1274 }
1275
1276
1277 int child_main(int argc, char *argv[])
1278 {
1279 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1280 return 0;
1281 }
1282
1283
1284 void start_server(int f_in, int f_out, int argc, char *argv[])
1285 {
1286 set_nonblocking(f_in);
1287 set_nonblocking(f_out);
1288
1289 io_set_sock_fds(f_in, f_out);
1290 setup_protocol(f_out, f_in);
1291
1292 if (protocol_version >= 23)
1293 io_start_multiplex_out(f_out);
1294 if (am_daemon && io_timeout && protocol_version >= 31)
1295 send_msg_int(MSG_IO_TIMEOUT, io_timeout);
1296
1297 if (am_sender) {
1298 keep_dirlinks = 0; /* Must be disabled on the sender. */
1299
1300 /* Mirror client_run()'s sender_keeps_checksum check: a daemon-
1301 * as-sender with -c and a `log format` containing %C will read
1302 * F_SUM(file) in log_formatted(), so make_file() must allocate
1303 * SUM_EXTRA_CNT. Without this, F_SUM() reads past the pool slot
1304 * and hex-encodes adjacent heap into the transfer log. */
1305 if (always_checksum
1306 && (log_format_has(stdout_format, 'C')
1307 || log_format_has(logfile_format, 'C')))
1308 sender_keeps_checksum = 1;
1309
1310 if (need_messages_from_generator)
1311 io_start_multiplex_in(f_in);
1312 else
1313 io_start_buffering_in(f_in);
1314 recv_filter_list(f_in);
1315 do_server_sender(f_in, f_out, argc, argv);
1316 } else
1317 do_server_recv(f_in, f_out, argc, argv);
1318 exit_cleanup(0);
1319 }
1320
1321 /* This is called once the connection has been negotiated. It is used
1322 * for rsyncd, remote-shell, and local connections. */
1323 int client_run(int f_in, int f_out, pid_t pid, int argc, char *argv[])
1324 {
1325 struct file_list *flist = NULL;
1326 int exit_code = 0, exit_code2 = 0;
1327 char *local_name = NULL;
1328
1329 cleanup_child_pid = pid;
1330 if (!read_batch) {
1331 set_nonblocking(f_in);
1332 set_nonblocking(f_out);
1333 }
1334
1335 io_set_sock_fds(f_in, f_out);
1336 setup_protocol(f_out,f_in);
1337
1338 /* We set our stderr file handle to blocking because ssh might have
1339 * set it to non-blocking. This can be particularly troublesome if
1340 * stderr is a clone of stdout, because ssh would have set our stdout
1341 * to non-blocking at the same time (which can easily cause us to lose
1342 * output from our print statements). This kluge shouldn't cause ssh
1343 * any problems for how we use it. Note also that we delayed setting
1344 * this until after the above protocol setup so that we know for sure
1345 * that ssh is done twiddling its file descriptors. */
1346 set_blocking(STDERR_FILENO);
1347
1348 if (am_sender) {
1349 keep_dirlinks = 0; /* Must be disabled on the sender. */
1350
1351 if (always_checksum
1352 && (log_format_has(stdout_format, 'C')
1353 || log_format_has(logfile_format, 'C')))
1354 sender_keeps_checksum = 1;
1355
1356 if (protocol_version >= 30)
1357 io_start_multiplex_out(f_out);
1358 else
1359 io_start_buffering_out(f_out);
1360 if (protocol_version >= 31 || (!filesfrom_host && protocol_version >= 23))
1361 io_start_multiplex_in(f_in);
1362 else
1363 io_start_buffering_in(f_in);
1364 send_filter_list(f_out);
1365 if (filesfrom_host)
1366 filesfrom_fd = f_in;
1367
1368 if (write_batch && !am_server)
1369 start_write_batch(f_out);
1370
1371 become_copy_as_user();
1372
1373 send_file_list(f_out, argc, argv);
1374 if (DEBUG_GTE(FLIST, 3))
1375 rprintf(FINFO,"file list sent\n");
1376
1377 if (protocol_version < 31 && filesfrom_host && protocol_version >= 23)
1378 io_start_multiplex_in(f_in);
1379
1380 io_flush(NORMAL_FLUSH);
1381 send_files(f_in, f_out);
1382 io_flush(FULL_FLUSH);
1383 handle_stats(-1);
1384 if (protocol_version >= 24)
1385 read_final_goodbye(f_in, f_out);
1386 if (pid != -1) {
1387 if (DEBUG_GTE(EXIT, 2))
1388 rprintf(FINFO,"client_run waiting on %d\n", (int) pid);
1389 io_flush(FULL_FLUSH);
1390 wait_process_with_flush(pid, &exit_code);
1391 }
1392 output_summary();
1393 io_flush(FULL_FLUSH);
1394 exit_cleanup(exit_code);
1395 }
1396
1397 if (!read_batch) {
1398 if (protocol_version >= 23)
1399 io_start_multiplex_in(f_in);
1400 if (need_messages_from_generator)
1401 io_start_multiplex_out(f_out);
1402 else
1403 io_start_buffering_out(f_out);
1404 }
1405
1406 become_copy_as_user();
1407
1408 send_filter_list(read_batch ? -1 : f_out);
1409
1410 if (filesfrom_fd >= 0) {
1411 start_filesfrom_forwarding(filesfrom_fd);
1412 filesfrom_fd = -1;
1413 }
1414
1415 if (write_batch && !am_server)
1416 start_write_batch(f_in);
1417 flist = recv_file_list(f_in, -1);
1418 if (inc_recurse && file_total == 1)
1419 recv_additional_file_list(f_in);
1420
1421 if (flist && flist->used > 0) {
1422 local_name = get_local_name(flist, argv[0]);
1423
1424 check_alt_basis_dirs();
1425
1426 exit_code2 = do_recv(f_in, f_out, local_name);
1427 } else {
1428 handle_stats(-1);
1429 output_summary();
1430 }
1431
1432 if (pid != -1) {
1433 if (DEBUG_GTE(RECV, 1))
1434 rprintf(FINFO,"client_run2 waiting on %d\n", (int) pid);
1435 io_flush(FULL_FLUSH);
1436 wait_process_with_flush(pid, &exit_code);
1437 }
1438
1439 return MAX(exit_code, exit_code2);
1440 }
1441
1442 /* Start a client for either type of remote connection. Work out
1443 * whether the arguments request a remote shell or rsyncd connection,
1444 * and call the appropriate connection function, then run_client.
1445 *
1446 * Calls either start_socket_client (for sockets) or do_cmd and
1447 * client_run (for ssh). */
1448 static int start_client(int argc, char *argv[])
1449 {
1450 char *p, *shell_machine = NULL, *shell_user = NULL;
1451 char **remote_argv;
1452 int remote_argc, env_port = rsync_port;
1453 int f_in, f_out;
1454 int ret;
1455 pid_t pid;
1456
1457 if (!read_batch) { /* for read_batch, NO source is specified */
1458 char *path = check_for_hostspec(argv[0], &shell_machine, &rsync_port);
1459 if (path) { /* source is remote */
1460 char *dummy_host;
1461 int dummy_port = 0;
1462 *argv = path;
1463 remote_argv = argv;
1464 remote_argc = argc;
1465 argv += argc - 1;
1466 if (argc == 1 || **argv == ':')
1467 argc = 0; /* no dest arg */
1468 else if (check_for_hostspec(*argv, &dummy_host, &dummy_port)) {
1469 rprintf(FERROR,
1470 "The source and destination cannot both be remote.\n");
1471 exit_cleanup(RERR_SYNTAX);
1472 } else {
1473 remote_argc--; /* don't count dest */
1474 argc = 1;
1475 }
1476 if (filesfrom_host && *filesfrom_host && strcmp(filesfrom_host, shell_machine) != 0) {
1477 rprintf(FERROR,
1478 "--files-from hostname is not the same as the transfer hostname\n");
1479 exit_cleanup(RERR_SYNTAX);
1480 }
1481 am_sender = 0;
1482 if (rsync_port)
1483 daemon_connection = shell_cmd ? 1 : -1;
1484 } else { /* source is local, check dest arg */
1485 am_sender = 1;
1486
1487 if (argc > 1) {
1488 p = argv[--argc];
1489 if (!*p)
1490 p = dot_dir_or_error();
1491 remote_argv = argv + argc;
1492 } else {
1493 static char *dotarg[1] = { "." };
1494 p = dotarg[0];
1495 remote_argv = dotarg;
1496 }
1497 remote_argc = 1;
1498
1499 path = check_for_hostspec(p, &shell_machine, &rsync_port);
1500 if (path && filesfrom_host && *filesfrom_host && strcmp(filesfrom_host, shell_machine) != 0) {
1501 rprintf(FERROR,
1502 "--files-from hostname is not the same as the transfer hostname\n");
1503 exit_cleanup(RERR_SYNTAX);
1504 }
1505 if (!path) { /* no hostspec found, so src & dest are local */
1506 local_server = 1;
1507 if (filesfrom_host) {
1508 rprintf(FERROR,
1509 "--files-from cannot be remote when the transfer is local\n");
1510 exit_cleanup(RERR_SYNTAX);
1511 }
1512 shell_machine = NULL;
1513 rsync_port = 0;
1514 } else { /* hostspec was found, so dest is remote */
1515 argv[argc] = path;
1516 if (rsync_port)
1517 daemon_connection = shell_cmd ? 1 : -1;
1518 }
1519 }
1520 } else { /* read_batch */
1521 local_server = 1;
1522 if (check_for_hostspec(argv[argc-1], &shell_machine, &rsync_port)) {
1523 rprintf(FERROR, "remote destination is not allowed with --read-batch\n");
1524 exit_cleanup(RERR_SYNTAX);
1525 }
1526 remote_argv = argv += argc - 1;
1527 remote_argc = argc = 1;
1528 rsync_port = 0;
1529 }
1530
1531 /* A local transfer doesn't unbackslash anything, so leave the args alone. */
1532 if (local_server) {
1533 old_style_args = 2;
1534 trust_sender_args = trust_sender_filter = 1;
1535 }
1536
1537 if (!rsync_port && remote_argc && !**remote_argv) /* Turn an empty arg into a dot dir. */
1538 *remote_argv = ".";
1539
1540 if (am_sender) {
1541 char *dummy_host;
1542 int dummy_port = rsync_port;
1543 int i;
1544 if (!argv[0][0])
1545 goto invalid_empty;
1546 /* For local source, extra source args must not have hostspec. */
1547 for (i = 1; i < argc; i++) {
1548 if (!argv[i][0]) {
1549 invalid_empty:
1550 rprintf(FERROR, "Empty source arg specified.\n");
1551 exit_cleanup(RERR_SYNTAX);
1552 }
1553 if (check_for_hostspec(argv[i], &dummy_host, &dummy_port)) {
1554 rprintf(FERROR, "Unexpected remote arg: %s\n", argv[i]);
1555 exit_cleanup(RERR_SYNTAX);
1556 }
1557 }
1558 } else {
1559 char *dummy_host;
1560 int dummy_port = rsync_port;
1561 int i;
1562 if (filesfrom_fd < 0)
1563 add_implied_include(remote_argv[0], daemon_connection);
1564 /* For remote source, any extra source args must have either
1565 * the same hostname or an empty hostname. */
1566 for (i = 1; i < remote_argc; i++) {
1567 char *arg = check_for_hostspec(remote_argv[i], &dummy_host, &dummy_port);
1568 if (!arg) {
1569 rprintf(FERROR, "Unexpected local arg: %s\n", remote_argv[i]);
1570 rprintf(FERROR, "If arg is a remote file/dir, prefix it with a colon (:).\n");
1571 exit_cleanup(RERR_SYNTAX);
1572 }
1573 if (*dummy_host && strcmp(dummy_host, shell_machine) != 0) {
1574 rprintf(FERROR, "All source args must come from the same machine.\n");
1575 exit_cleanup(RERR_SYNTAX);
1576 }
1577 if (rsync_port != dummy_port) {
1578 if (!rsync_port || !dummy_port)
1579 rprintf(FERROR, "All source args must use the same hostspec format.\n");
1580 else
1581 rprintf(FERROR, "All source args must use the same port number.\n");
1582 exit_cleanup(RERR_SYNTAX);
1583 }
1584 if (!rsync_port && !*arg) /* Turn an empty arg into a dot dir. */
1585 arg = ".";
1586 remote_argv[i] = arg;
1587 add_implied_include(arg, daemon_connection);
1588 }
1589 }
1590
1591 if (rsync_port < 0)
1592 rsync_port = RSYNC_PORT;
1593 else
1594 env_port = rsync_port;
1595
1596 if (daemon_connection < 0)
1597 return start_socket_client(shell_machine, remote_argc, remote_argv, argc, argv);
1598
1599 if (password_file && !daemon_connection) {
1600 rprintf(FERROR, "The --password-file option may only be "
1601 "used when accessing an rsync daemon.\n");
1602 exit_cleanup(RERR_SYNTAX);
1603 }
1604
1605 if (connect_timeout) {
1606 rprintf(FERROR, "The --contimeout option may only be "
1607 "used when connecting to an rsync daemon.\n");
1608 exit_cleanup(RERR_SYNTAX);
1609 }
1610
1611 if (shell_machine) {
1612 p = strrchr(shell_machine,'@');
1613 if (p) {
1614 *p = 0;
1615 shell_user = shell_machine;
1616 shell_machine = p+1;
1617 }
1618 if (*shell_machine == '-') {
1619 rprintf(FERROR, "Invalid remote host: hostnames may not start with '-'.\n");
1620 exit_cleanup(RERR_SYNTAX);
1621 }
1622 }
1623
1624 if (DEBUG_GTE(CMD, 2)) {
1625 rprintf(FINFO,"cmd=%s machine=%s user=%s path=%s\n",
1626 NS(shell_cmd), NS(shell_machine), NS(shell_user),
1627 NS(remote_argv[0]));
1628 }
1629
1630 #ifdef HAVE_PUTENV
1631 if (daemon_connection)
1632 set_env_num("RSYNC_PORT", env_port);
1633 #else
1634 (void)env_port;
1635 #endif
1636
1637 pid = do_cmd(shell_cmd, shell_machine, shell_user, remote_argv, remote_argc, &f_in, &f_out);
1638
1639 /* if we're running an rsync server on the remote host over a
1640 * remote shell command, we need to do the RSYNCD protocol first */
1641 if (daemon_connection) {
1642 int tmpret;
1643 tmpret = start_inband_exchange(f_in, f_out, shell_user, remote_argc, remote_argv);
1644 if (tmpret < 0)
1645 return tmpret;
1646 }
1647
1648 ret = client_run(f_in, f_out, pid, argc, argv);
1649
1650 fflush(stdout);
1651 fflush(stderr);
1652
1653 return ret;
1654 }
1655
1656
1657 static void sigusr1_handler(UNUSED(int val))
1658 {
1659 called_from_signal_handler = 1;
1660 exit_cleanup(RERR_SIGNAL1);
1661 }
1662
1663 /* SIGUSR2 tells the receiver child to wrap up. A signal handler must be
1664 * async-signal-safe, so it only sets a flag here; receive_sigusr2() does the
1665 * actual summary + shutdown (which use stdio/malloc/close) at a safe point in
1666 * the receiver's post-transfer wait loops (read_final_goodbye via perform_io,
1667 * and the trailing sleep). */
1668 static void sigusr2_handler(UNUSED(int val))
1669 {
1670 got_sigusr2 = 1;
1671 }
1672
1673 void receive_sigusr2(void)
1674 {
1675 if (!am_server)
1676 output_summary();
1677 close_all();
1678 #ifdef GCOV_COVERAGE
1679 /* The receiver child exits with _exit() here, bypassing the gcov atexit
1680 * flush; without this it writes no .gcda. */
1681 { extern void __gcov_dump(void); __gcov_dump(); }
1682 #endif
1683 if (got_xfer_error)
1684 _exit(RERR_PARTIAL);
1685 _exit(0);
1686 }
1687
1688 #if defined SIGINFO || defined SIGVTALRM
1689 static void siginfo_handler(UNUSED(int val))
1690 {
1691 if (!am_server && !INFO_GTE(PROGRESS, 1))
1692 want_progress_now = True;
1693 }
1694 #endif
1695
1696 void remember_children(UNUSED(int val))
1697 {
1698 #ifdef WNOHANG
1699 int cnt, status;
1700 pid_t pid;
1701 /* An empty waitpid() loop was put here by Tridge and we could never
1702 * get him to explain why he put it in, so rather than taking it
1703 * out we're instead saving the child exit statuses for later use.
1704 * The waitpid() loop presumably eliminates all possibility of leaving
1705 * zombie children, maybe that's why he did it. */
1706 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
1707 /* save the child's exit status */
1708 for (cnt = 0; cnt < MAXCHILDPROCS; cnt++) {
1709 if (pid_stat_table[cnt].pid == 0) {
1710 pid_stat_table[cnt].pid = pid;
1711 pid_stat_table[cnt].status = status;
1712 break;
1713 }
1714 }
1715 }
1716 #endif
1717 #ifndef HAVE_SIGACTION
1718 signal(SIGCHLD, remember_children);
1719 #endif
1720 }
1721
1722 /**
1723 * This routine catches signals and tries to send them to gdb.
1724 *
1725 * Because it's called from inside a signal handler it ought not to
1726 * use too many library routines.
1727 *
1728 * @todo Perhaps use "screen -X" instead/as well, to help people
1729 * debugging without easy access to X. Perhaps use an environment
1730 * variable, or just call a script?
1731 *
1732 * @todo The /proc/ magic probably only works on Linux (and
1733 * Solaris?) Can we be more portable?
1734 **/
1735 #ifdef MAINTAINER_MODE
1736 const char *get_panic_action(void)
1737 {
1738 const char *cmd_fmt = getenv("RSYNC_PANIC_ACTION");
1739
1740 if (cmd_fmt)
1741 return cmd_fmt;
1742 return "xterm -display :0 -T Panic -n Panic -e gdb /proc/%d/exe %d";
1743 }
1744
1745 /**
1746 * Handle a fatal signal by launching a debugger, controlled by $RSYNC_PANIC_ACTION.
1747 *
1748 * This signal handler is only installed if we were configured with
1749 * --enable-maintainer-mode. Perhaps it should always be on and we
1750 * should just look at the environment variable, but I'm a bit leery
1751 * of a signal sending us into a busy loop.
1752 **/
1753 static void rsync_panic_handler(UNUSED(int whatsig))
1754 {
1755 char cmd_buf[300];
1756 int ret, pid_int = getpid();
1757
1758 snprintf(cmd_buf, sizeof cmd_buf, get_panic_action(), pid_int, pid_int);
1759
1760 /* Unless we failed to execute gdb, we allow the process to
1761 * continue. I'm not sure if that's right. */
1762 ret = shell_exec(cmd_buf);
1763 if (ret)
1764 _exit(ret);
1765 }
1766 #endif
1767
1768 static void unset_env_var(const char *var)
1769 {
1770 #ifdef HAVE_UNSETENV
1771 unsetenv(var);
1772 #else
1773 #ifdef HAVE_PUTENV
1774 char *mem;
1775 if (asprintf(&mem, "%s=", var) < 0)
1776 out_of_memory("unset_env_var");
1777 putenv(mem);
1778 #else
1779 (void)var;
1780 #endif
1781 #endif
1782 }
1783
1784
1785 /* The symlink-race-safe path resolver (secure_relative_open) holds one open
1786 * dirfd per path component while it walks a path, plus an ancestor-dirfd cache
1787 * -- far more descriptors than legacy rsync's single open(). On a host with a
1788 * low default soft limit (e.g. OpenBSD's 128) a deep tree can hit EMFILE.
1789 * Raise the soft RLIMIT_NOFILE toward the hard limit (unprivileged, per
1790 * process; inherited by the sender/generator/receiver forks and daemon
1791 * children), but cap it: some systems set an enormous hard limit (2^20+) that
1792 * we don't want to adopt wholesale. */
1793 static void raise_fd_limit(void)
1794 {
1795 #if defined HAVE_GETRLIMIT && defined HAVE_SETRLIMIT && defined RLIMIT_NOFILE
1796 struct rlimit rl;
1797 rlim_t want = 4096; /* covers a MAXPATHLEN-deep walk + cache + headroom */
1798
1799 if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
1800 return;
1801 if (want > rl.rlim_max)
1802 want = rl.rlim_max; /* never exceed the (admin-set) hard limit */
1803 if (rl.rlim_cur < want) { /* only ever raise, never lower an inherited limit */
1804 rl.rlim_cur = want;
1805 (void)setrlimit(RLIMIT_NOFILE, &rl); /* best-effort */
1806 }
1807 #endif
1808 }
1809
1810 int main(int argc,char *argv[])
1811 {
1812 int ret;
1813
1814 raw_argc = argc;
1815 raw_argv = argv;
1816
1817 raise_fd_limit();
1818
1819 #ifdef HAVE_SIGACTION
1820 # ifdef HAVE_SIGPROCMASK
1821 sigset_t sigmask;
1822
1823 sigemptyset(&sigmask);
1824 # endif
1825 sigact.sa_flags = SA_NOCLDSTOP;
1826 #endif
1827 SIGACTMASK(SIGUSR1, sigusr1_handler);
1828 SIGACTMASK(SIGUSR2, sigusr2_handler);
1829 SIGACTMASK(SIGCHLD, remember_children);
1830 #ifdef MAINTAINER_MODE
1831 SIGACTMASK(SIGSEGV, rsync_panic_handler);
1832 SIGACTMASK(SIGFPE, rsync_panic_handler);
1833 SIGACTMASK(SIGABRT, rsync_panic_handler);
1834 SIGACTMASK(SIGBUS, rsync_panic_handler);
1835 #endif
1836 #ifdef SIGINFO
1837 SIGACTMASK(SIGINFO, siginfo_handler);
1838 #endif
1839 #ifdef SIGVTALRM
1840 SIGACTMASK(SIGVTALRM, siginfo_handler);
1841 #endif
1842
1843 starttime = time(NULL);
1844 our_uid = MY_UID();
1845 our_gid = MY_GID();
1846 am_root = our_uid == ROOT_UID;
1847
1848 // DISPLAY should not be emptied unconditionally
1849 if (!getenv("SSH_ASKPASS"))
1850 unset_env_var("DISPLAY");
1851
1852 #if defined USE_OPENSSL && defined SET_OPENSSL_CONF
1853 #define TO_STR2(x) #x
1854 #define TO_STR(x) TO_STR2(x)
1855 /* ./configure --with-openssl-conf=/etc/ssl/openssl-rsync.cnf
1856 * defines SET_OPENSSL_CONF as that unquoted pathname. */
1857 if (!getenv("OPENSSL_CONF")) /* Don't override it if it's already set. */
1858 set_env_str("OPENSSL_CONF", TO_STR(SET_OPENSSL_CONF));
1859 #undef TO_STR
1860 #undef TO_STR2
1861 #endif
1862
1863 memset(&stats, 0, sizeof(stats));
1864
1865 /* Even a non-daemon runs needs the default config values to be set, e.g.
1866 * lp_dont_compress() is queried when no --skip-compress option is set. */
1867 reset_daemon_vars();
1868
1869 if (argc < 2) {
1870 usage(FERROR);
1871 exit_cleanup(RERR_SYNTAX);
1872 }
1873
1874 /* Get the umask for use in permission calculations. We no longer set
1875 * it to zero; that is ugly and pointless now that all the callers that
1876 * relied on it have been reeducated to work with default ACLs. */
1877 umask(orig_umask = umask(0));
1878
1879 #if defined CONFIG_LOCALE && defined HAVE_SETLOCALE
1880 setlocale(LC_CTYPE, "");
1881 setlocale(LC_NUMERIC, "");
1882 #endif
1883
1884 if (!parse_arguments(&argc, (const char ***) &argv)) {
1885 option_error();
1886 exit_cleanup(RERR_SYNTAX);
1887 }
1888 if (write_batch
1889 && poptDupArgv(argc, (const char **)argv, &cooked_argc, (const char ***)&cooked_argv) != 0)
1890 out_of_memory("main");
1891
1892 SIGACTMASK(SIGINT, sig_int);
1893 SIGACTMASK(SIGHUP, sig_int);
1894 SIGACTMASK(SIGTERM, sig_int);
1895 #if defined HAVE_SIGACTION && HAVE_SIGPROCMASK
1896 sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
1897 #endif
1898
1899 /* Ignore SIGPIPE; we consistently check error codes and will
1900 * see the EPIPE. */
1901 SIGACTION(SIGPIPE, SIG_IGN);
1902 #ifdef SIGXFSZ
1903 SIGACTION(SIGXFSZ, SIG_IGN);
1904 #endif
1905
1906 /* Initialize change_dir() here because on some old systems getcwd
1907 * (implemented by forking "pwd" and reading its output) doesn't
1908 * work when there are other child processes. Also, on all systems
1909 * that implement getcwd that way "pwd" can't be found after chroot. */
1910 change_dir(NULL, CD_NORMAL);
1911
1912 if ((write_batch || read_batch) && !am_server) {
1913 open_batch_files(); /* sets batch_fd */
1914 if (read_batch)
1915 read_stream_flags(batch_fd);
1916 else
1917 write_stream_flags(batch_fd);
1918 }
1919 if (write_batch < 0)
1920 dry_run = 1;
1921
1922 if (am_server) {
1923 #ifdef ICONV_CONST
1924 setup_iconv();
1925 #endif
1926 } else if (am_daemon)
1927 return daemon_main();
1928
1929 if (am_server && protect_args) {
1930 char buf[MAXPATHLEN];
1931 protect_args = 2;
1932 read_args(STDIN_FILENO, NULL, buf, sizeof buf, 1, 0, &argv, &argc, NULL);
1933 if (!parse_arguments(&argc, (const char ***) &argv)) {
1934 option_error();
1935 exit_cleanup(RERR_SYNTAX);
1936 }
1937 }
1938
1939 if (argc < 1) {
1940 usage(FERROR);
1941 exit_cleanup(RERR_SYNTAX);
1942 }
1943
1944 if (am_server) {
1945 set_nonblocking(STDIN_FILENO);
1946 set_nonblocking(STDOUT_FILENO);
1947 if (am_daemon)
1948 return start_daemon(STDIN_FILENO, STDOUT_FILENO);
1949 start_server(STDIN_FILENO, STDOUT_FILENO, argc, argv);
1950 }
1951
1952 ret = start_client(argc, argv);
1953 if (ret == -1)
1954 exit_cleanup(RERR_STARTCLIENT);
1955 else
1956 exit_cleanup(ret);
1957
1958 return ret;
1959 }