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.
27 extern int output_motd;
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 open_noatime;
42 extern int sanitize_paths;
43 extern int numeric_ids;
44 extern int filesfrom_fd;
45 extern int remote_protocol;
46 extern int protocol_version;
47 extern int io_timeout;
49 extern int write_batch;
50 extern int default_af_hint;
51 extern int logfile_format_has_i;
52 extern int logfile_format_has_o_or_i;
53 extern char *bind_address;
54 extern char *config_file;
55 extern char *logfile_format;
56 extern char *files_from;
58 extern char *early_input_file;
59 extern struct chmod_mode_struct *chmod_modes;
60 extern filter_rule_list daemon_filter_list;
62 extern char *iconv_opt;
63 extern iconv_t ic_send, ic_recv;
72 int early_input_len = 0;
73 char *early_input = NULL;
74 struct chmod_mode_struct *daemon_chmod_modes;
76 #define EARLY_INPUT_CMD "#early_input="
77 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
79 /* module_dirlen is the length of the module_dir string when in daemon
80 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
81 * enabled module can have a non-"/" module_dir these days.) */
82 char *module_dir = NULL;
83 unsigned int module_dirlen = 0;
85 char *full_module_path;
87 static int rl_nulls = 0;
90 static struct sigaction sigact;
93 static item_list gid_list = EMPTY_ITEM_LIST;
95 /* Used when "reverse lookup" is off. */
96 const char undetermined_hostname[] = "UNDETERMINED";
99 * Run a client connected to an rsyncd. The alternative to this
100 * function for remote-shell connections is do_cmd().
102 * After negotiating which module to use and reading the server's
103 * motd, this hands over to client_run(). Telling the server the
104 * module will cause it to chroot/setuid/etc.
106 * Instead of doing a transfer, the client may at this stage instead
107 * get a listing of remote modules and exit.
109 * @return -1 for error in startup, or the result of client_run().
110 * Either way, it eventually gets passed to exit_cleanup().
112 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
113 int argc, char *argv[])
116 char *p, *user = NULL;
118 /* This is redundant with code in start_inband_exchange(), but this
119 * short-circuits a problem in the client before we open a socket,
120 * and the extra check won't hurt. */
121 if (**remote_argv == '/') {
123 "ERROR: The remote path must start with a module name not a /\n");
127 if ((p = strrchr(host, '@')) != NULL) {
133 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
135 exit_cleanup(RERR_SOCKETIO);
141 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
143 return ret ? ret : client_run(fd, fd, -1, argc, argv);
146 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
149 #if SUBPROTOCOL_VERSION != 0
150 int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
155 io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
157 char *motd = lp_motd_file();
159 FILE *f = fopen(motd, "r");
160 while (f && !feof(f)) {
161 int len = fread(buf, 1, bufsiz - 1, f);
163 write_buf(f_out, buf, len);
167 write_sbuf(f_out, "\n");
171 /* This strips the \n. */
172 if (!read_line_old(f_in, buf, bufsiz, 0)) {
174 rprintf(FERROR, "rsync: did not see server greeting\n");
178 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
180 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
182 io_printf(f_out, "@ERROR: protocol startup error\n");
186 if (remote_sub < 0) {
187 if (remote_protocol == 30) {
189 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
191 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
197 if (protocol_version > remote_protocol) {
198 protocol_version = remote_protocol;
201 } else if (protocol_version == remote_protocol) {
202 if (remote_sub != our_sub)
205 #if SUBPROTOCOL_VERSION != 0
206 else if (protocol_version < remote_protocol) {
212 if (protocol_version >= 30)
218 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
221 char line[BIGPATHBUFLEN];
222 char *sargs[MAX_ARGS];
226 assert(argc > 0 && *argv != NULL);
230 "ERROR: The remote path must start with a module name\n");
234 if (!(p = strchr(*argv, '/')))
235 modlen = strlen(*argv);
239 modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
240 strlcpy(modname, *argv, modlen + 1);
241 modname[modlen] = '/';
242 modname[modlen+1] = '\0';
245 user = getenv("USER");
247 user = getenv("LOGNAME");
249 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
252 if (early_input_file) {
254 FILE *f = fopen(early_input_file, "rb");
255 if (!f || do_fstat(fileno(f), &st) < 0) {
256 rsyserr(FERROR, errno, "failed to open %s", early_input_file);
259 early_input_len = st.st_size;
260 if (early_input_len > (int)sizeof line) {
261 rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
264 if (early_input_len > 0) {
265 io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
266 while (early_input_len > 0) {
269 rprintf(FERROR, "Early EOF in %s\n", early_input_file);
272 len = fread(line, 1, early_input_len, f);
274 write_buf(f_out, line, len);
275 early_input_len -= len;
282 /* set daemon_over_rsh to false since we need to build the
283 * true set of args passed through the rsh/ssh connection;
284 * this is a no-op for direct-socket-connection mode */
286 server_options(sargs, &sargc);
288 if (sargc >= MAX_ARGS - 2)
291 sargs[sargc++] = ".";
294 if (sargc >= MAX_ARGS - 1) {
296 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
297 exit_cleanup(RERR_SYNTAX);
299 if (strncmp(*argv, modname, modlen) == 0
300 && argv[0][modlen] == '\0')
301 sargs[sargc++] = modname; /* we send "modname/" */
302 else if (**argv == '-') {
303 if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
304 out_of_memory("start_inband_exchange");
306 sargs[sargc++] = *argv;
313 if (DEBUG_GTE(CMD, 1))
314 print_child_argv("sending daemon args:", sargs);
316 io_printf(f_out, "%.*s\n", modlen, modname);
318 /* Old servers may just drop the connection here,
319 rather than sending a proper EXIT command. Yuck. */
320 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
323 if (!read_line_old(f_in, line, sizeof line, 0)) {
324 rprintf(FERROR, "rsync: didn't get server startup line\n");
328 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
329 auth_client(f_out, user, line+18);
333 if (strcmp(line,"@RSYNCD: OK") == 0)
336 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
337 /* This is sent by recent versions of the
338 * server to terminate the listing of modules.
339 * We don't want to go on and transfer
340 * anything; just exit. */
344 if (strncmp(line, "@ERROR", 6) == 0) {
345 rprintf(FERROR, "%s\n", line);
346 /* This is always fatal; the server will now
347 * close the socket. */
351 /* This might be a MOTD line or a module listing, but there is
352 * no way to differentiate it. The manpage mentions this. */
354 rprintf(FINFO, "%s\n", line);
356 kluge_around_eof = 0;
359 for (i = 0; i < sargc; i++) {
360 if (!sargs[i]) /* stop at --protect-args NULL */
362 write_sbuf(f_out, sargs[i]);
363 write_byte(f_out, 0);
365 write_byte(f_out, 0);
367 for (i = 0; i < sargc; i++)
368 io_printf(f_out, "%s\n", sargs[i]);
369 write_sbuf(f_out, "\n");
373 send_protected_args(f_out, sargs);
375 if (protocol_version < 23) {
376 if (protocol_version == 22 || !am_sender)
377 io_start_multiplex_in(f_in);
386 static int read_arg_from_pipe(int fd, char *buf, int limit)
388 char *bp = buf, *eob = buf + limit - 1;
391 int got = read(fd, bp, 1);
393 if (got < 0 && errno == EINTR)
408 static void set_env_str(const char *var, const char *str)
412 if (asprintf(&mem, "%s=%s", var, str) < 0)
413 out_of_memory("set_env_str");
419 void set_env_num(const char *var, long num)
422 if (asprintf(&mem, "%s=%ld", var, num) < 0)
423 out_of_memory("set_env_num");
428 /* Used for both early exec & pre-xfer exec */
429 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
431 int arg_fds[2], error_fds[2], arg_fd;
434 if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
438 char buf[BIGPATHBUFLEN];
443 set_blocking(error_fds[1]);
448 set_blocking(arg_fd);
450 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
453 set_env_str("RSYNC_REQUEST", buf);
457 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
463 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
467 dup2(arg_fd, STDIN_FILENO);
471 dup2(error_fds[1], STDOUT_FILENO);
475 status = shell_exec(cmd);
477 if (!WIFEXITED(status))
479 _exit(WEXITSTATUS(status));
484 *error_fd_ptr = error_fds[0];
485 set_blocking(error_fds[0]);
489 arg_fd = *arg_fd_ptr = arg_fds[1];
490 set_blocking(arg_fd);
495 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int am_early)
502 write_buf(write_fd, request, strlen(request)+1);
504 for ( ; *early_argv; early_argv++)
505 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
506 j = 1; /* Skip arg0 name in argv. */
509 for ( ; argv[j]; j++)
510 write_buf(write_fd, argv[j], strlen(argv[j])+1);
512 write_byte(write_fd, 0);
514 if (am_early && early_input_len)
515 write_buf(write_fd, early_input, early_input_len);
520 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
522 char buf[BIGPATHBUFLEN], *bp, *cr;
523 int j, status = -1, msglen = sizeof buf - 1;
526 /* Read the stdout from the program. This it is only displayed
527 * to the user if the script also returns an error status. */
528 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
529 if ((j = read(read_fd, bp, msglen)) <= 0) {
534 break; /* Just ignore the read error for now... */
538 if ((cr = strchr(cr, '\r')) == NULL) {
543 break; /* wait for more data before we decide what to do */
545 memmove(cr, cr+1, j - (cr - bp));
558 if (wait_process(pid, &status, 0) < 0
559 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
561 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
562 desc, status, status < 0 ? ": " : "",
563 status < 0 ? strerror(errno) : "",
564 *buf ? ":" : "", buf) < 0)
565 return "out_of_memory in finish_pre_exec\n";
571 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
574 rsyserr(FLOG, errno, "chdir %s failed", dir);
576 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
577 io_printf(f_out, "@ERROR: chdir failed\n");
581 static int add_a_group(int f_out, const char *gname)
584 if (!group_to_gid(gname, &gid, True)) {
585 rprintf(FLOG, "Invalid gid %s\n", gname);
586 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
589 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
594 #ifdef HAVE_GETGROUPLIST
595 static int want_all_groups(int f_out, uid_t uid)
598 if ((err = getallgroups(uid, &gid_list)) != NULL) {
599 rsyserr(FLOG, errno, "%s", err);
600 io_printf(f_out, "@ERROR: %s\n", err);
605 #elif defined HAVE_INITGROUPS
606 static struct passwd *want_all_groups(int f_out, uid_t uid)
610 if ((pw = getpwuid(uid)) == NULL) {
611 rsyserr(FLOG, errno, "getpwuid failed");
612 io_printf(f_out, "@ERROR: getpwuid failed\n");
615 /* Start with the default group and initgroups() will add the rest. */
616 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
622 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
625 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
626 char line[BIGPATHBUFLEN];
627 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
628 struct passwd *pw = NULL;
632 char *p, *err_msg = NULL;
633 char *name = lp_name(i);
634 int use_chroot = lp_use_chroot(i);
635 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
636 int save_munge_symlinks;
637 pid_t pre_exec_pid = 0;
638 char *request = NULL;
640 set_env_str("RSYNC_MODULE_NAME", name);
643 iconv_opt = lp_charset(i);
649 /* If reverse lookup is disabled globally but enabled for this module,
650 * we need to do it now before the access check. */
651 if (host == undetermined_hostname && lp_reverse_lookup(i))
652 host = client_name(client_addr(f_in));
653 set_env_str("RSYNC_HOST_NAME", host);
654 set_env_str("RSYNC_HOST_ADDR", addr);
656 if (!allow_access(addr, &host, i)) {
657 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
660 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
663 "@ERROR: access denied to %s from %s (%s)\n",
670 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
674 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
676 rsyserr(FLOG, errno, "failed to open lock file %s",
678 io_printf(f_out, "@ERROR: failed to open lock file\n");
680 rprintf(FLOG, "max connections (%d) reached\n",
681 lp_max_connections(i));
682 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
683 lp_max_connections(i));
688 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
689 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
692 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
695 set_env_str("RSYNC_USER_NAME", auth_user);
699 if (lp_transfer_logging(module_id) && !logfile_format)
700 logfile_format = lp_log_format(module_id);
701 if (log_format_has(logfile_format, 'i'))
702 logfile_format_has_i = 1;
703 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
704 logfile_format_has_o_or_i = 1;
707 am_root = (uid == 0);
709 p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
711 if (!user_to_uid(p, &uid, True)) {
712 rprintf(FLOG, "Invalid uid %s\n", p);
713 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
720 p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
722 /* The "*" gid must be the first item in the list. */
723 if (strcmp(p, "*") == 0) {
724 #ifdef HAVE_GETGROUPLIST
725 if (want_all_groups(f_out, uid) < 0)
727 #elif defined HAVE_INITGROUPS
728 if ((pw = want_all_groups(f_out, uid)) == NULL)
731 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
732 io_printf(f_out, "@ERROR: invalid gid setting.\n");
735 } else if (add_a_group(f_out, p) < 0)
737 while ((p = conf_strtok(NULL)) != NULL) {
738 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
740 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
741 io_printf(f_out, "@ERROR: invalid gid setting.\n");
745 if (add_a_group(f_out, p) < 0)
748 } else if (am_root) {
749 if (add_a_group(f_out, NOBODY_GROUP) < 0)
753 module_dir = lp_path(module_id);
754 if (*module_dir == '\0') {
755 rprintf(FLOG, "No path specified for module %s\n", name);
756 io_printf(f_out, "@ERROR: no path setting.\n");
760 if ((p = strstr(module_dir, "/./")) != NULL) {
761 *p = '\0'; /* Temporary... */
762 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
763 return path_failure(f_out, module_dir, False);
765 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
766 return path_failure(f_out, strstr(module_dir, "/./"), False);
767 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
768 full_module_path = module_dir;
771 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
772 return path_failure(f_out, module_dir, False);
773 full_module_path = module_chdir;
778 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
779 return path_failure(f_out, module_dir, False);
780 full_module_path = module_dir = module_chdir;
782 set_env_str("RSYNC_MODULE_PATH", full_module_path);
784 if (module_dirlen == 1) {
786 set_filter_dir("/", 1);
788 set_filter_dir(module_dir, module_dirlen);
790 p = lp_filter(module_id);
791 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
792 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
794 p = lp_include_from(module_id);
795 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
796 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
798 p = lp_include(module_id);
799 parse_filter_str(&daemon_filter_list, p,
800 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
801 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
803 p = lp_exclude_from(module_id);
804 parse_filter_file(&daemon_filter_list, p, rule_template(0),
805 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
807 p = lp_exclude(module_id);
808 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
809 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
814 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id) || *lp_postxfer_exec(module_id))
815 && !getenv("RSYNC_NO_XFER_EXEC")) {
816 set_env_num("RSYNC_PID", (long)getpid());
818 /* For post-xfer exec, fork a new process to run the rsync
819 * daemon while this process waits for the exit status and
820 * runs the indicated command at that point. */
821 if (*lp_postxfer_exec(module_id)) {
824 rsyserr(FLOG, errno, "fork failed");
825 io_printf(f_out, "@ERROR: fork failed\n");
833 if (wait_process(pid, &status, 0) < 0)
835 set_env_num("RSYNC_RAW_STATUS", status);
836 if (WIFEXITED(status))
837 status = WEXITSTATUS(status);
840 set_env_num("RSYNC_EXIT_STATUS", status);
841 if (shell_exec(lp_postxfer_exec(module_id)) < 0)
847 /* For early exec, fork a child process to run the indicated
848 * command and wait for it to exit. */
849 if (*lp_early_exec(module_id)) {
851 pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
852 if (pid == (pid_t)-1) {
853 rsyserr(FLOG, errno, "early exec preparation failed");
854 io_printf(f_out, "@ERROR: early exec preparation failed\n");
857 write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
858 if (finish_pre_exec("early exec", pid, -1) != NULL) {
859 rsyserr(FLOG, errno, "early exec failed");
860 io_printf(f_out, "@ERROR: early exec failed\n");
865 /* For pre-xfer exec, fork a child process to run the indicated
866 * command, though it first waits for the parent process to
867 * send us the user's request via a pipe. */
868 if (*lp_prexfer_exec(module_id)) {
869 pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
870 if (pre_exec_pid == (pid_t)-1) {
871 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
872 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
886 * XXX: The 'use chroot' flag is a fairly reliable
887 * source of confusion, because it fails under two
888 * important circumstances: running as non-root,
889 * running on Win32 (or possibly others). On the
890 * other hand, if you are running as root, then it
891 * might be better to always use chroot.
893 * So, perhaps if we can't chroot we should just issue
894 * a warning, unless a "require chroot" flag is set,
895 * in which case we fail.
897 if (chroot(module_chdir)) {
898 rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
899 io_printf(f_out, "@ERROR: chroot failed\n");
902 module_chdir = module_dir;
905 if (!change_dir(module_chdir, CD_NORMAL))
906 return path_failure(f_out, module_chdir, True);
907 if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
910 if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
911 munge_symlinks = !use_chroot || module_dirlen;
912 if (munge_symlinks) {
914 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
915 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
916 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
917 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
919 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
920 exit_cleanup(RERR_UNSUPPORTED);
924 if (gid_list.count) {
925 gid_t *gid_array = gid_list.items;
926 if (setgid(gid_array[0])) {
927 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
928 io_printf(f_out, "@ERROR: setgid failed\n");
931 #ifdef HAVE_SETGROUPS
932 /* Set the group(s) we want to be active. */
933 if (setgroups(gid_list.count, gid_array)) {
934 rsyserr(FLOG, errno, "setgroups failed");
935 io_printf(f_out, "@ERROR: setgroups failed\n");
939 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
940 /* pw is set if the user wants all the user's groups. */
941 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
942 rsyserr(FLOG, errno, "initgroups failed");
943 io_printf(f_out, "@ERROR: initgroups failed\n");
956 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
957 io_printf(f_out, "@ERROR: setuid failed\n");
962 am_root = (our_uid == 0);
965 if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
966 tmpdir = lp_temp_dir(module_id);
967 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
969 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
975 io_printf(f_out, "@RSYNCD: OK\n");
977 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
980 save_munge_symlinks = munge_symlinks;
982 reset_output_levels(); /* future verbosity is controlled by client options */
983 ret = parse_arguments(&argc, (const char ***) &argv);
984 if (protect_args && ret) {
985 orig_early_argv = orig_argv;
987 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
989 ret = parse_arguments(&argc, (const char ***) &argv);
991 orig_early_argv = NULL;
993 /* The default is to use the user's setting unless the module sets True or False. */
994 if (lp_open_noatime(module_id) >= 0)
995 open_noatime = lp_open_noatime(module_id);
997 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
1000 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
1003 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1004 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1007 if (orig_early_argv)
1008 free(orig_early_argv);
1010 am_server = 1; /* Don't let someone try to be tricky. */
1012 if (lp_ignore_errors(module_id))
1014 if (write_batch < 0)
1017 if (lp_fake_super(module_id)) {
1018 if (preserve_xattrs > 1)
1019 preserve_xattrs = 1;
1021 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1024 if (filesfrom_fd == 0)
1025 filesfrom_fd = f_in;
1029 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1030 am_sender ? "on" : "to",
1031 request, auth_user, host, addr);
1033 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1034 am_sender ? "on" : "to",
1035 request, host, addr);
1041 /* don't allow the logs to be flooded too fast */
1042 limit_output_verbosity(lp_max_verbosity(module_id));
1045 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1046 io_start_multiplex_out(f_out);
1047 else if (!ret || err_msg) {
1048 /* We have to get I/O multiplexing started so that we can
1049 * get the error back to the client. This means getting
1050 * the protocol setup finished first in later versions. */
1051 setup_protocol(f_out, f_in);
1053 /* Since we failed in our option parsing, we may not
1054 * have finished parsing that the client sent us a
1055 * --files-from option, so look for it manually.
1056 * Without this, the socket would be in the wrong
1057 * state for the upcoming error message. */
1060 for (i = 0; i < argc; i++) {
1061 if (strncmp(argv[i], "--files-from", 12) == 0) {
1068 write_byte(f_out, 0);
1070 io_start_multiplex_out(f_out);
1073 if (!ret || err_msg) {
1075 while ((p = strchr(err_msg, '\n')) != NULL) {
1076 int len = p - err_msg + 1;
1077 rwrite(FERROR, err_msg, len, 0);
1081 rprintf(FERROR, "%s\n", err_msg);
1082 io_flush(MSG_FLUSH);
1086 exit_cleanup(RERR_UNSUPPORTED);
1091 if (ic_send != (iconv_t)-1) {
1092 iconv_close(ic_send);
1093 ic_send = (iconv_t)-1;
1095 if (ic_recv != (iconv_t)-1) {
1096 iconv_close(ic_recv);
1097 ic_recv = (iconv_t)-1;
1103 && (use_chroot ? lp_numeric_ids(module_id) != False : lp_numeric_ids(module_id) == True))
1104 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1106 if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1107 set_io_timeout(lp_timeout(module_id));
1109 /* If we have some incoming/outgoing chmod changes, append them to
1110 * any user-specified changes (making our changes have priority).
1111 * We also get a pointer to just our changes so that a receiver
1112 * process can use them separately if --perms wasn't specified. */
1114 p = lp_outgoing_chmod(module_id);
1116 p = lp_incoming_chmod(module_id);
1117 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1118 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1119 am_sender ? "outgo" : "incom", p);
1122 start_server(f_in, f_out, argc, argv);
1127 /* send a list of available modules to the client. Don't list those
1128 with "list = False". */
1129 static void send_listing(int fd)
1131 int n = lp_num_modules();
1134 for (i = 0; i < n; i++) {
1136 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1139 if (protocol_version >= 25)
1140 io_printf(fd,"@RSYNCD: EXIT\n");
1143 static int load_config(int globals_only)
1146 if (am_daemon < 0 && am_root <= 0)
1147 config_file = RSYNCD_USERCONF;
1149 config_file = RSYNCD_SYSCONF;
1151 return lp_load(config_file, globals_only);
1154 /* this is called when a connection is established to a client
1155 and we want to start talking. The setup of the system is done from
1157 int start_daemon(int f_in, int f_out)
1160 const char *addr, *host;
1164 /* At this point, am_server is only set for a daemon started via rsh.
1165 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1166 * a flag that can be checked later on to distinguish a normal daemon
1167 * from an rsh-run daemon. */
1171 io_set_sock_fds(f_in, f_out);
1173 /* We must load the config file before calling any function that
1174 * might cause log-file output to occur. This ensures that the
1175 * "log file" param gets honored for the 2 non-forked use-cases
1176 * (when rsync is run by init and run by a remote shell). */
1177 if (!load_config(0))
1178 exit_cleanup(RERR_SYNTAX);
1180 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1183 p = lp_daemon_chroot();
1185 log_init(0); /* Make use we've initialized syslog before chrooting. */
1186 if (chroot(p) < 0 || chdir("/") < 0) {
1187 rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1191 p = lp_daemon_gid();
1194 if (!group_to_gid(p, &gid, True)) {
1195 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1198 if (setgid(gid) < 0) {
1199 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1204 p = lp_daemon_uid();
1207 if (!user_to_uid(p, &uid, True)) {
1208 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1211 if (setuid(uid) < 0) {
1212 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1216 am_root = (our_uid == 0);
1219 addr = client_addr(f_in);
1220 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1221 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1223 if (am_daemon > 0) {
1224 set_socket_options(f_in, "SO_KEEPALIVE");
1225 set_nonblocking(f_in);
1228 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1232 if (!read_line_old(f_in, line, sizeof line, 0))
1235 if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1236 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1237 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1238 io_printf(f_out, "@ERROR: invalid early_input length\n");
1241 early_input = new_array(char, early_input_len);
1242 read_buf(f_in, early_input, early_input_len);
1244 if (!read_line_old(f_in, line, sizeof line, 0))
1248 if (!*line || strcmp(line, "#list") == 0) {
1249 rprintf(FLOG, "module-list request from %s (%s)\n",
1251 send_listing(f_out);
1256 /* it's some sort of command that I don't understand */
1257 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1261 if ((i = lp_number(line)) < 0) {
1262 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1264 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1268 #ifdef HAVE_SIGACTION
1269 sigact.sa_flags = SA_NOCLDSTOP;
1271 SIGACTION(SIGCHLD, remember_children);
1273 return rsync_module(f_in, f_out, i, addr, host);
1276 static void create_pid_file(void)
1278 char *pid_file = lp_pid_file();
1280 STRUCT_STAT st1, st2;
1283 if (!pid_file || !*pid_file)
1287 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1289 #define SAFE_OPEN_FLAGS (O_CREAT)
1292 /* These tests make sure that a temp-style lock dir is handled safely. */
1294 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1296 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1297 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1298 else if (!lock_range(pid_file_fd, 0, 4))
1300 else if (do_fstat(pid_file_fd, &st1) < 0)
1301 fail = "fstat opened";
1302 else if (st1.st_size > (int)sizeof pidbuf)
1303 fail = "find small";
1304 else if (do_lstat(pid_file, &st2) < 0)
1306 else if (!S_ISREG(st1.st_mode))
1307 fail = "avoid file overwrite race for";
1308 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1309 fail = "verify stat info for";
1310 #ifdef HAVE_FTRUNCATE
1311 else if (do_ftruncate(pid_file_fd, 0) < 0)
1315 pid_t pid = getpid();
1316 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1317 #ifndef HAVE_FTRUNCATE
1318 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1319 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1320 pidbuf[len++] = '\n';
1321 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1323 if (write(pid_file_fd, pidbuf, len) != len)
1325 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1330 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1331 fail, pid_file, strerror(errno));
1333 rprintf(FLOG, "%s", msg);
1334 exit_cleanup(RERR_FILEIO);
1337 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1340 /* Become a daemon, discarding the controlling terminal. */
1341 static void become_daemon(void)
1348 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1349 exit_cleanup(RERR_FILEIO);
1356 /* detach from the terminal */
1359 #elif defined TIOCNOTTY
1360 i = open("/dev/tty", O_RDWR);
1362 ioctl(i, (int)TIOCNOTTY, (char *)0);
1366 /* make sure that stdin, stdout an stderr don't stuff things
1367 * up (library functions, for example) */
1368 for (i = 0; i < 3; i++) {
1370 open("/dev/null", O_RDWR);
1374 int daemon_main(void)
1376 if (is_a_socket(STDIN_FILENO)) {
1379 /* we are running via inetd - close off stdout and
1380 * stderr so that library functions (and getopt) don't
1381 * try to use them. Redirect them to /dev/null */
1382 for (i = 1; i < 3; i++) {
1384 open("/dev/null", O_RDWR);
1387 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1390 if (!load_config(1)) {
1391 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1392 exit_cleanup(RERR_SYNTAX);
1401 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1402 rsync_port = RSYNC_PORT;
1403 if (bind_address == NULL && *lp_bind_address())
1404 bind_address = lp_bind_address();
1408 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1409 RSYNC_VERSION, rsync_port);
1410 /* TODO: If listening on a particular address, then show that
1411 * address too. In fact, why not just do getnameinfo on the
1412 * local address??? */
1414 start_accept_loop(rsync_port, start_daemon);