Some indentation fixes.
[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-2020 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 3 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, visit the http://fsf.org website.
20  */
21
22 #include "rsync.h"
23 #include "itypes.h"
24
25 extern int quiet;
26 extern int dry_run;
27 extern int output_motd;
28 extern int list_only;
29 extern int am_sender;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_root;
33 extern int msgs2stderr;
34 extern int rsync_port;
35 extern int protect_args;
36 extern int ignore_errors;
37 extern int preserve_xattrs;
38 extern int kluge_around_eof;
39 extern int daemon_over_rsh;
40 extern int munge_symlinks;
41 extern int sanitize_paths;
42 extern int numeric_ids;
43 extern int filesfrom_fd;
44 extern int remote_protocol;
45 extern int protocol_version;
46 extern int io_timeout;
47 extern int no_detach;
48 extern int write_batch;
49 extern int default_af_hint;
50 extern int logfile_format_has_i;
51 extern int logfile_format_has_o_or_i;
52 extern char *bind_address;
53 extern char *config_file;
54 extern char *logfile_format;
55 extern char *files_from;
56 extern char *tmpdir;
57 extern struct chmod_mode_struct *chmod_modes;
58 extern filter_rule_list daemon_filter_list;
59 #ifdef ICONV_OPTION
60 extern char *iconv_opt;
61 extern iconv_t ic_send, ic_recv;
62 #endif
63 extern uid_t our_uid;
64 extern gid_t our_gid;
65
66 char *auth_user;
67 int read_only = 0;
68 int module_id = -1;
69 int pid_file_fd = -1;
70 struct chmod_mode_struct *daemon_chmod_modes;
71
72 /* module_dirlen is the length of the module_dir string when in daemon
73  * mode and module_dir is not "/"; otherwise 0.  (Note that a chroot-
74  * enabled module can have a non-"/" module_dir these days.) */
75 char *module_dir = NULL;
76 unsigned int module_dirlen = 0;
77
78 char *full_module_path;
79
80 static int rl_nulls = 0;
81
82 #ifdef HAVE_SIGACTION
83 static struct sigaction sigact;
84 #endif
85
86 static item_list gid_list = EMPTY_ITEM_LIST;
87
88 /* Used when "reverse lookup" is off. */
89 const char undetermined_hostname[] = "UNDETERMINED";
90
91 /**
92  * Run a client connected to an rsyncd.  The alternative to this
93  * function for remote-shell connections is do_cmd().
94  *
95  * After negotiating which module to use and reading the server's
96  * motd, this hands over to client_run().  Telling the server the
97  * module will cause it to chroot/setuid/etc.
98  *
99  * Instead of doing a transfer, the client may at this stage instead
100  * get a listing of remote modules and exit.
101  *
102  * @return -1 for error in startup, or the result of client_run().
103  * Either way, it eventually gets passed to exit_cleanup().
104  **/
105 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
106                         int argc, char *argv[])
107 {
108         int fd, ret;
109         char *p, *user = NULL;
110
111         /* This is redundant with code in start_inband_exchange(), but this
112          * short-circuits a problem in the client before we open a socket,
113          * and the extra check won't hurt. */
114         if (**remote_argv == '/') {
115                 rprintf(FERROR,
116                         "ERROR: The remote path must start with a module name not a /\n");
117                 return -1;
118         }
119
120         if ((p = strrchr(host, '@')) != NULL) {
121                 user = host;
122                 host = p+1;
123                 *p = '\0';
124         }
125
126         fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
127         if (fd == -1)
128                 exit_cleanup(RERR_SOCKETIO);
129
130 #ifdef ICONV_CONST
131         setup_iconv();
132 #endif
133
134         ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
135
136         return ret ? ret : client_run(fd, fd, -1, argc, argv);
137 }
138
139 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
140 {
141         int remote_sub = -1;
142 #if SUBPROTOCOL_VERSION != 0
143         int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
144 #else
145         int our_sub = 0;
146 #endif
147         char *motd;
148
149         io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
150
151         if (!am_client) {
152                 motd = lp_motd_file();
153                 if (motd && *motd) {
154                         FILE *f = fopen(motd,"r");
155                         while (f && !feof(f)) {
156                                 int len = fread(buf, 1, bufsiz - 1, f);
157                                 if (len > 0)
158                                         write_buf(f_out, buf, len);
159                         }
160                         if (f)
161                                 fclose(f);
162                         write_sbuf(f_out, "\n");
163                 }
164         }
165
166         /* This strips the \n. */
167         if (!read_line_old(f_in, buf, bufsiz, 0)) {
168                 if (am_client)
169                         rprintf(FERROR, "rsync: did not see server greeting\n");
170                 return -1;
171         }
172
173         if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
174                 if (am_client)
175                         rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
176                 else
177                         io_printf(f_out, "@ERROR: protocol startup error\n");
178                 return -1;
179         }
180
181         if (remote_sub < 0) {
182                 if (remote_protocol == 30) {
183                         if (am_client)
184                                 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
185                         else
186                                 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
187                         return -1;
188                 }
189                 remote_sub = 0;
190         }
191
192         if (protocol_version > remote_protocol) {
193                 protocol_version = remote_protocol;
194                 if (remote_sub)
195                         protocol_version--;
196         } else if (protocol_version == remote_protocol) {
197                 if (remote_sub != our_sub)
198                         protocol_version--;
199         }
200 #if SUBPROTOCOL_VERSION != 0
201         else if (protocol_version < remote_protocol) {
202                 if (our_sub)
203                         protocol_version--;
204         }
205 #endif
206
207         if (protocol_version >= 30)
208                 rl_nulls = 1;
209
210         return 0;
211 }
212
213 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
214 {
215         int i, modlen;
216         char line[BIGPATHBUFLEN];
217         char *sargs[MAX_ARGS];
218         int sargc = 0;
219         char *p, *modname;
220
221         assert(argc > 0 && *argv != NULL);
222
223         if (**argv == '/') {
224                 rprintf(FERROR,
225                         "ERROR: The remote path must start with a module name\n");
226                 return -1;
227         }
228
229         if (!(p = strchr(*argv, '/')))
230                 modlen = strlen(*argv);
231         else
232                 modlen = p - *argv;
233
234         if (!(modname = new_array(char, modlen+1+1))) /* room for '/' & '\0' */
235                 out_of_memory("start_inband_exchange");
236         strlcpy(modname, *argv, modlen + 1);
237         modname[modlen] = '/';
238         modname[modlen+1] = '\0';
239
240         if (!user)
241                 user = getenv("USER");
242         if (!user)
243                 user = getenv("LOGNAME");
244
245         if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
246                 return -1;
247
248         /* set daemon_over_rsh to false since we need to build the
249          * true set of args passed through the rsh/ssh connection;
250          * this is a no-op for direct-socket-connection mode */
251         daemon_over_rsh = 0;
252         server_options(sargs, &sargc);
253
254         if (sargc >= MAX_ARGS - 2)
255                 goto arg_overflow;
256
257         sargs[sargc++] = ".";
258
259         while (argc > 0) {
260                 if (sargc >= MAX_ARGS - 1) {
261                   arg_overflow:
262                         rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
263                         exit_cleanup(RERR_SYNTAX);
264                 }
265                 if (strncmp(*argv, modname, modlen) == 0
266                  && argv[0][modlen] == '\0')
267                         sargs[sargc++] = modname; /* we send "modname/" */
268                 else if (**argv == '-') {
269                         if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
270                                 out_of_memory("start_inband_exchange");
271                 } else
272                         sargs[sargc++] = *argv;
273                 argv++;
274                 argc--;
275         }
276
277         sargs[sargc] = NULL;
278
279         if (DEBUG_GTE(CMD, 1))
280                 print_child_argv("sending daemon args:", sargs);
281
282         io_printf(f_out, "%.*s\n", modlen, modname);
283
284         /* Old servers may just drop the connection here,
285          rather than sending a proper EXIT command.  Yuck. */
286         kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
287
288         while (1) {
289                 if (!read_line_old(f_in, line, sizeof line, 0)) {
290                         rprintf(FERROR, "rsync: didn't get server startup line\n");
291                         return -1;
292                 }
293
294                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
295                         auth_client(f_out, user, line+18);
296                         continue;
297                 }
298
299                 if (strcmp(line,"@RSYNCD: OK") == 0)
300                         break;
301
302                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
303                         /* This is sent by recent versions of the
304                          * server to terminate the listing of modules.
305                          * We don't want to go on and transfer
306                          * anything; just exit. */
307                         exit(0);
308                 }
309
310                 if (strncmp(line, "@ERROR", 6) == 0) {
311                         rprintf(FERROR, "%s\n", line);
312                         /* This is always fatal; the server will now
313                          * close the socket. */
314                         return -1;
315                 }
316
317                 /* This might be a MOTD line or a module listing, but there is
318                  * no way to differentiate it.  The manpage mentions this. */
319                 if (output_motd)
320                         rprintf(FINFO, "%s\n", line);
321         }
322         kluge_around_eof = 0;
323
324         if (rl_nulls) {
325                 for (i = 0; i < sargc; i++) {
326                         if (!sargs[i]) /* stop at --protect-args NULL */
327                                 break;
328                         write_sbuf(f_out, sargs[i]);
329                         write_byte(f_out, 0);
330                 }
331                 write_byte(f_out, 0);
332         } else {
333                 for (i = 0; i < sargc; i++)
334                         io_printf(f_out, "%s\n", sargs[i]);
335                 write_sbuf(f_out, "\n");
336         }
337
338         if (protect_args)
339                 send_protected_args(f_out, sargs);
340
341         if (protocol_version < 23) {
342                 if (protocol_version == 22 || !am_sender)
343                         io_start_multiplex_in(f_in);
344         }
345
346         free(modname);
347
348         return 0;
349 }
350
351 #ifdef HAVE_PUTENV
352 static int read_arg_from_pipe(int fd, char *buf, int limit)
353 {
354         char *bp = buf, *eob = buf + limit - 1;
355
356         while (1) {
357                 int got = read(fd, bp, 1);
358                 if (got != 1) {
359                         if (got < 0 && errno == EINTR)
360                                 continue;
361                         return -1;
362                 }
363                 if (*bp == '\0')
364                         break;
365                 if (bp < eob)
366                         bp++;
367         }
368         *bp = '\0';
369
370         return bp - buf;
371 }
372 #endif
373
374 static void set_env_str(const char *var, const char *str)
375 {
376 #ifdef HAVE_PUTENV
377         char *mem;
378         if (asprintf(&mem, "%s=%s", var, str) < 0)
379                 out_of_memory("set_env_str");
380         putenv(mem);
381 #endif
382 }
383
384 #ifdef HAVE_PUTENV
385 void set_env_num(const char *var, long num)
386 {
387         char *mem;
388         if (asprintf(&mem, "%s=%ld", var, num) < 0)
389                 out_of_memory("set_env_num");
390         putenv(mem);
391 }
392 #endif
393
394 /* Used for both early exec & pre-xfer exec */
395 static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
396 {
397         int arg_fds[2], error_fds[2], arg_fd, error_fd;
398         pid_t pid;
399
400         if ((error_fd_ptr && pipe(error_fds) < 0) || (arg_fd_ptr && pipe(arg_fds) < 0) || (pid = fork()) < 0)
401                 return (pid_t)-1;
402
403         if (pid == 0) {
404                 char buf[BIGPATHBUFLEN];
405                 int j, len, status;
406
407                 if (error_fd_ptr) {
408                         close(error_fds[0]);
409                         error_fd = error_fds[1];
410                         set_blocking(error_fd);
411                 }
412
413                 if (arg_fd_ptr) {
414                         close(arg_fds[1]);
415                         arg_fd = arg_fds[0];
416                         set_blocking(arg_fd);
417
418                         len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
419                         if (len <= 0)
420                                 _exit(1);
421                         set_env_str("RSYNC_REQUEST", buf);
422
423                         for (j = 0; ; j++) {
424                                 char *p;
425                                 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
426                                 if (len <= 0) {
427                                         if (!len)
428                                                 break;
429                                         _exit(1);
430                                 }
431                                 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
432                                         putenv(p);
433                         }
434                         close(arg_fd);
435                 }
436
437                 if (error_fd_ptr) {
438                         close(STDIN_FILENO);
439                         dup2(error_fd, STDOUT_FILENO);
440                         close(error_fd);
441                 }
442
443                 status = shell_exec(cmd);
444
445                 if (!WIFEXITED(status))
446                         _exit(1);
447                 _exit(WEXITSTATUS(status));
448         }
449
450         if (error_fd_ptr) {
451                 close(error_fds[1]);
452                 error_fd = *error_fd_ptr = error_fds[0];
453                 set_blocking(error_fd);
454         }
455
456         if (arg_fd_ptr) {
457                 close(arg_fds[0]);
458                 arg_fd = *arg_fd_ptr = arg_fds[1];
459                 set_blocking(arg_fd);
460         }
461
462         return pid;
463 }
464
465 static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv)
466 {
467         int j = 0;
468
469         if (!request)
470                 request = "(NONE)";
471
472         write_buf(write_fd, request, strlen(request)+1);
473         if (early_argv) {
474                 for ( ; *early_argv; early_argv++)
475                         write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
476                 j = 1; /* Skip arg0 name in argv. */
477         }
478         for ( ; argv[j]; j++)
479                 write_buf(write_fd, argv[j], strlen(argv[j])+1);
480         write_byte(write_fd, 0);
481
482         close(write_fd);
483 }
484
485 static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
486 {
487         char buf[BIGPATHBUFLEN], *bp, *cr;
488         int j, status = -1, msglen = sizeof buf - 1;
489
490         if (read_fd >= 0) {
491                 /* Read the stdout from the program.  This it is only displayed
492                  * to the user if the script also returns an error status. */
493                 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
494                         if ((j = read(read_fd, bp, msglen)) <= 0) {
495                                 if (j == 0)
496                                         break;
497                                 if (errno == EINTR)
498                                         continue;
499                                 break; /* Just ignore the read error for now... */
500                         }
501                         bp[j] = '\0';
502                         while (1) {
503                                 if ((cr = strchr(cr, '\r')) == NULL) {
504                                         cr = bp + j;
505                                         break;
506                                 }
507                                 if (!cr[1])
508                                         break; /* wait for more data before we decide what to do */
509                                 if (cr[1] == '\n') {
510                                         memmove(cr, cr+1, j - (cr - bp));
511                                         j--;
512                                 } else
513                                         cr++;
514                         }
515                         bp += j;
516                 }
517                 *bp = '\0';
518
519                 close(read_fd);
520         } else
521                 *buf = '\0';
522
523         if (wait_process(pid, &status, 0) < 0
524          || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
525                 char *e;
526                 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
527                              desc, status, status < 0 ? ": " : "",
528                              status < 0 ? strerror(errno) : "",
529                              *buf ? ":" : "", buf) < 0)
530                         return "out_of_memory in finish_pre_exec\n";
531                 return e;
532         }
533         return NULL;
534 }
535
536 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
537 {
538         if (was_chdir)
539                 rsyserr(FLOG, errno, "chdir %s failed", dir);
540         else
541                 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
542         io_printf(f_out, "@ERROR: chdir failed\n");
543         return -1;
544 }
545
546 static int add_a_group(int f_out, const char *gname)
547 {
548         gid_t gid, *gid_p;
549         if (!group_to_gid(gname, &gid, True)) {
550                 rprintf(FLOG, "Invalid gid %s\n", gname);
551                 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
552                 return -1;
553         }
554         gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
555         *gid_p = gid;
556         return 0;
557 }
558
559 #ifdef HAVE_GETGROUPLIST
560 static int want_all_groups(int f_out, uid_t uid)
561 {
562         const char *err;
563         if ((err = getallgroups(uid, &gid_list)) != NULL) {
564                 rsyserr(FLOG, errno, "%s", err);
565                 io_printf(f_out, "@ERROR: %s\n", err);
566                 return -1;
567         }
568         return 0;
569 }
570 #elif defined HAVE_INITGROUPS
571 static struct passwd *want_all_groups(int f_out, uid_t uid)
572 {
573         struct passwd *pw;
574         gid_t *gid_p;
575         if ((pw = getpwuid(uid)) == NULL) {
576                 rsyserr(FLOG, errno, "getpwuid failed");
577                 io_printf(f_out, "@ERROR: getpwuid failed\n");
578                 return NULL;
579         }
580         /* Start with the default group and initgroups() will add the rest. */
581         gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
582         *gid_p = pw->pw_gid;
583         return pw;
584 }
585 #endif
586
587 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
588 {
589         int argc;
590         char **argv, **orig_argv, **orig_early_argv, *module_chdir;
591         char line[BIGPATHBUFLEN];
592 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
593         struct passwd *pw = NULL;
594 #endif
595         uid_t uid;
596         int set_uid;
597         char *p, *err_msg = NULL;
598         char *name = lp_name(i);
599         int use_chroot = lp_use_chroot(i);
600         int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
601         int save_munge_symlinks;
602         pid_t pre_exec_pid = 0;
603         char *request = NULL;
604
605         set_env_str("RSYNC_MODULE_NAME", name);
606
607 #ifdef ICONV_OPTION
608         iconv_opt = lp_charset(i);
609         if (*iconv_opt)
610                 setup_iconv();
611         iconv_opt = NULL;
612 #endif
613
614         /* If reverse lookup is disabled globally but enabled for this module,
615          * we need to do it now before the access check. */
616         if (host == undetermined_hostname && lp_reverse_lookup(i))
617                 host = client_name(client_addr(f_in));
618         set_env_str("RSYNC_HOST_NAME", host);
619         set_env_str("RSYNC_HOST_ADDR", addr);
620
621         if (!allow_access(addr, &host, i)) {
622                 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
623                         name, host, addr);
624                 if (!lp_list(i))
625                         io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
626                 else {
627                         io_printf(f_out,
628                                   "@ERROR: access denied to %s from %s (%s)\n",
629                                   name, host, addr);
630                 }
631                 return -1;
632         }
633
634         if (am_daemon > 0) {
635                 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
636                         name, host, addr);
637         }
638
639         if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
640                 if (errno) {
641                         rsyserr(FLOG, errno, "failed to open lock file %s",
642                                 lp_lock_file(i));
643                         io_printf(f_out, "@ERROR: failed to open lock file\n");
644                 } else {
645                         rprintf(FLOG, "max connections (%d) reached\n",
646                                 lp_max_connections(i));
647                         io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
648                                 lp_max_connections(i));
649                 }
650                 return -1;
651         }
652
653         read_only = lp_read_only(i); /* may also be overridden by auth_server() */
654         auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
655
656         if (!auth_user) {
657                 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
658                 return -1;
659         }
660         set_env_str("RSYNC_USER_NAME", auth_user);
661
662         module_id = i;
663
664         if (lp_transfer_logging(i) && !logfile_format)
665                 logfile_format = lp_log_format(i);
666         if (log_format_has(logfile_format, 'i'))
667                 logfile_format_has_i = 1;
668         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
669                 logfile_format_has_o_or_i = 1;
670
671         uid = MY_UID();
672         am_root = (uid == 0);
673
674         p = *lp_uid(i) ? lp_uid(i) : am_root ? NOBODY_USER : NULL;
675         if (p) {
676                 if (!user_to_uid(p, &uid, True)) {
677                         rprintf(FLOG, "Invalid uid %s\n", p);
678                         io_printf(f_out, "@ERROR: invalid uid %s\n", p);
679                         return -1;
680                 }
681                 set_uid = 1;
682         } else
683                 set_uid = 0;
684
685         p = *lp_gid(i) ? conf_strtok(lp_gid(i)) : NULL;
686         if (p) {
687                 /* The "*" gid must be the first item in the list. */
688                 if (strcmp(p, "*") == 0) {
689 #ifdef HAVE_GETGROUPLIST
690                         if (want_all_groups(f_out, uid) < 0)
691                                 return -1;
692 #elif defined HAVE_INITGROUPS
693                         if ((pw = want_all_groups(f_out, uid)) == NULL)
694                                 return -1;
695 #else
696                         rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
697                         io_printf(f_out, "@ERROR: invalid gid setting.\n");
698                         return -1;
699 #endif
700                 } else if (add_a_group(f_out, p) < 0)
701                         return -1;
702                 while ((p = conf_strtok(NULL)) != NULL) {
703 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
704                         if (pw) {
705                                 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
706                                 io_printf(f_out, "@ERROR: invalid gid setting.\n");
707                                 return -1;
708                         }
709 #endif
710                         if (add_a_group(f_out, p) < 0)
711                                 return -1;
712                 }
713         } else if (am_root) {
714                 if (add_a_group(f_out, NOBODY_GROUP) < 0)
715                         return -1;
716         }
717
718         module_dir = lp_path(i);
719         if (*module_dir == '\0') {
720                 rprintf(FLOG, "No path specified for module %s\n", name);
721                 io_printf(f_out, "@ERROR: no path setting.\n");
722                 return -1;
723         }
724         if (use_chroot) {
725                 if ((p = strstr(module_dir, "/./")) != NULL) {
726                         *p = '\0'; /* Temporary... */
727                         if (!(module_chdir = normalize_path(module_dir, True, NULL)))
728                                 return path_failure(f_out, module_dir, False);
729                         *p = '/';
730                         if (!(p = normalize_path(p + 2, True, &module_dirlen)))
731                                 return path_failure(f_out, strstr(module_dir, "/./"), False);
732                         if (!(full_module_path = normalize_path(module_dir, False, NULL)))
733                                 full_module_path = module_dir;
734                         module_dir = p;
735                 } else {
736                         if (!(module_chdir = normalize_path(module_dir, False, NULL)))
737                                 return path_failure(f_out, module_dir, False);
738                         full_module_path = module_chdir;
739                         module_dir = "/";
740                         module_dirlen = 1;
741                 }
742         } else {
743                 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
744                         return path_failure(f_out, module_dir, False);
745                 full_module_path = module_dir = module_chdir;
746         }
747         set_env_str("RSYNC_MODULE_PATH", full_module_path);
748
749         if (module_dirlen == 1) {
750                 module_dirlen = 0;
751                 set_filter_dir("/", 1);
752         } else
753                 set_filter_dir(module_dir, module_dirlen);
754
755         p = lp_filter(i);
756         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
757                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
758
759         p = lp_include_from(i);
760         parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
761                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
762
763         p = lp_include(i);
764         parse_filter_str(&daemon_filter_list, p,
765                 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
766                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
767
768         p = lp_exclude_from(i);
769         parse_filter_file(&daemon_filter_list, p, rule_template(0),
770                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
771
772         p = lp_exclude(i);
773         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
774                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
775
776         log_init(1);
777
778 #ifdef HAVE_PUTENV
779         if ((*lp_early_exec(i) || *lp_prexfer_exec(i) || *lp_postxfer_exec(i))
780          && !getenv("RSYNC_NO_XFER_EXEC")) {
781                 set_env_num("RSYNC_PID", (long)getpid());
782
783                 /* For post-xfer exec, fork a new process to run the rsync
784                  * daemon while this process waits for the exit status and
785                  * runs the indicated command at that point. */
786                 if (*lp_postxfer_exec(i)) {
787                         pid_t pid = fork();
788                         if (pid < 0) {
789                                 rsyserr(FLOG, errno, "fork failed");
790                                 io_printf(f_out, "@ERROR: fork failed\n");
791                                 return -1;
792                         }
793                         if (pid) {
794                                 int status;
795                                 close(f_in);
796                                 if (f_out != f_in)
797                                         close(f_out);
798                                 if (wait_process(pid, &status, 0) < 0)
799                                         status = -1;
800                                 set_env_num("RSYNC_RAW_STATUS", status);
801                                 if (WIFEXITED(status))
802                                         status = WEXITSTATUS(status);
803                                 else
804                                         status = -1;
805                                 set_env_num("RSYNC_EXIT_STATUS", status);
806                                 if (shell_exec(lp_postxfer_exec(i)) < 0)
807                                         status = -1;
808                                 _exit(status);
809                         }
810                 }
811
812                 /* For early exec, fork a child process to run the indicated
813                  * command and wait for it to exit. */
814                 if (*lp_early_exec(i)) {
815                         pid_t pid = start_pre_exec(lp_early_exec(i), NULL, NULL);
816                         if (pid == (pid_t)-1) {
817                                 rsyserr(FLOG, errno, "early exec preparation failed");
818                                 io_printf(f_out, "@ERROR: early exec preparation failed\n");
819                                 return -1;
820                         }
821                         if (finish_pre_exec("early exec", pid, -1) != NULL) {
822                                 rsyserr(FLOG, errno, "early exec failed");
823                                 io_printf(f_out, "@ERROR: early exec failed\n");
824                                 return -1;
825                         }
826                 }
827
828                 /* For pre-xfer exec, fork a child process to run the indicated
829                  * command, though it first waits for the parent process to
830                  * send us the user's request via a pipe. */
831                 if (*lp_prexfer_exec(i)) {
832                         pre_exec_pid = start_pre_exec(lp_prexfer_exec(i), &pre_exec_arg_fd, &pre_exec_error_fd);
833                         if (pre_exec_pid == (pid_t)-1) {
834                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
835                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
836                                 return -1;
837                         }
838                 }
839         }
840 #endif
841
842         if (use_chroot) {
843                 /*
844                  * XXX: The 'use chroot' flag is a fairly reliable
845                  * source of confusion, because it fails under two
846                  * important circumstances: running as non-root,
847                  * running on Win32 (or possibly others).  On the
848                  * other hand, if you are running as root, then it
849                  * might be better to always use chroot.
850                  *
851                  * So, perhaps if we can't chroot we should just issue
852                  * a warning, unless a "require chroot" flag is set,
853                  * in which case we fail.
854                  */
855                 if (chroot(module_chdir)) {
856                         rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
857                         io_printf(f_out, "@ERROR: chroot failed\n");
858                         return -1;
859                 }
860                 module_chdir = module_dir;
861         }
862
863         if (!change_dir(module_chdir, CD_NORMAL))
864                 return path_failure(f_out, module_chdir, True);
865         if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
866                 sanitize_paths = 1;
867
868         if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
869                 munge_symlinks = !use_chroot || module_dirlen;
870         if (munge_symlinks) {
871                 STRUCT_STAT st;
872                 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
873                 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
874                 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
875                         rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
876                                 prefix);
877                         io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
878                         exit_cleanup(RERR_UNSUPPORTED);
879                 }
880         }
881
882         if (gid_list.count) {
883                 gid_t *gid_array = gid_list.items;
884                 if (setgid(gid_array[0])) {
885                         rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
886                         io_printf(f_out, "@ERROR: setgid failed\n");
887                         return -1;
888                 }
889 #ifdef HAVE_SETGROUPS
890                 /* Set the group(s) we want to be active. */
891                 if (setgroups(gid_list.count, gid_array)) {
892                         rsyserr(FLOG, errno, "setgroups failed");
893                         io_printf(f_out, "@ERROR: setgroups failed\n");
894                         return -1;
895                 }
896 #endif
897 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
898                 /* pw is set if the user wants all the user's groups. */
899                 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
900                         rsyserr(FLOG, errno, "initgroups failed");
901                         io_printf(f_out, "@ERROR: initgroups failed\n");
902                         return -1;
903                 }
904 #endif
905                 our_gid = MY_GID();
906         }
907
908         if (set_uid) {
909                 if (setuid(uid) < 0
910 #ifdef HAVE_SETEUID
911                  || seteuid(uid) < 0
912 #endif
913                 ) {
914                         rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
915                         io_printf(f_out, "@ERROR: setuid failed\n");
916                         return -1;
917                 }
918
919                 our_uid = MY_UID();
920                 am_root = (our_uid == 0);
921         }
922
923         if (lp_temp_dir(i) && *lp_temp_dir(i)) {
924                 tmpdir = lp_temp_dir(i);
925                 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
926                         rprintf(FLOG,
927                                 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
928                                 name);
929                         tmpdir = NULL;
930                 }
931         }
932
933         io_printf(f_out, "@RSYNCD: OK\n");
934
935         read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
936         orig_argv = argv;
937
938         save_munge_symlinks = munge_symlinks;
939
940         reset_output_levels(); /* future verbosity is controlled by client options */
941         ret = parse_arguments(&argc, (const char ***) &argv);
942         if (protect_args && ret) {
943                 orig_early_argv = orig_argv;
944                 protect_args = 2;
945                 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
946                 orig_argv = argv;
947                 ret = parse_arguments(&argc, (const char ***) &argv);
948         } else
949                 orig_early_argv = NULL;
950
951         munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
952         if (am_daemon > 0)
953                 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
954
955         if (pre_exec_pid) {
956                 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv);
957                 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
958         }
959
960         if (orig_early_argv)
961                 free(orig_early_argv);
962
963         am_server = 1; /* Don't let someone try to be tricky. */
964         quiet = 0;
965         if (lp_ignore_errors(module_id))
966                 ignore_errors = 1;
967         if (write_batch < 0)
968                 dry_run = 1;
969
970         if (lp_fake_super(i)) {
971                 if (preserve_xattrs > 1)
972                         preserve_xattrs = 1;
973                 am_root = -1;
974         } else if (am_root < 0) /* Treat --fake-super from client as --super. */
975                 am_root = 2;
976
977         if (filesfrom_fd == 0)
978                 filesfrom_fd = f_in;
979
980         if (request) {
981                 if (*auth_user) {
982                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
983                                 am_sender ? "on" : "to",
984                                 request, auth_user, host, addr);
985                 } else {
986                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
987                                 am_sender ? "on" : "to",
988                                 request, host, addr);
989                 }
990                 free(request);
991         }
992
993 #ifndef DEBUG
994         /* don't allow the logs to be flooded too fast */
995         limit_output_verbosity(lp_max_verbosity(i));
996 #endif
997
998         if (protocol_version < 23 && (protocol_version == 22 || am_sender))
999                 io_start_multiplex_out(f_out);
1000         else if (!ret || err_msg) {
1001                 /* We have to get I/O multiplexing started so that we can
1002                  * get the error back to the client.  This means getting
1003                  * the protocol setup finished first in later versions. */
1004                 setup_protocol(f_out, f_in);
1005                 if (!am_sender) {
1006                         /* Since we failed in our option parsing, we may not
1007                          * have finished parsing that the client sent us a
1008                          * --files-from option, so look for it manually.
1009                          * Without this, the socket would be in the wrong
1010                          * state for the upcoming error message. */
1011                         if (!files_from) {
1012                                 int i;
1013                                 for (i = 0; i < argc; i++) {
1014                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
1015                                                 files_from = "";
1016                                                 break;
1017                                         }
1018                                 }
1019                         }
1020                         if (files_from)
1021                                 write_byte(f_out, 0);
1022                 }
1023                 io_start_multiplex_out(f_out);
1024         }
1025
1026         if (!ret || err_msg) {
1027                 if (err_msg) {
1028                         while ((p = strchr(err_msg, '\n')) != NULL) {
1029                                 int len = p - err_msg + 1;
1030                                 rwrite(FERROR, err_msg, len, 0);
1031                                 err_msg += len;
1032                         }
1033                         if (*err_msg)
1034                                 rprintf(FERROR, "%s\n", err_msg);
1035                         io_flush(MSG_FLUSH);
1036                 } else
1037                         option_error();
1038                 msleep(400);
1039                 exit_cleanup(RERR_UNSUPPORTED);
1040         }
1041
1042 #ifdef ICONV_OPTION
1043         if (!iconv_opt) {
1044                 if (ic_send != (iconv_t)-1) {
1045                         iconv_close(ic_send);
1046                         ic_send = (iconv_t)-1;
1047                 }
1048                 if (ic_recv != (iconv_t)-1) {
1049                         iconv_close(ic_recv);
1050                         ic_recv = (iconv_t)-1;
1051                 }
1052         }
1053 #endif
1054
1055         if (!numeric_ids
1056          && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
1057                 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1058
1059         if (lp_timeout(i) && (!io_timeout || lp_timeout(i) < io_timeout))
1060                 set_io_timeout(lp_timeout(i));
1061
1062         /* If we have some incoming/outgoing chmod changes, append them to
1063          * any user-specified changes (making our changes have priority).
1064          * We also get a pointer to just our changes so that a receiver
1065          * process can use them separately if --perms wasn't specified. */
1066         if (am_sender)
1067                 p = lp_outgoing_chmod(i);
1068         else
1069                 p = lp_incoming_chmod(i);
1070         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1071                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1072                         am_sender ? "outgo" : "incom", p);
1073         }
1074
1075         start_server(f_in, f_out, argc, argv);
1076
1077         return 0;
1078 }
1079
1080 /* send a list of available modules to the client. Don't list those
1081    with "list = False". */
1082 static void send_listing(int fd)
1083 {
1084         int n = lp_num_modules();
1085         int i;
1086
1087         for (i = 0; i < n; i++) {
1088                 if (lp_list(i))
1089                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1090         }
1091
1092         if (protocol_version >= 25)
1093                 io_printf(fd,"@RSYNCD: EXIT\n");
1094 }
1095
1096 static int load_config(int globals_only)
1097 {
1098         if (!config_file) {
1099                 if (am_daemon < 0 && am_root <= 0)
1100                         config_file = RSYNCD_USERCONF;
1101                 else
1102                         config_file = RSYNCD_SYSCONF;
1103         }
1104         return lp_load(config_file, globals_only);
1105 }
1106
1107 /* this is called when a connection is established to a client
1108    and we want to start talking. The setup of the system is done from
1109    here */
1110 int start_daemon(int f_in, int f_out)
1111 {
1112         char line[1024];
1113         const char *addr, *host;
1114         char *p;
1115         int i;
1116
1117         /* At this point, am_server is only set for a daemon started via rsh.
1118          * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1119          * a flag that can be checked later on to distinguish a normal daemon
1120          * from an rsh-run daemon. */
1121         if (am_server)
1122                 am_daemon = -1;
1123
1124         io_set_sock_fds(f_in, f_out);
1125
1126         /* We must load the config file before calling any function that
1127          * might cause log-file output to occur.  This ensures that the
1128          * "log file" param gets honored for the 2 non-forked use-cases
1129          * (when rsync is run by init and run by a remote shell). */
1130         if (!load_config(0))
1131                 exit_cleanup(RERR_SYNTAX);
1132
1133         if (lp_haproxy_header() && !read_haproxy_header(f_in))
1134                 return -1;
1135
1136         p = lp_daemon_chroot();
1137         if (*p) {
1138                 log_init(0); /* Make use we've initialized syslog before chrooting. */
1139                 if (chroot(p) < 0 || chdir("/") < 0) {
1140                         rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1141                         return -1;
1142                 }
1143         }
1144         p = lp_daemon_gid();
1145         if (*p) {
1146                 gid_t gid;
1147                 if (!group_to_gid(p, &gid, True)) {
1148                         rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1149                         return -1;
1150                 }
1151                 if (setgid(gid) < 0) {
1152                         rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1153                         return -1;
1154                 }
1155                 our_gid = MY_GID();
1156         }
1157         p = lp_daemon_uid();
1158         if (*p) {
1159                 uid_t uid;
1160                 if (!user_to_uid(p, &uid, True)) {
1161                         rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1162                         return -1;
1163                 }
1164                 if (setuid(uid) < 0) {
1165                         rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1166                         return -1;
1167                 }
1168                 our_uid = MY_UID();
1169                 am_root = (our_uid == 0);
1170         }
1171
1172         addr = client_addr(f_in);
1173         host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1174         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1175
1176         if (am_daemon > 0) {
1177                 set_socket_options(f_in, "SO_KEEPALIVE");
1178                 set_nonblocking(f_in);
1179         }
1180
1181         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1182                 return -1;
1183
1184         line[0] = 0;
1185         if (!read_line_old(f_in, line, sizeof line, 0))
1186                 return -1;
1187
1188         if (!*line || strcmp(line, "#list") == 0) {
1189                 rprintf(FLOG, "module-list request from %s (%s)\n",
1190                         host, addr);
1191                 send_listing(f_out);
1192                 return -1;
1193         }
1194
1195         if (*line == '#') {
1196                 /* it's some sort of command that I don't understand */
1197                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1198                 return -1;
1199         }
1200
1201         if ((i = lp_number(line)) < 0) {
1202                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1203                         line, host, addr);
1204                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1205                 return -1;
1206         }
1207
1208 #ifdef HAVE_SIGACTION
1209         sigact.sa_flags = SA_NOCLDSTOP;
1210 #endif
1211         SIGACTION(SIGCHLD, remember_children);
1212
1213         return rsync_module(f_in, f_out, i, addr, host);
1214 }
1215
1216 static void create_pid_file(void)
1217 {
1218         char *pid_file = lp_pid_file();
1219         char pidbuf[32];
1220         STRUCT_STAT st1, st2;
1221         char *fail = NULL;
1222
1223         if (!pid_file || !*pid_file)
1224                 return;
1225
1226 #ifdef O_NOFOLLOW
1227 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1228 #else
1229 #define SAFE_OPEN_FLAGS (O_CREAT)
1230 #endif
1231
1232         /* These tests make sure that a temp-style lock dir is handled safely. */
1233         st1.st_mode = 0;
1234         if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1235                 fail = "unlink";
1236         else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1237                 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1238         else if (!lock_range(pid_file_fd, 0, 4))
1239                 fail = "lock";
1240         else if (do_fstat(pid_file_fd, &st1) < 0)
1241                 fail = "fstat opened";
1242         else if (st1.st_size > (int)sizeof pidbuf)
1243                 fail = "find small";
1244         else if (do_lstat(pid_file, &st2) < 0)
1245                 fail = "lstat";
1246         else if (!S_ISREG(st1.st_mode))
1247                 fail = "avoid file overwrite race for";
1248         else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1249                 fail = "verify stat info for";
1250 #ifdef HAVE_FTRUNCATE
1251         else if (do_ftruncate(pid_file_fd, 0) < 0)
1252                 fail = "truncate";
1253 #endif
1254         else {
1255                 pid_t pid = getpid();
1256                 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1257 #ifndef HAVE_FTRUNCATE
1258                 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1259                 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1260                         pidbuf[len++] = '\n';
1261                 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1262 #endif
1263                 if (write(pid_file_fd, pidbuf, len) != len)
1264                          fail = "write";
1265                 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1266         }
1267
1268         if (fail) {
1269                 char msg[1024];
1270                 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1271                         fail, pid_file, strerror(errno));
1272                 fputs(msg, stderr);
1273                 rprintf(FLOG, "%s", msg);
1274                 exit_cleanup(RERR_FILEIO);
1275         }
1276
1277         /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1278 }
1279
1280 /* Become a daemon, discarding the controlling terminal. */
1281 static void become_daemon(void)
1282 {
1283         int i;
1284         pid_t pid = fork();
1285
1286         if (pid) {
1287                 if (pid < 0) {
1288                         fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1289                         exit_cleanup(RERR_FILEIO);
1290                 }
1291                 _exit(0);
1292         }
1293
1294         create_pid_file();
1295
1296         /* detach from the terminal */
1297 #ifdef HAVE_SETSID
1298         setsid();
1299 #elif defined TIOCNOTTY
1300         i = open("/dev/tty", O_RDWR);
1301         if (i >= 0) {
1302                 ioctl(i, (int)TIOCNOTTY, (char *)0);
1303                 close(i);
1304         }
1305 #endif
1306         /* make sure that stdin, stdout an stderr don't stuff things
1307          * up (library functions, for example) */
1308         for (i = 0; i < 3; i++) {
1309                 close(i);
1310                 open("/dev/null", O_RDWR);
1311         }
1312 }
1313
1314 int daemon_main(void)
1315 {
1316         if (is_a_socket(STDIN_FILENO)) {
1317                 int i;
1318
1319                 /* we are running via inetd - close off stdout and
1320                  * stderr so that library functions (and getopt) don't
1321                  * try to use them. Redirect them to /dev/null */
1322                 for (i = 1; i < 3; i++) {
1323                         close(i);
1324                         open("/dev/null", O_RDWR);
1325                 }
1326
1327                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1328         }
1329
1330         if (!load_config(1)) {
1331                 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1332                 exit_cleanup(RERR_SYNTAX);
1333         }
1334         set_dparams(0);
1335
1336         if (no_detach)
1337                 create_pid_file();
1338         else
1339                 become_daemon();
1340
1341         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1342                 rsync_port = RSYNC_PORT;
1343         if (bind_address == NULL && *lp_bind_address())
1344                 bind_address = lp_bind_address();
1345
1346         log_init(0);
1347
1348         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1349                 RSYNC_VERSION, rsync_port);
1350         /* TODO: If listening on a particular address, then show that
1351          * address too.  In fact, why not just do getnameinfo on the
1352          * local address??? */
1353
1354         start_accept_loop(rsync_port, start_daemon);
1355         return -1;
1356 }