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