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