The orig_umask value is now a mode_t.
[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 quiet;
32 extern int list_only;
33 extern int am_sender;
34 extern int am_server;
35 extern int am_daemon;
36 extern int am_root;
37 extern int rsync_port;
38 extern int kluge_around_eof;
39 extern int daemon_over_rsh;
40 extern int sanitize_paths;
41 extern int filesfrom_fd;
42 extern int remote_protocol;
43 extern int protocol_version;
44 extern int io_timeout;
45 extern int no_detach;
46 extern int default_af_hint;
47 extern mode_t orig_umask;
48 extern char *bind_address;
49 extern char *sockopts;
50 extern char *config_file;
51 extern char *files_from;
52 extern char *tmpdir;
53 extern struct chmod_mode_struct *chmod_modes;
54 extern struct filter_list_struct server_filter_list;
55
56 char *auth_user;
57 int read_only = 0;
58 int daemon_log_format_has_i = 0;
59 int daemon_log_format_has_o_or_i = 0;
60 int module_id = -1;
61 struct chmod_mode_struct *daemon_chmod_modes;
62
63 /* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
64 unsigned int module_dirlen = 0;
65
66 #ifdef HAVE_SIGACTION
67 static struct sigaction sigact;
68 #endif
69
70 /**
71  * Run a client connected to an rsyncd.  The alternative to this
72  * function for remote-shell connections is do_cmd().
73  *
74  * After negotiating which module to use and reading the server's
75  * motd, this hands over to client_run().  Telling the server the
76  * module will cause it to chroot/setuid/etc.
77  *
78  * Instead of doing a transfer, the client may at this stage instead
79  * get a listing of remote modules and exit.
80  *
81  * @return -1 for error in startup, or the result of client_run().
82  * Either way, it eventually gets passed to exit_cleanup().
83  **/
84 int start_socket_client(char *host, char *path, int argc, char *argv[])
85 {
86         int fd, ret;
87         char *p, *user = NULL;
88
89         /* This is redundant with code in start_inband_exchange(), but this
90          * short-circuits a problem in the client before we open a socket,
91          * and the extra check won't hurt. */
92         if (*path == '/') {
93                 rprintf(FERROR,
94                         "ERROR: The remote path must start with a module name not a /\n");
95                 return -1;
96         }
97
98         if ((p = strrchr(host, '@')) != NULL) {
99                 user = host;
100                 host = p+1;
101                 *p = '\0';
102         }
103
104         fd = open_socket_out_wrapped(host, rsync_port, bind_address,
105                                      default_af_hint);
106         if (fd == -1)
107                 exit_cleanup(RERR_SOCKETIO);
108
109         set_socket_options(fd, sockopts);
110
111         ret = start_inband_exchange(user, path, fd, fd, argc);
112
113         return ret ? ret : client_run(fd, fd, -1, argc, argv);
114 }
115
116 int start_inband_exchange(char *user, char *path, int f_in, int f_out, 
117                           int argc)
118 {
119         int i;
120         char *sargs[MAX_ARGS];
121         int sargc = 0;
122         char line[BIGPATHBUFLEN];
123         char *p;
124
125         if (argc == 0 && !am_sender)
126                 list_only |= 1;
127
128         if (*path == '/') {
129                 rprintf(FERROR,
130                         "ERROR: The remote path must start with a module name\n");
131                 return -1;
132         }
133
134         if (!user)
135                 user = getenv("USER");
136         if (!user)
137                 user = getenv("LOGNAME");
138
139         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
140
141         if (!read_line(f_in, line, sizeof line - 1)) {
142                 rprintf(FERROR, "rsync: did not see server greeting\n");
143                 return -1;
144         }
145
146         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
147                 /* note that read_line strips of \n or \r */
148                 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
149                         line);
150                 return -1;
151         }
152         if (protocol_version > remote_protocol)
153                 protocol_version = remote_protocol;
154
155         if (list_only && protocol_version >= 29)
156                 list_only |= 2;
157
158         /* set daemon_over_rsh to false since we need to build the
159          * true set of args passed through the rsh/ssh connection;
160          * this is a no-op for direct-socket-connection mode */
161         daemon_over_rsh = 0;
162         server_options(sargs, &sargc);
163
164         sargs[sargc++] = ".";
165
166         if (path && *path)
167                 sargs[sargc++] = path;
168
169         sargs[sargc] = NULL;
170
171         if (verbose > 1)
172                 print_child_argv(sargs);
173
174         p = strchr(path,'/');
175         if (p) *p = 0;
176         io_printf(f_out, "%s\n", path);
177         if (p) *p = '/';
178
179         /* Old servers may just drop the connection here,
180          rather than sending a proper EXIT command.  Yuck. */
181         kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
182
183         while (1) {
184                 if (!read_line(f_in, line, sizeof line - 1)) {
185                         rprintf(FERROR, "rsync: didn't get server startup line\n");
186                         return -1;
187                 }
188
189                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
190                         auth_client(f_out, user, line+18);
191                         continue;
192                 }
193
194                 if (strcmp(line,"@RSYNCD: OK") == 0)
195                         break;
196
197                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
198                         /* This is sent by recent versions of the
199                          * server to terminate the listing of modules.
200                          * We don't want to go on and transfer
201                          * anything; just exit. */
202                         exit(0);
203                 }
204
205                 if (strncmp(line, "@ERROR", 6) == 0) {
206                         rprintf(FERROR, "%s\n", line);
207                         /* This is always fatal; the server will now
208                          * close the socket. */
209                         return -1;
210                 }
211
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
229 static 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
254 static 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
271 static 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)) {
332                 if (log_format_has(lp_log_format(i), 'i'))
333                         daemon_log_format_has_i = 1;
334                 if (daemon_log_format_has_i
335                     || log_format_has(lp_log_format(i), 'o'))
336                         daemon_log_format_has_o_or_i = 1;
337         }
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();
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                                 char *ret1, *ret2;
427                                 if (wait_process(pid, &status, 0) < 0)
428                                         status = -1;
429                                 if (asprintf(&ret1, "RSYNC_RAW_STATUS=%d", status) > 0)
430                                         putenv(ret1);
431                                 if (WIFEXITED(status))
432                                         status = WEXITSTATUS(status);
433                                 else
434                                         status = -1;
435                                 if (asprintf(&ret2, "RSYNC_EXIT_STATUS=%d", status) > 0)
436                                         putenv(ret2);
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 (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
447                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
448                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
449                                 return -1;
450                         }
451                         if (pre_exec_pid == 0) {
452                                 char buf[BIGPATHBUFLEN];
453                                 int j, len;
454                                 close(fds[1]);
455                                 set_blocking(fds[0]);
456                                 len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
457                                 if (len <= 0)
458                                         _exit(1);
459                                 if (asprintf(&p, "RSYNC_REQUEST=%s", buf) < 0)
460                                         out_of_memory("rsync_module");
461                                 putenv(p);
462                                 for (j = 0; ; j++) {
463                                         len = read_arg_from_pipe(fds[0], buf,
464                                                                  BIGPATHBUFLEN);
465                                         if (len <= 0) {
466                                                 if (!len)
467                                                         break;
468                                                 _exit(1);
469                                         }
470                                         if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) < 0)
471                                                 out_of_memory("rsync_module");
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("/")) {
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))) {
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". */
711 static 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 */
728 int start_daemon(int f_in, int f_out)
729 {
730         char line[1024];
731         char *motd;
732         char *addr = client_addr(f_in);
733         char *host = client_name(f_in);
734         int i;
735
736         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
737
738         io_set_sock_fds(f_in, f_out);
739
740         if (!lp_load(config_file, 0))
741                 exit_cleanup(RERR_SYNTAX);
742
743         log_init();
744
745         if (!am_server) {
746                 set_socket_options(f_in, "SO_KEEPALIVE");
747                 if (sockopts)
748                         set_socket_options(f_in, sockopts);
749                 else
750                         set_socket_options(f_in, lp_socket_options());
751                 set_nonblocking(f_in);
752         }
753
754         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
755
756         motd = lp_motd_file();
757         if (motd && *motd) {
758                 FILE *f = fopen(motd,"r");
759                 while (f && !feof(f)) {
760                         int len = fread(line, 1, sizeof line - 1, f);
761                         if (len > 0) {
762                                 line[len] = 0;
763                                 io_printf(f_out, "%s", line);
764                         }
765                 }
766                 if (f)
767                         fclose(f);
768                 io_printf(f_out, "\n");
769         }
770
771         if (!read_line(f_in, line, sizeof line - 1))
772                 return -1;
773
774         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
775                 io_printf(f_out, "@ERROR: protocol startup error\n");
776                 return -1;
777         }
778         if (protocol_version > remote_protocol)
779                 protocol_version = remote_protocol;
780
781         line[0] = 0;
782         if (!read_line(f_in, line, sizeof line - 1))
783                 return -1;
784
785         if (!*line || strcmp(line, "#list") == 0) {
786                 rprintf(FLOG, "module-list request from %s (%s)\n",
787                         host, addr);
788                 send_listing(f_out);
789                 return -1;
790         }
791
792         if (*line == '#') {
793                 /* it's some sort of command that I don't understand */
794                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
795                 return -1;
796         }
797
798         if ((i = lp_number(line)) < 0) {
799                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
800                         line, host, addr);
801                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
802                 return -1;
803         }
804
805 #ifdef HAVE_SIGACTION
806         sigact.sa_flags = SA_NOCLDSTOP;
807 #endif
808         SIGACTION(SIGCHLD, remember_children);
809
810         return rsync_module(f_in, f_out, i, addr, host);
811 }
812
813 int daemon_main(void)
814 {
815         char *pid_file;
816
817         if (is_a_socket(STDIN_FILENO)) {
818                 int i;
819
820                 /* we are running via inetd - close off stdout and
821                  * stderr so that library functions (and getopt) don't
822                  * try to use them. Redirect them to /dev/null */
823                 for (i = 1; i < 3; i++) {
824                         close(i);
825                         open("/dev/null", O_RDWR);
826                 }
827
828                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
829         }
830
831         if (!no_detach)
832                 become_daemon();
833
834         if (!lp_load(config_file, 1))
835                 exit_cleanup(RERR_SYNTAX);
836
837         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
838                 rsync_port = RSYNC_PORT;
839         if (bind_address == NULL && *lp_bind_address())
840                 bind_address = lp_bind_address();
841
842         log_init();
843
844         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
845                 RSYNC_VERSION, rsync_port);
846         /* TODO: If listening on a particular address, then show that
847          * address too.  In fact, why not just do inet_ntop on the
848          * local address??? */
849
850         if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
851                 char pidbuf[16];
852                 int fd;
853                 pid_t pid = getpid();
854                 cleanup_set_pid(pid);
855                 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
856                                         0666 & ~orig_umask)) == -1) {
857                         cleanup_set_pid(0);
858                         rsyserr(FLOG, errno, "failed to create pid file %s",
859                                 pid_file);
860                         exit_cleanup(RERR_FILEIO);
861                 }
862                 snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
863                 write(fd, pidbuf, strlen(pidbuf));
864                 close(fd);
865         }
866
867         start_accept_loop(rsync_port, start_daemon);
868         return -1;
869 }