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.
28 extern int output_motd;
34 extern int msgs2stderr;
35 extern int rsync_port;
36 extern int protect_args;
37 extern int ignore_errors;
38 extern int preserve_xattrs;
39 extern int kluge_around_eof;
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 pid_t namecvt_pid = 0;
75 struct chmod_mode_struct *daemon_chmod_modes;
77 #define EARLY_INPUT_CMD "#early_input="
78 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
80 /* module_dirlen is the length of the module_dir string when in daemon
81 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
82 * enabled module can have a non-"/" module_dir these days.) */
83 char *module_dir = NULL;
84 unsigned int module_dirlen = 0;
86 char *full_module_path;
88 static int rl_nulls = 0;
89 static int namecvt_fd_req = -1, namecvt_fd_ans = -1;
92 static struct sigaction sigact;
95 static item_list gid_list = EMPTY_ITEM_LIST;
97 /* Used when "reverse lookup" is off. */
98 const char undetermined_hostname[] = "UNDETERMINED";
101 * Run a client connected to an rsyncd. The alternative to this
102 * function for remote-shell connections is do_cmd().
104 * After negotiating which module to use and reading the server's
105 * motd, this hands over to client_run(). Telling the server the
106 * module will cause it to chroot/setuid/etc.
108 * Instead of doing a transfer, the client may at this stage instead
109 * get a listing of remote modules and exit.
111 * @return -1 for error in startup, or the result of client_run().
112 * Either way, it eventually gets passed to exit_cleanup().
114 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
115 int argc, char *argv[])
118 char *p, *user = NULL;
120 /* This is redundant with code in start_inband_exchange(), but this
121 * short-circuits a problem in the client before we open a socket,
122 * and the extra check won't hurt. */
123 if (**remote_argv == '/') {
125 "ERROR: The remote path must start with a module name not a /\n");
129 if ((p = strrchr(host, '@')) != NULL) {
135 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
137 exit_cleanup(RERR_SOCKETIO);
143 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
145 return ret ? ret : client_run(fd, fd, -1, argc, argv);
148 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
151 #if SUBPROTOCOL_VERSION != 0
152 int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
157 io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
159 char *motd = lp_motd_file();
161 FILE *f = fopen(motd, "r");
162 while (f && !feof(f)) {
163 int len = fread(buf, 1, bufsiz - 1, f);
165 write_buf(f_out, buf, len);
169 write_sbuf(f_out, "\n");
173 /* This strips the \n. */
174 if (!read_line_old(f_in, buf, bufsiz, 0)) {
176 rprintf(FERROR, "rsync: did not see server greeting\n");
180 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
182 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
184 io_printf(f_out, "@ERROR: protocol startup error\n");
188 if (remote_sub < 0) {
189 if (remote_protocol == 30) {
191 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
193 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
199 if (protocol_version > remote_protocol) {
200 protocol_version = remote_protocol;
203 } else if (protocol_version == remote_protocol) {
204 if (remote_sub != our_sub)
207 #if SUBPROTOCOL_VERSION != 0
208 else if (protocol_version < remote_protocol) {
214 if (protocol_version >= 30)
220 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
223 char line[BIGPATHBUFLEN];
224 char *sargs[MAX_ARGS];
228 assert(argc > 0 && *argv != NULL);
232 "ERROR: The remote path must start with a module name\n");
236 if (!(p = strchr(*argv, '/')))
237 modlen = strlen(*argv);
241 modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
242 strlcpy(modname, *argv, modlen + 1);
243 modname[modlen] = '/';
244 modname[modlen+1] = '\0';
247 user = getenv("USER");
249 user = getenv("LOGNAME");
251 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
254 if (early_input_file) {
256 FILE *f = fopen(early_input_file, "rb");
257 if (!f || do_fstat(fileno(f), &st) < 0) {
258 rsyserr(FERROR, errno, "failed to open %s", early_input_file);
261 early_input_len = st.st_size;
262 if (early_input_len > (int)sizeof line) {
263 rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
266 if (early_input_len > 0) {
267 io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
268 while (early_input_len > 0) {
271 rprintf(FERROR, "Early EOF in %s\n", early_input_file);
274 len = fread(line, 1, early_input_len, f);
276 write_buf(f_out, line, len);
277 early_input_len -= len;
284 server_options(sargs, &sargc);
286 if (sargc >= MAX_ARGS - 2)
289 sargs[sargc++] = ".";
292 if (sargc >= MAX_ARGS - 1) {
294 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
295 exit_cleanup(RERR_SYNTAX);
297 if (strncmp(*argv, modname, modlen) == 0
298 && argv[0][modlen] == '\0')
299 sargs[sargc++] = modname; /* we send "modname/" */
300 else if (**argv == '-') {
301 if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
302 out_of_memory("start_inband_exchange");
304 sargs[sargc++] = *argv;
311 if (DEBUG_GTE(CMD, 1))
312 print_child_argv("sending daemon args:", sargs);
314 io_printf(f_out, "%.*s\n", modlen, modname);
316 /* Old servers may just drop the connection here,
317 rather than sending a proper EXIT command. Yuck. */
318 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
321 if (!read_line_old(f_in, line, sizeof line, 0)) {
322 rprintf(FERROR, "rsync: didn't get server startup line\n");
326 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
327 auth_client(f_out, user, line+18);
331 if (strcmp(line,"@RSYNCD: OK") == 0)
334 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
335 /* This is sent by recent versions of the
336 * server to terminate the listing of modules.
337 * We don't want to go on and transfer
338 * anything; just exit. */
342 if (strncmp(line, "@ERROR", 6) == 0) {
343 rprintf(FERROR, "%s\n", line);
344 /* This is always fatal; the server will now
345 * close the socket. */
349 /* This might be a MOTD line or a module listing, but there is
350 * no way to differentiate it. The manpage mentions this. */
352 rprintf(FINFO, "%s\n", line);
354 kluge_around_eof = 0;
357 for (i = 0; i < sargc; i++) {
358 if (!sargs[i]) /* stop at --protect-args NULL */
360 write_sbuf(f_out, sargs[i]);
361 write_byte(f_out, 0);
363 write_byte(f_out, 0);
365 for (i = 0; i < sargc; i++)
366 io_printf(f_out, "%s\n", sargs[i]);
367 write_sbuf(f_out, "\n");
371 send_protected_args(f_out, sargs);
373 if (protocol_version < 23) {
374 if (protocol_version == 22 || !am_sender)
375 io_start_multiplex_in(f_in);
384 static int read_arg_from_pipe(int fd, char *buf, int limit)
386 char *bp = buf, *eob = buf + limit - 1;
389 int got = read(fd, bp, 1);
391 if (got < 0 && errno == EINTR)
406 static void set_env_str(const char *var, const char *str)
410 if (asprintf(&mem, "%s=%s", var, str) < 0)
411 out_of_memory("set_env_str");
417 void set_env_num(const char *var, long num)
420 if (asprintf(&mem, "%s=%ld", var, num) < 0)
421 out_of_memory("set_env_num");
426 /* Used for "early exec", "pre-xfer exec", and the "name converter" script. */
427 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
429 int arg_fds[2], error_fds[2], arg_fd;
432 if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
436 char buf[BIGPATHBUFLEN];
441 set_blocking(error_fds[1]);
446 set_blocking(arg_fd);
448 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
451 set_env_str("RSYNC_REQUEST", buf);
455 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
461 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
465 dup2(arg_fd, STDIN_FILENO);
469 dup2(error_fds[1], STDOUT_FILENO);
473 status = shell_exec(cmd);
475 if (!WIFEXITED(status))
477 _exit(WEXITSTATUS(status));
482 *error_fd_ptr = error_fds[0];
483 set_blocking(error_fds[0]);
487 arg_fd = *arg_fd_ptr = arg_fds[1];
488 set_blocking(arg_fd);
493 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int exec_type)
500 write_buf(write_fd, request, strlen(request)+1);
502 for ( ; *early_argv; early_argv++)
503 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
504 j = 1; /* Skip arg0 name in argv. */
507 for ( ; argv[j]; j++)
508 write_buf(write_fd, argv[j], strlen(argv[j])+1);
510 write_byte(write_fd, 0);
512 if (exec_type == 1 && early_input_len)
513 write_buf(write_fd, early_input, early_input_len);
515 if (exec_type != 2) /* the name converter needs this left open */
519 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
521 char buf[BIGPATHBUFLEN], *bp, *cr;
522 int j, status = -1, msglen = sizeof buf - 1;
525 /* Read the stdout from the program. This it is only displayed
526 * to the user if the script also returns an error status. */
527 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
528 if ((j = read(read_fd, bp, msglen)) <= 0) {
533 break; /* Just ignore the read error for now... */
537 if ((cr = strchr(cr, '\r')) == NULL) {
542 break; /* wait for more data before we decide what to do */
544 memmove(cr, cr+1, j - (cr - bp));
557 if (wait_process(pid, &status, 0) < 0
558 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
560 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
561 desc, status, status < 0 ? ": " : "",
562 status < 0 ? strerror(errno) : "",
563 *buf ? ":" : "", buf) < 0)
564 return "out_of_memory in finish_pre_exec\n";
570 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
573 rsyserr(FLOG, errno, "chdir %s failed", dir);
575 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
576 io_printf(f_out, "@ERROR: chdir failed\n");
580 static int add_a_group(int f_out, const char *gname)
583 if (!group_to_gid(gname, &gid, True)) {
584 rprintf(FLOG, "Invalid gid %s\n", gname);
585 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
588 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
593 #ifdef HAVE_GETGROUPLIST
594 static int want_all_groups(int f_out, uid_t uid)
597 if ((err = getallgroups(uid, &gid_list)) != NULL) {
598 rsyserr(FLOG, errno, "%s", err);
599 io_printf(f_out, "@ERROR: %s\n", err);
604 #elif defined HAVE_INITGROUPS
605 static struct passwd *want_all_groups(int f_out, uid_t uid)
609 if ((pw = getpwuid(uid)) == NULL) {
610 rsyserr(FLOG, errno, "getpwuid failed");
611 io_printf(f_out, "@ERROR: getpwuid failed\n");
614 /* Start with the default group and initgroups() will add the rest. */
615 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
621 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
624 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
625 char line[BIGPATHBUFLEN];
626 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
627 struct passwd *pw = NULL;
631 char *p, *err_msg = NULL;
632 char *name = lp_name(i);
633 int use_chroot = lp_use_chroot(i);
634 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
635 int save_munge_symlinks;
636 pid_t pre_exec_pid = 0;
637 char *request = NULL;
639 set_env_str("RSYNC_MODULE_NAME", name);
642 iconv_opt = lp_charset(i);
648 /* If reverse lookup is disabled globally but enabled for this module,
649 * we need to do it now before the access check. */
650 if (host == undetermined_hostname && lp_reverse_lookup(i))
651 host = client_name(client_addr(f_in));
652 set_env_str("RSYNC_HOST_NAME", host);
653 set_env_str("RSYNC_HOST_ADDR", addr);
655 if (!allow_access(addr, &host, i)) {
656 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
659 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
662 "@ERROR: access denied to %s from %s (%s)\n",
669 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
673 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
675 rsyserr(FLOG, errno, "failed to open lock file %s",
677 io_printf(f_out, "@ERROR: failed to open lock file\n");
679 rprintf(FLOG, "max connections (%d) reached\n",
680 lp_max_connections(i));
681 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
682 lp_max_connections(i));
687 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
688 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
691 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
694 set_env_str("RSYNC_USER_NAME", auth_user);
698 if (lp_transfer_logging(module_id) && !logfile_format)
699 logfile_format = lp_log_format(module_id);
700 if (log_format_has(logfile_format, 'i'))
701 logfile_format_has_i = 1;
702 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
703 logfile_format_has_o_or_i = 1;
706 am_root = (uid == ROOT_UID);
708 p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
710 if (!user_to_uid(p, &uid, True)) {
711 rprintf(FLOG, "Invalid uid %s\n", p);
712 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
719 p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
721 /* The "*" gid must be the first item in the list. */
722 if (strcmp(p, "*") == 0) {
723 #ifdef HAVE_GETGROUPLIST
724 if (want_all_groups(f_out, uid) < 0)
726 #elif defined HAVE_INITGROUPS
727 if ((pw = want_all_groups(f_out, uid)) == NULL)
730 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
731 io_printf(f_out, "@ERROR: invalid gid setting.\n");
734 } else if (add_a_group(f_out, p) < 0)
736 while ((p = conf_strtok(NULL)) != NULL) {
737 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
739 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
740 io_printf(f_out, "@ERROR: invalid gid setting.\n");
744 if (add_a_group(f_out, p) < 0)
747 } else if (am_root) {
748 if (add_a_group(f_out, NOBODY_GROUP) < 0)
752 module_dir = lp_path(module_id);
753 if (*module_dir == '\0') {
754 rprintf(FLOG, "No path specified for module %s\n", name);
755 io_printf(f_out, "@ERROR: no path setting.\n");
759 if ((p = strstr(module_dir, "/./")) != NULL) {
760 *p = '\0'; /* Temporary... */
761 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
762 return path_failure(f_out, module_dir, False);
764 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
765 return path_failure(f_out, strstr(module_dir, "/./"), False);
766 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
767 full_module_path = module_dir;
770 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
771 return path_failure(f_out, module_dir, False);
772 full_module_path = module_chdir;
777 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
778 return path_failure(f_out, module_dir, False);
779 full_module_path = module_dir = module_chdir;
781 set_env_str("RSYNC_MODULE_PATH", full_module_path);
783 if (module_dirlen == 1) {
785 set_filter_dir("/", 1);
787 set_filter_dir(module_dir, module_dirlen);
789 p = lp_filter(module_id);
790 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
791 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
793 p = lp_include_from(module_id);
794 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
795 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
797 p = lp_include(module_id);
798 parse_filter_str(&daemon_filter_list, p,
799 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
800 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
802 p = lp_exclude_from(module_id);
803 parse_filter_file(&daemon_filter_list, p, rule_template(0),
804 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
806 p = lp_exclude(module_id);
807 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
808 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
813 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
814 || *lp_postxfer_exec(module_id) || *lp_name_converter(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");
877 if (*lp_name_converter(module_id)) {
878 namecvt_pid = start_pre_exec(lp_name_converter(module_id), &namecvt_fd_req, &namecvt_fd_ans);
879 if (namecvt_pid == (pid_t)-1) {
880 rsyserr(FLOG, errno, "name-converter exec preparation failed");
881 io_printf(f_out, "@ERROR: name-converter exec preparation failed\n");
895 * XXX: The 'use chroot' flag is a fairly reliable
896 * source of confusion, because it fails under two
897 * important circumstances: running as non-root,
898 * running on Win32 (or possibly others). On the
899 * other hand, if you are running as root, then it
900 * might be better to always use chroot.
902 * So, perhaps if we can't chroot we should just issue
903 * a warning, unless a "require chroot" flag is set,
904 * in which case we fail.
906 if (chroot(module_chdir)) {
907 rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
908 io_printf(f_out, "@ERROR: chroot failed\n");
911 module_chdir = module_dir;
914 if (!change_dir(module_chdir, CD_NORMAL))
915 return path_failure(f_out, module_chdir, True);
916 if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
919 if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
920 munge_symlinks = !use_chroot || module_dirlen;
921 if (munge_symlinks) {
923 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
924 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
925 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
926 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
928 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
929 exit_cleanup(RERR_UNSUPPORTED);
933 if (gid_list.count) {
934 gid_t *gid_array = gid_list.items;
935 if (setgid(gid_array[0])) {
936 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
937 io_printf(f_out, "@ERROR: setgid failed\n");
940 #ifdef HAVE_SETGROUPS
941 /* Set the group(s) we want to be active. */
942 if (setgroups(gid_list.count, gid_array)) {
943 rsyserr(FLOG, errno, "setgroups failed");
944 io_printf(f_out, "@ERROR: setgroups failed\n");
948 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
949 /* pw is set if the user wants all the user's groups. */
950 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
951 rsyserr(FLOG, errno, "initgroups failed");
952 io_printf(f_out, "@ERROR: initgroups failed\n");
965 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
966 io_printf(f_out, "@ERROR: setuid failed\n");
971 am_root = (our_uid == ROOT_UID);
974 if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
975 tmpdir = lp_temp_dir(module_id);
976 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
978 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
984 io_printf(f_out, "@RSYNCD: OK\n");
986 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
989 save_munge_symlinks = munge_symlinks;
991 reset_output_levels(); /* future verbosity is controlled by client options */
992 ret = parse_arguments(&argc, (const char ***) &argv);
993 if (protect_args && ret) {
994 orig_early_argv = orig_argv;
996 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
998 ret = parse_arguments(&argc, (const char ***) &argv);
1000 orig_early_argv = NULL;
1002 /* The default is to use the user's setting unless the module sets True or False. */
1003 if (lp_open_noatime(module_id) >= 0)
1004 open_noatime = lp_open_noatime(module_id);
1006 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
1009 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
1012 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1013 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1017 write_pre_exec_args(namecvt_fd_req, request, orig_early_argv, orig_argv, 2);
1019 if (orig_early_argv)
1020 free(orig_early_argv);
1022 am_server = 1; /* Don't let someone try to be tricky. */
1024 if (lp_ignore_errors(module_id))
1026 if (write_batch < 0)
1029 if (lp_fake_super(module_id)) {
1030 if (preserve_xattrs > 1)
1031 preserve_xattrs = 1;
1033 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1036 if (filesfrom_fd == 0)
1037 filesfrom_fd = f_in;
1041 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1042 am_sender ? "on" : "to",
1043 request, auth_user, host, addr);
1045 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1046 am_sender ? "on" : "to",
1047 request, host, addr);
1053 /* don't allow the logs to be flooded too fast */
1054 limit_output_verbosity(lp_max_verbosity(module_id));
1057 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1058 io_start_multiplex_out(f_out);
1059 else if (!ret || err_msg) {
1060 /* We have to get I/O multiplexing started so that we can
1061 * get the error back to the client. This means getting
1062 * the protocol setup finished first in later versions. */
1063 setup_protocol(f_out, f_in);
1065 /* Since we failed in our option parsing, we may not
1066 * have finished parsing that the client sent us a
1067 * --files-from option, so look for it manually.
1068 * Without this, the socket would be in the wrong
1069 * state for the upcoming error message. */
1072 for (i = 0; i < argc; i++) {
1073 if (strncmp(argv[i], "--files-from", 12) == 0) {
1080 write_byte(f_out, 0);
1082 io_start_multiplex_out(f_out);
1085 if (!ret || err_msg) {
1087 while ((p = strchr(err_msg, '\n')) != NULL) {
1088 int len = p - err_msg + 1;
1089 rwrite(FERROR, err_msg, len, 0);
1093 rprintf(FERROR, "%s\n", err_msg);
1094 io_flush(MSG_FLUSH);
1098 exit_cleanup(RERR_UNSUPPORTED);
1103 if (ic_send != (iconv_t)-1) {
1104 iconv_close(ic_send);
1105 ic_send = (iconv_t)-1;
1107 if (ic_recv != (iconv_t)-1) {
1108 iconv_close(ic_recv);
1109 ic_recv = (iconv_t)-1;
1115 && (use_chroot ? lp_numeric_ids(module_id) != False && !*lp_name_converter(module_id)
1116 : lp_numeric_ids(module_id) == True))
1117 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1119 if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1120 set_io_timeout(lp_timeout(module_id));
1122 /* If we have some incoming/outgoing chmod changes, append them to
1123 * any user-specified changes (making our changes have priority).
1124 * We also get a pointer to just our changes so that a receiver
1125 * process can use them separately if --perms wasn't specified. */
1127 p = lp_outgoing_chmod(module_id);
1129 p = lp_incoming_chmod(module_id);
1130 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1131 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1132 am_sender ? "outgo" : "incom", p);
1135 start_server(f_in, f_out, argc, argv);
1140 BOOL namecvt_call(const char *cmd, const char **name_p, id_t *id_p)
1146 len = snprintf(buf, sizeof buf, "%s %s\n", cmd, *name_p);
1148 len = snprintf(buf, sizeof buf, "%s %ld\n", cmd, (long)*id_p);
1149 if (len >= (int)sizeof buf) {
1150 rprintf(FERROR, "namecvt_call() request was too large.\n");
1151 exit_cleanup(RERR_UNSUPPORTED);
1154 while ((got = write(namecvt_fd_req, buf, len)) != len) {
1155 if (got < 0 && errno == EINTR)
1157 rprintf(FERROR, "Connection to name-converter failed.\n");
1158 exit_cleanup(RERR_SOCKETIO);
1161 if (!read_line_old(namecvt_fd_ans, buf, sizeof buf, 0))
1165 *id_p = (id_t)atol(buf);
1167 *name_p = strdup(buf);
1172 /* send a list of available modules to the client. Don't list those
1173 with "list = False". */
1174 static void send_listing(int fd)
1176 int n = lp_num_modules();
1179 for (i = 0; i < n; i++) {
1181 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1184 if (protocol_version >= 25)
1185 io_printf(fd,"@RSYNCD: EXIT\n");
1188 static int load_config(int globals_only)
1191 if (am_daemon < 0 && am_root <= 0)
1192 config_file = RSYNCD_USERCONF;
1194 config_file = RSYNCD_SYSCONF;
1196 return lp_load(config_file, globals_only);
1199 /* this is called when a connection is established to a client
1200 and we want to start talking. The setup of the system is done from
1202 int start_daemon(int f_in, int f_out)
1205 const char *addr, *host;
1209 /* At this point, am_server is only set for a daemon started via rsh.
1210 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1211 * a flag that can be checked later on to distinguish a normal daemon
1212 * from an rsh-run daemon. */
1216 io_set_sock_fds(f_in, f_out);
1218 /* We must load the config file before calling any function that
1219 * might cause log-file output to occur. This ensures that the
1220 * "log file" param gets honored for the 2 non-forked use-cases
1221 * (when rsync is run by init and run by a remote shell). */
1222 if (!load_config(0))
1223 exit_cleanup(RERR_SYNTAX);
1225 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1228 p = lp_daemon_chroot();
1230 log_init(0); /* Make use we've initialized syslog before chrooting. */
1231 if (chroot(p) < 0 || chdir("/") < 0) {
1232 rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1236 p = lp_daemon_gid();
1239 if (!group_to_gid(p, &gid, True)) {
1240 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1243 if (setgid(gid) < 0) {
1244 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1249 p = lp_daemon_uid();
1252 if (!user_to_uid(p, &uid, True)) {
1253 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1256 if (setuid(uid) < 0) {
1257 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1261 am_root = (our_uid == ROOT_UID);
1264 addr = client_addr(f_in);
1265 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1266 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1268 if (am_daemon > 0) {
1269 set_socket_options(f_in, "SO_KEEPALIVE");
1270 set_nonblocking(f_in);
1273 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1277 if (!read_line_old(f_in, line, sizeof line, 0))
1280 if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1281 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1282 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1283 io_printf(f_out, "@ERROR: invalid early_input length\n");
1286 early_input = new_array(char, early_input_len);
1287 read_buf(f_in, early_input, early_input_len);
1289 if (!read_line_old(f_in, line, sizeof line, 0))
1293 if (!*line || strcmp(line, "#list") == 0) {
1294 rprintf(FLOG, "module-list request from %s (%s)\n",
1296 send_listing(f_out);
1301 /* it's some sort of command that I don't understand */
1302 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1306 if ((i = lp_number(line)) < 0) {
1307 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1309 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1313 #ifdef HAVE_SIGACTION
1314 sigact.sa_flags = SA_NOCLDSTOP;
1316 SIGACTION(SIGCHLD, remember_children);
1318 return rsync_module(f_in, f_out, i, addr, host);
1321 static void create_pid_file(void)
1323 char *pid_file = lp_pid_file();
1325 STRUCT_STAT st1, st2;
1328 if (!pid_file || !*pid_file)
1332 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1334 #define SAFE_OPEN_FLAGS (O_CREAT)
1337 /* These tests make sure that a temp-style lock dir is handled safely. */
1339 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1341 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1342 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1343 else if (!lock_range(pid_file_fd, 0, 4))
1345 else if (do_fstat(pid_file_fd, &st1) < 0)
1346 fail = "fstat opened";
1347 else if (st1.st_size > (int)sizeof pidbuf)
1348 fail = "find small";
1349 else if (do_lstat(pid_file, &st2) < 0)
1351 else if (!S_ISREG(st1.st_mode))
1352 fail = "avoid file overwrite race for";
1353 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1354 fail = "verify stat info for";
1355 #ifdef HAVE_FTRUNCATE
1356 else if (do_ftruncate(pid_file_fd, 0) < 0)
1360 pid_t pid = getpid();
1361 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1362 #ifndef HAVE_FTRUNCATE
1363 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1364 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1365 pidbuf[len++] = '\n';
1366 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1368 if (write(pid_file_fd, pidbuf, len) != len)
1370 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1375 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1376 fail, pid_file, strerror(errno));
1378 rprintf(FLOG, "%s", msg);
1379 exit_cleanup(RERR_FILEIO);
1382 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1385 /* Become a daemon, discarding the controlling terminal. */
1386 static void become_daemon(void)
1393 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1394 exit_cleanup(RERR_FILEIO);
1401 /* detach from the terminal */
1404 #elif defined TIOCNOTTY
1405 i = open("/dev/tty", O_RDWR);
1407 ioctl(i, (int)TIOCNOTTY, (char *)0);
1411 /* make sure that stdin, stdout an stderr don't stuff things
1412 * up (library functions, for example) */
1413 for (i = 0; i < 3; i++) {
1415 open("/dev/null", O_RDWR);
1419 int daemon_main(void)
1421 if (is_a_socket(STDIN_FILENO)) {
1424 /* we are running via inetd - close off stdout and
1425 * stderr so that library functions (and getopt) don't
1426 * try to use them. Redirect them to /dev/null */
1427 for (i = 1; i < 3; i++) {
1429 open("/dev/null", O_RDWR);
1432 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1435 if (!load_config(1)) {
1436 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1437 exit_cleanup(RERR_SYNTAX);
1446 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1447 rsync_port = RSYNC_PORT;
1448 if (bind_address == NULL && *lp_bind_address())
1449 bind_address = lp_bind_address();
1453 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1454 rsync_version(), rsync_port);
1455 /* TODO: If listening on a particular address, then show that
1456 * address too. In fact, why not just do getnameinfo on the
1457 * local address??? */
1459 start_accept_loop(rsync_port, start_daemon);