Put the rsync-ssl-rsh helper script into a lib dir.
[rsync.git] / clientserver.c
blob91f78b7b753f4814b94e1866f78614316feff822
1 /*
2 * The socket based protocol for setting up a connection with rsyncd.
4 * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5 * Copyright (C) 2001-2002 Martin Pool <mbp@samba.org>
6 * Copyright (C) 2002-2020 Wayne Davison
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
22 #include "rsync.h"
23 #include "itypes.h"
25 extern int quiet;
26 extern int dry_run;
27 extern int output_motd;
28 extern int list_only;
29 extern int am_sender;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_root;
33 extern int msgs2stderr;
34 extern int rsync_port;
35 extern int protect_args;
36 extern int ignore_errors;
37 extern int preserve_xattrs;
38 extern int kluge_around_eof;
39 extern int daemon_over_rsh;
40 extern int munge_symlinks;
41 extern int sanitize_paths;
42 extern int numeric_ids;
43 extern int filesfrom_fd;
44 extern int remote_protocol;
45 extern int protocol_version;
46 extern int io_timeout;
47 extern int no_detach;
48 extern int write_batch;
49 extern int default_af_hint;
50 extern int logfile_format_has_i;
51 extern int logfile_format_has_o_or_i;
52 extern char *bind_address;
53 extern char *config_file;
54 extern char *logfile_format;
55 extern char *files_from;
56 extern char *tmpdir;
57 extern struct chmod_mode_struct *chmod_modes;
58 extern filter_rule_list daemon_filter_list;
59 #ifdef ICONV_OPTION
60 extern char *iconv_opt;
61 extern iconv_t ic_send, ic_recv;
62 #endif
63 extern uid_t our_uid;
64 extern gid_t our_gid;
66 char *auth_user;
67 int read_only = 0;
68 int module_id = -1;
69 int pid_file_fd = -1;
70 struct chmod_mode_struct *daemon_chmod_modes;
72 /* module_dirlen is the length of the module_dir string when in daemon
73 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
74 * enabled module can have a non-"/" module_dir these days.) */
75 char *module_dir = NULL;
76 unsigned int module_dirlen = 0;
78 char *full_module_path;
80 static int rl_nulls = 0;
82 #ifdef HAVE_SIGACTION
83 static struct sigaction sigact;
84 #endif
86 static item_list gid_list = EMPTY_ITEM_LIST;
88 /* Used when "reverse lookup" is off. */
89 const char undetermined_hostname[] = "UNDETERMINED";
91 /**
92 * Run a client connected to an rsyncd. The alternative to this
93 * function for remote-shell connections is do_cmd().
95 * After negotiating which module to use and reading the server's
96 * motd, this hands over to client_run(). Telling the server the
97 * module will cause it to chroot/setuid/etc.
99 * Instead of doing a transfer, the client may at this stage instead
100 * get a listing of remote modules and exit.
102 * @return -1 for error in startup, or the result of client_run().
103 * Either way, it eventually gets passed to exit_cleanup().
105 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
106 int argc, char *argv[])
108 int fd, ret;
109 char *p, *user = NULL;
111 /* This is redundant with code in start_inband_exchange(), but this
112 * short-circuits a problem in the client before we open a socket,
113 * and the extra check won't hurt. */
114 if (**remote_argv == '/') {
115 rprintf(FERROR,
116 "ERROR: The remote path must start with a module name not a /\n");
117 return -1;
120 if ((p = strrchr(host, '@')) != NULL) {
121 user = host;
122 host = p+1;
123 *p = '\0';
126 fd = open_socket_out_wrapped(host, rsync_port, bind_address,
127 default_af_hint);
128 if (fd == -1)
129 exit_cleanup(RERR_SOCKETIO);
131 #ifdef ICONV_CONST
132 setup_iconv();
133 #endif
135 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
137 return ret ? ret : client_run(fd, fd, -1, argc, argv);
140 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
142 int remote_sub = -1;
143 #if SUBPROTOCOL_VERSION != 0
144 int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
145 #else
146 int our_sub = 0;
147 #endif
148 char *motd;
150 io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
152 if (!am_client) {
153 motd = lp_motd_file();
154 if (motd && *motd) {
155 FILE *f = fopen(motd,"r");
156 while (f && !feof(f)) {
157 int len = fread(buf, 1, bufsiz - 1, f);
158 if (len > 0)
159 write_buf(f_out, buf, len);
161 if (f)
162 fclose(f);
163 write_sbuf(f_out, "\n");
167 /* This strips the \n. */
168 if (!read_line_old(f_in, buf, bufsiz, 0)) {
169 if (am_client)
170 rprintf(FERROR, "rsync: did not see server greeting\n");
171 return -1;
174 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
175 if (am_client)
176 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
177 else
178 io_printf(f_out, "@ERROR: protocol startup error\n");
179 return -1;
182 if (remote_sub < 0) {
183 if (remote_protocol == 30) {
184 if (am_client)
185 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
186 else
187 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
188 return -1;
190 remote_sub = 0;
193 if (protocol_version > remote_protocol) {
194 protocol_version = remote_protocol;
195 if (remote_sub)
196 protocol_version--;
197 } else if (protocol_version == remote_protocol) {
198 if (remote_sub != our_sub)
199 protocol_version--;
201 #if SUBPROTOCOL_VERSION != 0
202 else if (protocol_version < remote_protocol) {
203 if (our_sub)
204 protocol_version--;
206 #endif
208 if (protocol_version >= 30)
209 rl_nulls = 1;
211 return 0;
214 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
216 int i, modlen;
217 char line[BIGPATHBUFLEN];
218 char *sargs[MAX_ARGS];
219 int sargc = 0;
220 char *p, *modname;
222 assert(argc > 0 && *argv != NULL);
224 if (**argv == '/') {
225 rprintf(FERROR,
226 "ERROR: The remote path must start with a module name\n");
227 return -1;
230 if (!(p = strchr(*argv, '/')))
231 modlen = strlen(*argv);
232 else
233 modlen = p - *argv;
235 if (!(modname = new_array(char, modlen+1+1))) /* room for '/' & '\0' */
236 out_of_memory("start_inband_exchange");
237 strlcpy(modname, *argv, modlen + 1);
238 modname[modlen] = '/';
239 modname[modlen+1] = '\0';
241 if (!user)
242 user = getenv("USER");
243 if (!user)
244 user = getenv("LOGNAME");
246 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
247 return -1;
249 /* set daemon_over_rsh to false since we need to build the
250 * true set of args passed through the rsh/ssh connection;
251 * this is a no-op for direct-socket-connection mode */
252 daemon_over_rsh = 0;
253 server_options(sargs, &sargc);
255 if (sargc >= MAX_ARGS - 2)
256 goto arg_overflow;
258 sargs[sargc++] = ".";
260 while (argc > 0) {
261 if (sargc >= MAX_ARGS - 1) {
262 arg_overflow:
263 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
264 exit_cleanup(RERR_SYNTAX);
266 if (strncmp(*argv, modname, modlen) == 0
267 && argv[0][modlen] == '\0')
268 sargs[sargc++] = modname; /* we send "modname/" */
269 else if (**argv == '-') {
270 if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
271 out_of_memory("start_inband_exchange");
272 } else
273 sargs[sargc++] = *argv;
274 argv++;
275 argc--;
278 sargs[sargc] = NULL;
280 if (DEBUG_GTE(CMD, 1))
281 print_child_argv("sending daemon args:", sargs);
283 io_printf(f_out, "%.*s\n", modlen, modname);
285 /* Old servers may just drop the connection here,
286 rather than sending a proper EXIT command. Yuck. */
287 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
289 while (1) {
290 if (!read_line_old(f_in, line, sizeof line, 0)) {
291 rprintf(FERROR, "rsync: didn't get server startup line\n");
292 return -1;
295 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
296 auth_client(f_out, user, line+18);
297 continue;
300 if (strcmp(line,"@RSYNCD: OK") == 0)
301 break;
303 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
304 /* This is sent by recent versions of the
305 * server to terminate the listing of modules.
306 * We don't want to go on and transfer
307 * anything; just exit. */
308 exit(0);
311 if (strncmp(line, "@ERROR", 6) == 0) {
312 rprintf(FERROR, "%s\n", line);
313 /* This is always fatal; the server will now
314 * close the socket. */
315 return -1;
318 /* This might be a MOTD line or a module listing, but there is
319 * no way to differentiate it. The manpage mentions this. */
320 if (output_motd)
321 rprintf(FINFO, "%s\n", line);
323 kluge_around_eof = 0;
325 if (rl_nulls) {
326 for (i = 0; i < sargc; i++) {
327 if (!sargs[i]) /* stop at --protect-args NULL */
328 break;
329 write_sbuf(f_out, sargs[i]);
330 write_byte(f_out, 0);
332 write_byte(f_out, 0);
333 } else {
334 for (i = 0; i < sargc; i++)
335 io_printf(f_out, "%s\n", sargs[i]);
336 write_sbuf(f_out, "\n");
339 if (protect_args)
340 send_protected_args(f_out, sargs);
342 if (protocol_version < 23) {
343 if (protocol_version == 22 || !am_sender)
344 io_start_multiplex_in(f_in);
347 free(modname);
349 return 0;
352 static char *finish_pre_exec(pid_t pid, int write_fd, int read_fd, char *request,
353 char **early_argv, char **argv)
355 char buf[BIGPATHBUFLEN], *bp;
356 int j = 0, status = -1, msglen = sizeof buf - 1;
358 if (!request)
359 request = "(NONE)";
361 write_buf(write_fd, request, strlen(request)+1);
362 if (early_argv) {
363 for ( ; *early_argv; early_argv++)
364 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
365 j = 1; /* Skip arg0 name in argv. */
367 for ( ; argv[j]; j++)
368 write_buf(write_fd, argv[j], strlen(argv[j])+1);
369 write_byte(write_fd, 0);
371 close(write_fd);
373 /* Read the stdout from the pre-xfer exec program. This it is only
374 * displayed to the user if the script also returns an error status. */
375 for (bp = buf; msglen > 0; msglen -= j) {
376 if ((j = read(read_fd, bp, msglen)) <= 0) {
377 if (j == 0)
378 break;
379 if (errno == EINTR)
380 continue;
381 break; /* Just ignore the read error for now... */
383 bp += j;
384 if (j > 1 && bp[-1] == '\n' && bp[-2] == '\r') {
385 bp--;
386 j--;
387 bp[-1] = '\n';
390 *bp = '\0';
392 close(read_fd);
394 if (wait_process(pid, &status, 0) < 0
395 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
396 char *e;
397 if (asprintf(&e, "pre-xfer exec returned failure (%d)%s%s%s\n%s",
398 status, status < 0 ? ": " : "",
399 status < 0 ? strerror(errno) : "",
400 *buf ? ":" : "", buf) < 0)
401 return "out_of_memory in finish_pre_exec\n";
402 return e;
404 return NULL;
407 #ifdef HAVE_PUTENV
408 static int read_arg_from_pipe(int fd, char *buf, int limit)
410 char *bp = buf, *eob = buf + limit - 1;
412 while (1) {
413 int got = read(fd, bp, 1);
414 if (got != 1) {
415 if (got < 0 && errno == EINTR)
416 continue;
417 return -1;
419 if (*bp == '\0')
420 break;
421 if (bp < eob)
422 bp++;
424 *bp = '\0';
426 return bp - buf;
428 #endif
430 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
432 if (was_chdir)
433 rsyserr(FLOG, errno, "chdir %s failed", dir);
434 else
435 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
436 io_printf(f_out, "@ERROR: chdir failed\n");
437 return -1;
440 static int add_a_group(int f_out, const char *gname)
442 gid_t gid, *gid_p;
443 if (!group_to_gid(gname, &gid, True)) {
444 rprintf(FLOG, "Invalid gid %s\n", gname);
445 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
446 return -1;
448 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
449 *gid_p = gid;
450 return 0;
453 #ifdef HAVE_GETGROUPLIST
454 static int want_all_groups(int f_out, uid_t uid)
456 const char *err;
457 if ((err = getallgroups(uid, &gid_list)) != NULL) {
458 rsyserr(FLOG, errno, "%s", err);
459 io_printf(f_out, "@ERROR: %s\n", err);
460 return -1;
462 return 0;
464 #elif defined HAVE_INITGROUPS
465 static struct passwd *want_all_groups(int f_out, uid_t uid)
467 struct passwd *pw;
468 gid_t *gid_p;
469 if ((pw = getpwuid(uid)) == NULL) {
470 rsyserr(FLOG, errno, "getpwuid failed");
471 io_printf(f_out, "@ERROR: getpwuid failed\n");
472 return NULL;
474 /* Start with the default group and initgroups() will add the rest. */
475 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
476 *gid_p = pw->pw_gid;
477 return pw;
479 #endif
481 static void set_env_str(const char *var, const char *str)
483 #ifdef HAVE_PUTENV
484 char *mem;
485 if (asprintf(&mem, "%s=%s", var, str) < 0)
486 out_of_memory("set_env_str");
487 putenv(mem);
488 #endif
491 #ifdef HAVE_PUTENV
492 void set_env_num(const char *var, long num)
494 char *mem;
495 if (asprintf(&mem, "%s=%ld", var, num) < 0)
496 out_of_memory("set_env_num");
497 putenv(mem);
499 #endif
501 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
503 int argc;
504 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
505 char line[BIGPATHBUFLEN];
506 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
507 struct passwd *pw = NULL;
508 #endif
509 uid_t uid;
510 int set_uid;
511 char *p, *err_msg = NULL;
512 char *name = lp_name(i);
513 int use_chroot = lp_use_chroot(i);
514 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
515 int save_munge_symlinks;
516 pid_t pre_exec_pid = 0;
517 char *request = NULL;
519 set_env_str("RSYNC_MODULE_NAME", name);
521 #ifdef ICONV_OPTION
522 iconv_opt = lp_charset(i);
523 if (*iconv_opt)
524 setup_iconv();
525 iconv_opt = NULL;
526 #endif
528 /* If reverse lookup is disabled globally but enabled for this module,
529 * we need to do it now before the access check. */
530 if (host == undetermined_hostname && lp_reverse_lookup(i))
531 host = client_name(f_in);
532 set_env_str("RSYNC_HOST_NAME", host);
533 set_env_str("RSYNC_HOST_ADDR", addr);
535 if (!allow_access(addr, &host, i)) {
536 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
537 name, host, addr);
538 if (!lp_list(i))
539 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
540 else {
541 io_printf(f_out,
542 "@ERROR: access denied to %s from %s (%s)\n",
543 name, host, addr);
545 return -1;
548 if (am_daemon > 0) {
549 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
550 name, host, addr);
553 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
554 if (errno) {
555 rsyserr(FLOG, errno, "failed to open lock file %s",
556 lp_lock_file(i));
557 io_printf(f_out, "@ERROR: failed to open lock file\n");
558 } else {
559 rprintf(FLOG, "max connections (%d) reached\n",
560 lp_max_connections(i));
561 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
562 lp_max_connections(i));
564 return -1;
567 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
568 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
570 if (!auth_user) {
571 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
572 return -1;
574 set_env_str("RSYNC_USER_NAME", auth_user);
576 module_id = i;
578 if (lp_transfer_logging(i) && !logfile_format)
579 logfile_format = lp_log_format(i);
580 if (log_format_has(logfile_format, 'i'))
581 logfile_format_has_i = 1;
582 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
583 logfile_format_has_o_or_i = 1;
585 uid = MY_UID();
586 am_root = (uid == 0);
588 p = *lp_uid(i) ? lp_uid(i) : am_root ? NOBODY_USER : NULL;
589 if (p) {
590 if (!user_to_uid(p, &uid, True)) {
591 rprintf(FLOG, "Invalid uid %s\n", p);
592 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
593 return -1;
595 set_uid = 1;
596 } else
597 set_uid = 0;
599 p = *lp_gid(i) ? conf_strtok(lp_gid(i)) : NULL;
600 if (p) {
601 /* The "*" gid must be the first item in the list. */
602 if (strcmp(p, "*") == 0) {
603 #ifdef HAVE_GETGROUPLIST
604 if (want_all_groups(f_out, uid) < 0)
605 return -1;
606 #elif defined HAVE_INITGROUPS
607 if ((pw = want_all_groups(f_out, uid)) == NULL)
608 return -1;
609 #else
610 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
611 io_printf(f_out, "@ERROR: invalid gid setting.\n");
612 return -1;
613 #endif
614 } else if (add_a_group(f_out, p) < 0)
615 return -1;
616 while ((p = conf_strtok(NULL)) != NULL) {
617 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
618 if (pw) {
619 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
620 io_printf(f_out, "@ERROR: invalid gid setting.\n");
621 return -1;
623 #endif
624 if (add_a_group(f_out, p) < 0)
625 return -1;
627 } else if (am_root) {
628 if (add_a_group(f_out, NOBODY_GROUP) < 0)
629 return -1;
632 module_dir = lp_path(i);
633 if (*module_dir == '\0') {
634 rprintf(FLOG, "No path specified for module %s\n", name);
635 io_printf(f_out, "@ERROR: no path setting.\n");
636 return -1;
638 if (use_chroot) {
639 if ((p = strstr(module_dir, "/./")) != NULL) {
640 *p = '\0'; /* Temporary... */
641 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
642 return path_failure(f_out, module_dir, False);
643 *p = '/';
644 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
645 return path_failure(f_out, strstr(module_dir, "/./"), False);
646 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
647 full_module_path = module_dir;
648 module_dir = p;
649 } else {
650 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
651 return path_failure(f_out, module_dir, False);
652 full_module_path = module_chdir;
653 module_dir = "/";
654 module_dirlen = 1;
656 } else {
657 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
658 return path_failure(f_out, module_dir, False);
659 full_module_path = module_dir = module_chdir;
661 set_env_str("RSYNC_MODULE_PATH", full_module_path);
663 if (module_dirlen == 1) {
664 module_dirlen = 0;
665 set_filter_dir("/", 1);
666 } else
667 set_filter_dir(module_dir, module_dirlen);
669 p = lp_filter(i);
670 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
671 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
673 p = lp_include_from(i);
674 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
675 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
677 p = lp_include(i);
678 parse_filter_str(&daemon_filter_list, p,
679 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
680 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
682 p = lp_exclude_from(i);
683 parse_filter_file(&daemon_filter_list, p, rule_template(0),
684 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
686 p = lp_exclude(i);
687 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
688 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
690 log_init(1);
692 #ifdef HAVE_PUTENV
693 if ((*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) && !getenv("RSYNC_NO_XFER_EXEC")) {
694 int status;
696 /* For post-xfer exec, fork a new process to run the rsync
697 * daemon while this process waits for the exit status and
698 * runs the indicated command at that point. */
699 if (*lp_postxfer_exec(i)) {
700 pid_t pid = fork();
701 if (pid < 0) {
702 rsyserr(FLOG, errno, "fork failed");
703 io_printf(f_out, "@ERROR: fork failed\n");
704 return -1;
706 if (pid) {
707 close(f_in);
708 if (f_out != f_in)
709 close(f_out);
710 set_env_num("RSYNC_PID", (long)pid);
711 if (wait_process(pid, &status, 0) < 0)
712 status = -1;
713 set_env_num("RSYNC_RAW_STATUS", status);
714 if (WIFEXITED(status))
715 status = WEXITSTATUS(status);
716 else
717 status = -1;
718 set_env_num("RSYNC_EXIT_STATUS", status);
719 if (shell_exec(lp_postxfer_exec(i)) < 0)
720 status = -1;
721 _exit(status);
724 /* For pre-xfer exec, fork a child process to run the indicated
725 * command, though it first waits for the parent process to
726 * send us the user's request via a pipe. */
727 if (*lp_prexfer_exec(i)) {
728 int arg_fds[2], error_fds[2];
729 set_env_num("RSYNC_PID", (long)getpid());
730 if (pipe(arg_fds) < 0 || pipe(error_fds) < 0 || (pre_exec_pid = fork()) < 0) {
731 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
732 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
733 return -1;
735 if (pre_exec_pid == 0) {
736 char buf[BIGPATHBUFLEN];
737 int j, len;
738 close(arg_fds[1]);
739 close(error_fds[0]);
740 pre_exec_arg_fd = arg_fds[0];
741 pre_exec_error_fd = error_fds[1];
742 set_blocking(pre_exec_arg_fd);
743 set_blocking(pre_exec_error_fd);
744 len = read_arg_from_pipe(pre_exec_arg_fd, buf, BIGPATHBUFLEN);
745 if (len <= 0)
746 _exit(1);
747 set_env_str("RSYNC_REQUEST", buf);
748 for (j = 0; ; j++) {
749 len = read_arg_from_pipe(pre_exec_arg_fd, buf,
750 BIGPATHBUFLEN);
751 if (len <= 0) {
752 if (!len)
753 break;
754 _exit(1);
756 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
757 putenv(p);
759 close(pre_exec_arg_fd);
760 close(STDIN_FILENO);
761 dup2(pre_exec_error_fd, STDOUT_FILENO);
762 close(pre_exec_error_fd);
763 status = shell_exec(lp_prexfer_exec(i));
764 if (!WIFEXITED(status))
765 _exit(1);
766 _exit(WEXITSTATUS(status));
768 close(arg_fds[0]);
769 close(error_fds[1]);
770 pre_exec_arg_fd = arg_fds[1];
771 pre_exec_error_fd = error_fds[0];
772 set_blocking(pre_exec_arg_fd);
773 set_blocking(pre_exec_error_fd);
776 #endif
778 if (use_chroot) {
780 * XXX: The 'use chroot' flag is a fairly reliable
781 * source of confusion, because it fails under two
782 * important circumstances: running as non-root,
783 * running on Win32 (or possibly others). On the
784 * other hand, if you are running as root, then it
785 * might be better to always use chroot.
787 * So, perhaps if we can't chroot we should just issue
788 * a warning, unless a "require chroot" flag is set,
789 * in which case we fail.
791 if (chroot(module_chdir)) {
792 rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
793 io_printf(f_out, "@ERROR: chroot failed\n");
794 return -1;
796 module_chdir = module_dir;
799 if (!change_dir(module_chdir, CD_NORMAL))
800 return path_failure(f_out, module_chdir, True);
801 if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
802 sanitize_paths = 1;
804 if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
805 munge_symlinks = !use_chroot || module_dirlen;
806 if (munge_symlinks) {
807 STRUCT_STAT st;
808 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
809 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
810 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
811 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
812 prefix);
813 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
814 exit_cleanup(RERR_UNSUPPORTED);
818 if (gid_list.count) {
819 gid_t *gid_array = gid_list.items;
820 if (setgid(gid_array[0])) {
821 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
822 io_printf(f_out, "@ERROR: setgid failed\n");
823 return -1;
825 #ifdef HAVE_SETGROUPS
826 /* Set the group(s) we want to be active. */
827 if (setgroups(gid_list.count, gid_array)) {
828 rsyserr(FLOG, errno, "setgroups failed");
829 io_printf(f_out, "@ERROR: setgroups failed\n");
830 return -1;
832 #endif
833 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
834 /* pw is set if the user wants all the user's groups. */
835 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
836 rsyserr(FLOG, errno, "initgroups failed");
837 io_printf(f_out, "@ERROR: initgroups failed\n");
838 return -1;
840 #endif
841 our_gid = MY_GID();
844 if (set_uid) {
845 if (setuid(uid) < 0
846 #ifdef HAVE_SETEUID
847 || seteuid(uid) < 0
848 #endif
850 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
851 io_printf(f_out, "@ERROR: setuid failed\n");
852 return -1;
855 our_uid = MY_UID();
856 am_root = (our_uid == 0);
859 if (lp_temp_dir(i) && *lp_temp_dir(i)) {
860 tmpdir = lp_temp_dir(i);
861 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
862 rprintf(FLOG,
863 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
864 name);
865 tmpdir = NULL;
869 io_printf(f_out, "@RSYNCD: OK\n");
871 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
872 orig_argv = argv;
874 save_munge_symlinks = munge_symlinks;
876 reset_output_levels(); /* future verbosity is controlled by client options */
877 ret = parse_arguments(&argc, (const char ***) &argv);
878 if (protect_args && ret) {
879 orig_early_argv = orig_argv;
880 protect_args = 2;
881 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
882 orig_argv = argv;
883 ret = parse_arguments(&argc, (const char ***) &argv);
884 } else
885 orig_early_argv = NULL;
887 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
888 if (am_daemon > 0)
889 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
891 if (pre_exec_pid) {
892 err_msg = finish_pre_exec(pre_exec_pid, pre_exec_arg_fd, pre_exec_error_fd,
893 request, orig_early_argv, orig_argv);
896 if (orig_early_argv)
897 free(orig_early_argv);
899 am_server = 1; /* Don't let someone try to be tricky. */
900 quiet = 0;
901 if (lp_ignore_errors(module_id))
902 ignore_errors = 1;
903 if (write_batch < 0)
904 dry_run = 1;
906 if (lp_fake_super(i)) {
907 if (preserve_xattrs > 1)
908 preserve_xattrs = 1;
909 am_root = -1;
910 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
911 am_root = 2;
913 if (filesfrom_fd == 0)
914 filesfrom_fd = f_in;
916 if (request) {
917 if (*auth_user) {
918 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
919 am_sender ? "on" : "to",
920 request, auth_user, host, addr);
921 } else {
922 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
923 am_sender ? "on" : "to",
924 request, host, addr);
926 free(request);
929 #ifndef DEBUG
930 /* don't allow the logs to be flooded too fast */
931 limit_output_verbosity(lp_max_verbosity(i));
932 #endif
934 if (protocol_version < 23
935 && (protocol_version == 22 || am_sender))
936 io_start_multiplex_out(f_out);
937 else if (!ret || err_msg) {
938 /* We have to get I/O multiplexing started so that we can
939 * get the error back to the client. This means getting
940 * the protocol setup finished first in later versions. */
941 setup_protocol(f_out, f_in);
942 if (!am_sender) {
943 /* Since we failed in our option parsing, we may not
944 * have finished parsing that the client sent us a
945 * --files-from option, so look for it manually.
946 * Without this, the socket would be in the wrong
947 * state for the upcoming error message. */
948 if (!files_from) {
949 int i;
950 for (i = 0; i < argc; i++) {
951 if (strncmp(argv[i], "--files-from", 12) == 0) {
952 files_from = "";
953 break;
957 if (files_from)
958 write_byte(f_out, 0);
960 io_start_multiplex_out(f_out);
963 if (!ret || err_msg) {
964 if (err_msg) {
965 while ((p = strchr(err_msg, '\n')) != NULL) {
966 int len = p - err_msg + 1;
967 rwrite(FERROR, err_msg, len, 0);
968 err_msg += len;
970 if (*err_msg)
971 rprintf(FERROR, "%s\n", err_msg);
972 io_flush(MSG_FLUSH);
973 } else
974 option_error();
975 msleep(400);
976 exit_cleanup(RERR_UNSUPPORTED);
979 #ifdef ICONV_OPTION
980 if (!iconv_opt) {
981 if (ic_send != (iconv_t)-1) {
982 iconv_close(ic_send);
983 ic_send = (iconv_t)-1;
985 if (ic_recv != (iconv_t)-1) {
986 iconv_close(ic_recv);
987 ic_recv = (iconv_t)-1;
990 #endif
992 if (!numeric_ids
993 && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
994 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
996 if (lp_timeout(i) && (!io_timeout || lp_timeout(i) < io_timeout))
997 set_io_timeout(lp_timeout(i));
999 /* If we have some incoming/outgoing chmod changes, append them to
1000 * any user-specified changes (making our changes have priority).
1001 * We also get a pointer to just our changes so that a receiver
1002 * process can use them separately if --perms wasn't specified. */
1003 if (am_sender)
1004 p = lp_outgoing_chmod(i);
1005 else
1006 p = lp_incoming_chmod(i);
1007 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1008 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1009 am_sender ? "outgo" : "incom", p);
1012 start_server(f_in, f_out, argc, argv);
1014 return 0;
1017 /* send a list of available modules to the client. Don't list those
1018 with "list = False". */
1019 static void send_listing(int fd)
1021 int n = lp_num_modules();
1022 int i;
1024 for (i = 0; i < n; i++) {
1025 if (lp_list(i))
1026 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1029 if (protocol_version >= 25)
1030 io_printf(fd,"@RSYNCD: EXIT\n");
1033 static int load_config(int globals_only)
1035 if (!config_file) {
1036 if (am_daemon < 0 && am_root <= 0)
1037 config_file = RSYNCD_USERCONF;
1038 else
1039 config_file = RSYNCD_SYSCONF;
1041 return lp_load(config_file, globals_only);
1044 /* this is called when a connection is established to a client
1045 and we want to start talking. The setup of the system is done from
1046 here */
1047 int start_daemon(int f_in, int f_out)
1049 char line[1024];
1050 const char *addr, *host;
1051 char *p;
1052 int i;
1054 /* At this point, am_server is only set for a daemon started via rsh.
1055 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1056 * a flag that can be checked later on to distinguish a normal daemon
1057 * from an rsh-run daemon. */
1058 if (am_server)
1059 am_daemon = -1;
1061 io_set_sock_fds(f_in, f_out);
1063 /* We must load the config file before calling any function that
1064 * might cause log-file output to occur. This ensures that the
1065 * "log file" param gets honored for the 2 non-forked use-cases
1066 * (when rsync is run by init and run by a remote shell). */
1067 if (!load_config(0))
1068 exit_cleanup(RERR_SYNTAX);
1070 p = lp_daemon_chroot();
1071 if (*p) {
1072 log_init(0); /* Make use we've initialized syslog before chrooting. */
1073 if (chroot(p) < 0 || chdir("/") < 0) {
1074 rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1075 return -1;
1078 p = lp_daemon_gid();
1079 if (*p) {
1080 gid_t gid;
1081 if (!group_to_gid(p, &gid, True)) {
1082 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1083 return -1;
1085 if (setgid(gid) < 0) {
1086 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1087 return -1;
1089 our_gid = MY_GID();
1091 p = lp_daemon_uid();
1092 if (*p) {
1093 uid_t uid;
1094 if (!user_to_uid(p, &uid, True)) {
1095 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1096 return -1;
1098 if (setuid(uid) < 0) {
1099 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1100 return -1;
1102 our_uid = MY_UID();
1103 am_root = (our_uid == 0);
1106 addr = client_addr(f_in);
1107 host = lp_reverse_lookup(-1) ? client_name(f_in) : undetermined_hostname;
1108 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1110 if (am_daemon > 0) {
1111 set_socket_options(f_in, "SO_KEEPALIVE");
1112 set_nonblocking(f_in);
1115 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1116 return -1;
1118 line[0] = 0;
1119 if (!read_line_old(f_in, line, sizeof line, 0))
1120 return -1;
1122 if (!*line || strcmp(line, "#list") == 0) {
1123 rprintf(FLOG, "module-list request from %s (%s)\n",
1124 host, addr);
1125 send_listing(f_out);
1126 return -1;
1129 if (*line == '#') {
1130 /* it's some sort of command that I don't understand */
1131 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1132 return -1;
1135 if ((i = lp_number(line)) < 0) {
1136 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1137 line, host, addr);
1138 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1139 return -1;
1142 #ifdef HAVE_SIGACTION
1143 sigact.sa_flags = SA_NOCLDSTOP;
1144 #endif
1145 SIGACTION(SIGCHLD, remember_children);
1147 return rsync_module(f_in, f_out, i, addr, host);
1150 static void create_pid_file(void)
1152 char *pid_file = lp_pid_file();
1153 char pidbuf[32];
1154 STRUCT_STAT st1, st2;
1155 char *fail = NULL;
1157 if (!pid_file || !*pid_file)
1158 return;
1160 #ifdef O_NOFOLLOW
1161 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1162 #else
1163 #define SAFE_OPEN_FLAGS (O_CREAT)
1164 #endif
1166 /* These tests make sure that a temp-style lock dir is handled safely. */
1167 st1.st_mode = 0;
1168 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1169 fail = "unlink";
1170 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1171 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1172 else if (!lock_range(pid_file_fd, 0, 4))
1173 fail = "lock";
1174 else if (do_fstat(pid_file_fd, &st1) < 0)
1175 fail = "fstat opened";
1176 else if (st1.st_size > (int)sizeof pidbuf)
1177 fail = "find small";
1178 else if (do_lstat(pid_file, &st2) < 0)
1179 fail = "lstat";
1180 else if (!S_ISREG(st1.st_mode))
1181 fail = "avoid file overwrite race for";
1182 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1183 fail = "verify stat info for";
1184 #ifdef HAVE_FTRUNCATE
1185 else if (do_ftruncate(pid_file_fd, 0) < 0)
1186 fail = "truncate";
1187 #endif
1188 else {
1189 pid_t pid = getpid();
1190 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1191 #ifndef HAVE_FTRUNCATE
1192 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1193 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1194 pidbuf[len++] = '\n';
1195 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1196 #endif
1197 if (write(pid_file_fd, pidbuf, len) != len)
1198 fail = "write";
1199 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1202 if (fail) {
1203 char msg[1024];
1204 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1205 fail, pid_file, strerror(errno));
1206 fputs(msg, stderr);
1207 rprintf(FLOG, "%s", msg);
1208 exit_cleanup(RERR_FILEIO);
1211 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1214 /* Become a daemon, discarding the controlling terminal. */
1215 static void become_daemon(void)
1217 int i;
1218 pid_t pid = fork();
1220 if (pid) {
1221 if (pid < 0) {
1222 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1223 exit_cleanup(RERR_FILEIO);
1225 _exit(0);
1228 create_pid_file();
1230 /* detach from the terminal */
1231 #ifdef HAVE_SETSID
1232 setsid();
1233 #elif defined TIOCNOTTY
1234 i = open("/dev/tty", O_RDWR);
1235 if (i >= 0) {
1236 ioctl(i, (int)TIOCNOTTY, (char *)0);
1237 close(i);
1239 #endif
1240 /* make sure that stdin, stdout an stderr don't stuff things
1241 * up (library functions, for example) */
1242 for (i = 0; i < 3; i++) {
1243 close(i);
1244 open("/dev/null", O_RDWR);
1248 int daemon_main(void)
1250 if (is_a_socket(STDIN_FILENO)) {
1251 int i;
1253 /* we are running via inetd - close off stdout and
1254 * stderr so that library functions (and getopt) don't
1255 * try to use them. Redirect them to /dev/null */
1256 for (i = 1; i < 3; i++) {
1257 close(i);
1258 open("/dev/null", O_RDWR);
1261 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1264 if (!load_config(1)) {
1265 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1266 exit_cleanup(RERR_SYNTAX);
1268 set_dparams(0);
1270 if (no_detach)
1271 create_pid_file();
1272 else
1273 become_daemon();
1275 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1276 rsync_port = RSYNC_PORT;
1277 if (bind_address == NULL && *lp_bind_address())
1278 bind_address = lp_bind_address();
1280 log_init(0);
1282 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1283 RSYNC_VERSION, rsync_port);
1284 /* TODO: If listening on a particular address, then show that
1285 * address too. In fact, why not just do getnameinfo on the
1286 * local address??? */
1288 start_accept_loop(rsync_port, start_daemon);
1289 return -1;