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-2022 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 old_style_args;
51 extern int default_af_hint;
52 extern int logfile_format_has_i;
53 extern int logfile_format_has_o_or_i;
54 extern char *bind_address;
55 extern char *config_file;
56 extern char *logfile_format;
57 extern char *files_from;
59 extern char *early_input_file;
60 extern struct chmod_mode_struct *chmod_modes;
61 extern filter_rule_list daemon_filter_list;
63 extern char *iconv_opt;
64 extern iconv_t ic_send, ic_recv;
70 char *daemon_auth_choices;
74 int early_input_len = 0;
75 char *early_input = NULL;
76 pid_t namecvt_pid = 0;
77 struct chmod_mode_struct *daemon_chmod_modes;
79 #define EARLY_INPUT_CMD "#early_input="
80 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
82 /* module_dirlen is the length of the module_dir string when in daemon
83 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
84 * enabled module can have a non-"/" module_dir these days.) */
85 char *module_dir = NULL;
86 unsigned int module_dirlen = 0;
88 char *full_module_path;
90 static int rl_nulls = 0;
91 static int namecvt_fd_req = -1, namecvt_fd_ans = -1;
94 static struct sigaction sigact;
97 static item_list gid_list = EMPTY_ITEM_LIST;
99 /* Used when "reverse lookup" is off. */
100 const char undetermined_hostname[] = "UNDETERMINED";
103 * Run a client connected to an rsyncd. The alternative to this
104 * function for remote-shell connections is do_cmd().
106 * After negotiating which module to use and reading the server's
107 * motd, this hands over to client_run(). Telling the server the
108 * module will cause it to chroot/setuid/etc.
110 * Instead of doing a transfer, the client may at this stage instead
111 * get a listing of remote modules and exit.
113 * @return -1 for error in startup, or the result of client_run().
114 * Either way, it eventually gets passed to exit_cleanup().
116 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
117 int argc, char *argv[])
120 char *p, *user = NULL;
122 /* This is redundant with code in start_inband_exchange(), but this
123 * short-circuits a problem in the client before we open a socket,
124 * and the extra check won't hurt. */
125 if (**remote_argv == '/') {
127 "ERROR: The remote path must start with a module name not a /\n");
131 if ((p = strrchr(host, '@')) != NULL) {
137 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
139 exit_cleanup(RERR_SOCKETIO);
145 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
147 return ret ? ret : client_run(fd, fd, -1, argc, argv);
150 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
153 int our_sub = get_subprotocol_version();
155 output_daemon_greeting(f_out, am_client);
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: the server omitted the subprotocol value: %s\n", buf);
191 io_printf(f_out, "@ERROR: your client omitted the subprotocol value: %s\n", buf);
197 daemon_auth_choices = strchr(buf + 9, ' ');
198 if (daemon_auth_choices) {
200 daemon_auth_choices = strdup(daemon_auth_choices + 1);
201 if ((cp = strchr(daemon_auth_choices, '\n')) != NULL)
203 } else if (remote_protocol > 31) {
205 rprintf(FERROR, "rsync: the server omitted the digest name list: %s\n", buf);
207 io_printf(f_out, "@ERROR: your client omitted the digest name list: %s\n", buf);
211 if (protocol_version > remote_protocol) {
212 protocol_version = remote_protocol;
215 } else if (protocol_version == remote_protocol) {
216 if (remote_sub != our_sub)
219 #if SUBPROTOCOL_VERSION != 0
220 else if (protocol_version < remote_protocol) {
226 if (protocol_version >= 30)
232 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
235 char line[BIGPATHBUFLEN];
236 char *sargs[MAX_ARGS];
240 assert(argc > 0 && *argv != NULL);
244 "ERROR: The remote path must start with a module name\n");
248 if (!(p = strchr(*argv, '/')))
249 modlen = strlen(*argv);
253 modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
254 strlcpy(modname, *argv, modlen + 1);
255 modname[modlen] = '/';
256 modname[modlen+1] = '\0';
259 user = getenv("USER");
261 user = getenv("LOGNAME");
263 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
266 if (early_input_file) {
268 FILE *f = fopen(early_input_file, "rb");
269 if (!f || do_fstat(fileno(f), &st) < 0) {
270 rsyserr(FERROR, errno, "failed to open %s", early_input_file);
273 early_input_len = st.st_size;
274 if (early_input_len > (int)sizeof line) {
275 rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
278 if (early_input_len > 0) {
279 io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
280 while (early_input_len > 0) {
283 rprintf(FERROR, "Early EOF in %s\n", early_input_file);
286 len = fread(line, 1, early_input_len, f);
288 write_buf(f_out, line, len);
289 early_input_len -= len;
296 server_options(sargs, &sargc);
298 if (sargc >= MAX_ARGS - 2)
301 sargs[sargc++] = ".";
304 snprintf(line, sizeof line, " %.*s/", modlen, modname);
307 if (sargc >= MAX_ARGS - 1) {
309 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
310 exit_cleanup(RERR_SYNTAX);
312 if (strncmp(*argv, modname, modlen) == 0 && argv[0][modlen] == '\0')
313 sargs[sargc++] = modname; /* we send "modname/" */
316 int extra_chars = *arg == '-' ? 2 : 0; /* a leading dash needs a "./" prefix. */
317 /* If --old-args was not specified, make sure that the arg won't split at a mod name! */
318 if (!old_style_args && (p = strstr(arg, line)) != NULL) {
321 } while ((p = strstr(p+1, line)) != NULL);
325 char *t = arg = new_array(char, strlen(arg) + extra_chars + 1);
331 if (*f == ' ' && strncmp(f, line, modlen+2) == 0) {
340 sargs[sargc++] = arg;
348 if (DEBUG_GTE(CMD, 1))
349 print_child_argv("sending daemon args:", sargs);
351 io_printf(f_out, "%.*s\n", modlen, modname);
353 /* Old servers may just drop the connection here,
354 rather than sending a proper EXIT command. Yuck. */
355 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
358 if (!read_line_old(f_in, line, sizeof line, 0)) {
359 rprintf(FERROR, "rsync: didn't get server startup line\n");
363 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
364 auth_client(f_out, user, line+18);
368 if (strcmp(line,"@RSYNCD: OK") == 0)
371 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
372 /* This is sent by recent versions of the
373 * server to terminate the listing of modules.
374 * We don't want to go on and transfer
375 * anything; just exit. */
379 if (strncmp(line, "@ERROR", 6) == 0) {
380 rprintf(FERROR, "%s\n", line);
381 /* This is always fatal; the server will now
382 * close the socket. */
386 /* This might be a MOTD line or a module listing, but there is
387 * no way to differentiate it. The manpage mentions this. */
389 rprintf(FINFO, "%s\n", line);
391 kluge_around_eof = 0;
394 for (i = 0; i < sargc; i++) {
395 if (!sargs[i]) /* stop at --secluded-args NULL */
397 write_sbuf(f_out, sargs[i]);
398 write_byte(f_out, 0);
400 write_byte(f_out, 0);
402 for (i = 0; i < sargc; i++)
403 io_printf(f_out, "%s\n", sargs[i]);
404 write_sbuf(f_out, "\n");
408 send_protected_args(f_out, sargs);
410 if (protocol_version < 23) {
411 if (protocol_version == 22 || !am_sender)
412 io_start_multiplex_in(f_in);
420 #if defined HAVE_SETENV || defined HAVE_PUTENV
421 static int read_arg_from_pipe(int fd, char *buf, int limit)
423 char *bp = buf, *eob = buf + limit - 1;
426 int got = read(fd, bp, 1);
428 if (got < 0 && errno == EINTR)
443 void set_env_str(const char *var, const char *str)
446 if (setenv(var, str, 1) < 0)
447 out_of_memory("set_env_str");
451 if (asprintf(&mem, "%s=%s", var, str) < 0)
452 out_of_memory("set_env_str");
461 #if defined HAVE_SETENV || defined HAVE_PUTENV
463 static void set_envN_str(const char *var, int num, const char *str)
467 (void)snprintf(buf, sizeof buf, "%s%d", var, num);
468 if (setenv(buf, str, 1) < 0)
469 out_of_memory("set_env_str");
473 if (asprintf(&mem, "%s%d=%s", var, num, str) < 0)
474 out_of_memory("set_envN_str");
480 void set_env_num(const char *var, long num)
484 (void)snprintf(val, sizeof val, "%ld", num);
485 if (setenv(var, val, 1) < 0)
486 out_of_memory("set_env_str");
490 if (asprintf(&mem, "%s=%ld", var, num) < 0)
491 out_of_memory("set_env_num");
497 /* Used for "early exec", "pre-xfer exec", and the "name converter" script. */
498 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
500 int arg_fds[2], error_fds[2], arg_fd;
503 if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
507 char buf[BIGPATHBUFLEN];
512 set_blocking(error_fds[1]);
517 set_blocking(arg_fd);
519 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
522 set_env_str("RSYNC_REQUEST", buf);
525 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
531 set_envN_str("RSYNC_ARG", j, buf);
534 dup2(arg_fd, STDIN_FILENO);
538 dup2(error_fds[1], STDOUT_FILENO);
542 status = shell_exec(cmd);
544 if (!WIFEXITED(status))
546 _exit(WEXITSTATUS(status));
551 *error_fd_ptr = error_fds[0];
552 set_blocking(error_fds[0]);
556 arg_fd = *arg_fd_ptr = arg_fds[1];
557 set_blocking(arg_fd);
564 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int exec_type)
571 write_buf(write_fd, request, strlen(request)+1);
573 for ( ; *early_argv; early_argv++)
574 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
575 j = 1; /* Skip arg0 name in argv. */
578 for ( ; argv[j]; j++)
579 write_buf(write_fd, argv[j], strlen(argv[j])+1);
581 write_byte(write_fd, 0);
583 if (exec_type == 1 && early_input_len)
584 write_buf(write_fd, early_input, early_input_len);
586 if (exec_type != 2) /* the name converter needs this left open */
590 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
592 char buf[BIGPATHBUFLEN], *bp, *cr;
593 int j, status = -1, msglen = sizeof buf - 1;
596 /* Read the stdout from the program. This it is only displayed
597 * to the user if the script also returns an error status. */
598 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
599 if ((j = read(read_fd, bp, msglen)) <= 0) {
604 break; /* Just ignore the read error for now... */
608 if ((cr = strchr(cr, '\r')) == NULL) {
613 break; /* wait for more data before we decide what to do */
615 memmove(cr, cr+1, j - (cr - bp));
628 if (wait_process(pid, &status, 0) < 0
629 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
631 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
632 desc, status, status < 0 ? ": " : "",
633 status < 0 ? strerror(errno) : "",
634 *buf ? ":" : "", buf) < 0)
635 return "out_of_memory in finish_pre_exec\n";
641 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
644 rsyserr(FLOG, errno, "chdir %s failed", dir);
646 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
647 io_printf(f_out, "@ERROR: chdir failed\n");
651 static int add_a_group(int f_out, const char *gname)
654 if (!group_to_gid(gname, &gid, True)) {
655 rprintf(FLOG, "Invalid gid %s\n", gname);
656 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
659 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
664 #ifdef HAVE_GETGROUPLIST
665 static int want_all_groups(int f_out, uid_t uid)
668 if ((err = getallgroups(uid, &gid_list)) != NULL) {
669 rsyserr(FLOG, errno, "%s", err);
670 io_printf(f_out, "@ERROR: %s\n", err);
675 #elif defined HAVE_INITGROUPS
676 static struct passwd *want_all_groups(int f_out, uid_t uid)
680 if ((pw = getpwuid(uid)) == NULL) {
681 rsyserr(FLOG, errno, "getpwuid failed");
682 io_printf(f_out, "@ERROR: getpwuid failed\n");
685 /* Start with the default group and initgroups() will add the rest. */
686 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
692 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
695 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
696 char line[BIGPATHBUFLEN];
697 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
698 struct passwd *pw = NULL;
702 char *p, *err_msg = NULL;
703 char *name = lp_name(i);
704 int use_chroot = lp_use_chroot(i); /* might be 1 (yes), 0 (no), or -1 (unset) */
705 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
706 int save_munge_symlinks;
707 pid_t pre_exec_pid = 0;
708 char *request = NULL;
710 set_env_str("RSYNC_MODULE_NAME", name);
713 iconv_opt = lp_charset(i);
719 /* If reverse lookup is disabled globally but enabled for this module,
720 * we need to do it now before the access check. */
721 if (host == undetermined_hostname && lp_reverse_lookup(i))
722 host = client_name(client_addr(f_in));
723 set_env_str("RSYNC_HOST_NAME", host);
724 set_env_str("RSYNC_HOST_ADDR", addr);
726 if (!allow_access(addr, &host, i)) {
727 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
730 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
733 "@ERROR: access denied to %s from %s (%s)\n",
740 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
744 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
746 rsyserr(FLOG, errno, "failed to open lock file %s",
748 io_printf(f_out, "@ERROR: failed to open lock file\n");
750 rprintf(FLOG, "max connections (%d) reached\n",
751 lp_max_connections(i));
752 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
753 lp_max_connections(i));
758 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
759 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
762 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
765 set_env_str("RSYNC_USER_NAME", auth_user);
769 if (lp_transfer_logging(module_id) && !logfile_format)
770 logfile_format = lp_log_format(module_id);
771 if (log_format_has(logfile_format, 'i'))
772 logfile_format_has_i = 1;
773 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
774 logfile_format_has_o_or_i = 1;
777 am_root = (uid == ROOT_UID);
779 p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
781 if (!user_to_uid(p, &uid, True)) {
782 rprintf(FLOG, "Invalid uid %s\n", p);
783 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
790 p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
792 /* The "*" gid must be the first item in the list. */
793 if (strcmp(p, "*") == 0) {
794 #ifdef HAVE_GETGROUPLIST
795 if (want_all_groups(f_out, uid) < 0)
797 #elif defined HAVE_INITGROUPS
798 if ((pw = want_all_groups(f_out, uid)) == NULL)
801 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
802 io_printf(f_out, "@ERROR: invalid gid setting.\n");
805 } else if (add_a_group(f_out, p) < 0)
807 while ((p = conf_strtok(NULL)) != NULL) {
808 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
810 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
811 io_printf(f_out, "@ERROR: invalid gid setting.\n");
815 if (add_a_group(f_out, p) < 0)
818 } else if (am_root) {
819 if (add_a_group(f_out, NOBODY_GROUP) < 0)
823 module_dir = lp_path(module_id);
824 if (*module_dir == '\0') {
825 rprintf(FLOG, "No path specified for module %s\n", name);
826 io_printf(f_out, "@ERROR: no path setting.\n");
829 if (use_chroot < 0) {
830 if (strstr(module_dir, "/./") != NULL)
831 use_chroot = 1; /* The module is expecting a chroot inner & outer path. */
832 else if (chroot("/") < 0) {
833 rprintf(FLOG, "chroot test failed: %s. "
834 "Switching 'use chroot' from unset to false.\n",
839 rsyserr(FLOG, errno, "chdir(\"/\") failed");
844 if ((p = strstr(module_dir, "/./")) != NULL) {
845 *p = '\0'; /* Temporary... */
846 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
847 return path_failure(f_out, module_dir, False);
849 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
850 return path_failure(f_out, strstr(module_dir, "/./"), False);
851 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
852 full_module_path = module_dir;
855 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
856 return path_failure(f_out, module_dir, False);
857 full_module_path = module_chdir;
862 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
863 return path_failure(f_out, module_dir, False);
864 full_module_path = module_dir = module_chdir;
866 set_env_str("RSYNC_MODULE_PATH", full_module_path);
868 if (module_dirlen == 1) {
870 set_filter_dir("/", 1);
872 set_filter_dir(module_dir, module_dirlen);
874 p = lp_filter(module_id);
875 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
876 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
878 p = lp_include_from(module_id);
879 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
880 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
882 p = lp_include(module_id);
883 parse_filter_str(&daemon_filter_list, p,
884 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
885 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
887 p = lp_exclude_from(module_id);
888 parse_filter_file(&daemon_filter_list, p, rule_template(0),
889 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
891 p = lp_exclude(module_id);
892 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
893 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
897 #if defined HAVE_SETENV || defined HAVE_PUTENV
898 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
899 || *lp_postxfer_exec(module_id) || *lp_name_converter(module_id))
900 && !getenv("RSYNC_NO_XFER_EXEC")) {
901 set_env_num("RSYNC_PID", (long)getpid());
903 /* For post-xfer exec, fork a new process to run the rsync
904 * daemon while this process waits for the exit status and
905 * runs the indicated command at that point. */
906 if (*lp_postxfer_exec(module_id)) {
909 rsyserr(FLOG, errno, "fork failed");
910 io_printf(f_out, "@ERROR: fork failed\n");
918 if (wait_process(pid, &status, 0) < 0)
920 set_env_num("RSYNC_RAW_STATUS", status);
921 if (WIFEXITED(status))
922 status = WEXITSTATUS(status);
925 set_env_num("RSYNC_EXIT_STATUS", status);
926 if (shell_exec(lp_postxfer_exec(module_id)) < 0)
932 /* For early exec, fork a child process to run the indicated
933 * command and wait for it to exit. */
934 if (*lp_early_exec(module_id)) {
936 pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
937 if (pid == (pid_t)-1) {
938 rsyserr(FLOG, errno, "early exec preparation failed");
939 io_printf(f_out, "@ERROR: early exec preparation failed\n");
942 write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
943 if (finish_pre_exec("early exec", pid, -1) != NULL) {
944 rsyserr(FLOG, errno, "early exec failed");
945 io_printf(f_out, "@ERROR: early exec failed\n");
950 /* For pre-xfer exec, fork a child process to run the indicated
951 * command, though it first waits for the parent process to
952 * send us the user's request via a pipe. */
953 if (*lp_prexfer_exec(module_id)) {
954 pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
955 if (pre_exec_pid == (pid_t)-1) {
956 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
957 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
962 if (*lp_name_converter(module_id)) {
963 namecvt_pid = start_pre_exec(lp_name_converter(module_id), &namecvt_fd_req, &namecvt_fd_ans);
964 if (namecvt_pid == (pid_t)-1) {
965 rsyserr(FLOG, errno, "name-converter exec preparation failed");
966 io_printf(f_out, "@ERROR: name-converter exec preparation failed\n");
979 if (chroot(module_chdir)) {
980 rsyserr(FLOG, errno, "chroot(\"%s\") failed", module_chdir);
981 io_printf(f_out, "@ERROR: chroot failed\n");
984 module_chdir = module_dir;
987 if (!change_dir(module_chdir, CD_NORMAL))
988 return path_failure(f_out, module_chdir, True);
992 if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
993 munge_symlinks = !use_chroot || module_dirlen;
994 if (munge_symlinks) {
996 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
997 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
998 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
999 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
1001 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
1002 exit_cleanup(RERR_UNSUPPORTED);
1006 if (gid_list.count) {
1007 gid_t *gid_array = gid_list.items;
1008 if (setgid(gid_array[0])) {
1009 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
1010 io_printf(f_out, "@ERROR: setgid failed\n");
1013 #ifdef HAVE_SETGROUPS
1014 /* Set the group(s) we want to be active. */
1015 if (setgroups(gid_list.count, gid_array)) {
1016 rsyserr(FLOG, errno, "setgroups failed");
1017 io_printf(f_out, "@ERROR: setgroups failed\n");
1021 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
1022 /* pw is set if the user wants all the user's groups. */
1023 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
1024 rsyserr(FLOG, errno, "initgroups failed");
1025 io_printf(f_out, "@ERROR: initgroups failed\n");
1038 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
1039 io_printf(f_out, "@ERROR: setuid failed\n");
1044 am_root = (our_uid == ROOT_UID);
1047 if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
1048 tmpdir = lp_temp_dir(module_id);
1049 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
1051 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
1057 io_printf(f_out, "@RSYNCD: OK\n");
1059 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
1062 save_munge_symlinks = munge_symlinks;
1064 reset_output_levels(); /* future verbosity is controlled by client options */
1065 ret = parse_arguments(&argc, (const char ***) &argv);
1066 if (protect_args && ret) {
1067 orig_early_argv = orig_argv;
1069 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
1071 ret = parse_arguments(&argc, (const char ***) &argv);
1073 orig_early_argv = NULL;
1075 /* The default is to use the user's setting unless the module sets True or False. */
1076 if (lp_open_noatime(module_id) >= 0)
1077 open_noatime = lp_open_noatime(module_id);
1079 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
1082 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
1085 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1086 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1090 write_pre_exec_args(namecvt_fd_req, request, orig_early_argv, orig_argv, 2);
1092 if (orig_early_argv)
1093 free(orig_early_argv);
1095 am_server = 1; /* Don't let someone try to be tricky. */
1097 if (lp_ignore_errors(module_id))
1099 if (write_batch < 0)
1102 if (lp_fake_super(module_id)) {
1103 if (preserve_xattrs > 1)
1104 preserve_xattrs = 1;
1106 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1109 if (filesfrom_fd == 0)
1110 filesfrom_fd = f_in;
1114 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1115 am_sender ? "on" : "to",
1116 request, auth_user, host, addr);
1118 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1119 am_sender ? "on" : "to",
1120 request, host, addr);
1126 /* don't allow the logs to be flooded too fast */
1127 limit_output_verbosity(lp_max_verbosity(module_id));
1130 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1131 io_start_multiplex_out(f_out);
1132 else if (!ret || err_msg) {
1133 /* We have to get I/O multiplexing started so that we can
1134 * get the error back to the client. This means getting
1135 * the protocol setup finished first in later versions. */
1136 setup_protocol(f_out, f_in);
1138 /* Since we failed in our option parsing, we may not
1139 * have finished parsing that the client sent us a
1140 * --files-from option, so look for it manually.
1141 * Without this, the socket would be in the wrong
1142 * state for the upcoming error message. */
1145 for (i = 0; i < argc; i++) {
1146 if (strncmp(argv[i], "--files-from", 12) == 0) {
1153 write_byte(f_out, 0);
1155 io_start_multiplex_out(f_out);
1158 if (!ret || err_msg) {
1160 while ((p = strchr(err_msg, '\n')) != NULL) {
1161 int len = p - err_msg + 1;
1162 rwrite(FERROR, err_msg, len, 0);
1166 rprintf(FERROR, "%s\n", err_msg);
1167 io_flush(MSG_FLUSH);
1171 exit_cleanup(RERR_UNSUPPORTED);
1176 if (ic_send != (iconv_t)-1) {
1177 iconv_close(ic_send);
1178 ic_send = (iconv_t)-1;
1180 if (ic_recv != (iconv_t)-1) {
1181 iconv_close(ic_recv);
1182 ic_recv = (iconv_t)-1;
1188 && (use_chroot ? lp_numeric_ids(module_id) != False && !*lp_name_converter(module_id)
1189 : lp_numeric_ids(module_id) == True))
1190 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1192 if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1193 set_io_timeout(lp_timeout(module_id));
1195 /* If we have some incoming/outgoing chmod changes, append them to
1196 * any user-specified changes (making our changes have priority).
1197 * We also get a pointer to just our changes so that a receiver
1198 * process can use them separately if --perms wasn't specified. */
1200 p = lp_outgoing_chmod(module_id);
1202 p = lp_incoming_chmod(module_id);
1203 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1204 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1205 am_sender ? "outgo" : "incom", p);
1208 start_server(f_in, f_out, argc, argv);
1213 BOOL namecvt_call(const char *cmd, const char **name_p, id_t *id_p)
1219 len = snprintf(buf, sizeof buf, "%s %s\n", cmd, *name_p);
1221 len = snprintf(buf, sizeof buf, "%s %ld\n", cmd, (long)*id_p);
1222 if (len >= (int)sizeof buf) {
1223 rprintf(FERROR, "namecvt_call() request was too large.\n");
1224 exit_cleanup(RERR_UNSUPPORTED);
1227 while ((got = write(namecvt_fd_req, buf, len)) != len) {
1228 if (got < 0 && errno == EINTR)
1230 rprintf(FERROR, "Connection to name-converter failed.\n");
1231 exit_cleanup(RERR_SOCKETIO);
1234 if (!read_line_old(namecvt_fd_ans, buf, sizeof buf, 0))
1238 *id_p = (id_t)atol(buf);
1240 *name_p = strdup(buf);
1245 /* send a list of available modules to the client. Don't list those
1246 with "list = False". */
1247 static void send_listing(int fd)
1249 int n = lp_num_modules();
1252 for (i = 0; i < n; i++) {
1254 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1257 if (protocol_version >= 25)
1258 io_printf(fd,"@RSYNCD: EXIT\n");
1261 static int load_config(int globals_only)
1264 if (am_daemon < 0 && am_root <= 0)
1265 config_file = RSYNCD_USERCONF;
1267 config_file = RSYNCD_SYSCONF;
1269 return lp_load(config_file, globals_only);
1272 /* this is called when a connection is established to a client
1273 and we want to start talking. The setup of the system is done from
1275 int start_daemon(int f_in, int f_out)
1278 const char *addr, *host;
1282 /* At this point, am_server is only set for a daemon started via rsh.
1283 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1284 * a flag that can be checked later on to distinguish a normal daemon
1285 * from an rsh-run daemon. */
1289 io_set_sock_fds(f_in, f_out);
1291 /* We must load the config file before calling any function that
1292 * might cause log-file output to occur. This ensures that the
1293 * "log file" param gets honored for the 2 non-forked use-cases
1294 * (when rsync is run by init and run by a remote shell). */
1295 if (!load_config(0))
1296 exit_cleanup(RERR_SYNTAX);
1298 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1301 p = lp_daemon_chroot();
1303 log_init(0); /* Make use we've initialized syslog before chrooting. */
1304 if (chroot(p) < 0) {
1305 rsyserr(FLOG, errno, "daemon chroot(\"%s\") failed", p);
1308 if (chdir("/") < 0) {
1309 rsyserr(FLOG, errno, "daemon chdir(\"/\") failed");
1313 p = lp_daemon_gid();
1316 if (!group_to_gid(p, &gid, True)) {
1317 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1320 if (setgid(gid) < 0) {
1321 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1326 p = lp_daemon_uid();
1329 if (!user_to_uid(p, &uid, True)) {
1330 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1333 if (setuid(uid) < 0) {
1334 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1338 am_root = (our_uid == ROOT_UID);
1341 addr = client_addr(f_in);
1342 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1343 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1345 if (am_daemon > 0) {
1346 set_socket_options(f_in, "SO_KEEPALIVE");
1347 set_nonblocking(f_in);
1350 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1354 if (!read_line_old(f_in, line, sizeof line, 0))
1357 if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1358 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1359 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1360 io_printf(f_out, "@ERROR: invalid early_input length\n");
1363 early_input = new_array(char, early_input_len);
1364 read_buf(f_in, early_input, early_input_len);
1366 if (!read_line_old(f_in, line, sizeof line, 0))
1370 if (!*line || strcmp(line, "#list") == 0) {
1371 rprintf(FLOG, "module-list request from %s (%s)\n",
1373 send_listing(f_out);
1378 /* it's some sort of command that I don't understand */
1379 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1383 if ((i = lp_number(line)) < 0) {
1384 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1386 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1390 #ifdef HAVE_SIGACTION
1391 sigact.sa_flags = SA_NOCLDSTOP;
1393 SIGACTION(SIGCHLD, remember_children);
1395 return rsync_module(f_in, f_out, i, addr, host);
1398 static void create_pid_file(void)
1400 char *pid_file = lp_pid_file();
1402 STRUCT_STAT st1, st2;
1405 if (!pid_file || !*pid_file)
1409 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1411 #define SAFE_OPEN_FLAGS (O_CREAT)
1414 /* These tests make sure that a temp-style lock dir is handled safely. */
1416 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1418 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1419 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1420 else if (!lock_range(pid_file_fd, 0, 4))
1422 else if (do_fstat(pid_file_fd, &st1) < 0)
1423 fail = "fstat opened";
1424 else if (st1.st_size > (int)sizeof pidbuf)
1425 fail = "find small";
1426 else if (do_lstat(pid_file, &st2) < 0)
1428 else if (!S_ISREG(st1.st_mode))
1429 fail = "avoid file overwrite race for";
1430 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1431 fail = "verify stat info for";
1432 #ifdef HAVE_FTRUNCATE
1433 else if (do_ftruncate(pid_file_fd, 0) < 0)
1437 pid_t pid = getpid();
1438 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1439 #ifndef HAVE_FTRUNCATE
1440 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1441 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1442 pidbuf[len++] = '\n';
1443 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1445 if (write(pid_file_fd, pidbuf, len) != len)
1447 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1452 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1453 fail, pid_file, strerror(errno));
1455 rprintf(FLOG, "%s", msg);
1456 exit_cleanup(RERR_FILEIO);
1459 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1462 /* Become a daemon, discarding the controlling terminal. */
1463 static void become_daemon(void)
1470 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1471 exit_cleanup(RERR_FILEIO);
1478 /* detach from the terminal */
1481 #elif defined TIOCNOTTY
1482 i = open("/dev/tty", O_RDWR);
1484 ioctl(i, (int)TIOCNOTTY, (char *)0);
1488 /* make sure that stdin, stdout an stderr don't stuff things
1489 * up (library functions, for example) */
1490 for (i = 0; i < 3; i++) {
1492 open("/dev/null", O_RDWR);
1496 int daemon_main(void)
1498 if (is_a_socket(STDIN_FILENO)) {
1501 /* we are running via inetd - close off stdout and
1502 * stderr so that library functions (and getopt) don't
1503 * try to use them. Redirect them to /dev/null */
1504 for (i = 1; i < 3; i++) {
1506 open("/dev/null", O_RDWR);
1509 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1512 if (!load_config(1)) {
1513 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1514 exit_cleanup(RERR_SYNTAX);
1523 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1524 rsync_port = RSYNC_PORT;
1525 if (bind_address == NULL && *lp_bind_address())
1526 bind_address = lp_bind_address();
1530 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1531 rsync_version(), rsync_port);
1532 /* TODO: If listening on a particular address, then show that
1533 * address too. In fact, why not just do getnameinfo on the
1534 * local address??? */
1536 start_accept_loop(rsync_port, start_daemon);