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