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