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