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, 2003, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
27 extern int output_motd;
33 extern int rsync_port;
34 extern int ignore_errors;
35 extern int kluge_around_eof;
36 extern int daemon_over_rsh;
37 extern int sanitize_paths;
38 extern int filesfrom_fd;
39 extern int remote_protocol;
40 extern int protocol_version;
41 extern int io_timeout;
43 extern int default_af_hint;
44 extern int logfile_format_has_i;
45 extern int logfile_format_has_o_or_i;
46 extern mode_t orig_umask;
47 extern char *bind_address;
48 extern char *sockopts;
49 extern char *config_file;
50 extern char *logfile_format;
51 extern char *files_from;
53 extern struct chmod_mode_struct *chmod_modes;
54 extern struct filter_list_struct server_filter_list;
59 struct chmod_mode_struct *daemon_chmod_modes;
61 /* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
62 unsigned int module_dirlen = 0;
65 static struct sigaction sigact;
69 * Run a client connected to an rsyncd. The alternative to this
70 * function for remote-shell connections is do_cmd().
72 * After negotiating which module to use and reading the server's
73 * motd, this hands over to client_run(). Telling the server the
74 * module will cause it to chroot/setuid/etc.
76 * Instead of doing a transfer, the client may at this stage instead
77 * get a listing of remote modules and exit.
79 * @return -1 for error in startup, or the result of client_run().
80 * Either way, it eventually gets passed to exit_cleanup().
82 int start_socket_client(char *host, char *path, int argc, char *argv[])
85 char *p, *user = NULL;
87 /* This is redundant with code in start_inband_exchange(), but this
88 * short-circuits a problem in the client before we open a socket,
89 * and the extra check won't hurt. */
92 "ERROR: The remote path must start with a module name not a /\n");
96 if ((p = strrchr(host, '@')) != NULL) {
102 fd = open_socket_out_wrapped(host, rsync_port, bind_address,
105 exit_cleanup(RERR_SOCKETIO);
107 set_socket_options(fd, sockopts);
109 ret = start_inband_exchange(user, path, fd, fd, argc);
111 return ret ? ret : client_run(fd, fd, -1, argc, argv);
114 int start_inband_exchange(const char *user, char *path, int f_in, int f_out,
118 char *sargs[MAX_ARGS];
120 char line[BIGPATHBUFLEN];
123 if (argc == 0 && !am_sender)
128 "ERROR: The remote path must start with a module name\n");
133 user = getenv("USER");
135 user = getenv("LOGNAME");
137 io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
139 if (!read_line(f_in, line, sizeof line - 1)) {
140 rprintf(FERROR, "rsync: did not see server greeting\n");
144 if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
145 /* note that read_line strips of \n or \r */
146 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
150 if (protocol_version > remote_protocol)
151 protocol_version = remote_protocol;
153 if (list_only && protocol_version >= 29)
156 /* set daemon_over_rsh to false since we need to build the
157 * true set of args passed through the rsh/ssh connection;
158 * this is a no-op for direct-socket-connection mode */
160 server_options(sargs, &sargc);
162 sargs[sargc++] = ".";
165 sargs[sargc++] = path;
170 print_child_argv(sargs);
172 p = strchr(path,'/');
174 io_printf(f_out, "%s\n", path);
177 /* Old servers may just drop the connection here,
178 rather than sending a proper EXIT command. Yuck. */
179 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
182 if (!read_line(f_in, line, sizeof line - 1)) {
183 rprintf(FERROR, "rsync: didn't get server startup line\n");
187 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
188 auth_client(f_out, user, line+18);
192 if (strcmp(line,"@RSYNCD: OK") == 0)
195 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
196 /* This is sent by recent versions of the
197 * server to terminate the listing of modules.
198 * We don't want to go on and transfer
199 * anything; just exit. */
203 if (strncmp(line, "@ERROR", 6) == 0) {
204 rprintf(FERROR, "%s\n", line);
205 /* This is always fatal; the server will now
206 * close the socket. */
210 /* This might be a MOTD line or a module listing, but there is
211 * no way to differentiate it. The manpage mentions this. */
213 rprintf(FINFO, "%s\n", line);
215 kluge_around_eof = 0;
217 for (i = 0; i < sargc; i++) {
218 io_printf(f_out, "%s\n", sargs[i]);
220 io_printf(f_out, "\n");
222 if (protocol_version < 23) {
223 if (protocol_version == 22 || !am_sender)
224 io_start_multiplex_in();
230 static char *finish_pre_exec(pid_t pid, int fd, char *request,
231 int argc, char *argv[])
236 write_buf(fd, request, strlen(request)+1);
237 for (j = 0; j < argc; j++)
238 write_buf(fd, argv[j], strlen(argv[j])+1);
245 if (wait_process(pid, &status, 0) < 0
246 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
248 if (asprintf(&e, "pre-xfer exec returned failure (%d)%s%s\n",
249 status, status < 0 ? ": " : "",
250 status < 0 ? strerror(errno) : "") < 0)
251 out_of_memory("finish_pre_exec");
257 static int read_arg_from_pipe(int fd, char *buf, int limit)
259 char *bp = buf, *eob = buf + limit - 1;
262 if (read(fd, bp, 1) != 1)
274 static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
279 char line[BIGPATHBUFLEN];
280 uid_t uid = (uid_t)-2; /* canonically "nobody" */
281 gid_t gid = (gid_t)-2;
282 char *p, *err_msg = NULL;
283 char *name = lp_name(i);
284 int use_chroot = lp_use_chroot(i);
286 int ret, pre_exec_fd = -1;
287 pid_t pre_exec_pid = 0;
288 char *request = NULL;
290 if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
291 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
294 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
297 "@ERROR: access denied to %s from %s (%s)\n",
303 if (am_daemon && am_server) {
304 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
308 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
310 rsyserr(FLOG, errno, "failed to open lock file %s",
312 io_printf(f_out, "@ERROR: failed to open lock file\n");
314 rprintf(FLOG, "max connections (%d) reached\n",
315 lp_max_connections(i));
316 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
317 lp_max_connections(i));
322 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
325 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
334 if (lp_transfer_logging(i) && !logfile_format)
335 logfile_format = lp_log_format(i);
336 if (log_format_has(logfile_format, 'i'))
337 logfile_format_has_i = 1;
338 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
339 logfile_format_has_o_or_i = 1;
341 am_root = (MY_UID() == 0);
345 if (!name_to_uid(p, &uid)) {
347 rprintf(FLOG, "Invalid uid %s\n", p);
348 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
355 if (!name_to_gid(p, &gid)) {
357 rprintf(FLOG, "Invalid gid %s\n", p);
358 io_printf(f_out, "@ERROR: invalid gid %s\n", p);
365 /* TODO: If we're not root, but the configuration requests
366 * that we change to some uid other than the current one, then
369 /* TODO: Perhaps take a list of gids, and make them into the
370 * supplementary groups. */
372 if (use_chroot || (module_dirlen = strlen(lp_path(i))) == 1) {
374 set_filter_dir("/", 1);
376 set_filter_dir(lp_path(i), module_dirlen);
379 parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
382 p = lp_include_from(i);
383 parse_filter_file(&server_filter_list, p, MATCHFLG_INCLUDE,
384 XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
387 parse_rule(&server_filter_list, p,
388 MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
389 XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
391 p = lp_exclude_from(i);
392 parse_filter_file(&server_filter_list, p, 0,
393 XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
396 parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
397 XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
402 if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
403 char *modname, *modpath, *hostaddr, *hostname, *username;
405 if (asprintf(&modname, "RSYNC_MODULE_NAME=%s", name) < 0
406 || asprintf(&modpath, "RSYNC_MODULE_PATH=%s", lp_path(i)) < 0
407 || asprintf(&hostaddr, "RSYNC_HOST_ADDR=%s", addr) < 0
408 || asprintf(&hostname, "RSYNC_HOST_NAME=%s", host) < 0
409 || asprintf(&username, "RSYNC_USER_NAME=%s", auth_user) < 0)
410 out_of_memory("rsync_module");
417 /* For post-xfer exec, fork a new process to run the rsync
418 * daemon while this process waits for the exit status and
419 * runs the indicated command at that point. */
420 if (*lp_postxfer_exec(i)) {
423 rsyserr(FLOG, errno, "fork failed");
424 io_printf(f_out, "@ERROR: fork failed\n");
428 if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
430 if (wait_process(pid, &status, 0) < 0)
432 if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
434 if (WIFEXITED(status))
435 status = WEXITSTATUS(status);
438 if (asprintf(&p, "RSYNC_EXIT_STATUS=%d", status) > 0)
440 system(lp_postxfer_exec(i));
444 /* For pre-xfer exec, fork a child process to run the indicated
445 * command, though it first waits for the parent process to
446 * send us the user's request via a pipe. */
447 if (*lp_prexfer_exec(i)) {
449 if (asprintf(&p, "RSYNC_PID=%ld", (long)getpid()) > 0)
451 if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
452 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
453 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
456 if (pre_exec_pid == 0) {
457 char buf[BIGPATHBUFLEN];
460 set_blocking(fds[0]);
461 len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
464 if (asprintf(&p, "RSYNC_REQUEST=%s", buf) > 0)
467 len = read_arg_from_pipe(fds[0], buf,
474 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) > 0)
479 close(STDOUT_FILENO);
480 status = system(lp_prexfer_exec(i));
481 if (!WIFEXITED(status))
483 _exit(WEXITSTATUS(status));
486 set_blocking(fds[1]);
487 pre_exec_fd = fds[1];
495 * XXX: The 'use chroot' flag is a fairly reliable
496 * source of confusion, because it fails under two
497 * important circumstances: running as non-root,
498 * running on Win32 (or possibly others). On the
499 * other hand, if you are running as root, then it
500 * might be better to always use chroot.
502 * So, perhaps if we can't chroot we should just issue
503 * a warning, unless a "require chroot" flag is set,
504 * in which case we fail.
506 if (chroot(lp_path(i))) {
507 rsyserr(FLOG, errno, "chroot %s failed",
509 io_printf(f_out, "@ERROR: chroot failed\n");
513 if (!push_dir("/", 0)) {
514 rsyserr(FLOG, errno, "chdir %s failed\n",
516 io_printf(f_out, "@ERROR: chdir failed\n");
521 if (!push_dir(lp_path(i), 0)) {
522 rsyserr(FLOG, errno, "chdir %s failed\n",
524 io_printf(f_out, "@ERROR: chdir failed\n");
531 /* XXXX: You could argue that if the daemon is started
532 * by a non-root user and they explicitly specify a
533 * gid, then we should try to change to that gid --
534 * this could be possible if it's already in their
535 * supplementary groups. */
537 /* TODO: Perhaps we need to document that if rsyncd is
538 * started by somebody other than root it will inherit
539 * all their supplementary groups. */
542 rsyserr(FLOG, errno, "setgid %d failed", (int)gid);
543 io_printf(f_out, "@ERROR: setgid failed\n");
546 #ifdef HAVE_SETGROUPS
547 /* Get rid of any supplementary groups this process
548 * might have inheristed. */
549 if (setgroups(1, &gid)) {
550 rsyserr(FLOG, errno, "setgroups failed");
551 io_printf(f_out, "@ERROR: setgroups failed\n");
557 rsyserr(FLOG, errno, "setuid %d failed", (int)uid);
558 io_printf(f_out, "@ERROR: setuid failed\n");
562 am_root = (MY_UID() == 0);
565 if (lp_temp_dir(i) && *lp_temp_dir(i)) {
566 tmpdir = lp_temp_dir(i);
567 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
569 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
575 io_printf(f_out, "@RSYNCD: OK\n");
578 if (!(argv = new_array(char *, maxargs)))
579 out_of_memory("rsync_module");
580 argv[argc++] = "rsyncd";
583 if (!read_line(f_in, line, sizeof line - 1))
591 if (argc == maxargs) {
593 if (!(argv = realloc_array(argv, char *, maxargs)))
594 out_of_memory("rsync_module");
596 if (!(argv[argc] = strdup(p)))
597 out_of_memory("rsync_module");
599 switch (start_glob) {
602 if (strcmp(line, ".") == 0)
607 err_msg = finish_pre_exec(pre_exec_pid,
617 glob_expand(name, &argv, &argc, &maxargs);
623 err_msg = finish_pre_exec(pre_exec_pid, pre_exec_fd, request,
627 verbose = 0; /* future verbosity is controlled by client options */
628 ret = parse_arguments(&argc, (const char ***) &argv, 0);
629 quiet = 0; /* Don't let someone try to be tricky. */
630 if (lp_ignore_errors(module_id))
633 if (filesfrom_fd == 0)
638 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
639 am_sender ? "on" : "to",
640 request, auth_user, host, addr);
642 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
643 am_sender ? "on" : "to",
644 request, host, addr);
650 /* don't allow the logs to be flooded too fast */
651 if (verbose > lp_max_verbosity(i))
652 verbose = lp_max_verbosity(i);
655 if (protocol_version < 23
656 && (protocol_version == 22 || am_sender))
657 io_start_multiplex_out();
658 else if (!ret || err_msg) {
659 /* We have to get I/O multiplexing started so that we can
660 * get the error back to the client. This means getting
661 * the protocol setup finished first in later versions. */
662 setup_protocol(f_out, f_in);
664 /* Since we failed in our option parsing, we may not
665 * have finished parsing that the client sent us a
666 * --files-from option, so look for it manually.
667 * Without this, the socket would be in the wrong
668 * state for the upcoming error message. */
671 for (i = 0; i < argc; i++) {
672 if (strncmp(argv[i], "--files-from", 12) == 0) {
679 write_byte(f_out, 0);
681 io_start_multiplex_out();
684 if (!ret || err_msg) {
686 rwrite(FERROR, err_msg, strlen(err_msg));
690 exit_cleanup(RERR_UNSUPPORTED);
693 if (lp_timeout(i) && lp_timeout(i) > io_timeout)
694 set_io_timeout(lp_timeout(i));
696 /* If we have some incoming/outgoing chmod changes, append them to
697 * any user-specified changes (making our changes have priority).
698 * We also get a pointer to just our changes so that a receiver
699 * process can use them separately if --perms wasn't specified. */
701 p = lp_outgoing_chmod(i);
703 p = lp_incoming_chmod(i);
704 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
705 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
706 am_sender ? "outgo" : "incom", p);
709 start_server(f_in, f_out, argc, argv);
714 /* send a list of available modules to the client. Don't list those
715 with "list = False". */
716 static void send_listing(int fd)
718 int n = lp_numservices();
721 for (i = 0; i < n; i++) {
723 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
726 if (protocol_version >= 25)
727 io_printf(fd,"@RSYNCD: EXIT\n");
730 /* this is called when a connection is established to a client
731 and we want to start talking. The setup of the system is done from
733 int start_daemon(int f_in, int f_out)
736 char *motd, *addr, *host;
739 io_set_sock_fds(f_in, f_out);
741 /* We must load the config file before calling any function that
742 * might cause log-file output to occur. This ensures that the
743 * "log file" param gets honored for the 2 non-forked use-cases
744 * (when rsync is run by init and run by a remote shell). */
745 if (!lp_load(config_file, 0))
746 exit_cleanup(RERR_SYNTAX);
748 addr = client_addr(f_in);
749 host = client_name(f_in);
750 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
753 set_socket_options(f_in, "SO_KEEPALIVE");
755 set_socket_options(f_in, sockopts);
757 set_socket_options(f_in, lp_socket_options());
758 set_nonblocking(f_in);
761 io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
763 motd = lp_motd_file();
765 FILE *f = fopen(motd,"r");
766 while (f && !feof(f)) {
767 int len = fread(line, 1, sizeof line - 1, f);
770 io_printf(f_out, "%s", line);
775 io_printf(f_out, "\n");
778 if (!read_line(f_in, line, sizeof line - 1))
781 if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
782 io_printf(f_out, "@ERROR: protocol startup error\n");
785 if (protocol_version > remote_protocol)
786 protocol_version = remote_protocol;
789 if (!read_line(f_in, line, sizeof line - 1))
792 if (!*line || strcmp(line, "#list") == 0) {
793 rprintf(FLOG, "module-list request from %s (%s)\n",
800 /* it's some sort of command that I don't understand */
801 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
805 if ((i = lp_number(line)) < 0) {
806 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
808 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
812 #ifdef HAVE_SIGACTION
813 sigact.sa_flags = SA_NOCLDSTOP;
815 SIGACTION(SIGCHLD, remember_children);
817 return rsync_module(f_in, f_out, i, addr, host);
820 int daemon_main(void)
824 if (is_a_socket(STDIN_FILENO)) {
827 /* we are running via inetd - close off stdout and
828 * stderr so that library functions (and getopt) don't
829 * try to use them. Redirect them to /dev/null */
830 for (i = 1; i < 3; i++) {
832 open("/dev/null", O_RDWR);
835 return start_daemon(STDIN_FILENO, STDIN_FILENO);
841 if (!lp_load(config_file, 1))
842 exit_cleanup(RERR_SYNTAX);
844 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
845 rsync_port = RSYNC_PORT;
846 if (bind_address == NULL && *lp_bind_address())
847 bind_address = lp_bind_address();
851 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
852 RSYNC_VERSION, rsync_port);
853 /* TODO: If listening on a particular address, then show that
854 * address too. In fact, why not just do inet_ntop on the
855 * local address??? */
857 if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
860 pid_t pid = getpid();
861 cleanup_set_pid(pid);
862 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
863 0666 & ~orig_umask)) == -1) {
865 rsyserr(FLOG, errno, "failed to create pid file %s",
867 exit_cleanup(RERR_FILEIO);
869 snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
870 write(fd, pidbuf, strlen(pidbuf));
874 start_accept_loop(rsync_port, start_daemon);