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