1/*
2 * The socket based protocol for setting up a connection with rsyncd.
3 *
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
7 *
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.
12 *
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.
17 *
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.
21 */
22
23#include "rsync.h"
24
25extern int verbose;
26extern int quiet;
27extern int output_motd;
28extern int list_only;
29extern int am_sender;
30extern int am_server;
31extern int am_daemon;
32extern int am_root;
33extern int rsync_port;
34extern int kluge_around_eof;
35extern int daemon_over_rsh;
36extern int sanitize_paths;
37extern int filesfrom_fd;
38extern int remote_protocol;
39extern int protocol_version;
40extern int io_timeout;
41extern int no_detach;
42extern int default_af_hint;
43extern int logfile_format_has_i;
44extern int logfile_format_has_o_or_i;
45extern mode_t orig_umask;
46extern char *bind_address;
47extern char *sockopts;
48extern char *config_file;
49extern char *logfile_format;
50extern char *files_from;
51extern char *tmpdir;
52extern struct chmod_mode_struct *chmod_modes;
53extern struct filter_list_struct server_filter_list;
54
55char *auth_user;
56int read_only = 0;
57int module_id = -1;
58int munge_symlinks = 0;
59struct chmod_mode_struct *daemon_chmod_modes;
60
61/* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
62unsigned int module_dirlen = 0;
63
64#ifdef HAVE_SIGACTION
65static struct sigaction sigact;
66#endif
67
68/**
69 * Run a client connected to an rsyncd.  The alternative to this
70 * function for remote-shell connections is do_cmd().
71 *
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.
75 *
76 * Instead of doing a transfer, the client may at this stage instead
77 * get a listing of remote modules and exit.
78 *
79 * @return -1 for error in startup, or the result of client_run().
80 * Either way, it eventually gets passed to exit_cleanup().
81 **/
82int start_socket_client(char *host, char *path, int argc, char *argv[])
83{
84	int fd, ret;
85	char *p, *user = NULL;
86
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. */
90	if (*path == '/') {
91		rprintf(FERROR,
92			"ERROR: The remote path must start with a module name not a /\n");
93		return -1;
94	}
95
96	if ((p = strrchr(host, '@')) != NULL) {
97		user = host;
98		host = p+1;
99		*p = '\0';
100	}
101
102	fd = open_socket_out_wrapped(host, rsync_port, bind_address,
103				     default_af_hint);
104	if (fd == -1)
105		exit_cleanup(RERR_SOCKETIO);
106
107	set_socket_options(fd, sockopts);
108
109	ret = start_inband_exchange(user, path, fd, fd, argc);
110
111	return ret ? ret : client_run(fd, fd, -1, argc, argv);
112}
113
114int start_inband_exchange(char *user, char *path, int f_in, int f_out,
115			  int argc)
116{
117	int i;
118	char *sargs[MAX_ARGS];
119	int sargc = 0;
120	char line[BIGPATHBUFLEN];
121	char *p;
122
123	if (argc == 0 && !am_sender)
124		list_only |= 1;
125
126	if (*path == '/') {
127		rprintf(FERROR,
128			"ERROR: The remote path must start with a module name\n");
129		return -1;
130	}
131
132	if (!user)
133		user = getenv("USER");
134	if (!user)
135		user = getenv("LOGNAME");
136
137	io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
138
139	if (!read_line(f_in, line, sizeof line - 1)) {
140		rprintf(FERROR, "rsync: did not see server greeting\n");
141		return -1;
142	}
143
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",
147			line);
148		return -1;
149	}
150	if (protocol_version > remote_protocol)
151		protocol_version = remote_protocol;
152
153	if (list_only && protocol_version >= 29)
154		list_only |= 2;
155
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 */
159	daemon_over_rsh = 0;
160	server_options(sargs, &sargc);
161
162	sargs[sargc++] = ".";
163
164	if (path && *path)
165		sargs[sargc++] = path;
166
167	sargs[sargc] = NULL;
168
169	if (verbose > 1)
170		print_child_argv(sargs);
171
172	p = strchr(path,'/');
173	if (p) *p = 0;
174	io_printf(f_out, "%s\n", path);
175	if (p) *p = '/';
176
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;
180
181	while (1) {
182		if (!read_line(f_in, line, sizeof line - 1)) {
183			rprintf(FERROR, "rsync: didn't get server startup line\n");
184			return -1;
185		}
186
187		if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
188			auth_client(f_out, user, line+18);
189			continue;
190		}
191
192		if (strcmp(line,"@RSYNCD: OK") == 0)
193			break;
194
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. */
200			exit(0);
201		}
202
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. */
207			return -1;
208		}
209
210		/* This might be a MOTD line or a module listing, but there is
211		 * no way to differentiate it.  The manpage mentions this. */
212		if (output_motd)
213			rprintf(FINFO, "%s\n", line);
214	}
215	kluge_around_eof = 0;
216
217	for (i = 0; i < sargc; i++) {
218		io_printf(f_out, "%s\n", sargs[i]);
219	}
220	io_printf(f_out, "\n");
221
222	if (protocol_version < 23) {
223		if (protocol_version == 22 || !am_sender)
224			io_start_multiplex_in();
225	}
226
227	return 0;
228}
229
230static char *finish_pre_exec(pid_t pid, int fd, char *request,
231			     int argc, char *argv[])
232{
233	int j, status = -1;
234
235	if (request) {
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);
239	}
240
241	write_byte(fd, 0);
242
243	close(fd);
244
245	if (wait_process(pid, &status, 0) < 0
246	 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
247		char *e;
248		if (asprintf(&e, "pre-xfer exec returned failure (%d)\n", status) < 0)
249			out_of_memory("finish_pre_exec");
250		return e;
251	}
252	return NULL;
253}
254
255static int read_arg_from_pipe(int fd, char *buf, int limit)
256{
257	char *bp = buf, *eob = buf + limit - 1;
258
259	while (1) {
260	    if (read(fd, bp, 1) != 1)
261		return -1;
262	    if (*bp == '\0')
263		break;
264	    if (bp < eob)
265		bp++;
266	}
267	*bp = '\0';
268
269	return bp - buf;
270}
271
272static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
273{
274	int argc = 0;
275	int maxargs;
276	char **argv;
277	char line[BIGPATHBUFLEN];
278	uid_t uid = (uid_t)-2;  /* canonically "nobody" */
279	gid_t gid = (gid_t)-2;
280	char *p, *err_msg = NULL;
281	char *name = lp_name(i);
282	int use_chroot = lp_use_chroot(i);
283	int start_glob = 0;
284	int ret, pre_exec_fd = -1;
285	pid_t pre_exec_pid = 0;
286	char *request = NULL;
287
288	if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
289		rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
290			name, host, addr);
291		if (!lp_list(i))
292			io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
293		else {
294			io_printf(f_out,
295				  "@ERROR: access denied to %s from %s (%s)\n",
296				  name, host, addr);
297		}
298		return -1;
299	}
300
301	if (am_daemon && am_server) {
302		rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
303			name, host, addr);
304	}
305
306	if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
307		if (errno) {
308			rsyserr(FLOG, errno, "failed to open lock file %s",
309				lp_lock_file(i));
310			io_printf(f_out, "@ERROR: failed to open lock file\n");
311		} else {
312			rprintf(FLOG, "max connections (%d) reached\n",
313				lp_max_connections(i));
314			io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
315				lp_max_connections(i));
316		}
317		return -1;
318	}
319
320	auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
321
322	if (!auth_user) {
323		io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
324		return -1;
325	}
326
327	module_id = i;
328
329	if (lp_read_only(i))
330		read_only = 1;
331
332	if (lp_transfer_logging(i) && !logfile_format)
333		logfile_format = lp_log_format(i);
334	if (log_format_has(logfile_format, 'i'))
335		logfile_format_has_i = 1;
336	if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
337		logfile_format_has_o_or_i = 1;
338
339	am_root = (MY_UID() == 0);
340
341	if (am_root) {
342		p = lp_uid(i);
343		if (!name_to_uid(p, &uid)) {
344			if (!isdigit(*(unsigned char *)p)) {
345				rprintf(FLOG, "Invalid uid %s\n", p);
346				io_printf(f_out, "@ERROR: invalid uid %s\n", p);
347				return -1;
348			}
349			uid = atoi(p);
350		}
351
352		p = lp_gid(i);
353		if (!name_to_gid(p, &gid)) {
354			if (!isdigit(*(unsigned char *)p)) {
355				rprintf(FLOG, "Invalid gid %s\n", p);
356				io_printf(f_out, "@ERROR: invalid gid %s\n", p);
357				return -1;
358			}
359			gid = atoi(p);
360		}
361	}
362
363	/* TODO: If we're not root, but the configuration requests
364	 * that we change to some uid other than the current one, then
365	 * log a warning. */
366
367	/* TODO: Perhaps take a list of gids, and make them into the
368	 * supplementary groups. */
369
370	if (use_chroot || (module_dirlen = strlen(lp_path(i))) == 1) {
371		module_dirlen = 0;
372		set_filter_dir("/", 1);
373	} else
374		set_filter_dir(lp_path(i), module_dirlen);
375
376	p = lp_filter(i);
377	parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
378		   XFLG_ABS_IF_SLASH);
379
380	p = lp_include_from(i);
381	parse_filter_file(&server_filter_list, p, MATCHFLG_INCLUDE,
382	    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
383
384	p = lp_include(i);
385	parse_rule(&server_filter_list, p,
386		   MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
387		   XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
388
389	p = lp_exclude_from(i);
390	parse_filter_file(&server_filter_list, p, 0,
391	    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
392
393	p = lp_exclude(i);
394	parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
395		   XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
396
397	log_init(1);
398
399#ifdef HAVE_PUTENV
400	if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
401		char *modname, *modpath, *hostaddr, *hostname, *username;
402		int status;
403		if (asprintf(&modname, "RSYNC_MODULE_NAME=%s", name) < 0
404		 || asprintf(&modpath, "RSYNC_MODULE_PATH=%s", lp_path(i)) < 0
405		 || asprintf(&hostaddr, "RSYNC_HOST_ADDR=%s", addr) < 0
406		 || asprintf(&hostname, "RSYNC_HOST_NAME=%s", host) < 0
407		 || asprintf(&username, "RSYNC_USER_NAME=%s", auth_user) < 0)
408			out_of_memory("rsync_module");
409		putenv(modname);
410		putenv(modpath);
411		putenv(hostaddr);
412		putenv(hostname);
413		putenv(username);
414		umask(orig_umask);
415		/* For post-xfer exec, fork a new process to run the rsync
416		 * daemon while this process waits for the exit status and
417		 * runs the indicated command at that point. */
418		if (*lp_postxfer_exec(i)) {
419			pid_t pid = fork();
420			if (pid < 0) {
421				rsyserr(FLOG, errno, "fork failed");
422				io_printf(f_out, "@ERROR: fork failed\n");
423				return -1;
424			}
425			if (pid) {
426				if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
427					putenv(p);
428				if (wait_process(pid, &status, 0) < 0)
429					status = -1;
430				if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
431					putenv(p);
432				if (WIFEXITED(status))
433					status = WEXITSTATUS(status);
434				else
435					status = -1;
436				if (asprintf(&p, "RSYNC_EXIT_STATUS=%d", status) > 0)
437					putenv(p);
438				system(lp_postxfer_exec(i));
439				_exit(status);
440			}
441		}
442		/* For pre-xfer exec, fork a child process to run the indicated
443		 * command, though it first waits for the parent process to
444		 * send us the user's request via a pipe. */
445		if (*lp_prexfer_exec(i)) {
446			int fds[2];
447			if (asprintf(&p, "RSYNC_PID=%ld", (long)getpid()) > 0)
448				putenv(p);
449			if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
450				rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
451				io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
452				return -1;
453			}
454			if (pre_exec_pid == 0) {
455				char buf[BIGPATHBUFLEN];
456				int j, len;
457				close(fds[1]);
458				set_blocking(fds[0]);
459				len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
460				if (len <= 0)
461					_exit(1);
462				if (asprintf(&p, "RSYNC_REQUEST=%s", buf) > 0)
463					putenv(p);
464				for (j = 0; ; j++) {
465					len = read_arg_from_pipe(fds[0], buf,
466								 BIGPATHBUFLEN);
467					if (len <= 0) {
468						if (!len)
469							break;
470						_exit(1);
471					}
472					if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) > 0)
473						putenv(p);
474				}
475				close(fds[0]);
476				close(STDIN_FILENO);
477				close(STDOUT_FILENO);
478				status = system(lp_prexfer_exec(i));
479				if (!WIFEXITED(status))
480					_exit(1);
481				_exit(WEXITSTATUS(status));
482			}
483			close(fds[0]);
484			set_blocking(fds[1]);
485			pre_exec_fd = fds[1];
486		}
487		umask(0);
488	}
489#endif
490
491	if (use_chroot) {
492		/*
493		 * XXX: The 'use chroot' flag is a fairly reliable
494		 * source of confusion, because it fails under two
495		 * important circumstances: running as non-root,
496		 * running on Win32 (or possibly others).  On the
497		 * other hand, if you are running as root, then it
498		 * might be better to always use chroot.
499		 *
500		 * So, perhaps if we can't chroot we should just issue
501		 * a warning, unless a "require chroot" flag is set,
502		 * in which case we fail.
503		 */
504		if (chroot(lp_path(i))) {
505			rsyserr(FLOG, errno, "chroot %s failed",
506				lp_path(i));
507			io_printf(f_out, "@ERROR: chroot failed\n");
508			return -1;
509		}
510
511		if (!push_dir("/", 0)) {
512			rsyserr(FLOG, errno, "chdir %s failed\n",
513				lp_path(i));
514			io_printf(f_out, "@ERROR: chdir failed\n");
515			return -1;
516		}
517
518	} else {
519		if (!push_dir(lp_path(i), 0)) {
520			rsyserr(FLOG, errno, "chdir %s failed\n",
521				lp_path(i));
522			io_printf(f_out, "@ERROR: chdir failed\n");
523			return -1;
524		}
525		sanitize_paths = 1;
526	}
527
528	if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
529		munge_symlinks = !use_chroot;
530	if (munge_symlinks) {
531		STRUCT_STAT st;
532		if (stat(SYMLINK_PREFIX, &st) == 0 && S_ISDIR(st.st_mode)) {
533			rprintf(FLOG, "Symlink munging is unsupported when a %s directory exists.\n",
534				SYMLINK_PREFIX);
535			io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
536			exit_cleanup(RERR_UNSUPPORTED);
537		}
538	}
539
540	if (am_root) {
541		/* XXXX: You could argue that if the daemon is started
542		 * by a non-root user and they explicitly specify a
543		 * gid, then we should try to change to that gid --
544		 * this could be possible if it's already in their
545		 * supplementary groups. */
546
547		/* TODO: Perhaps we need to document that if rsyncd is
548		 * started by somebody other than root it will inherit
549		 * all their supplementary groups. */
550
551		if (setgid(gid)) {
552			rsyserr(FLOG, errno, "setgid %d failed", (int)gid);
553			io_printf(f_out, "@ERROR: setgid failed\n");
554			return -1;
555		}
556#ifdef HAVE_SETGROUPS
557		/* Get rid of any supplementary groups this process
558		 * might have inheristed. */
559		if (setgroups(1, &gid)) {
560			rsyserr(FLOG, errno, "setgroups failed");
561			io_printf(f_out, "@ERROR: setgroups failed\n");
562			return -1;
563		}
564#endif
565
566		if (setuid(uid)) {
567			rsyserr(FLOG, errno, "setuid %d failed", (int)uid);
568			io_printf(f_out, "@ERROR: setuid failed\n");
569			return -1;
570		}
571
572		am_root = (MY_UID() == 0);
573	}
574
575	if (lp_temp_dir(i) && *lp_temp_dir(i)) {
576		tmpdir = lp_temp_dir(i);
577		if (strlen(tmpdir) >= MAXPATHLEN - 10) {
578			rprintf(FLOG,
579				"the 'temp dir' value for %s is WAY too long -- ignoring.\n",
580				name);
581			tmpdir = NULL;
582		}
583	}
584
585	io_printf(f_out, "@RSYNCD: OK\n");
586
587	maxargs = MAX_ARGS;
588	if (!(argv = new_array(char *, maxargs)))
589		out_of_memory("rsync_module");
590	argv[argc++] = "rsyncd";
591
592	while (1) {
593		if (!read_line(f_in, line, sizeof line - 1))
594			return -1;
595
596		if (!*line)
597			break;
598
599		p = line;
600
601		if (argc == maxargs) {
602			maxargs += MAX_ARGS;
603			if (!(argv = realloc_array(argv, char *, maxargs)))
604				out_of_memory("rsync_module");
605		}
606		if (!(argv[argc] = strdup(p)))
607			out_of_memory("rsync_module");
608
609		switch (start_glob) {
610		case 0:
611			argc++;
612			if (strcmp(line, ".") == 0)
613				start_glob = 1;
614			break;
615		case 1:
616			if (pre_exec_pid) {
617				err_msg = finish_pre_exec(pre_exec_pid,
618							  pre_exec_fd, p,
619							  argc, argv);
620				pre_exec_pid = 0;
621			}
622			request = strdup(p);
623			start_glob = 2;
624			/* FALL THROUGH */
625		default:
626			if (!err_msg)
627				glob_expand(name, &argv, &argc, &maxargs);
628			break;
629		}
630	}
631
632	if (pre_exec_pid) {
633		err_msg = finish_pre_exec(pre_exec_pid, pre_exec_fd, request,
634					  argc, argv);
635	}
636
637	verbose = 0; /* future verbosity is controlled by client options */
638	ret = parse_arguments(&argc, (const char ***) &argv, 0);
639	quiet = 0; /* Don't let someone try to be tricky. */
640
641	if (filesfrom_fd == 0)
642		filesfrom_fd = f_in;
643
644	if (request) {
645		if (*auth_user) {
646			rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
647				am_sender ? "on" : "to",
648				request, auth_user, host, addr);
649		} else {
650			rprintf(FLOG, "rsync %s %s from %s (%s)\n",
651				am_sender ? "on" : "to",
652				request, host, addr);
653		}
654		free(request);
655	}
656
657#ifndef DEBUG
658	/* don't allow the logs to be flooded too fast */
659	if (verbose > lp_max_verbosity(i))
660		verbose = lp_max_verbosity(i);
661#endif
662
663	if (protocol_version < 23
664	    && (protocol_version == 22 || am_sender))
665		io_start_multiplex_out();
666	else if (!ret || err_msg) {
667		/* We have to get I/O multiplexing started so that we can
668		 * get the error back to the client.  This means getting
669		 * the protocol setup finished first in later versions. */
670		setup_protocol(f_out, f_in);
671		if (!am_sender) {
672			/* Since we failed in our option parsing, we may not
673			 * have finished parsing that the client sent us a
674			 * --files-from option, so look for it manually.
675			 * Without this, the socket would be in the wrong
676			 * state for the upcoming error message. */
677			if (!files_from) {
678				int i;
679				for (i = 0; i < argc; i++) {
680					if (strncmp(argv[i], "--files-from", 12) == 0) {
681						files_from = "";
682						break;
683					}
684				}
685			}
686			if (files_from)
687				write_byte(f_out, 0);
688		}
689		io_start_multiplex_out();
690	}
691
692	if (!ret || err_msg) {
693		if (err_msg)
694			rprintf(FERROR, "%s", err_msg);
695		else
696			option_error();
697		msleep(400);
698		exit_cleanup(RERR_UNSUPPORTED);
699	}
700
701	if (lp_timeout(i) && lp_timeout(i) > io_timeout)
702		set_io_timeout(lp_timeout(i));
703
704	/* If we have some incoming/outgoing chmod changes, append them to
705	 * any user-specified changes (making our changes have priority).
706	 * We also get a pointer to just our changes so that a receiver
707	 * process can use them separately if --perms wasn't specified. */
708	if (am_sender)
709		p = lp_outgoing_chmod(i);
710	else
711		p = lp_incoming_chmod(i);
712	if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
713		rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
714			am_sender ? "outgo" : "incom", p);
715	}
716
717	start_server(f_in, f_out, argc, argv);
718
719	return 0;
720}
721
722/* send a list of available modules to the client. Don't list those
723   with "list = False". */
724static void send_listing(int fd)
725{
726	int n = lp_numservices();
727	int i;
728
729	for (i = 0; i < n; i++) {
730		if (lp_list(i))
731			io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
732	}
733
734	if (protocol_version >= 25)
735		io_printf(fd,"@RSYNCD: EXIT\n");
736}
737
738/* this is called when a connection is established to a client
739   and we want to start talking. The setup of the system is done from
740   here */
741int start_daemon(int f_in, int f_out)
742{
743	char line[1024];
744	char *motd, *addr, *host;
745	int i;
746
747	io_set_sock_fds(f_in, f_out);
748
749	/* We must load the config file before calling any function that
750	 * might cause log-file output to occur.  This ensures that the
751	 * "log file" param gets honored for the 2 non-forked use-cases
752	 * (when rsync is run by init and run by a remote shell). */
753	if (!lp_load(config_file, 0))
754		exit_cleanup(RERR_SYNTAX);
755
756	addr = client_addr(f_in);
757	host = client_name(f_in);
758	rprintf(FLOG, "connect from %s (%s)\n", host, addr);
759
760	if (!am_server) {
761		set_socket_options(f_in, "SO_KEEPALIVE");
762		if (sockopts)
763			set_socket_options(f_in, sockopts);
764		else
765			set_socket_options(f_in, lp_socket_options());
766		set_nonblocking(f_in);
767	}
768
769	io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
770
771	motd = lp_motd_file();
772	if (motd && *motd) {
773		FILE *f = fopen(motd,"r");
774		while (f && !feof(f)) {
775			int len = fread(line, 1, sizeof line - 1, f);
776			if (len > 0) {
777				line[len] = 0;
778				io_printf(f_out, "%s", line);
779			}
780		}
781		if (f)
782			fclose(f);
783		io_printf(f_out, "\n");
784	}
785
786	if (!read_line(f_in, line, sizeof line - 1))
787		return -1;
788
789	if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
790		io_printf(f_out, "@ERROR: protocol startup error\n");
791		return -1;
792	}
793	if (protocol_version > remote_protocol)
794		protocol_version = remote_protocol;
795
796	line[0] = 0;
797	if (!read_line(f_in, line, sizeof line - 1))
798		return -1;
799
800	if (!*line || strcmp(line, "#list") == 0) {
801		rprintf(FLOG, "module-list request from %s (%s)\n",
802			host, addr);
803		send_listing(f_out);
804		return -1;
805	}
806
807	if (*line == '#') {
808		/* it's some sort of command that I don't understand */
809		io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
810		return -1;
811	}
812
813	if ((i = lp_number(line)) < 0) {
814		rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
815			line, host, addr);
816		io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
817		return -1;
818	}
819
820#ifdef HAVE_SIGACTION
821	sigact.sa_flags = SA_NOCLDSTOP;
822#endif
823	SIGACTION(SIGCHLD, remember_children);
824
825	return rsync_module(f_in, f_out, i, addr, host);
826}
827
828int daemon_main(void)
829{
830	char *pid_file;
831
832	if (is_a_socket(STDIN_FILENO)) {
833		int i;
834
835		/* we are running via inetd - close off stdout and
836		 * stderr so that library functions (and getopt) don't
837		 * try to use them. Redirect them to /dev/null */
838		for (i = 1; i < 3; i++) {
839			close(i);
840			open("/dev/null", O_RDWR);
841		}
842
843		return start_daemon(STDIN_FILENO, STDIN_FILENO);
844	}
845
846	if (!no_detach)
847		become_daemon();
848
849	if (!lp_load(config_file, 1))
850		exit_cleanup(RERR_SYNTAX);
851
852	if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
853		rsync_port = RSYNC_PORT;
854	if (bind_address == NULL && *lp_bind_address())
855		bind_address = lp_bind_address();
856
857	log_init(0);
858
859	rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
860		RSYNC_VERSION, rsync_port);
861	/* TODO: If listening on a particular address, then show that
862	 * address too.  In fact, why not just do inet_ntop on the
863	 * local address??? */
864
865	if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
866		char pidbuf[16];
867		int fd;
868		pid_t pid = getpid();
869		cleanup_set_pid(pid);
870		if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
871					0666 & ~orig_umask)) == -1) {
872			cleanup_set_pid(0);
873			rsyserr(FLOG, errno, "failed to create pid file %s",
874				pid_file);
875			exit_cleanup(RERR_FILEIO);
876		}
877		snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
878		write(fd, pidbuf, strlen(pidbuf));
879		close(fd);
880	}
881
882	start_accept_loop(rsync_port, start_daemon);
883	return -1;
884}
885