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 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;
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;
57 extern struct chmod_mode_struct *chmod_modes;
58 extern filter_rule_list daemon_filter_list;
60 extern char *iconv_opt;
61 extern iconv_t ic_send, ic_recv;
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;
83 static struct sigaction sigact;
86 static item_list gid_list = EMPTY_ITEM_LIST;
88 /* Used when "reverse lookup" is off. */
89 const char undetermined_hostname[] = "UNDETERMINED";
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[])
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 == '/') {
116 "ERROR: The remote path must start with a module name not a /\n");
120 if ((p = strrchr(host, '@')) != NULL) {
126 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
128 exit_cleanup(RERR_SOCKETIO);
134 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
136 return ret ? ret : client_run(fd, fd, -1, argc, argv);
139 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
142 #if SUBPROTOCOL_VERSION != 0
143 int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
149 io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
152 motd = lp_motd_file();
154 FILE *f = fopen(motd,"r");
155 while (f && !feof(f)) {
156 int len = fread(buf, 1, bufsiz - 1, f);
158 write_buf(f_out, buf, len);
162 write_sbuf(f_out, "\n");
166 /* This strips the \n. */
167 if (!read_line_old(f_in, buf, bufsiz, 0)) {
169 rprintf(FERROR, "rsync: did not see server greeting\n");
173 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
175 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
177 io_printf(f_out, "@ERROR: protocol startup error\n");
181 if (remote_sub < 0) {
182 if (remote_protocol == 30) {
184 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
186 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
192 if (protocol_version > remote_protocol) {
193 protocol_version = remote_protocol;
196 } else if (protocol_version == remote_protocol) {
197 if (remote_sub != our_sub)
200 #if SUBPROTOCOL_VERSION != 0
201 else if (protocol_version < remote_protocol) {
207 if (protocol_version >= 30)
213 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
216 char line[BIGPATHBUFLEN];
217 char *sargs[MAX_ARGS];
221 assert(argc > 0 && *argv != NULL);
225 "ERROR: The remote path must start with a module name\n");
229 if (!(p = strchr(*argv, '/')))
230 modlen = strlen(*argv);
234 if (!(modname = new_array(char, modlen+1+1))) /* room for '/' & '\0' */
235 out_of_memory("start_inband_exchange");
236 strlcpy(modname, *argv, modlen + 1);
237 modname[modlen] = '/';
238 modname[modlen+1] = '\0';
241 user = getenv("USER");
243 user = getenv("LOGNAME");
245 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
248 /* set daemon_over_rsh to false since we need to build the
249 * true set of args passed through the rsh/ssh connection;
250 * this is a no-op for direct-socket-connection mode */
252 server_options(sargs, &sargc);
254 if (sargc >= MAX_ARGS - 2)
257 sargs[sargc++] = ".";
260 if (sargc >= MAX_ARGS - 1) {
262 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
263 exit_cleanup(RERR_SYNTAX);
265 if (strncmp(*argv, modname, modlen) == 0
266 && argv[0][modlen] == '\0')
267 sargs[sargc++] = modname; /* we send "modname/" */
268 else if (**argv == '-') {
269 if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
270 out_of_memory("start_inband_exchange");
272 sargs[sargc++] = *argv;
279 if (DEBUG_GTE(CMD, 1))
280 print_child_argv("sending daemon args:", sargs);
282 io_printf(f_out, "%.*s\n", modlen, modname);
284 /* Old servers may just drop the connection here,
285 rather than sending a proper EXIT command. Yuck. */
286 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
289 if (!read_line_old(f_in, line, sizeof line, 0)) {
290 rprintf(FERROR, "rsync: didn't get server startup line\n");
294 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
295 auth_client(f_out, user, line+18);
299 if (strcmp(line,"@RSYNCD: OK") == 0)
302 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
303 /* This is sent by recent versions of the
304 * server to terminate the listing of modules.
305 * We don't want to go on and transfer
306 * anything; just exit. */
310 if (strncmp(line, "@ERROR", 6) == 0) {
311 rprintf(FERROR, "%s\n", line);
312 /* This is always fatal; the server will now
313 * close the socket. */
317 /* This might be a MOTD line or a module listing, but there is
318 * no way to differentiate it. The manpage mentions this. */
320 rprintf(FINFO, "%s\n", line);
322 kluge_around_eof = 0;
325 for (i = 0; i < sargc; i++) {
326 if (!sargs[i]) /* stop at --protect-args NULL */
328 write_sbuf(f_out, sargs[i]);
329 write_byte(f_out, 0);
331 write_byte(f_out, 0);
333 for (i = 0; i < sargc; i++)
334 io_printf(f_out, "%s\n", sargs[i]);
335 write_sbuf(f_out, "\n");
339 send_protected_args(f_out, sargs);
341 if (protocol_version < 23) {
342 if (protocol_version == 22 || !am_sender)
343 io_start_multiplex_in(f_in);
352 static int read_arg_from_pipe(int fd, char *buf, int limit)
354 char *bp = buf, *eob = buf + limit - 1;
357 int got = read(fd, bp, 1);
359 if (got < 0 && errno == EINTR)
374 static void set_env_str(const char *var, const char *str)
378 if (asprintf(&mem, "%s=%s", var, str) < 0)
379 out_of_memory("set_env_str");
385 void set_env_num(const char *var, long num)
388 if (asprintf(&mem, "%s=%ld", var, num) < 0)
389 out_of_memory("set_env_num");
394 /* Used for both early exec & pre-xfer exec */
395 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
397 int arg_fds[2], error_fds[2], arg_fd;
400 if ((error_fd_ptr && pipe(error_fds) < 0) || (arg_fd_ptr && pipe(arg_fds) < 0) || (pid = fork()) < 0)
404 char buf[BIGPATHBUFLEN];
409 set_blocking(error_fds[1]);
415 set_blocking(arg_fd);
417 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
420 set_env_str("RSYNC_REQUEST", buf);
424 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
430 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
437 dup2(error_fds[1], STDOUT_FILENO);
443 status = shell_exec(cmd);
445 if (!WIFEXITED(status))
447 _exit(WEXITSTATUS(status));
452 *error_fd_ptr = error_fds[0];
453 set_blocking(error_fds[0]);
458 arg_fd = *arg_fd_ptr = arg_fds[1];
459 set_blocking(arg_fd);
465 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv)
472 write_buf(write_fd, request, strlen(request)+1);
474 for ( ; *early_argv; early_argv++)
475 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
476 j = 1; /* Skip arg0 name in argv. */
478 for ( ; argv[j]; j++)
479 write_buf(write_fd, argv[j], strlen(argv[j])+1);
480 write_byte(write_fd, 0);
485 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
487 char buf[BIGPATHBUFLEN], *bp, *cr;
488 int j, status = -1, msglen = sizeof buf - 1;
491 /* Read the stdout from the program. This it is only displayed
492 * to the user if the script also returns an error status. */
493 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
494 if ((j = read(read_fd, bp, msglen)) <= 0) {
499 break; /* Just ignore the read error for now... */
503 if ((cr = strchr(cr, '\r')) == NULL) {
508 break; /* wait for more data before we decide what to do */
510 memmove(cr, cr+1, j - (cr - bp));
523 if (wait_process(pid, &status, 0) < 0
524 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
526 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
527 desc, status, status < 0 ? ": " : "",
528 status < 0 ? strerror(errno) : "",
529 *buf ? ":" : "", buf) < 0)
530 return "out_of_memory in finish_pre_exec\n";
536 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
539 rsyserr(FLOG, errno, "chdir %s failed", dir);
541 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
542 io_printf(f_out, "@ERROR: chdir failed\n");
546 static int add_a_group(int f_out, const char *gname)
549 if (!group_to_gid(gname, &gid, True)) {
550 rprintf(FLOG, "Invalid gid %s\n", gname);
551 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
554 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
559 #ifdef HAVE_GETGROUPLIST
560 static int want_all_groups(int f_out, uid_t uid)
563 if ((err = getallgroups(uid, &gid_list)) != NULL) {
564 rsyserr(FLOG, errno, "%s", err);
565 io_printf(f_out, "@ERROR: %s\n", err);
570 #elif defined HAVE_INITGROUPS
571 static struct passwd *want_all_groups(int f_out, uid_t uid)
575 if ((pw = getpwuid(uid)) == NULL) {
576 rsyserr(FLOG, errno, "getpwuid failed");
577 io_printf(f_out, "@ERROR: getpwuid failed\n");
580 /* Start with the default group and initgroups() will add the rest. */
581 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
587 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
590 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
591 char line[BIGPATHBUFLEN];
592 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
593 struct passwd *pw = NULL;
597 char *p, *err_msg = NULL;
598 char *name = lp_name(i);
599 int use_chroot = lp_use_chroot(i);
600 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
601 int save_munge_symlinks;
602 pid_t pre_exec_pid = 0;
603 char *request = NULL;
605 set_env_str("RSYNC_MODULE_NAME", name);
608 iconv_opt = lp_charset(i);
614 /* If reverse lookup is disabled globally but enabled for this module,
615 * we need to do it now before the access check. */
616 if (host == undetermined_hostname && lp_reverse_lookup(i))
617 host = client_name(client_addr(f_in));
618 set_env_str("RSYNC_HOST_NAME", host);
619 set_env_str("RSYNC_HOST_ADDR", addr);
621 if (!allow_access(addr, &host, i)) {
622 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
625 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
628 "@ERROR: access denied to %s from %s (%s)\n",
635 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
639 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
641 rsyserr(FLOG, errno, "failed to open lock file %s",
643 io_printf(f_out, "@ERROR: failed to open lock file\n");
645 rprintf(FLOG, "max connections (%d) reached\n",
646 lp_max_connections(i));
647 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
648 lp_max_connections(i));
653 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
654 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
657 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
660 set_env_str("RSYNC_USER_NAME", auth_user);
664 if (lp_transfer_logging(i) && !logfile_format)
665 logfile_format = lp_log_format(i);
666 if (log_format_has(logfile_format, 'i'))
667 logfile_format_has_i = 1;
668 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
669 logfile_format_has_o_or_i = 1;
672 am_root = (uid == 0);
674 p = *lp_uid(i) ? lp_uid(i) : am_root ? NOBODY_USER : NULL;
676 if (!user_to_uid(p, &uid, True)) {
677 rprintf(FLOG, "Invalid uid %s\n", p);
678 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
685 p = *lp_gid(i) ? conf_strtok(lp_gid(i)) : NULL;
687 /* The "*" gid must be the first item in the list. */
688 if (strcmp(p, "*") == 0) {
689 #ifdef HAVE_GETGROUPLIST
690 if (want_all_groups(f_out, uid) < 0)
692 #elif defined HAVE_INITGROUPS
693 if ((pw = want_all_groups(f_out, uid)) == NULL)
696 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
697 io_printf(f_out, "@ERROR: invalid gid setting.\n");
700 } else if (add_a_group(f_out, p) < 0)
702 while ((p = conf_strtok(NULL)) != NULL) {
703 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
705 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
706 io_printf(f_out, "@ERROR: invalid gid setting.\n");
710 if (add_a_group(f_out, p) < 0)
713 } else if (am_root) {
714 if (add_a_group(f_out, NOBODY_GROUP) < 0)
718 module_dir = lp_path(i);
719 if (*module_dir == '\0') {
720 rprintf(FLOG, "No path specified for module %s\n", name);
721 io_printf(f_out, "@ERROR: no path setting.\n");
725 if ((p = strstr(module_dir, "/./")) != NULL) {
726 *p = '\0'; /* Temporary... */
727 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
728 return path_failure(f_out, module_dir, False);
730 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
731 return path_failure(f_out, strstr(module_dir, "/./"), False);
732 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
733 full_module_path = module_dir;
736 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
737 return path_failure(f_out, module_dir, False);
738 full_module_path = module_chdir;
743 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
744 return path_failure(f_out, module_dir, False);
745 full_module_path = module_dir = module_chdir;
747 set_env_str("RSYNC_MODULE_PATH", full_module_path);
749 if (module_dirlen == 1) {
751 set_filter_dir("/", 1);
753 set_filter_dir(module_dir, module_dirlen);
756 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
757 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
759 p = lp_include_from(i);
760 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
761 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
764 parse_filter_str(&daemon_filter_list, p,
765 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
766 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
768 p = lp_exclude_from(i);
769 parse_filter_file(&daemon_filter_list, p, rule_template(0),
770 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
773 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
774 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
779 if ((*lp_early_exec(i) || *lp_prexfer_exec(i) || *lp_postxfer_exec(i))
780 && !getenv("RSYNC_NO_XFER_EXEC")) {
781 set_env_num("RSYNC_PID", (long)getpid());
783 /* For post-xfer exec, fork a new process to run the rsync
784 * daemon while this process waits for the exit status and
785 * runs the indicated command at that point. */
786 if (*lp_postxfer_exec(i)) {
789 rsyserr(FLOG, errno, "fork failed");
790 io_printf(f_out, "@ERROR: fork failed\n");
798 if (wait_process(pid, &status, 0) < 0)
800 set_env_num("RSYNC_RAW_STATUS", status);
801 if (WIFEXITED(status))
802 status = WEXITSTATUS(status);
805 set_env_num("RSYNC_EXIT_STATUS", status);
806 if (shell_exec(lp_postxfer_exec(i)) < 0)
812 /* For early exec, fork a child process to run the indicated
813 * command and wait for it to exit. */
814 if (*lp_early_exec(i)) {
815 pid_t pid = start_pre_exec(lp_early_exec(i), NULL, NULL);
816 if (pid == (pid_t)-1) {
817 rsyserr(FLOG, errno, "early exec preparation failed");
818 io_printf(f_out, "@ERROR: early exec preparation failed\n");
821 if (finish_pre_exec("early exec", pid, -1) != NULL) {
822 rsyserr(FLOG, errno, "early exec failed");
823 io_printf(f_out, "@ERROR: early exec failed\n");
828 /* For pre-xfer exec, fork a child process to run the indicated
829 * command, though it first waits for the parent process to
830 * send us the user's request via a pipe. */
831 if (*lp_prexfer_exec(i)) {
832 pre_exec_pid = start_pre_exec(lp_prexfer_exec(i), &pre_exec_arg_fd, &pre_exec_error_fd);
833 if (pre_exec_pid == (pid_t)-1) {
834 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
835 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
844 * XXX: The 'use chroot' flag is a fairly reliable
845 * source of confusion, because it fails under two
846 * important circumstances: running as non-root,
847 * running on Win32 (or possibly others). On the
848 * other hand, if you are running as root, then it
849 * might be better to always use chroot.
851 * So, perhaps if we can't chroot we should just issue
852 * a warning, unless a "require chroot" flag is set,
853 * in which case we fail.
855 if (chroot(module_chdir)) {
856 rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
857 io_printf(f_out, "@ERROR: chroot failed\n");
860 module_chdir = module_dir;
863 if (!change_dir(module_chdir, CD_NORMAL))
864 return path_failure(f_out, module_chdir, True);
865 if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
868 if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
869 munge_symlinks = !use_chroot || module_dirlen;
870 if (munge_symlinks) {
872 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
873 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
874 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
875 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
877 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
878 exit_cleanup(RERR_UNSUPPORTED);
882 if (gid_list.count) {
883 gid_t *gid_array = gid_list.items;
884 if (setgid(gid_array[0])) {
885 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
886 io_printf(f_out, "@ERROR: setgid failed\n");
889 #ifdef HAVE_SETGROUPS
890 /* Set the group(s) we want to be active. */
891 if (setgroups(gid_list.count, gid_array)) {
892 rsyserr(FLOG, errno, "setgroups failed");
893 io_printf(f_out, "@ERROR: setgroups failed\n");
897 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
898 /* pw is set if the user wants all the user's groups. */
899 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
900 rsyserr(FLOG, errno, "initgroups failed");
901 io_printf(f_out, "@ERROR: initgroups failed\n");
914 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
915 io_printf(f_out, "@ERROR: setuid failed\n");
920 am_root = (our_uid == 0);
923 if (lp_temp_dir(i) && *lp_temp_dir(i)) {
924 tmpdir = lp_temp_dir(i);
925 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
927 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
933 io_printf(f_out, "@RSYNCD: OK\n");
935 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
938 save_munge_symlinks = munge_symlinks;
940 reset_output_levels(); /* future verbosity is controlled by client options */
941 ret = parse_arguments(&argc, (const char ***) &argv);
942 if (protect_args && ret) {
943 orig_early_argv = orig_argv;
945 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
947 ret = parse_arguments(&argc, (const char ***) &argv);
949 orig_early_argv = NULL;
951 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
953 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
956 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv);
957 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
961 free(orig_early_argv);
963 am_server = 1; /* Don't let someone try to be tricky. */
965 if (lp_ignore_errors(module_id))
970 if (lp_fake_super(i)) {
971 if (preserve_xattrs > 1)
974 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
977 if (filesfrom_fd == 0)
982 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
983 am_sender ? "on" : "to",
984 request, auth_user, host, addr);
986 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
987 am_sender ? "on" : "to",
988 request, host, addr);
994 /* don't allow the logs to be flooded too fast */
995 limit_output_verbosity(lp_max_verbosity(i));
998 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
999 io_start_multiplex_out(f_out);
1000 else if (!ret || err_msg) {
1001 /* We have to get I/O multiplexing started so that we can
1002 * get the error back to the client. This means getting
1003 * the protocol setup finished first in later versions. */
1004 setup_protocol(f_out, f_in);
1006 /* Since we failed in our option parsing, we may not
1007 * have finished parsing that the client sent us a
1008 * --files-from option, so look for it manually.
1009 * Without this, the socket would be in the wrong
1010 * state for the upcoming error message. */
1013 for (i = 0; i < argc; i++) {
1014 if (strncmp(argv[i], "--files-from", 12) == 0) {
1021 write_byte(f_out, 0);
1023 io_start_multiplex_out(f_out);
1026 if (!ret || err_msg) {
1028 while ((p = strchr(err_msg, '\n')) != NULL) {
1029 int len = p - err_msg + 1;
1030 rwrite(FERROR, err_msg, len, 0);
1034 rprintf(FERROR, "%s\n", err_msg);
1035 io_flush(MSG_FLUSH);
1039 exit_cleanup(RERR_UNSUPPORTED);
1044 if (ic_send != (iconv_t)-1) {
1045 iconv_close(ic_send);
1046 ic_send = (iconv_t)-1;
1048 if (ic_recv != (iconv_t)-1) {
1049 iconv_close(ic_recv);
1050 ic_recv = (iconv_t)-1;
1056 && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
1057 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1059 if (lp_timeout(i) && (!io_timeout || lp_timeout(i) < io_timeout))
1060 set_io_timeout(lp_timeout(i));
1062 /* If we have some incoming/outgoing chmod changes, append them to
1063 * any user-specified changes (making our changes have priority).
1064 * We also get a pointer to just our changes so that a receiver
1065 * process can use them separately if --perms wasn't specified. */
1067 p = lp_outgoing_chmod(i);
1069 p = lp_incoming_chmod(i);
1070 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1071 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1072 am_sender ? "outgo" : "incom", p);
1075 start_server(f_in, f_out, argc, argv);
1080 /* send a list of available modules to the client. Don't list those
1081 with "list = False". */
1082 static void send_listing(int fd)
1084 int n = lp_num_modules();
1087 for (i = 0; i < n; i++) {
1089 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1092 if (protocol_version >= 25)
1093 io_printf(fd,"@RSYNCD: EXIT\n");
1096 static int load_config(int globals_only)
1099 if (am_daemon < 0 && am_root <= 0)
1100 config_file = RSYNCD_USERCONF;
1102 config_file = RSYNCD_SYSCONF;
1104 return lp_load(config_file, globals_only);
1107 /* this is called when a connection is established to a client
1108 and we want to start talking. The setup of the system is done from
1110 int start_daemon(int f_in, int f_out)
1113 const char *addr, *host;
1117 /* At this point, am_server is only set for a daemon started via rsh.
1118 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1119 * a flag that can be checked later on to distinguish a normal daemon
1120 * from an rsh-run daemon. */
1124 io_set_sock_fds(f_in, f_out);
1126 /* We must load the config file before calling any function that
1127 * might cause log-file output to occur. This ensures that the
1128 * "log file" param gets honored for the 2 non-forked use-cases
1129 * (when rsync is run by init and run by a remote shell). */
1130 if (!load_config(0))
1131 exit_cleanup(RERR_SYNTAX);
1133 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1136 p = lp_daemon_chroot();
1138 log_init(0); /* Make use we've initialized syslog before chrooting. */
1139 if (chroot(p) < 0 || chdir("/") < 0) {
1140 rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1144 p = lp_daemon_gid();
1147 if (!group_to_gid(p, &gid, True)) {
1148 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1151 if (setgid(gid) < 0) {
1152 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1157 p = lp_daemon_uid();
1160 if (!user_to_uid(p, &uid, True)) {
1161 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1164 if (setuid(uid) < 0) {
1165 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1169 am_root = (our_uid == 0);
1172 addr = client_addr(f_in);
1173 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1174 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1176 if (am_daemon > 0) {
1177 set_socket_options(f_in, "SO_KEEPALIVE");
1178 set_nonblocking(f_in);
1181 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1185 if (!read_line_old(f_in, line, sizeof line, 0))
1188 if (!*line || strcmp(line, "#list") == 0) {
1189 rprintf(FLOG, "module-list request from %s (%s)\n",
1191 send_listing(f_out);
1196 /* it's some sort of command that I don't understand */
1197 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1201 if ((i = lp_number(line)) < 0) {
1202 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1204 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1208 #ifdef HAVE_SIGACTION
1209 sigact.sa_flags = SA_NOCLDSTOP;
1211 SIGACTION(SIGCHLD, remember_children);
1213 return rsync_module(f_in, f_out, i, addr, host);
1216 static void create_pid_file(void)
1218 char *pid_file = lp_pid_file();
1220 STRUCT_STAT st1, st2;
1223 if (!pid_file || !*pid_file)
1227 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1229 #define SAFE_OPEN_FLAGS (O_CREAT)
1232 /* These tests make sure that a temp-style lock dir is handled safely. */
1234 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1236 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1237 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1238 else if (!lock_range(pid_file_fd, 0, 4))
1240 else if (do_fstat(pid_file_fd, &st1) < 0)
1241 fail = "fstat opened";
1242 else if (st1.st_size > (int)sizeof pidbuf)
1243 fail = "find small";
1244 else if (do_lstat(pid_file, &st2) < 0)
1246 else if (!S_ISREG(st1.st_mode))
1247 fail = "avoid file overwrite race for";
1248 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1249 fail = "verify stat info for";
1250 #ifdef HAVE_FTRUNCATE
1251 else if (do_ftruncate(pid_file_fd, 0) < 0)
1255 pid_t pid = getpid();
1256 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1257 #ifndef HAVE_FTRUNCATE
1258 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1259 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1260 pidbuf[len++] = '\n';
1261 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1263 if (write(pid_file_fd, pidbuf, len) != len)
1265 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1270 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1271 fail, pid_file, strerror(errno));
1273 rprintf(FLOG, "%s", msg);
1274 exit_cleanup(RERR_FILEIO);
1277 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1280 /* Become a daemon, discarding the controlling terminal. */
1281 static void become_daemon(void)
1288 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1289 exit_cleanup(RERR_FILEIO);
1296 /* detach from the terminal */
1299 #elif defined TIOCNOTTY
1300 i = open("/dev/tty", O_RDWR);
1302 ioctl(i, (int)TIOCNOTTY, (char *)0);
1306 /* make sure that stdin, stdout an stderr don't stuff things
1307 * up (library functions, for example) */
1308 for (i = 0; i < 3; i++) {
1310 open("/dev/null", O_RDWR);
1314 int daemon_main(void)
1316 if (is_a_socket(STDIN_FILENO)) {
1319 /* we are running via inetd - close off stdout and
1320 * stderr so that library functions (and getopt) don't
1321 * try to use them. Redirect them to /dev/null */
1322 for (i = 1; i < 3; i++) {
1324 open("/dev/null", O_RDWR);
1327 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1330 if (!load_config(1)) {
1331 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1332 exit_cleanup(RERR_SYNTAX);
1341 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1342 rsync_port = RSYNC_PORT;
1343 if (bind_address == NULL && *lp_bind_address())
1344 bind_address = lp_bind_address();
1348 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1349 RSYNC_VERSION, rsync_port);
1350 /* TODO: If listening on a particular address, then show that
1351 * address too. In fact, why not just do getnameinfo on the
1352 * local address??? */
1354 start_accept_loop(rsync_port, start_daemon);