A helper file for cleanup.c.
[rsync/rsync.git] / clientserver.c
1 /*
2  * The socket based protocol for setting up a connection with rsyncd.
3  *
4  * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5  * Copyright (C) 2001-2002 Martin Pool <mbp@samba.org>
6  * Copyright (C) 2002, 2003, 2004, 2005, 2006 Wayne Davison
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21  */
22
23 #include "rsync.h"
24
25 extern int verbose;
26 extern int quiet;
27 extern int list_only;
28 extern int am_sender;
29 extern int am_server;
30 extern int am_daemon;
31 extern int am_root;
32 extern int rsync_port;
33 extern int kluge_around_eof;
34 extern int daemon_over_rsh;
35 extern int sanitize_paths;
36 extern int filesfrom_fd;
37 extern int remote_protocol;
38 extern int protocol_version;
39 extern int io_timeout;
40 extern int no_detach;
41 extern int default_af_hint;
42 extern int logfile_format_has_i;
43 extern int logfile_format_has_o_or_i;
44 extern mode_t orig_umask;
45 extern char *bind_address;
46 extern char *sockopts;
47 extern char *config_file;
48 extern char *logfile_format;
49 extern char *files_from;
50 extern char *tmpdir;
51 extern struct chmod_mode_struct *chmod_modes;
52 extern struct filter_list_struct server_filter_list;
53
54 char *auth_user;
55 int read_only = 0;
56 int module_id = -1;
57 struct chmod_mode_struct *daemon_chmod_modes;
58
59 /* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
60 unsigned int module_dirlen = 0;
61
62 #ifdef HAVE_SIGACTION
63 static struct sigaction sigact;
64 #endif
65
66 /**
67  * Run a client connected to an rsyncd.  The alternative to this
68  * function for remote-shell connections is do_cmd().
69  *
70  * After negotiating which module to use and reading the server's
71  * motd, this hands over to client_run().  Telling the server the
72  * module will cause it to chroot/setuid/etc.
73  *
74  * Instead of doing a transfer, the client may at this stage instead
75  * get a listing of remote modules and exit.
76  *
77  * @return -1 for error in startup, or the result of client_run().
78  * Either way, it eventually gets passed to exit_cleanup().
79  **/
80 int start_socket_client(char *host, char *path, int argc, char *argv[])
81 {
82         int fd, ret;
83         char *p, *user = NULL;
84
85         /* This is redundant with code in start_inband_exchange(), but this
86          * short-circuits a problem in the client before we open a socket,
87          * and the extra check won't hurt. */
88         if (*path == '/') {
89                 rprintf(FERROR,
90                         "ERROR: The remote path must start with a module name not a /\n");
91                 return -1;
92         }
93
94         if ((p = strrchr(host, '@')) != NULL) {
95                 user = host;
96                 host = p+1;
97                 *p = '\0';
98         }
99
100         fd = open_socket_out_wrapped(host, rsync_port, bind_address,
101                                      default_af_hint);
102         if (fd == -1)
103                 exit_cleanup(RERR_SOCKETIO);
104
105         set_socket_options(fd, sockopts);
106
107         ret = start_inband_exchange(user, path, fd, fd, argc);
108
109         return ret ? ret : client_run(fd, fd, -1, argc, argv);
110 }
111
112 int start_inband_exchange(char *user, char *path, int f_in, int f_out,
113                           int argc)
114 {
115         int i;
116         char *sargs[MAX_ARGS];
117         int sargc = 0;
118         char line[BIGPATHBUFLEN];
119         char *p;
120
121         if (argc == 0 && !am_sender)
122                 list_only |= 1;
123
124         if (*path == '/') {
125                 rprintf(FERROR,
126                         "ERROR: The remote path must start with a module name\n");
127                 return -1;
128         }
129
130         if (!user)
131                 user = getenv("USER");
132         if (!user)
133                 user = getenv("LOGNAME");
134
135         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
136
137         if (!read_line(f_in, line, sizeof line - 1)) {
138                 rprintf(FERROR, "rsync: did not see server greeting\n");
139                 return -1;
140         }
141
142         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
143                 /* note that read_line strips of \n or \r */
144                 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
145                         line);
146                 return -1;
147         }
148         if (protocol_version > remote_protocol)
149                 protocol_version = remote_protocol;
150
151         if (list_only && protocol_version >= 29)
152                 list_only |= 2;
153
154         /* set daemon_over_rsh to false since we need to build the
155          * true set of args passed through the rsh/ssh connection;
156          * this is a no-op for direct-socket-connection mode */
157         daemon_over_rsh = 0;
158         server_options(sargs, &sargc);
159
160         sargs[sargc++] = ".";
161
162         if (path && *path)
163                 sargs[sargc++] = path;
164
165         sargs[sargc] = NULL;
166
167         if (verbose > 1)
168                 print_child_argv(sargs);
169
170         p = strchr(path,'/');
171         if (p) *p = 0;
172         io_printf(f_out, "%s\n", path);
173         if (p) *p = '/';
174
175         /* Old servers may just drop the connection here,
176          rather than sending a proper EXIT command.  Yuck. */
177         kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
178
179         while (1) {
180                 if (!read_line(f_in, line, sizeof line - 1)) {
181                         rprintf(FERROR, "rsync: didn't get server startup line\n");
182                         return -1;
183                 }
184
185                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
186                         auth_client(f_out, user, line+18);
187                         continue;
188                 }
189
190                 if (strcmp(line,"@RSYNCD: OK") == 0)
191                         break;
192
193                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
194                         /* This is sent by recent versions of the
195                          * server to terminate the listing of modules.
196                          * We don't want to go on and transfer
197                          * anything; just exit. */
198                         exit(0);
199                 }
200
201                 if (strncmp(line, "@ERROR", 6) == 0) {
202                         rprintf(FERROR, "%s\n", line);
203                         /* This is always fatal; the server will now
204                          * close the socket. */
205                         return -1;
206                 }
207
208                 rprintf(FINFO, "%s\n", line);
209         }
210         kluge_around_eof = 0;
211
212         for (i = 0; i < sargc; i++) {
213                 io_printf(f_out, "%s\n", sargs[i]);
214         }
215         io_printf(f_out, "\n");
216
217         if (protocol_version < 23) {
218                 if (protocol_version == 22 || !am_sender)
219                         io_start_multiplex_in();
220         }
221
222         return 0;
223 }
224
225 static char *finish_pre_exec(pid_t pid, int fd, char *request,
226                              int argc, char *argv[])
227 {
228         int j, status = -1;
229
230         if (request) {
231                 write_buf(fd, request, strlen(request)+1);
232                 for (j = 0; j < argc; j++)
233                         write_buf(fd, argv[j], strlen(argv[j])+1);
234         }
235
236         write_byte(fd, 0);
237
238         close(fd);
239
240         if (wait_process(pid, &status, 0) < 0
241          || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
242                 char *e;
243                 if (asprintf(&e, "pre-xfer exec returned failure (%d)\n", status) < 0)
244                         out_of_memory("finish_pre_exec");
245                 return e;
246         }
247         return NULL;
248 }
249
250 static int read_arg_from_pipe(int fd, char *buf, int limit)
251 {
252         char *bp = buf, *eob = buf + limit - 1;
253
254         while (1) {
255             if (read(fd, bp, 1) != 1)
256                 return -1;
257             if (*bp == '\0')
258                 break;
259             if (bp < eob)
260                 bp++;
261         }
262         *bp = '\0';
263
264         return bp - buf;
265 }
266
267 static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
268 {
269         int argc = 0;
270         int maxargs;
271         char **argv;
272         char line[BIGPATHBUFLEN];
273         uid_t uid = (uid_t)-2;  /* canonically "nobody" */
274         gid_t gid = (gid_t)-2;
275         char *p, *err_msg = NULL;
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) && !logfile_format)
328                 logfile_format = lp_log_format(i);
329         if (log_format_has(logfile_format, 'i'))
330                 logfile_format_has_i = 1;
331         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
332                 logfile_format_has_o_or_i = 1;
333
334         am_root = (MY_UID() == 0);
335
336         if (am_root) {
337                 p = lp_uid(i);
338                 if (!name_to_uid(p, &uid)) {
339                         if (!isdigit(*(unsigned char *)p)) {
340                                 rprintf(FLOG, "Invalid uid %s\n", p);
341                                 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
342                                 return -1;
343                         }
344                         uid = atoi(p);
345                 }
346
347                 p = lp_gid(i);
348                 if (!name_to_gid(p, &gid)) {
349                         if (!isdigit(*(unsigned char *)p)) {
350                                 rprintf(FLOG, "Invalid gid %s\n", p);
351                                 io_printf(f_out, "@ERROR: invalid gid %s\n", p);
352                                 return -1;
353                         }
354                         gid = atoi(p);
355                 }
356         }
357
358         /* TODO: If we're not root, but the configuration requests
359          * that we change to some uid other than the current one, then
360          * log a warning. */
361
362         /* TODO: Perhaps take a list of gids, and make them into the
363          * supplementary groups. */
364
365         if (use_chroot || (module_dirlen = strlen(lp_path(i))) == 1) {
366                 module_dirlen = 0;
367                 set_filter_dir("/", 1);
368         } else
369                 set_filter_dir(lp_path(i), module_dirlen);
370
371         p = lp_filter(i);
372         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
373                    XFLG_ABS_IF_SLASH);
374
375         p = lp_include_from(i);
376         parse_filter_file(&server_filter_list, p, MATCHFLG_INCLUDE,
377             XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
378
379         p = lp_include(i);
380         parse_rule(&server_filter_list, p,
381                    MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
382                    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
383
384         p = lp_exclude_from(i);
385         parse_filter_file(&server_filter_list, p, 0,
386             XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
387
388         p = lp_exclude(i);
389         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
390                    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
391
392         log_init(1);
393
394 #ifdef HAVE_PUTENV
395         if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
396                 char *modname, *modpath, *hostaddr, *hostname, *username;
397                 int status;
398                 if (asprintf(&modname, "RSYNC_MODULE_NAME=%s", name) < 0
399                  || asprintf(&modpath, "RSYNC_MODULE_PATH=%s", lp_path(i)) < 0
400                  || asprintf(&hostaddr, "RSYNC_HOST_ADDR=%s", addr) < 0
401                  || asprintf(&hostname, "RSYNC_HOST_NAME=%s", host) < 0
402                  || asprintf(&username, "RSYNC_USER_NAME=%s", auth_user) < 0)
403                         out_of_memory("rsync_module");
404                 putenv(modname);
405                 putenv(modpath);
406                 putenv(hostaddr);
407                 putenv(hostname);
408                 putenv(username);
409                 umask(orig_umask);
410                 /* For post-xfer exec, fork a new process to run the rsync
411                  * daemon while this process waits for the exit status and
412                  * runs the indicated command at that point. */
413                 if (*lp_postxfer_exec(i)) {
414                         pid_t pid = fork();
415                         if (pid < 0) {
416                                 rsyserr(FLOG, errno, "fork failed");
417                                 io_printf(f_out, "@ERROR: fork failed\n");
418                                 return -1;
419                         }
420                         if (pid) {
421                                 if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
422                                         putenv(p);
423                                 if (wait_process(pid, &status, 0) < 0)
424                                         status = -1;
425                                 if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
426                                         putenv(p);
427                                 if (WIFEXITED(status))
428                                         status = WEXITSTATUS(status);
429                                 else
430                                         status = -1;
431                                 if (asprintf(&p, "RSYNC_EXIT_STATUS=%d", status) > 0)
432                                         putenv(p);
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 (asprintf(&p, "RSYNC_PID=%ld", (long)getpid()) > 0)
443                                 putenv(p);
444                         if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
445                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
446                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
447                                 return -1;
448                         }
449                         if (pre_exec_pid == 0) {
450                                 char buf[BIGPATHBUFLEN];
451                                 int j, len;
452                                 close(fds[1]);
453                                 set_blocking(fds[0]);
454                                 len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
455                                 if (len <= 0)
456                                         _exit(1);
457                                 if (asprintf(&p, "RSYNC_REQUEST=%s", buf) > 0)
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                                                 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("/", 0)) {
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), 0)) {
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         quiet = 0; /* Don't let someone try to be tricky. */
623
624         if (filesfrom_fd == 0)
625                 filesfrom_fd = f_in;
626
627         if (request) {
628                 if (*auth_user) {
629                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
630                                 am_sender ? "on" : "to",
631                                 request, auth_user, host, addr);
632                 } else {
633                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
634                                 am_sender ? "on" : "to",
635                                 request, host, addr);
636                 }
637                 free(request);
638         }
639
640 #ifndef DEBUG
641         /* don't allow the logs to be flooded too fast */
642         if (verbose > lp_max_verbosity(i))
643                 verbose = lp_max_verbosity(i);
644 #endif
645
646         if (protocol_version < 23
647             && (protocol_version == 22 || am_sender))
648                 io_start_multiplex_out();
649         else if (!ret || err_msg) {
650                 /* We have to get I/O multiplexing started so that we can
651                  * get the error back to the client.  This means getting
652                  * the protocol setup finished first in later versions. */
653                 setup_protocol(f_out, f_in);
654                 if (!am_sender) {
655                         /* Since we failed in our option parsing, we may not
656                          * have finished parsing that the client sent us a
657                          * --files-from option, so look for it manually.
658                          * Without this, the socket would be in the wrong
659                          * state for the upcoming error message. */
660                         if (!files_from) {
661                                 int i;
662                                 for (i = 0; i < argc; i++) {
663                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
664                                                 files_from = "";
665                                                 break;
666                                         }
667                                 }
668                         }
669                         if (files_from)
670                                 write_byte(f_out, 0);
671                 }
672                 io_start_multiplex_out();
673         }
674
675         if (!ret || err_msg) {
676                 if (err_msg)
677                         rprintf(FERROR, err_msg);
678                 else
679                         option_error();
680                 msleep(400);
681                 exit_cleanup(RERR_UNSUPPORTED);
682         }
683
684         if (lp_timeout(i) && lp_timeout(i) > io_timeout)
685                 set_io_timeout(lp_timeout(i));
686
687         /* If we have some incoming/outgoing chmod changes, append them to
688          * any user-specified changes (making our changes have priority).
689          * We also get a pointer to just our changes so that a receiver
690          * process can use them separately if --perms wasn't specified. */
691         if (am_sender)
692                 p = lp_outgoing_chmod(i);
693         else
694                 p = lp_incoming_chmod(i);
695         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
696                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
697                         am_sender ? "outgo" : "incom", p);
698         }
699
700         start_server(f_in, f_out, argc, argv);
701
702         return 0;
703 }
704
705 /* send a list of available modules to the client. Don't list those
706    with "list = False". */
707 static void send_listing(int fd)
708 {
709         int n = lp_numservices();
710         int i;
711
712         for (i = 0; i < n; i++) {
713                 if (lp_list(i))
714                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
715         }
716
717         if (protocol_version >= 25)
718                 io_printf(fd,"@RSYNCD: EXIT\n");
719 }
720
721 /* this is called when a connection is established to a client
722    and we want to start talking. The setup of the system is done from
723    here */
724 int start_daemon(int f_in, int f_out)
725 {
726         char line[1024];
727         char *motd, *addr, *host;
728         int i;
729
730         io_set_sock_fds(f_in, f_out);
731
732         /* We must load the config file before calling any function that
733          * might cause log-file output to occur.  This ensures that the
734          * "log file" param gets honored for the 2 non-forked use-cases
735          * (when rsync is run by init and run by a remote shell). */
736         if (!lp_load(config_file, 0))
737                 exit_cleanup(RERR_SYNTAX);
738
739         addr = client_addr(f_in);
740         host = client_name(f_in);
741         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
742
743         if (!am_server) {
744                 set_socket_options(f_in, "SO_KEEPALIVE");
745                 if (sockopts)
746                         set_socket_options(f_in, sockopts);
747                 else
748                         set_socket_options(f_in, lp_socket_options());
749                 set_nonblocking(f_in);
750         }
751
752         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
753
754         motd = lp_motd_file();
755         if (motd && *motd) {
756                 FILE *f = fopen(motd,"r");
757                 while (f && !feof(f)) {
758                         int len = fread(line, 1, sizeof line - 1, f);
759                         if (len > 0) {
760                                 line[len] = 0;
761                                 io_printf(f_out, "%s", line);
762                         }
763                 }
764                 if (f)
765                         fclose(f);
766                 io_printf(f_out, "\n");
767         }
768
769         if (!read_line(f_in, line, sizeof line - 1))
770                 return -1;
771
772         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
773                 io_printf(f_out, "@ERROR: protocol startup error\n");
774                 return -1;
775         }
776         if (protocol_version > remote_protocol)
777                 protocol_version = remote_protocol;
778
779         line[0] = 0;
780         if (!read_line(f_in, line, sizeof line - 1))
781                 return -1;
782
783         if (!*line || strcmp(line, "#list") == 0) {
784                 rprintf(FLOG, "module-list request from %s (%s)\n",
785                         host, addr);
786                 send_listing(f_out);
787                 return -1;
788         }
789
790         if (*line == '#') {
791                 /* it's some sort of command that I don't understand */
792                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
793                 return -1;
794         }
795
796         if ((i = lp_number(line)) < 0) {
797                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
798                         line, host, addr);
799                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
800                 return -1;
801         }
802
803 #ifdef HAVE_SIGACTION
804         sigact.sa_flags = SA_NOCLDSTOP;
805 #endif
806         SIGACTION(SIGCHLD, remember_children);
807
808         return rsync_module(f_in, f_out, i, addr, host);
809 }
810
811 int daemon_main(void)
812 {
813         char *pid_file;
814
815         if (is_a_socket(STDIN_FILENO)) {
816                 int i;
817
818                 /* we are running via inetd - close off stdout and
819                  * stderr so that library functions (and getopt) don't
820                  * try to use them. Redirect them to /dev/null */
821                 for (i = 1; i < 3; i++) {
822                         close(i);
823                         open("/dev/null", O_RDWR);
824                 }
825
826                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
827         }
828
829         if (!no_detach)
830                 become_daemon();
831
832         if (!lp_load(config_file, 1))
833                 exit_cleanup(RERR_SYNTAX);
834
835         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
836                 rsync_port = RSYNC_PORT;
837         if (bind_address == NULL && *lp_bind_address())
838                 bind_address = lp_bind_address();
839
840         log_init(0);
841
842         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
843                 RSYNC_VERSION, rsync_port);
844         /* TODO: If listening on a particular address, then show that
845          * address too.  In fact, why not just do inet_ntop on the
846          * local address??? */
847
848         if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
849                 char pidbuf[16];
850                 int fd;
851                 pid_t pid = getpid();
852                 cleanup_set_pid(pid);
853                 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
854                                         0666 & ~orig_umask)) == -1) {
855                         cleanup_set_pid(0);
856                         rsyserr(FLOG, errno, "failed to create pid file %s",
857                                 pid_file);
858                         exit_cleanup(RERR_FILEIO);
859                 }
860                 snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
861                 write(fd, pidbuf, strlen(pidbuf));
862                 close(fd);
863         }
864
865         start_accept_loop(rsync_port, start_daemon);
866         return -1;
867 }