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
,
129 exit_cleanup(RERR_SOCKETIO
);
135 ret
= start_inband_exchange(fd
, fd
, user
, remote_argc
, remote_argv
);
137 return ret
? ret
: client_run(fd
, fd
, -1, argc
, argv
);
140 static int exchange_protocols(int f_in
, int f_out
, char *buf
, size_t bufsiz
, int am_client
)
143 #if SUBPROTOCOL_VERSION != 0
144 int our_sub
= protocol_version
< PROTOCOL_VERSION
? 0 : SUBPROTOCOL_VERSION
;
150 io_printf(f_out
, "@RSYNCD: %d.%d\n", protocol_version
, our_sub
);
153 motd
= lp_motd_file();
155 FILE *f
= fopen(motd
,"r");
156 while (f
&& !feof(f
)) {
157 int len
= fread(buf
, 1, bufsiz
- 1, f
);
159 write_buf(f_out
, buf
, len
);
163 write_sbuf(f_out
, "\n");
167 /* This strips the \n. */
168 if (!read_line_old(f_in
, buf
, bufsiz
, 0)) {
170 rprintf(FERROR
, "rsync: did not see server greeting\n");
174 if (sscanf(buf
, "@RSYNCD: %d.%d", &remote_protocol
, &remote_sub
) < 1) {
176 rprintf(FERROR
, "rsync: server sent \"%s\" rather than greeting\n", buf
);
178 io_printf(f_out
, "@ERROR: protocol startup error\n");
182 if (remote_sub
< 0) {
183 if (remote_protocol
== 30) {
185 rprintf(FERROR
, "rsync: server is speaking an incompatible beta of protocol 30\n");
187 io_printf(f_out
, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
193 if (protocol_version
> remote_protocol
) {
194 protocol_version
= remote_protocol
;
197 } else if (protocol_version
== remote_protocol
) {
198 if (remote_sub
!= our_sub
)
201 #if SUBPROTOCOL_VERSION != 0
202 else if (protocol_version
< remote_protocol
) {
208 if (protocol_version
>= 30)
214 int start_inband_exchange(int f_in
, int f_out
, const char *user
, int argc
, char *argv
[])
217 char line
[BIGPATHBUFLEN
];
218 char *sargs
[MAX_ARGS
];
222 assert(argc
> 0 && *argv
!= NULL
);
226 "ERROR: The remote path must start with a module name\n");
230 if (!(p
= strchr(*argv
, '/')))
231 modlen
= strlen(*argv
);
235 if (!(modname
= new_array(char, modlen
+1+1))) /* room for '/' & '\0' */
236 out_of_memory("start_inband_exchange");
237 strlcpy(modname
, *argv
, modlen
+ 1);
238 modname
[modlen
] = '/';
239 modname
[modlen
+1] = '\0';
242 user
= getenv("USER");
244 user
= getenv("LOGNAME");
246 if (exchange_protocols(f_in
, f_out
, line
, sizeof line
, 1) < 0)
249 /* set daemon_over_rsh to false since we need to build the
250 * true set of args passed through the rsh/ssh connection;
251 * this is a no-op for direct-socket-connection mode */
253 server_options(sargs
, &sargc
);
255 if (sargc
>= MAX_ARGS
- 2)
258 sargs
[sargc
++] = ".";
261 if (sargc
>= MAX_ARGS
- 1) {
263 rprintf(FERROR
, "internal: args[] overflowed in do_cmd()\n");
264 exit_cleanup(RERR_SYNTAX
);
266 if (strncmp(*argv
, modname
, modlen
) == 0
267 && argv
[0][modlen
] == '\0')
268 sargs
[sargc
++] = modname
; /* we send "modname/" */
269 else if (**argv
== '-') {
270 if (asprintf(sargs
+ sargc
++, "./%s", *argv
) < 0)
271 out_of_memory("start_inband_exchange");
273 sargs
[sargc
++] = *argv
;
280 if (DEBUG_GTE(CMD
, 1))
281 print_child_argv("sending daemon args:", sargs
);
283 io_printf(f_out
, "%.*s\n", modlen
, modname
);
285 /* Old servers may just drop the connection here,
286 rather than sending a proper EXIT command. Yuck. */
287 kluge_around_eof
= list_only
&& protocol_version
< 25 ? 1 : 0;
290 if (!read_line_old(f_in
, line
, sizeof line
, 0)) {
291 rprintf(FERROR
, "rsync: didn't get server startup line\n");
295 if (strncmp(line
,"@RSYNCD: AUTHREQD ",18) == 0) {
296 auth_client(f_out
, user
, line
+18);
300 if (strcmp(line
,"@RSYNCD: OK") == 0)
303 if (strcmp(line
,"@RSYNCD: EXIT") == 0) {
304 /* This is sent by recent versions of the
305 * server to terminate the listing of modules.
306 * We don't want to go on and transfer
307 * anything; just exit. */
311 if (strncmp(line
, "@ERROR", 6) == 0) {
312 rprintf(FERROR
, "%s\n", line
);
313 /* This is always fatal; the server will now
314 * close the socket. */
318 /* This might be a MOTD line or a module listing, but there is
319 * no way to differentiate it. The manpage mentions this. */
321 rprintf(FINFO
, "%s\n", line
);
323 kluge_around_eof
= 0;
326 for (i
= 0; i
< sargc
; i
++) {
327 if (!sargs
[i
]) /* stop at --protect-args NULL */
329 write_sbuf(f_out
, sargs
[i
]);
330 write_byte(f_out
, 0);
332 write_byte(f_out
, 0);
334 for (i
= 0; i
< sargc
; i
++)
335 io_printf(f_out
, "%s\n", sargs
[i
]);
336 write_sbuf(f_out
, "\n");
340 send_protected_args(f_out
, sargs
);
342 if (protocol_version
< 23) {
343 if (protocol_version
== 22 || !am_sender
)
344 io_start_multiplex_in(f_in
);
352 static char *finish_pre_exec(pid_t pid
, int write_fd
, int read_fd
, char *request
,
353 char **early_argv
, char **argv
)
355 char buf
[BIGPATHBUFLEN
], *bp
;
356 int j
= 0, status
= -1, msglen
= sizeof buf
- 1;
361 write_buf(write_fd
, request
, strlen(request
)+1);
363 for ( ; *early_argv
; early_argv
++)
364 write_buf(write_fd
, *early_argv
, strlen(*early_argv
)+1);
365 j
= 1; /* Skip arg0 name in argv. */
367 for ( ; argv
[j
]; j
++)
368 write_buf(write_fd
, argv
[j
], strlen(argv
[j
])+1);
369 write_byte(write_fd
, 0);
373 /* Read the stdout from the pre-xfer exec program. This it is only
374 * displayed to the user if the script also returns an error status. */
375 for (bp
= buf
; msglen
> 0; msglen
-= j
) {
376 if ((j
= read(read_fd
, bp
, msglen
)) <= 0) {
381 break; /* Just ignore the read error for now... */
384 if (j
> 1 && bp
[-1] == '\n' && bp
[-2] == '\r') {
394 if (wait_process(pid
, &status
, 0) < 0
395 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
397 if (asprintf(&e
, "pre-xfer exec returned failure (%d)%s%s%s\n%s",
398 status
, status
< 0 ? ": " : "",
399 status
< 0 ? strerror(errno
) : "",
400 *buf
? ":" : "", buf
) < 0)
401 return "out_of_memory in finish_pre_exec\n";
408 static int read_arg_from_pipe(int fd
, char *buf
, int limit
)
410 char *bp
= buf
, *eob
= buf
+ limit
- 1;
413 int got
= read(fd
, bp
, 1);
415 if (got
< 0 && errno
== EINTR
)
430 static int path_failure(int f_out
, const char *dir
, BOOL was_chdir
)
433 rsyserr(FLOG
, errno
, "chdir %s failed", dir
);
435 rprintf(FLOG
, "normalize_path(%s) failed\n", dir
);
436 io_printf(f_out
, "@ERROR: chdir failed\n");
440 static int add_a_group(int f_out
, const char *gname
)
443 if (!group_to_gid(gname
, &gid
, True
)) {
444 rprintf(FLOG
, "Invalid gid %s\n", gname
);
445 io_printf(f_out
, "@ERROR: invalid gid %s\n", gname
);
448 gid_p
= EXPAND_ITEM_LIST(&gid_list
, gid_t
, -32);
453 #ifdef HAVE_GETGROUPLIST
454 static int want_all_groups(int f_out
, uid_t uid
)
457 if ((err
= getallgroups(uid
, &gid_list
)) != NULL
) {
458 rsyserr(FLOG
, errno
, "%s", err
);
459 io_printf(f_out
, "@ERROR: %s\n", err
);
464 #elif defined HAVE_INITGROUPS
465 static struct passwd
*want_all_groups(int f_out
, uid_t uid
)
469 if ((pw
= getpwuid(uid
)) == NULL
) {
470 rsyserr(FLOG
, errno
, "getpwuid failed");
471 io_printf(f_out
, "@ERROR: getpwuid failed\n");
474 /* Start with the default group and initgroups() will add the rest. */
475 gid_p
= EXPAND_ITEM_LIST(&gid_list
, gid_t
, -32);
481 static void set_env_str(const char *var
, const char *str
)
485 if (asprintf(&mem
, "%s=%s", var
, str
) < 0)
486 out_of_memory("set_env_str");
492 void set_env_num(const char *var
, long num
)
495 if (asprintf(&mem
, "%s=%ld", var
, num
) < 0)
496 out_of_memory("set_env_num");
501 static int rsync_module(int f_in
, int f_out
, int i
, const char *addr
, const char *host
)
504 char **argv
, **orig_argv
, **orig_early_argv
, *module_chdir
;
505 char line
[BIGPATHBUFLEN
];
506 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
507 struct passwd
*pw
= NULL
;
511 char *p
, *err_msg
= NULL
;
512 char *name
= lp_name(i
);
513 int use_chroot
= lp_use_chroot(i
);
514 int ret
, pre_exec_arg_fd
= -1, pre_exec_error_fd
= -1;
515 int save_munge_symlinks
;
516 pid_t pre_exec_pid
= 0;
517 char *request
= NULL
;
519 set_env_str("RSYNC_MODULE_NAME", name
);
522 iconv_opt
= lp_charset(i
);
528 /* If reverse lookup is disabled globally but enabled for this module,
529 * we need to do it now before the access check. */
530 if (host
== undetermined_hostname
&& lp_reverse_lookup(i
))
531 host
= client_name(f_in
);
532 set_env_str("RSYNC_HOST_NAME", host
);
533 set_env_str("RSYNC_HOST_ADDR", addr
);
535 if (!allow_access(addr
, &host
, i
)) {
536 rprintf(FLOG
, "rsync denied on module %s from %s (%s)\n",
539 io_printf(f_out
, "@ERROR: Unknown module '%s'\n", name
);
542 "@ERROR: access denied to %s from %s (%s)\n",
549 rprintf(FLOG
, "rsync allowed access on module %s from %s (%s)\n",
553 if (!claim_connection(lp_lock_file(i
), lp_max_connections(i
))) {
555 rsyserr(FLOG
, errno
, "failed to open lock file %s",
557 io_printf(f_out
, "@ERROR: failed to open lock file\n");
559 rprintf(FLOG
, "max connections (%d) reached\n",
560 lp_max_connections(i
));
561 io_printf(f_out
, "@ERROR: max connections (%d) reached -- try again later\n",
562 lp_max_connections(i
));
567 read_only
= lp_read_only(i
); /* may also be overridden by auth_server() */
568 auth_user
= auth_server(f_in
, f_out
, i
, host
, addr
, "@RSYNCD: AUTHREQD ");
571 io_printf(f_out
, "@ERROR: auth failed on module %s\n", name
);
574 set_env_str("RSYNC_USER_NAME", auth_user
);
578 if (lp_transfer_logging(i
) && !logfile_format
)
579 logfile_format
= lp_log_format(i
);
580 if (log_format_has(logfile_format
, 'i'))
581 logfile_format_has_i
= 1;
582 if (logfile_format_has_i
|| log_format_has(logfile_format
, 'o'))
583 logfile_format_has_o_or_i
= 1;
586 am_root
= (uid
== 0);
588 p
= *lp_uid(i
) ? lp_uid(i
) : am_root
? NOBODY_USER
: NULL
;
590 if (!user_to_uid(p
, &uid
, True
)) {
591 rprintf(FLOG
, "Invalid uid %s\n", p
);
592 io_printf(f_out
, "@ERROR: invalid uid %s\n", p
);
599 p
= *lp_gid(i
) ? conf_strtok(lp_gid(i
)) : NULL
;
601 /* The "*" gid must be the first item in the list. */
602 if (strcmp(p
, "*") == 0) {
603 #ifdef HAVE_GETGROUPLIST
604 if (want_all_groups(f_out
, uid
) < 0)
606 #elif defined HAVE_INITGROUPS
607 if ((pw
= want_all_groups(f_out
, uid
)) == NULL
)
610 rprintf(FLOG
, "This rsync does not support a gid of \"*\"\n");
611 io_printf(f_out
, "@ERROR: invalid gid setting.\n");
614 } else if (add_a_group(f_out
, p
) < 0)
616 while ((p
= conf_strtok(NULL
)) != NULL
) {
617 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
619 rprintf(FLOG
, "This rsync cannot add groups after \"*\".\n");
620 io_printf(f_out
, "@ERROR: invalid gid setting.\n");
624 if (add_a_group(f_out
, p
) < 0)
627 } else if (am_root
) {
628 if (add_a_group(f_out
, NOBODY_GROUP
) < 0)
632 module_dir
= lp_path(i
);
633 if (*module_dir
== '\0') {
634 rprintf(FLOG
, "No path specified for module %s\n", name
);
635 io_printf(f_out
, "@ERROR: no path setting.\n");
639 if ((p
= strstr(module_dir
, "/./")) != NULL
) {
640 *p
= '\0'; /* Temporary... */
641 if (!(module_chdir
= normalize_path(module_dir
, True
, NULL
)))
642 return path_failure(f_out
, module_dir
, False
);
644 if (!(p
= normalize_path(p
+ 2, True
, &module_dirlen
)))
645 return path_failure(f_out
, strstr(module_dir
, "/./"), False
);
646 if (!(full_module_path
= normalize_path(module_dir
, False
, NULL
)))
647 full_module_path
= module_dir
;
650 if (!(module_chdir
= normalize_path(module_dir
, False
, NULL
)))
651 return path_failure(f_out
, module_dir
, False
);
652 full_module_path
= module_chdir
;
657 if (!(module_chdir
= normalize_path(module_dir
, False
, &module_dirlen
)))
658 return path_failure(f_out
, module_dir
, False
);
659 full_module_path
= module_dir
= module_chdir
;
661 set_env_str("RSYNC_MODULE_PATH", full_module_path
);
663 if (module_dirlen
== 1) {
665 set_filter_dir("/", 1);
667 set_filter_dir(module_dir
, module_dirlen
);
670 parse_filter_str(&daemon_filter_list
, p
, rule_template(FILTRULE_WORD_SPLIT
),
671 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
);
673 p
= lp_include_from(i
);
674 parse_filter_file(&daemon_filter_list
, p
, rule_template(FILTRULE_INCLUDE
),
675 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
| XFLG_FATAL_ERRORS
);
678 parse_filter_str(&daemon_filter_list
, p
,
679 rule_template(FILTRULE_INCLUDE
| FILTRULE_WORD_SPLIT
),
680 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
);
682 p
= lp_exclude_from(i
);
683 parse_filter_file(&daemon_filter_list
, p
, rule_template(0),
684 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
| XFLG_FATAL_ERRORS
);
687 parse_filter_str(&daemon_filter_list
, p
, rule_template(FILTRULE_WORD_SPLIT
),
688 XFLG_ABS_IF_SLASH
| XFLG_DIR2WILD3
| XFLG_OLD_PREFIXES
);
693 if ((*lp_prexfer_exec(i
) || *lp_postxfer_exec(i
)) && !getenv("RSYNC_NO_XFER_EXEC")) {
696 /* For post-xfer exec, fork a new process to run the rsync
697 * daemon while this process waits for the exit status and
698 * runs the indicated command at that point. */
699 if (*lp_postxfer_exec(i
)) {
702 rsyserr(FLOG
, errno
, "fork failed");
703 io_printf(f_out
, "@ERROR: fork failed\n");
710 set_env_num("RSYNC_PID", (long)pid
);
711 if (wait_process(pid
, &status
, 0) < 0)
713 set_env_num("RSYNC_RAW_STATUS", status
);
714 if (WIFEXITED(status
))
715 status
= WEXITSTATUS(status
);
718 set_env_num("RSYNC_EXIT_STATUS", status
);
719 if (shell_exec(lp_postxfer_exec(i
)) < 0)
724 /* For pre-xfer exec, fork a child process to run the indicated
725 * command, though it first waits for the parent process to
726 * send us the user's request via a pipe. */
727 if (*lp_prexfer_exec(i
)) {
728 int arg_fds
[2], error_fds
[2];
729 set_env_num("RSYNC_PID", (long)getpid());
730 if (pipe(arg_fds
) < 0 || pipe(error_fds
) < 0 || (pre_exec_pid
= fork()) < 0) {
731 rsyserr(FLOG
, errno
, "pre-xfer exec preparation failed");
732 io_printf(f_out
, "@ERROR: pre-xfer exec preparation failed\n");
735 if (pre_exec_pid
== 0) {
736 char buf
[BIGPATHBUFLEN
];
740 pre_exec_arg_fd
= arg_fds
[0];
741 pre_exec_error_fd
= error_fds
[1];
742 set_blocking(pre_exec_arg_fd
);
743 set_blocking(pre_exec_error_fd
);
744 len
= read_arg_from_pipe(pre_exec_arg_fd
, buf
, BIGPATHBUFLEN
);
747 set_env_str("RSYNC_REQUEST", buf
);
749 len
= read_arg_from_pipe(pre_exec_arg_fd
, buf
,
756 if (asprintf(&p
, "RSYNC_ARG%d=%s", j
, buf
) >= 0)
759 close(pre_exec_arg_fd
);
761 dup2(pre_exec_error_fd
, STDOUT_FILENO
);
762 close(pre_exec_error_fd
);
763 status
= shell_exec(lp_prexfer_exec(i
));
764 if (!WIFEXITED(status
))
766 _exit(WEXITSTATUS(status
));
770 pre_exec_arg_fd
= arg_fds
[1];
771 pre_exec_error_fd
= error_fds
[0];
772 set_blocking(pre_exec_arg_fd
);
773 set_blocking(pre_exec_error_fd
);
780 * XXX: The 'use chroot' flag is a fairly reliable
781 * source of confusion, because it fails under two
782 * important circumstances: running as non-root,
783 * running on Win32 (or possibly others). On the
784 * other hand, if you are running as root, then it
785 * might be better to always use chroot.
787 * So, perhaps if we can't chroot we should just issue
788 * a warning, unless a "require chroot" flag is set,
789 * in which case we fail.
791 if (chroot(module_chdir
)) {
792 rsyserr(FLOG
, errno
, "chroot %s failed", module_chdir
);
793 io_printf(f_out
, "@ERROR: chroot failed\n");
796 module_chdir
= module_dir
;
799 if (!change_dir(module_chdir
, CD_NORMAL
))
800 return path_failure(f_out
, module_chdir
, True
);
801 if (module_dirlen
|| (!use_chroot
&& !*lp_daemon_chroot()))
804 if ((munge_symlinks
= lp_munge_symlinks(i
)) < 0)
805 munge_symlinks
= !use_chroot
|| module_dirlen
;
806 if (munge_symlinks
) {
808 char prefix
[SYMLINK_PREFIX_LEN
]; /* NOT +1 ! */
809 strlcpy(prefix
, SYMLINK_PREFIX
, sizeof prefix
); /* trim the trailing slash */
810 if (do_stat(prefix
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
811 rprintf(FLOG
, "Symlink munging is unsafe when a %s directory exists.\n",
813 io_printf(f_out
, "@ERROR: daemon security issue -- contact admin\n", name
);
814 exit_cleanup(RERR_UNSUPPORTED
);
818 if (gid_list
.count
) {
819 gid_t
*gid_array
= gid_list
.items
;
820 if (setgid(gid_array
[0])) {
821 rsyserr(FLOG
, errno
, "setgid %ld failed", (long)gid_array
[0]);
822 io_printf(f_out
, "@ERROR: setgid failed\n");
825 #ifdef HAVE_SETGROUPS
826 /* Set the group(s) we want to be active. */
827 if (setgroups(gid_list
.count
, gid_array
)) {
828 rsyserr(FLOG
, errno
, "setgroups failed");
829 io_printf(f_out
, "@ERROR: setgroups failed\n");
833 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
834 /* pw is set if the user wants all the user's groups. */
835 if (pw
&& initgroups(pw
->pw_name
, pw
->pw_gid
) < 0) {
836 rsyserr(FLOG
, errno
, "initgroups failed");
837 io_printf(f_out
, "@ERROR: initgroups failed\n");
850 rsyserr(FLOG
, errno
, "setuid %ld failed", (long)uid
);
851 io_printf(f_out
, "@ERROR: setuid failed\n");
856 am_root
= (our_uid
== 0);
859 if (lp_temp_dir(i
) && *lp_temp_dir(i
)) {
860 tmpdir
= lp_temp_dir(i
);
861 if (strlen(tmpdir
) >= MAXPATHLEN
- 10) {
863 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
869 io_printf(f_out
, "@RSYNCD: OK\n");
871 read_args(f_in
, name
, line
, sizeof line
, rl_nulls
, &argv
, &argc
, &request
);
874 save_munge_symlinks
= munge_symlinks
;
876 reset_output_levels(); /* future verbosity is controlled by client options */
877 ret
= parse_arguments(&argc
, (const char ***) &argv
);
878 if (protect_args
&& ret
) {
879 orig_early_argv
= orig_argv
;
881 read_args(f_in
, name
, line
, sizeof line
, 1, &argv
, &argc
, &request
);
883 ret
= parse_arguments(&argc
, (const char ***) &argv
);
885 orig_early_argv
= NULL
;
887 munge_symlinks
= save_munge_symlinks
; /* The client mustn't control this. */
889 msgs2stderr
= 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
892 err_msg
= finish_pre_exec(pre_exec_pid
, pre_exec_arg_fd
, pre_exec_error_fd
,
893 request
, orig_early_argv
, orig_argv
);
897 free(orig_early_argv
);
899 am_server
= 1; /* Don't let someone try to be tricky. */
901 if (lp_ignore_errors(module_id
))
906 if (lp_fake_super(i
)) {
907 if (preserve_xattrs
> 1)
910 } else if (am_root
< 0) /* Treat --fake-super from client as --super. */
913 if (filesfrom_fd
== 0)
918 rprintf(FLOG
, "rsync %s %s from %s@%s (%s)\n",
919 am_sender
? "on" : "to",
920 request
, auth_user
, host
, addr
);
922 rprintf(FLOG
, "rsync %s %s from %s (%s)\n",
923 am_sender
? "on" : "to",
924 request
, host
, addr
);
930 /* don't allow the logs to be flooded too fast */
931 limit_output_verbosity(lp_max_verbosity(i
));
934 if (protocol_version
< 23
935 && (protocol_version
== 22 || am_sender
))
936 io_start_multiplex_out(f_out
);
937 else if (!ret
|| err_msg
) {
938 /* We have to get I/O multiplexing started so that we can
939 * get the error back to the client. This means getting
940 * the protocol setup finished first in later versions. */
941 setup_protocol(f_out
, f_in
);
943 /* Since we failed in our option parsing, we may not
944 * have finished parsing that the client sent us a
945 * --files-from option, so look for it manually.
946 * Without this, the socket would be in the wrong
947 * state for the upcoming error message. */
950 for (i
= 0; i
< argc
; i
++) {
951 if (strncmp(argv
[i
], "--files-from", 12) == 0) {
958 write_byte(f_out
, 0);
960 io_start_multiplex_out(f_out
);
963 if (!ret
|| err_msg
) {
965 while ((p
= strchr(err_msg
, '\n')) != NULL
) {
966 int len
= p
- err_msg
+ 1;
967 rwrite(FERROR
, err_msg
, len
, 0);
971 rprintf(FERROR
, "%s\n", err_msg
);
976 exit_cleanup(RERR_UNSUPPORTED
);
981 if (ic_send
!= (iconv_t
)-1) {
982 iconv_close(ic_send
);
983 ic_send
= (iconv_t
)-1;
985 if (ic_recv
!= (iconv_t
)-1) {
986 iconv_close(ic_recv
);
987 ic_recv
= (iconv_t
)-1;
993 && (use_chroot
? lp_numeric_ids(i
) != False
: lp_numeric_ids(i
) == True
))
994 numeric_ids
= -1; /* Set --numeric-ids w/o breaking protocol. */
996 if (lp_timeout(i
) && (!io_timeout
|| lp_timeout(i
) < io_timeout
))
997 set_io_timeout(lp_timeout(i
));
999 /* If we have some incoming/outgoing chmod changes, append them to
1000 * any user-specified changes (making our changes have priority).
1001 * We also get a pointer to just our changes so that a receiver
1002 * process can use them separately if --perms wasn't specified. */
1004 p
= lp_outgoing_chmod(i
);
1006 p
= lp_incoming_chmod(i
);
1007 if (*p
&& !(daemon_chmod_modes
= parse_chmod(p
, &chmod_modes
))) {
1008 rprintf(FLOG
, "Invalid \"%sing chmod\" directive: %s\n",
1009 am_sender
? "outgo" : "incom", p
);
1012 start_server(f_in
, f_out
, argc
, argv
);
1017 /* send a list of available modules to the client. Don't list those
1018 with "list = False". */
1019 static void send_listing(int fd
)
1021 int n
= lp_num_modules();
1024 for (i
= 0; i
< n
; i
++) {
1026 io_printf(fd
, "%-15s\t%s\n", lp_name(i
), lp_comment(i
));
1029 if (protocol_version
>= 25)
1030 io_printf(fd
,"@RSYNCD: EXIT\n");
1033 static int load_config(int globals_only
)
1036 if (am_daemon
< 0 && am_root
<= 0)
1037 config_file
= RSYNCD_USERCONF
;
1039 config_file
= RSYNCD_SYSCONF
;
1041 return lp_load(config_file
, globals_only
);
1044 /* this is called when a connection is established to a client
1045 and we want to start talking. The setup of the system is done from
1047 int start_daemon(int f_in
, int f_out
)
1050 const char *addr
, *host
;
1054 /* At this point, am_server is only set for a daemon started via rsh.
1055 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1056 * a flag that can be checked later on to distinguish a normal daemon
1057 * from an rsh-run daemon. */
1061 io_set_sock_fds(f_in
, f_out
);
1063 /* We must load the config file before calling any function that
1064 * might cause log-file output to occur. This ensures that the
1065 * "log file" param gets honored for the 2 non-forked use-cases
1066 * (when rsync is run by init and run by a remote shell). */
1067 if (!load_config(0))
1068 exit_cleanup(RERR_SYNTAX
);
1070 p
= lp_daemon_chroot();
1072 log_init(0); /* Make use we've initialized syslog before chrooting. */
1073 if (chroot(p
) < 0 || chdir("/") < 0) {
1074 rsyserr(FLOG
, errno
, "daemon chroot %s failed", p
);
1078 p
= lp_daemon_gid();
1081 if (!group_to_gid(p
, &gid
, True
)) {
1082 rprintf(FLOG
, "Invalid daemon gid: %s\n", p
);
1085 if (setgid(gid
) < 0) {
1086 rsyserr(FLOG
, errno
, "Unable to set group to daemon gid %ld", (long)gid
);
1091 p
= lp_daemon_uid();
1094 if (!user_to_uid(p
, &uid
, True
)) {
1095 rprintf(FLOG
, "Invalid daemon uid: %s\n", p
);
1098 if (setuid(uid
) < 0) {
1099 rsyserr(FLOG
, errno
, "Unable to set user to daemon uid %ld", (long)uid
);
1103 am_root
= (our_uid
== 0);
1106 addr
= client_addr(f_in
);
1107 host
= lp_reverse_lookup(-1) ? client_name(f_in
) : undetermined_hostname
;
1108 rprintf(FLOG
, "connect from %s (%s)\n", host
, addr
);
1110 if (am_daemon
> 0) {
1111 set_socket_options(f_in
, "SO_KEEPALIVE");
1112 set_nonblocking(f_in
);
1115 if (exchange_protocols(f_in
, f_out
, line
, sizeof line
, 0) < 0)
1119 if (!read_line_old(f_in
, line
, sizeof line
, 0))
1122 if (!*line
|| strcmp(line
, "#list") == 0) {
1123 rprintf(FLOG
, "module-list request from %s (%s)\n",
1125 send_listing(f_out
);
1130 /* it's some sort of command that I don't understand */
1131 io_printf(f_out
, "@ERROR: Unknown command '%s'\n", line
);
1135 if ((i
= lp_number(line
)) < 0) {
1136 rprintf(FLOG
, "unknown module '%s' tried from %s (%s)\n",
1138 io_printf(f_out
, "@ERROR: Unknown module '%s'\n", line
);
1142 #ifdef HAVE_SIGACTION
1143 sigact
.sa_flags
= SA_NOCLDSTOP
;
1145 SIGACTION(SIGCHLD
, remember_children
);
1147 return rsync_module(f_in
, f_out
, i
, addr
, host
);
1150 static void create_pid_file(void)
1152 char *pid_file
= lp_pid_file();
1154 STRUCT_STAT st1
, st2
;
1157 if (!pid_file
|| !*pid_file
)
1161 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1163 #define SAFE_OPEN_FLAGS (O_CREAT)
1166 /* These tests make sure that a temp-style lock dir is handled safely. */
1168 if (do_lstat(pid_file
, &st1
) == 0 && !S_ISREG(st1
.st_mode
) && unlink(pid_file
) < 0)
1170 else if ((pid_file_fd
= do_open(pid_file
, O_RDWR
|SAFE_OPEN_FLAGS
, 0664)) < 0)
1171 fail
= S_ISREG(st1
.st_mode
) ? "open" : "create";
1172 else if (!lock_range(pid_file_fd
, 0, 4))
1174 else if (do_fstat(pid_file_fd
, &st1
) < 0)
1175 fail
= "fstat opened";
1176 else if (st1
.st_size
> (int)sizeof pidbuf
)
1177 fail
= "find small";
1178 else if (do_lstat(pid_file
, &st2
) < 0)
1180 else if (!S_ISREG(st1
.st_mode
))
1181 fail
= "avoid file overwrite race for";
1182 else if (st1
.st_dev
!= st2
.st_dev
|| st1
.st_ino
!= st2
.st_ino
)
1183 fail
= "verify stat info for";
1184 #ifdef HAVE_FTRUNCATE
1185 else if (do_ftruncate(pid_file_fd
, 0) < 0)
1189 pid_t pid
= getpid();
1190 int len
= snprintf(pidbuf
, sizeof pidbuf
, "%d\n", (int)pid
);
1191 #ifndef HAVE_FTRUNCATE
1192 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1193 while (len
< st1
.st_size
) /* We already verified that st_size chars fits in the buffer. */
1194 pidbuf
[len
++] = '\n';
1195 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1197 if (write(pid_file_fd
, pidbuf
, len
) != len
)
1199 cleanup_set_pid(pid
); /* Mark the file for removal on exit, even if the write failed. */
1204 snprintf(msg
, sizeof msg
, "failed to %s pid file %s: %s\n",
1205 fail
, pid_file
, strerror(errno
));
1207 rprintf(FLOG
, "%s", msg
);
1208 exit_cleanup(RERR_FILEIO
);
1211 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1214 /* Become a daemon, discarding the controlling terminal. */
1215 static void become_daemon(void)
1222 fprintf(stderr
, "failed to fork: %s\n", strerror(errno
));
1223 exit_cleanup(RERR_FILEIO
);
1230 /* detach from the terminal */
1233 #elif defined TIOCNOTTY
1234 i
= open("/dev/tty", O_RDWR
);
1236 ioctl(i
, (int)TIOCNOTTY
, (char *)0);
1240 /* make sure that stdin, stdout an stderr don't stuff things
1241 * up (library functions, for example) */
1242 for (i
= 0; i
< 3; i
++) {
1244 open("/dev/null", O_RDWR
);
1248 int daemon_main(void)
1250 if (is_a_socket(STDIN_FILENO
)) {
1253 /* we are running via inetd - close off stdout and
1254 * stderr so that library functions (and getopt) don't
1255 * try to use them. Redirect them to /dev/null */
1256 for (i
= 1; i
< 3; i
++) {
1258 open("/dev/null", O_RDWR
);
1261 return start_daemon(STDIN_FILENO
, STDIN_FILENO
);
1264 if (!load_config(1)) {
1265 fprintf(stderr
, "Failed to parse config file: %s\n", config_file
);
1266 exit_cleanup(RERR_SYNTAX
);
1275 if (rsync_port
== 0 && (rsync_port
= lp_rsync_port()) == 0)
1276 rsync_port
= RSYNC_PORT
;
1277 if (bind_address
== NULL
&& *lp_bind_address())
1278 bind_address
= lp_bind_address();
1282 rprintf(FLOG
, "rsyncd version %s starting, listening on port %d\n",
1283 RSYNC_VERSION
, rsync_port
);
1284 /* TODO: If listening on a particular address, then show that
1285 * address too. In fact, why not just do getnameinfo on the
1286 * local address??? */
1288 start_accept_loop(rsync_port
, start_daemon
);