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 char *early_input_file
;
58 extern struct chmod_mode_struct
*chmod_modes
;
59 extern filter_rule_list daemon_filter_list
;
61 extern char *iconv_opt
;
62 extern iconv_t ic_send
, ic_recv
;
71 int early_input_len
= 0;
72 char *early_input
= NULL
;
73 struct chmod_mode_struct
*daemon_chmod_modes
;
75 #define EARLY_INPUT_CMD "#early_input="
76 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
78 /* module_dirlen is the length of the module_dir string when in daemon
79 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
80 * enabled module can have a non-"/" module_dir these days.) */
81 char *module_dir
= NULL
;
82 unsigned int module_dirlen
= 0;
84 char *full_module_path
;
86 static int rl_nulls
= 0;
89 static struct sigaction sigact
;
92 static item_list gid_list
= EMPTY_ITEM_LIST
;
94 /* Used when "reverse lookup" is off. */
95 const char undetermined_hostname
[] = "UNDETERMINED";
98 * Run a client connected to an rsyncd. The alternative to this
99 * function for remote-shell connections is do_cmd().
101 * After negotiating which module to use and reading the server's
102 * motd, this hands over to client_run(). Telling the server the
103 * module will cause it to chroot/setuid/etc.
105 * Instead of doing a transfer, the client may at this stage instead
106 * get a listing of remote modules and exit.
108 * @return -1 for error in startup, or the result of client_run().
109 * Either way, it eventually gets passed to exit_cleanup().
111 int start_socket_client(char *host
, int remote_argc
, char *remote_argv
[],
112 int argc
, char *argv
[])
115 char *p
, *user
= NULL
;
117 /* This is redundant with code in start_inband_exchange(), but this
118 * short-circuits a problem in the client before we open a socket,
119 * and the extra check won't hurt. */
120 if (**remote_argv
== '/') {
122 "ERROR: The remote path must start with a module name not a /\n");
126 if ((p
= strrchr(host
, '@')) != NULL
) {
132 fd
= open_socket_out_wrapped(host
, rsync_port
, bind_address
, default_af_hint
);
134 exit_cleanup(RERR_SOCKETIO
);
140 ret
= start_inband_exchange(fd
, fd
, user
, remote_argc
, remote_argv
);
142 return ret
? ret
: client_run(fd
, fd
, -1, argc
, argv
);
145 static int exchange_protocols(int f_in
, int f_out
, char *buf
, size_t bufsiz
, int am_client
)
148 #if SUBPROTOCOL_VERSION != 0
149 int our_sub
= protocol_version
< PROTOCOL_VERSION
? 0 : SUBPROTOCOL_VERSION
;
154 io_printf(f_out
, "@RSYNCD: %d.%d\n", protocol_version
, our_sub
);
156 char *motd
= lp_motd_file();
158 FILE *f
= fopen(motd
, "r");
159 while (f
&& !feof(f
)) {
160 int len
= fread(buf
, 1, bufsiz
- 1, f
);
162 write_buf(f_out
, buf
, len
);
166 write_sbuf(f_out
, "\n");
170 /* This strips the \n. */
171 if (!read_line_old(f_in
, buf
, bufsiz
, 0)) {
173 rprintf(FERROR
, "rsync: did not see server greeting\n");
177 if (sscanf(buf
, "@RSYNCD: %d.%d", &remote_protocol
, &remote_sub
) < 1) {
179 rprintf(FERROR
, "rsync: server sent \"%s\" rather than greeting\n", buf
);
181 io_printf(f_out
, "@ERROR: protocol startup error\n");
185 if (remote_sub
< 0) {
186 if (remote_protocol
== 30) {
188 rprintf(FERROR
, "rsync: server is speaking an incompatible beta of protocol 30\n");
190 io_printf(f_out
, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
196 if (protocol_version
> remote_protocol
) {
197 protocol_version
= remote_protocol
;
200 } else if (protocol_version
== remote_protocol
) {
201 if (remote_sub
!= our_sub
)
204 #if SUBPROTOCOL_VERSION != 0
205 else if (protocol_version
< remote_protocol
) {
211 if (protocol_version
>= 30)
217 int start_inband_exchange(int f_in
, int f_out
, const char *user
, int argc
, char *argv
[])
220 char line
[BIGPATHBUFLEN
];
221 char *sargs
[MAX_ARGS
];
225 assert(argc
> 0 && *argv
!= NULL
);
229 "ERROR: The remote path must start with a module name\n");
233 if (!(p
= strchr(*argv
, '/')))
234 modlen
= strlen(*argv
);
238 if (!(modname
= new_array(char, modlen
+1+1))) /* room for '/' & '\0' */
239 out_of_memory("start_inband_exchange");
240 strlcpy(modname
, *argv
, modlen
+ 1);
241 modname
[modlen
] = '/';
242 modname
[modlen
+1] = '\0';
245 user
= getenv("USER");
247 user
= getenv("LOGNAME");
249 if (exchange_protocols(f_in
, f_out
, line
, sizeof line
, 1) < 0)
252 if (early_input_file
) {
254 FILE *f
= fopen(early_input_file
, "rb");
255 if (!f
|| do_fstat(fileno(f
), &st
) < 0) {
256 rsyserr(FERROR
, errno
, "failed to open %s", early_input_file
);
259 early_input_len
= st
.st_size
;
260 if (early_input_len
>= (int)sizeof line
) {
261 rprintf(FERROR
, "%s is >= %d bytes.\n", early_input_file
, (int)sizeof line
);
264 if (early_input_len
> 0) {
265 io_printf(f_out
, EARLY_INPUT_CMD
"%d\n", early_input_len
);
266 while (early_input_len
> 0) {
269 rprintf(FERROR
, "Early EOF in %s\n", early_input_file
);
272 len
= fread(line
, 1, early_input_len
/ 2 + 1, f
);
274 write_buf(f_out
, line
, len
);
275 early_input_len
-= len
;
282 /* set daemon_over_rsh to false since we need to build the
283 * true set of args passed through the rsh/ssh connection;
284 * this is a no-op for direct-socket-connection mode */
286 server_options(sargs
, &sargc
);
288 if (sargc
>= MAX_ARGS
- 2)
291 sargs
[sargc
++] = ".";
294 if (sargc
>= MAX_ARGS
- 1) {
296 rprintf(FERROR
, "internal: args[] overflowed in do_cmd()\n");
297 exit_cleanup(RERR_SYNTAX
);
299 if (strncmp(*argv
, modname
, modlen
) == 0
300 && argv
[0][modlen
] == '\0')
301 sargs
[sargc
++] = modname
; /* we send "modname/" */
302 else if (**argv
== '-') {
303 if (asprintf(sargs
+ sargc
++, "./%s", *argv
) < 0)
304 out_of_memory("start_inband_exchange");
306 sargs
[sargc
++] = *argv
;
313 if (DEBUG_GTE(CMD
, 1))
314 print_child_argv("sending daemon args:", sargs
);
316 io_printf(f_out
, "%.*s\n", modlen
, modname
);
318 /* Old servers may just drop the connection here,
319 rather than sending a proper EXIT command. Yuck. */
320 kluge_around_eof
= list_only
&& protocol_version
< 25 ? 1 : 0;
323 if (!read_line_old(f_in
, line
, sizeof line
, 0)) {
324 rprintf(FERROR
, "rsync: didn't get server startup line\n");
328 if (strncmp(line
,"@RSYNCD: AUTHREQD ",18) == 0) {
329 auth_client(f_out
, user
, line
+18);
333 if (strcmp(line
,"@RSYNCD: OK") == 0)
336 if (strcmp(line
,"@RSYNCD: EXIT") == 0) {
337 /* This is sent by recent versions of the
338 * server to terminate the listing of modules.
339 * We don't want to go on and transfer
340 * anything; just exit. */
344 if (strncmp(line
, "@ERROR", 6) == 0) {
345 rprintf(FERROR
, "%s\n", line
);
346 /* This is always fatal; the server will now
347 * close the socket. */
351 /* This might be a MOTD line or a module listing, but there is
352 * no way to differentiate it. The manpage mentions this. */
354 rprintf(FINFO
, "%s\n", line
);
356 kluge_around_eof
= 0;
359 for (i
= 0; i
< sargc
; i
++) {
360 if (!sargs
[i
]) /* stop at --protect-args NULL */
362 write_sbuf(f_out
, sargs
[i
]);
363 write_byte(f_out
, 0);
365 write_byte(f_out
, 0);
367 for (i
= 0; i
< sargc
; i
++)
368 io_printf(f_out
, "%s\n", sargs
[i
]);
369 write_sbuf(f_out
, "\n");
373 send_protected_args(f_out
, sargs
);
375 if (protocol_version
< 23) {
376 if (protocol_version
== 22 || !am_sender
)
377 io_start_multiplex_in(f_in
);
386 static int read_arg_from_pipe(int fd
, char *buf
, int limit
)
388 char *bp
= buf
, *eob
= buf
+ limit
- 1;
391 int got
= read(fd
, bp
, 1);
393 if (got
< 0 && errno
== EINTR
)
408 static void set_env_str(const char *var
, const char *str
)
412 if (asprintf(&mem
, "%s=%s", var
, str
) < 0)
413 out_of_memory("set_env_str");
419 void set_env_num(const char *var
, long num
)
422 if (asprintf(&mem
, "%s=%ld", var
, num
) < 0)
423 out_of_memory("set_env_num");
428 /* Used for both early exec & pre-xfer exec */
429 static pid_t
start_pre_exec(const char *cmd
, int *arg_fd_ptr
, int *error_fd_ptr
)
431 int arg_fds
[2], error_fds
[2], arg_fd
;
434 if ((error_fd_ptr
&& pipe(error_fds
) < 0) || pipe(arg_fds
) < 0 || (pid
= fork()) < 0)
438 char buf
[BIGPATHBUFLEN
];
443 set_blocking(error_fds
[1]);
448 set_blocking(arg_fd
);
450 len
= read_arg_from_pipe(arg_fd
, buf
, BIGPATHBUFLEN
);
453 set_env_str("RSYNC_REQUEST", buf
);
457 len
= read_arg_from_pipe(arg_fd
, buf
, BIGPATHBUFLEN
);
463 if (asprintf(&p
, "RSYNC_ARG%d=%s", j
, buf
) >= 0)
467 dup2(arg_fd
, STDIN_FILENO
);
471 dup2(error_fds
[1], STDOUT_FILENO
);
475 status
= shell_exec(cmd
);
477 if (!WIFEXITED(status
))
479 _exit(WEXITSTATUS(status
));
484 *error_fd_ptr
= error_fds
[0];
485 set_blocking(error_fds
[0]);
489 arg_fd
= *arg_fd_ptr
= arg_fds
[1];
490 set_blocking(arg_fd
);
495 static void write_pre_exec_args(int write_fd
, char *request
, char **early_argv
, char **argv
, int am_early
)
502 write_buf(write_fd
, request
, strlen(request
)+1);
504 for ( ; *early_argv
; early_argv
++)
505 write_buf(write_fd
, *early_argv
, strlen(*early_argv
)+1);
506 j
= 1; /* Skip arg0 name in argv. */
509 for ( ; argv
[j
]; j
++)
510 write_buf(write_fd
, argv
[j
], strlen(argv
[j
])+1);
512 write_byte(write_fd
, 0);
514 if (am_early
&& early_input_len
)
515 write_buf(write_fd
, early_input
, early_input_len
);
520 static char *finish_pre_exec(const char *desc
, pid_t pid
, int read_fd
)
522 char buf
[BIGPATHBUFLEN
], *bp
, *cr
;
523 int j
, status
= -1, msglen
= sizeof buf
- 1;
526 /* Read the stdout from the program. This it is only displayed
527 * to the user if the script also returns an error status. */
528 for (bp
= buf
, cr
= buf
; msglen
> 0; msglen
-= j
) {
529 if ((j
= read(read_fd
, bp
, msglen
)) <= 0) {
534 break; /* Just ignore the read error for now... */
538 if ((cr
= strchr(cr
, '\r')) == NULL
) {
543 break; /* wait for more data before we decide what to do */
545 memmove(cr
, cr
+1, j
- (cr
- bp
));
558 if (wait_process(pid
, &status
, 0) < 0
559 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
561 if (asprintf(&e
, "%s returned failure (%d)%s%s%s\n%s",
562 desc
, status
, status
< 0 ? ": " : "",
563 status
< 0 ? strerror(errno
) : "",
564 *buf
? ":" : "", buf
) < 0)
565 return "out_of_memory in finish_pre_exec\n";
571 static int path_failure(int f_out
, const char *dir
, BOOL was_chdir
)
574 rsyserr(FLOG
, errno
, "chdir %s failed", dir
);
576 rprintf(FLOG
, "normalize_path(%s) failed\n", dir
);
577 io_printf(f_out
, "@ERROR: chdir failed\n");
581 static int add_a_group(int f_out
, const char *gname
)
584 if (!group_to_gid(gname
, &gid
, True
)) {
585 rprintf(FLOG
, "Invalid gid %s\n", gname
);
586 io_printf(f_out
, "@ERROR: invalid gid %s\n", gname
);
589 gid_p
= EXPAND_ITEM_LIST(&gid_list
, gid_t
, -32);
594 #ifdef HAVE_GETGROUPLIST
595 static int want_all_groups(int f_out
, uid_t uid
)
598 if ((err
= getallgroups(uid
, &gid_list
)) != NULL
) {
599 rsyserr(FLOG
, errno
, "%s", err
);
600 io_printf(f_out
, "@ERROR: %s\n", err
);
605 #elif defined HAVE_INITGROUPS
606 static struct passwd
*want_all_groups(int f_out
, uid_t uid
)
610 if ((pw
= getpwuid(uid
)) == NULL
) {
611 rsyserr(FLOG
, errno
, "getpwuid failed");
612 io_printf(f_out
, "@ERROR: getpwuid failed\n");
615 /* Start with the default group and initgroups() will add the rest. */
616 gid_p
= EXPAND_ITEM_LIST(&gid_list
, gid_t
, -32);
622 static int rsync_module(int f_in
, int f_out
, int i
, const char *addr
, const char *host
)
625 char **argv
, **orig_argv
, **orig_early_argv
, *module_chdir
;
626 char line
[BIGPATHBUFLEN
];
627 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
628 struct passwd
*pw
= NULL
;
632 char *p
, *err_msg
= NULL
;
633 char *name
= lp_name(i
);
634 int use_chroot
= lp_use_chroot(i
);
635 int ret
, pre_exec_arg_fd
= -1, pre_exec_error_fd
= -1;
636 int save_munge_symlinks
;
637 pid_t pre_exec_pid
= 0;
638 char *request
= NULL
;
640 set_env_str("RSYNC_MODULE_NAME", name
);
643 iconv_opt
= lp_charset(i
);
649 /* If reverse lookup is disabled globally but enabled for this module,
650 * we need to do it now before the access check. */
651 if (host
== undetermined_hostname
&& lp_reverse_lookup(i
))
652 host
= client_name(client_addr(f_in
));
653 set_env_str("RSYNC_HOST_NAME", host
);
654 set_env_str("RSYNC_HOST_ADDR", addr
);
656 if (!allow_access(addr
, &host
, i
)) {
657 rprintf(FLOG
, "rsync denied on module %s from %s (%s)\n",
660 io_printf(f_out
, "@ERROR: Unknown module '%s'\n", name
);
663 "@ERROR: access denied to %s from %s (%s)\n",
670 rprintf(FLOG
, "rsync allowed access on module %s from %s (%s)\n",
674 if (!claim_connection(lp_lock_file(i
), lp_max_connections(i
))) {
676 rsyserr(FLOG
, errno
, "failed to open lock file %s",
678 io_printf(f_out
, "@ERROR: failed to open lock file\n");
680 rprintf(FLOG
, "max connections (%d) reached\n",
681 lp_max_connections(i
));
682 io_printf(f_out
, "@ERROR: max connections (%d) reached -- try again later\n",
683 lp_max_connections(i
));
688 read_only
= lp_read_only(i
); /* may also be overridden by auth_server() */
689 auth_user
= auth_server(f_in
, f_out
, i
, host
, addr
, "@RSYNCD: AUTHREQD ");
692 io_printf(f_out
, "@ERROR: auth failed on module %s\n", name
);
695 set_env_str("RSYNC_USER_NAME", auth_user
);
699 if (lp_transfer_logging(i
) && !logfile_format
)
700 logfile_format
= lp_log_format(i
);
701 if (log_format_has(logfile_format
, 'i'))
702 logfile_format_has_i
= 1;
703 if (logfile_format_has_i
|| log_format_has(logfile_format
, 'o'))
704 logfile_format_has_o_or_i
= 1;
707 am_root
= (uid
== 0);
709 p
= *lp_uid(i
) ? lp_uid(i
) : am_root
? NOBODY_USER
: NULL
;
711 if (!user_to_uid(p
, &uid
, True
)) {
712 rprintf(FLOG
, "Invalid uid %s\n", p
);
713 io_printf(f_out
, "@ERROR: invalid uid %s\n", p
);
720 p
= *lp_gid(i
) ? conf_strtok(lp_gid(i
)) : NULL
;
722 /* The "*" gid must be the first item in the list. */
723 if (strcmp(p
, "*") == 0) {
724 #ifdef HAVE_GETGROUPLIST
725 if (want_all_groups(f_out
, uid
) < 0)
727 #elif defined HAVE_INITGROUPS
728 if ((pw
= want_all_groups(f_out
, uid
)) == NULL
)
731 rprintf(FLOG
, "This rsync does not support a gid of \"*\"\n");
732 io_printf(f_out
, "@ERROR: invalid gid setting.\n");
735 } else if (add_a_group(f_out
, p
) < 0)
737 while ((p
= conf_strtok(NULL
)) != NULL
) {
738 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
740 rprintf(FLOG
, "This rsync cannot add groups after \"*\".\n");
741 io_printf(f_out
, "@ERROR: invalid gid setting.\n");
745 if (add_a_group(f_out
, p
) < 0)
748 } else if (am_root
) {
749 if (add_a_group(f_out
, NOBODY_GROUP
) < 0)
753 module_dir
= lp_path(i
);
754 if (*module_dir
== '\0') {
755 rprintf(FLOG
, "No path specified for module %s\n", name
);
756 io_printf(f_out
, "@ERROR: no path setting.\n");
760 if ((p
= strstr(module_dir
, "/./")) != NULL
) {
761 *p
= '\0'; /* Temporary... */
762 if (!(module_chdir
= normalize_path(module_dir
, True
, NULL
)))
763 return path_failure(f_out
, module_dir
, False
);
765 if (!(p
= normalize_path(p
+ 2, True
, &module_dirlen
)))
766 return path_failure(f_out
, strstr(module_dir
, "/./"), False
);
767 if (!(full_module_path
= normalize_path(module_dir
, False
, NULL
)))
768 full_module_path
= module_dir
;
771 if (!(module_chdir
= normalize_path(module_dir
, False
, NULL
)))
772 return path_failure(f_out
, module_dir
, False
);
773 full_module_path
= module_chdir
;
778 if (!(module_chdir
= normalize_path(module_dir
, False
, &module_dirlen
)))
779 return path_failure(f_out
, module_dir
, False
);
780 full_module_path
= module_dir
= module_chdir
;
782 set_env_str("RSYNC_MODULE_PATH", full_module_path
);
784 if (module_dirlen
== 1) {
786 set_filter_dir("/", 1);
788 set_filter_dir(module_dir
, module_dirlen
);
791 parse_filter_str(&daemon_filter_list
, p
, rule_template(FILTRULE_WORD_SPLIT
),
792 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
);
794 p
= lp_include_from(i
);
795 parse_filter_file(&daemon_filter_list
, p
, rule_template(FILTRULE_INCLUDE
),
796 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
| XFLG_FATAL_ERRORS
);
799 parse_filter_str(&daemon_filter_list
, p
,
800 rule_template(FILTRULE_INCLUDE
| FILTRULE_WORD_SPLIT
),
801 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
);
803 p
= lp_exclude_from(i
);
804 parse_filter_file(&daemon_filter_list
, p
, rule_template(0),
805 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
| XFLG_FATAL_ERRORS
);
808 parse_filter_str(&daemon_filter_list
, p
, rule_template(FILTRULE_WORD_SPLIT
),
809 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
);
814 if ((*lp_early_exec(i
) || *lp_prexfer_exec(i
) || *lp_postxfer_exec(i
))
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(i
)) {
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(i
)) < 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(i
)) {
851 pid_t pid
= start_pre_exec(lp_early_exec(i
), &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(i
)) {
869 pre_exec_pid
= start_pre_exec(lp_prexfer_exec(i
), &pre_exec_arg_fd
, &pre_exec_error_fd
);
870 if (pre_exec_pid
== (pid_t
)-1) {
871 rsyserr(FLOG
, errno
, "pre-xfer exec preparation failed");
872 io_printf(f_out
, "@ERROR: pre-xfer exec preparation failed\n");
886 * XXX: The 'use chroot' flag is a fairly reliable
887 * source of confusion, because it fails under two
888 * important circumstances: running as non-root,
889 * running on Win32 (or possibly others). On the
890 * other hand, if you are running as root, then it
891 * might be better to always use chroot.
893 * So, perhaps if we can't chroot we should just issue
894 * a warning, unless a "require chroot" flag is set,
895 * in which case we fail.
897 if (chroot(module_chdir
)) {
898 rsyserr(FLOG
, errno
, "chroot %s failed", module_chdir
);
899 io_printf(f_out
, "@ERROR: chroot failed\n");
902 module_chdir
= module_dir
;
905 if (!change_dir(module_chdir
, CD_NORMAL
))
906 return path_failure(f_out
, module_chdir
, True
);
907 if (module_dirlen
|| (!use_chroot
&& !*lp_daemon_chroot()))
910 if ((munge_symlinks
= lp_munge_symlinks(i
)) < 0)
911 munge_symlinks
= !use_chroot
|| module_dirlen
;
912 if (munge_symlinks
) {
914 char prefix
[SYMLINK_PREFIX_LEN
]; /* NOT +1 ! */
915 strlcpy(prefix
, SYMLINK_PREFIX
, sizeof prefix
); /* trim the trailing slash */
916 if (do_stat(prefix
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
917 rprintf(FLOG
, "Symlink munging is unsafe when a %s directory exists.\n",
919 io_printf(f_out
, "@ERROR: daemon security issue -- contact admin\n", name
);
920 exit_cleanup(RERR_UNSUPPORTED
);
924 if (gid_list
.count
) {
925 gid_t
*gid_array
= gid_list
.items
;
926 if (setgid(gid_array
[0])) {
927 rsyserr(FLOG
, errno
, "setgid %ld failed", (long)gid_array
[0]);
928 io_printf(f_out
, "@ERROR: setgid failed\n");
931 #ifdef HAVE_SETGROUPS
932 /* Set the group(s) we want to be active. */
933 if (setgroups(gid_list
.count
, gid_array
)) {
934 rsyserr(FLOG
, errno
, "setgroups failed");
935 io_printf(f_out
, "@ERROR: setgroups failed\n");
939 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
940 /* pw is set if the user wants all the user's groups. */
941 if (pw
&& initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
942 rsyserr(FLOG
, errno
, "initgroups failed");
943 io_printf(f_out
, "@ERROR: initgroups failed\n");
956 rsyserr(FLOG
, errno
, "setuid %ld failed", (long)uid
);
957 io_printf(f_out
, "@ERROR: setuid failed\n");
962 am_root
= (our_uid
== 0);
965 if (lp_temp_dir(i
) && *lp_temp_dir(i
)) {
966 tmpdir
= lp_temp_dir(i
);
967 if (strlen(tmpdir
) >= MAXPATHLEN
- 10) {
969 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
975 io_printf(f_out
, "@RSYNCD: OK\n");
977 read_args(f_in
, name
, line
, sizeof line
, rl_nulls
, &argv
, &argc
, &request
);
980 save_munge_symlinks
= munge_symlinks
;
982 reset_output_levels(); /* future verbosity is controlled by client options */
983 ret
= parse_arguments(&argc
, (const char ***) &argv
);
984 if (protect_args
&& ret
) {
985 orig_early_argv
= orig_argv
;
987 read_args(f_in
, name
, line
, sizeof line
, 1, &argv
, &argc
, &request
);
989 ret
= parse_arguments(&argc
, (const char ***) &argv
);
991 orig_early_argv
= NULL
;
993 munge_symlinks
= save_munge_symlinks
; /* The client mustn't control this. */
995 msgs2stderr
= 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
998 write_pre_exec_args(pre_exec_arg_fd
, request
, orig_early_argv
, orig_argv
, 0);
999 err_msg
= finish_pre_exec("pre-xfer exec", pre_exec_pid
, pre_exec_error_fd
);
1002 if (orig_early_argv
)
1003 free(orig_early_argv
);
1005 am_server
= 1; /* Don't let someone try to be tricky. */
1007 if (lp_ignore_errors(module_id
))
1009 if (write_batch
< 0)
1012 if (lp_fake_super(i
)) {
1013 if (preserve_xattrs
> 1)
1014 preserve_xattrs
= 1;
1016 } else if (am_root
< 0) /* Treat --fake-super from client as --super. */
1019 if (filesfrom_fd
== 0)
1020 filesfrom_fd
= f_in
;
1024 rprintf(FLOG
, "rsync %s %s from %s@%s (%s)\n",
1025 am_sender
? "on" : "to",
1026 request
, auth_user
, host
, addr
);
1028 rprintf(FLOG
, "rsync %s %s from %s (%s)\n",
1029 am_sender
? "on" : "to",
1030 request
, host
, addr
);
1036 /* don't allow the logs to be flooded too fast */
1037 limit_output_verbosity(lp_max_verbosity(i
));
1040 if (protocol_version
< 23 && (protocol_version
== 22 || am_sender
))
1041 io_start_multiplex_out(f_out
);
1042 else if (!ret
|| err_msg
) {
1043 /* We have to get I/O multiplexing started so that we can
1044 * get the error back to the client. This means getting
1045 * the protocol setup finished first in later versions. */
1046 setup_protocol(f_out
, f_in
);
1048 /* Since we failed in our option parsing, we may not
1049 * have finished parsing that the client sent us a
1050 * --files-from option, so look for it manually.
1051 * Without this, the socket would be in the wrong
1052 * state for the upcoming error message. */
1055 for (i
= 0; i
< argc
; i
++) {
1056 if (strncmp(argv
[i
], "--files-from", 12) == 0) {
1063 write_byte(f_out
, 0);
1065 io_start_multiplex_out(f_out
);
1068 if (!ret
|| err_msg
) {
1070 while ((p
= strchr(err_msg
, '\n')) != NULL
) {
1071 int len
= p
- err_msg
+ 1;
1072 rwrite(FERROR
, err_msg
, len
, 0);
1076 rprintf(FERROR
, "%s\n", err_msg
);
1077 io_flush(MSG_FLUSH
);
1081 exit_cleanup(RERR_UNSUPPORTED
);
1086 if (ic_send
!= (iconv_t
)-1) {
1087 iconv_close(ic_send
);
1088 ic_send
= (iconv_t
)-1;
1090 if (ic_recv
!= (iconv_t
)-1) {
1091 iconv_close(ic_recv
);
1092 ic_recv
= (iconv_t
)-1;
1098 && (use_chroot
? lp_numeric_ids(i
) != False
: lp_numeric_ids(i
) == True
))
1099 numeric_ids
= -1; /* Set --numeric-ids w/o breaking protocol. */
1101 if (lp_timeout(i
) && (!io_timeout
|| lp_timeout(i
) < io_timeout
))
1102 set_io_timeout(lp_timeout(i
));
1104 /* If we have some incoming/outgoing chmod changes, append them to
1105 * any user-specified changes (making our changes have priority).
1106 * We also get a pointer to just our changes so that a receiver
1107 * process can use them separately if --perms wasn't specified. */
1109 p
= lp_outgoing_chmod(i
);
1111 p
= lp_incoming_chmod(i
);
1112 if (*p
&& !(daemon_chmod_modes
= parse_chmod(p
, &chmod_modes
))) {
1113 rprintf(FLOG
, "Invalid \"%sing chmod\" directive: %s\n",
1114 am_sender
? "outgo" : "incom", p
);
1117 start_server(f_in
, f_out
, argc
, argv
);
1122 /* send a list of available modules to the client. Don't list those
1123 with "list = False". */
1124 static void send_listing(int fd
)
1126 int n
= lp_num_modules();
1129 for (i
= 0; i
< n
; i
++) {
1131 io_printf(fd
, "%-15s\t%s\n", lp_name(i
), lp_comment(i
));
1134 if (protocol_version
>= 25)
1135 io_printf(fd
,"@RSYNCD: EXIT\n");
1138 static int load_config(int globals_only
)
1141 if (am_daemon
< 0 && am_root
<= 0)
1142 config_file
= RSYNCD_USERCONF
;
1144 config_file
= RSYNCD_SYSCONF
;
1146 return lp_load(config_file
, globals_only
);
1149 /* this is called when a connection is established to a client
1150 and we want to start talking. The setup of the system is done from
1152 int start_daemon(int f_in
, int f_out
)
1155 const char *addr
, *host
;
1159 /* At this point, am_server is only set for a daemon started via rsh.
1160 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1161 * a flag that can be checked later on to distinguish a normal daemon
1162 * from an rsh-run daemon. */
1166 io_set_sock_fds(f_in
, f_out
);
1168 /* We must load the config file before calling any function that
1169 * might cause log-file output to occur. This ensures that the
1170 * "log file" param gets honored for the 2 non-forked use-cases
1171 * (when rsync is run by init and run by a remote shell). */
1172 if (!load_config(0))
1173 exit_cleanup(RERR_SYNTAX
);
1175 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in
))
1178 p
= lp_daemon_chroot();
1180 log_init(0); /* Make use we've initialized syslog before chrooting. */
1181 if (chroot(p
) < 0 || chdir("/") < 0) {
1182 rsyserr(FLOG
, errno
, "daemon chroot %s failed", p
);
1186 p
= lp_daemon_gid();
1189 if (!group_to_gid(p
, &gid
, True
)) {
1190 rprintf(FLOG
, "Invalid daemon gid: %s\n", p
);
1193 if (setgid(gid
) < 0) {
1194 rsyserr(FLOG
, errno
, "Unable to set group to daemon gid %ld", (long)gid
);
1199 p
= lp_daemon_uid();
1202 if (!user_to_uid(p
, &uid
, True
)) {
1203 rprintf(FLOG
, "Invalid daemon uid: %s\n", p
);
1206 if (setuid(uid
) < 0) {
1207 rsyserr(FLOG
, errno
, "Unable to set user to daemon uid %ld", (long)uid
);
1211 am_root
= (our_uid
== 0);
1214 addr
= client_addr(f_in
);
1215 host
= lp_reverse_lookup(-1) ? client_name(addr
) : undetermined_hostname
;
1216 rprintf(FLOG
, "connect from %s (%s)\n", host
, addr
);
1218 if (am_daemon
> 0) {
1219 set_socket_options(f_in
, "SO_KEEPALIVE");
1220 set_nonblocking(f_in
);
1223 if (exchange_protocols(f_in
, f_out
, line
, sizeof line
, 0) < 0)
1227 if (!read_line_old(f_in
, line
, sizeof line
, 0))
1230 if (strncmp(line
, EARLY_INPUT_CMD
, EARLY_INPUT_CMDLEN
) == 0) {
1231 early_input_len
= strtol(line
+ EARLY_INPUT_CMDLEN
, NULL
, 10);
1232 if (early_input_len
<= 0 || early_input_len
>= BIGPATHBUFLEN
) {
1233 io_printf(f_out
, "@ERROR: invalid early_input length\n");
1236 if (!(early_input
= new_array(char, early_input_len
)))
1237 out_of_memory("exchange_protocols");
1238 read_buf(f_in
, early_input
, early_input_len
);
1240 if (!read_line_old(f_in
, line
, sizeof line
, 0))
1244 if (!*line
|| strcmp(line
, "#list") == 0) {
1245 rprintf(FLOG
, "module-list request from %s (%s)\n",
1247 send_listing(f_out
);
1252 /* it's some sort of command that I don't understand */
1253 io_printf(f_out
, "@ERROR: Unknown command '%s'\n", line
);
1257 if ((i
= lp_number(line
)) < 0) {
1258 rprintf(FLOG
, "unknown module '%s' tried from %s (%s)\n",
1260 io_printf(f_out
, "@ERROR: Unknown module '%s'\n", line
);
1264 #ifdef HAVE_SIGACTION
1265 sigact
.sa_flags
= SA_NOCLDSTOP
;
1267 SIGACTION(SIGCHLD
, remember_children
);
1269 return rsync_module(f_in
, f_out
, i
, addr
, host
);
1272 static void create_pid_file(void)
1274 char *pid_file
= lp_pid_file();
1276 STRUCT_STAT st1
, st2
;
1279 if (!pid_file
|| !*pid_file
)
1283 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1285 #define SAFE_OPEN_FLAGS (O_CREAT)
1288 /* These tests make sure that a temp-style lock dir is handled safely. */
1290 if (do_lstat(pid_file
, &st1
) == 0 && !S_ISREG(st1
.st_mode
) && unlink(pid_file
) < 0)
1292 else if ((pid_file_fd
= do_open(pid_file
, O_RDWR
|SAFE_OPEN_FLAGS
, 0664)) < 0)
1293 fail
= S_ISREG(st1
.st_mode
) ? "open" : "create";
1294 else if (!lock_range(pid_file_fd
, 0, 4))
1296 else if (do_fstat(pid_file_fd
, &st1
) < 0)
1297 fail
= "fstat opened";
1298 else if (st1
.st_size
> (int)sizeof pidbuf
)
1299 fail
= "find small";
1300 else if (do_lstat(pid_file
, &st2
) < 0)
1302 else if (!S_ISREG(st1
.st_mode
))
1303 fail
= "avoid file overwrite race for";
1304 else if (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)
1305 fail
= "verify stat info for";
1306 #ifdef HAVE_FTRUNCATE
1307 else if (do_ftruncate(pid_file_fd
, 0) < 0)
1311 pid_t pid
= getpid();
1312 int len
= snprintf(pidbuf
, sizeof pidbuf
, "%d\n", (int)pid
);
1313 #ifndef HAVE_FTRUNCATE
1314 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1315 while (len
< st1
.st_size
) /* We already verified that st_size chars fits in the buffer. */
1316 pidbuf
[len
++] = '\n';
1317 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1319 if (write(pid_file_fd
, pidbuf
, len
) != len
)
1321 cleanup_set_pid(pid
); /* Mark the file for removal on exit, even if the write failed. */
1326 snprintf(msg
, sizeof msg
, "failed to %s pid file %s: %s\n",
1327 fail
, pid_file
, strerror(errno
));
1329 rprintf(FLOG
, "%s", msg
);
1330 exit_cleanup(RERR_FILEIO
);
1333 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1336 /* Become a daemon, discarding the controlling terminal. */
1337 static void become_daemon(void)
1344 fprintf(stderr
, "failed to fork: %s\n", strerror(errno
));
1345 exit_cleanup(RERR_FILEIO
);
1352 /* detach from the terminal */
1355 #elif defined TIOCNOTTY
1356 i
= open("/dev/tty", O_RDWR
);
1358 ioctl(i
, (int)TIOCNOTTY
, (char *)0);
1362 /* make sure that stdin, stdout an stderr don't stuff things
1363 * up (library functions, for example) */
1364 for (i
= 0; i
< 3; i
++) {
1366 open("/dev/null", O_RDWR
);
1370 int daemon_main(void)
1372 if (is_a_socket(STDIN_FILENO
)) {
1375 /* we are running via inetd - close off stdout and
1376 * stderr so that library functions (and getopt) don't
1377 * try to use them. Redirect them to /dev/null */
1378 for (i
= 1; i
< 3; i
++) {
1380 open("/dev/null", O_RDWR
);
1383 return start_daemon(STDIN_FILENO
, STDIN_FILENO
);
1386 if (!load_config(1)) {
1387 fprintf(stderr
, "Failed to parse config file: %s\n", config_file
);
1388 exit_cleanup(RERR_SYNTAX
);
1397 if (rsync_port
== 0 && (rsync_port
= lp_rsync_port()) == 0)
1398 rsync_port
= RSYNC_PORT
;
1399 if (bind_address
== NULL
&& *lp_bind_address())
1400 bind_address
= lp_bind_address();
1404 rprintf(FLOG
, "rsyncd version %s starting, listening on port %d\n",
1405 RSYNC_VERSION
, rsync_port
);
1406 /* TODO: If listening on a particular address, then show that
1407 * address too. In fact, why not just do getnameinfo on the
1408 * local address??? */
1410 start_accept_loop(rsync_port
, start_daemon
);