More tweaks for Actions.
[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); /* might be 1 (yes), 0 (no), or -1 (unset) */
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 < 0) {
830                 if (strstr(module_dir, "/./") != NULL)
831                         use_chroot = 1; /* The module is expecting a chroot inner & outer path. */
832                 else if (chroot("/") < 0) {
833                         rprintf(FLOG, "chroot test failed: %s. "
834                                       "Switching 'use chroot' from unset to false.\n",
835                                       strerror(errno));
836                         use_chroot = 0;
837                 } else {
838                         if (chdir("/") < 0)
839                             rsyserr(FLOG, errno, "chdir(\"/\") failed");
840                         use_chroot = 1;
841                 }
842         }
843         if (use_chroot) {
844                 if ((p = strstr(module_dir, "/./")) != NULL) {
845                         *p = '\0'; /* Temporary... */
846                         if (!(module_chdir = normalize_path(module_dir, True, NULL)))
847                                 return path_failure(f_out, module_dir, False);
848                         *p = '/';
849                         if (!(p = normalize_path(p + 2, True, &module_dirlen)))
850                                 return path_failure(f_out, strstr(module_dir, "/./"), False);
851                         if (!(full_module_path = normalize_path(module_dir, False, NULL)))
852                                 full_module_path = module_dir;
853                         module_dir = p;
854                 } else {
855                         if (!(module_chdir = normalize_path(module_dir, False, NULL)))
856                                 return path_failure(f_out, module_dir, False);
857                         full_module_path = module_chdir;
858                         module_dir = "/";
859                         module_dirlen = 1;
860                 }
861         } else {
862                 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
863                         return path_failure(f_out, module_dir, False);
864                 full_module_path = module_dir = module_chdir;
865         }
866         set_env_str("RSYNC_MODULE_PATH", full_module_path);
867
868         if (module_dirlen == 1) {
869                 module_dirlen = 0;
870                 set_filter_dir("/", 1);
871         } else
872                 set_filter_dir(module_dir, module_dirlen);
873
874         p = lp_filter(module_id);
875         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
876                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
877
878         p = lp_include_from(module_id);
879         parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
880                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
881
882         p = lp_include(module_id);
883         parse_filter_str(&daemon_filter_list, p,
884                 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
885                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
886
887         p = lp_exclude_from(module_id);
888         parse_filter_file(&daemon_filter_list, p, rule_template(0),
889                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
890
891         p = lp_exclude(module_id);
892         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
893                 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
894
895         log_init(1);
896
897 #if defined HAVE_SETENV || defined HAVE_PUTENV
898         if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id)
899           || *lp_postxfer_exec(module_id) || *lp_name_converter(module_id))
900          && !getenv("RSYNC_NO_XFER_EXEC")) {
901                 set_env_num("RSYNC_PID", (long)getpid());
902
903                 /* For post-xfer exec, fork a new process to run the rsync
904                  * daemon while this process waits for the exit status and
905                  * runs the indicated command at that point. */
906                 if (*lp_postxfer_exec(module_id)) {
907                         pid_t pid = fork();
908                         if (pid < 0) {
909                                 rsyserr(FLOG, errno, "fork failed");
910                                 io_printf(f_out, "@ERROR: fork failed\n");
911                                 return -1;
912                         }
913                         if (pid) {
914                                 int status;
915                                 close(f_in);
916                                 if (f_out != f_in)
917                                         close(f_out);
918                                 if (wait_process(pid, &status, 0) < 0)
919                                         status = -1;
920                                 set_env_num("RSYNC_RAW_STATUS", status);
921                                 if (WIFEXITED(status))
922                                         status = WEXITSTATUS(status);
923                                 else
924                                         status = -1;
925                                 set_env_num("RSYNC_EXIT_STATUS", status);
926                                 if (shell_exec(lp_postxfer_exec(module_id)) < 0)
927                                         status = -1;
928                                 _exit(status);
929                         }
930                 }
931
932                 /* For early exec, fork a child process to run the indicated
933                  * command and wait for it to exit. */
934                 if (*lp_early_exec(module_id)) {
935                         int arg_fd;
936                         pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
937                         if (pid == (pid_t)-1) {
938                                 rsyserr(FLOG, errno, "early exec preparation failed");
939                                 io_printf(f_out, "@ERROR: early exec preparation failed\n");
940                                 return -1;
941                         }
942                         write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
943                         if (finish_pre_exec("early exec", pid, -1) != NULL) {
944                                 rsyserr(FLOG, errno, "early exec failed");
945                                 io_printf(f_out, "@ERROR: early exec failed\n");
946                                 return -1;
947                         }
948                 }
949
950                 /* For pre-xfer exec, fork a child process to run the indicated
951                  * command, though it first waits for the parent process to
952                  * send us the user's request via a pipe. */
953                 if (*lp_prexfer_exec(module_id)) {
954                         pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
955                         if (pre_exec_pid == (pid_t)-1) {
956                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
957                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
958                                 return -1;
959                         }
960                 }
961
962                 if (*lp_name_converter(module_id)) {
963                         namecvt_pid = start_pre_exec(lp_name_converter(module_id), &namecvt_fd_req, &namecvt_fd_ans);
964                         if (namecvt_pid == (pid_t)-1) {
965                                 rsyserr(FLOG, errno, "name-converter exec preparation failed");
966                                 io_printf(f_out, "@ERROR: name-converter exec preparation failed\n");
967                                 return -1;
968                         }
969                 }
970         }
971 #endif
972
973         if (early_input) {
974                 free(early_input);
975                 early_input = NULL;
976         }
977
978         if (use_chroot) {
979                 if (chroot(module_chdir)) {
980                         rsyserr(FLOG, errno, "chroot(\"%s\") failed", module_chdir);
981                         io_printf(f_out, "@ERROR: chroot failed\n");
982                         return -1;
983                 }
984                 module_chdir = module_dir;
985         }
986
987         if (!change_dir(module_chdir, CD_NORMAL))
988                 return path_failure(f_out, module_chdir, True);
989         if (module_dirlen)
990                 sanitize_paths = 1;
991
992         if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
993                 munge_symlinks = !use_chroot || module_dirlen;
994         if (munge_symlinks) {
995                 STRUCT_STAT st;
996                 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
997                 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
998                 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
999                         rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
1000                                 prefix);
1001                         io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
1002                         exit_cleanup(RERR_UNSUPPORTED);
1003                 }
1004         }
1005
1006         if (gid_list.count) {
1007                 gid_t *gid_array = gid_list.items;
1008                 if (setgid(gid_array[0])) {
1009                         rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
1010                         io_printf(f_out, "@ERROR: setgid failed\n");
1011                         return -1;
1012                 }
1013 #ifdef HAVE_SETGROUPS
1014                 /* Set the group(s) we want to be active. */
1015                 if (setgroups(gid_list.count, gid_array)) {
1016                         rsyserr(FLOG, errno, "setgroups failed");
1017                         io_printf(f_out, "@ERROR: setgroups failed\n");
1018                         return -1;
1019                 }
1020 #endif
1021 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
1022                 /* pw is set if the user wants all the user's groups. */
1023                 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
1024                         rsyserr(FLOG, errno, "initgroups failed");
1025                         io_printf(f_out, "@ERROR: initgroups failed\n");
1026                         return -1;
1027                 }
1028 #endif
1029                 our_gid = MY_GID();
1030         }
1031
1032         if (set_uid) {
1033                 if (setuid(uid) < 0
1034 #ifdef HAVE_SETEUID
1035                  || seteuid(uid) < 0
1036 #endif
1037                 ) {
1038                         rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
1039                         io_printf(f_out, "@ERROR: setuid failed\n");
1040                         return -1;
1041                 }
1042
1043                 our_uid = MY_UID();
1044                 am_root = (our_uid == ROOT_UID);
1045         }
1046
1047         if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
1048                 tmpdir = lp_temp_dir(module_id);
1049                 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
1050                         rprintf(FLOG,
1051                                 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
1052                                 name);
1053                         tmpdir = NULL;
1054                 }
1055         }
1056
1057         io_printf(f_out, "@RSYNCD: OK\n");
1058
1059         read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
1060         orig_argv = argv;
1061
1062         save_munge_symlinks = munge_symlinks;
1063
1064         reset_output_levels(); /* future verbosity is controlled by client options */
1065         ret = parse_arguments(&argc, (const char ***) &argv);
1066         if (protect_args && ret) {
1067                 orig_early_argv = orig_argv;
1068                 protect_args = 2;
1069                 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
1070                 orig_argv = argv;
1071                 ret = parse_arguments(&argc, (const char ***) &argv);
1072         } else
1073                 orig_early_argv = NULL;
1074
1075         /* The default is to use the user's setting unless the module sets True or False. */
1076         if (lp_open_noatime(module_id) >= 0)
1077                 open_noatime = lp_open_noatime(module_id);
1078
1079         munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
1080
1081         if (am_daemon > 0)
1082                 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
1083
1084         if (pre_exec_pid) {
1085                 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1086                 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1087         }
1088
1089         if (namecvt_pid)
1090                 write_pre_exec_args(namecvt_fd_req, request, orig_early_argv, orig_argv, 2);
1091
1092         if (orig_early_argv)
1093                 free(orig_early_argv);
1094
1095         am_server = 1; /* Don't let someone try to be tricky. */
1096         quiet = 0;
1097         if (lp_ignore_errors(module_id))
1098                 ignore_errors = 1;
1099         if (write_batch < 0)
1100                 dry_run = 1;
1101
1102         if (lp_fake_super(module_id)) {
1103                 if (preserve_xattrs > 1)
1104                         preserve_xattrs = 1;
1105                 am_root = -1;
1106         } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1107                 am_root = 2;
1108
1109         if (filesfrom_fd == 0)
1110                 filesfrom_fd = f_in;
1111
1112         if (request) {
1113                 if (*auth_user) {
1114                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1115                                 am_sender ? "on" : "to",
1116                                 request, auth_user, host, addr);
1117                 } else {
1118                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1119                                 am_sender ? "on" : "to",
1120                                 request, host, addr);
1121                 }
1122                 free(request);
1123         }
1124
1125 #ifndef DEBUG
1126         /* don't allow the logs to be flooded too fast */
1127         limit_output_verbosity(lp_max_verbosity(module_id));
1128 #endif
1129
1130         if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1131                 io_start_multiplex_out(f_out);
1132         else if (!ret || err_msg) {
1133                 /* We have to get I/O multiplexing started so that we can
1134                  * get the error back to the client.  This means getting
1135                  * the protocol setup finished first in later versions. */
1136                 setup_protocol(f_out, f_in);
1137                 if (!am_sender) {
1138                         /* Since we failed in our option parsing, we may not
1139                          * have finished parsing that the client sent us a
1140                          * --files-from option, so look for it manually.
1141                          * Without this, the socket would be in the wrong
1142                          * state for the upcoming error message. */
1143                         if (!files_from) {
1144                                 int i;
1145                                 for (i = 0; i < argc; i++) {
1146                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
1147                                                 files_from = "";
1148                                                 break;
1149                                         }
1150                                 }
1151                         }
1152                         if (files_from)
1153                                 write_byte(f_out, 0);
1154                 }
1155                 io_start_multiplex_out(f_out);
1156         }
1157
1158         if (!ret || err_msg) {
1159                 if (err_msg) {
1160                         while ((p = strchr(err_msg, '\n')) != NULL) {
1161                                 int len = p - err_msg + 1;
1162                                 rwrite(FERROR, err_msg, len, 0);
1163                                 err_msg += len;
1164                         }
1165                         if (*err_msg)
1166                                 rprintf(FERROR, "%s\n", err_msg);
1167                         io_flush(MSG_FLUSH);
1168                 } else
1169                         option_error();
1170                 msleep(400);
1171                 exit_cleanup(RERR_UNSUPPORTED);
1172         }
1173
1174 #ifdef ICONV_OPTION
1175         if (!iconv_opt) {
1176                 if (ic_send != (iconv_t)-1) {
1177                         iconv_close(ic_send);
1178                         ic_send = (iconv_t)-1;
1179                 }
1180                 if (ic_recv != (iconv_t)-1) {
1181                         iconv_close(ic_recv);
1182                         ic_recv = (iconv_t)-1;
1183                 }
1184         }
1185 #endif
1186
1187         if (!numeric_ids
1188          && (use_chroot ? lp_numeric_ids(module_id) != False && !*lp_name_converter(module_id)
1189                         : lp_numeric_ids(module_id) == True))
1190                 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1191
1192         if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1193                 set_io_timeout(lp_timeout(module_id));
1194
1195         /* If we have some incoming/outgoing chmod changes, append them to
1196          * any user-specified changes (making our changes have priority).
1197          * We also get a pointer to just our changes so that a receiver
1198          * process can use them separately if --perms wasn't specified. */
1199         if (am_sender)
1200                 p = lp_outgoing_chmod(module_id);
1201         else
1202                 p = lp_incoming_chmod(module_id);
1203         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1204                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1205                         am_sender ? "outgo" : "incom", p);
1206         }
1207
1208         start_server(f_in, f_out, argc, argv);
1209
1210         return 0;
1211 }
1212
1213 BOOL namecvt_call(const char *cmd, const char **name_p, id_t *id_p)
1214 {
1215         char buf[1024];
1216         int got, len;
1217
1218         if (*name_p)
1219                 len = snprintf(buf, sizeof buf, "%s %s\n", cmd, *name_p);
1220         else
1221                 len = snprintf(buf, sizeof buf, "%s %ld\n", cmd, (long)*id_p);
1222         if (len >= (int)sizeof buf) {
1223                 rprintf(FERROR, "namecvt_call() request was too large.\n");
1224                 exit_cleanup(RERR_UNSUPPORTED);
1225         }
1226
1227         while ((got = write(namecvt_fd_req, buf, len)) != len) {
1228                 if (got < 0 && errno == EINTR)
1229                         continue;
1230                 rprintf(FERROR, "Connection to name-converter failed.\n");
1231                 exit_cleanup(RERR_SOCKETIO);
1232         }
1233
1234         if (!read_line_old(namecvt_fd_ans, buf, sizeof buf, 0))
1235                 return False;
1236
1237         if (*name_p)
1238                 *id_p = (id_t)atol(buf);
1239         else
1240                 *name_p = strdup(buf);
1241
1242         return True;
1243 }
1244
1245 /* send a list of available modules to the client. Don't list those
1246    with "list = False". */
1247 static void send_listing(int fd)
1248 {
1249         int n = lp_num_modules();
1250         int i;
1251
1252         for (i = 0; i < n; i++) {
1253                 if (lp_list(i))
1254                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1255         }
1256
1257         if (protocol_version >= 25)
1258                 io_printf(fd,"@RSYNCD: EXIT\n");
1259 }
1260
1261 static int load_config(int globals_only)
1262 {
1263         if (!config_file) {
1264                 if (am_daemon < 0 && am_root <= 0)
1265                         config_file = RSYNCD_USERCONF;
1266                 else
1267                         config_file = RSYNCD_SYSCONF;
1268         }
1269         return lp_load(config_file, globals_only);
1270 }
1271
1272 /* this is called when a connection is established to a client
1273    and we want to start talking. The setup of the system is done from
1274    here */
1275 int start_daemon(int f_in, int f_out)
1276 {
1277         char line[1024];
1278         const char *addr, *host;
1279         char *p;
1280         int i;
1281
1282         /* At this point, am_server is only set for a daemon started via rsh.
1283          * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1284          * a flag that can be checked later on to distinguish a normal daemon
1285          * from an rsh-run daemon. */
1286         if (am_server)
1287                 am_daemon = -1;
1288
1289         io_set_sock_fds(f_in, f_out);
1290
1291         /* We must load the config file before calling any function that
1292          * might cause log-file output to occur.  This ensures that the
1293          * "log file" param gets honored for the 2 non-forked use-cases
1294          * (when rsync is run by init and run by a remote shell). */
1295         if (!load_config(0))
1296                 exit_cleanup(RERR_SYNTAX);
1297
1298         if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1299                 return -1;
1300
1301         p = lp_daemon_chroot();
1302         if (*p) {
1303                 log_init(0); /* Make use we've initialized syslog before chrooting. */
1304                 if (chroot(p) < 0) {
1305                         rsyserr(FLOG, errno, "daemon chroot(\"%s\") failed", p);
1306                         return -1;
1307                 }
1308                 if (chdir("/") < 0) {
1309                         rsyserr(FLOG, errno, "daemon chdir(\"/\") failed");
1310                         return -1;
1311                 }
1312         }
1313         p = lp_daemon_gid();
1314         if (*p) {
1315                 gid_t gid;
1316                 if (!group_to_gid(p, &gid, True)) {
1317                         rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1318                         return -1;
1319                 }
1320                 if (setgid(gid) < 0) {
1321                         rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1322                         return -1;
1323                 }
1324                 our_gid = MY_GID();
1325         }
1326         p = lp_daemon_uid();
1327         if (*p) {
1328                 uid_t uid;
1329                 if (!user_to_uid(p, &uid, True)) {
1330                         rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1331                         return -1;
1332                 }
1333                 if (setuid(uid) < 0) {
1334                         rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1335                         return -1;
1336                 }
1337                 our_uid = MY_UID();
1338                 am_root = (our_uid == ROOT_UID);
1339         }
1340
1341         addr = client_addr(f_in);
1342         host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1343         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1344
1345         if (am_daemon > 0) {
1346                 set_socket_options(f_in, "SO_KEEPALIVE");
1347                 set_nonblocking(f_in);
1348         }
1349
1350         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1351                 return -1;
1352
1353         line[0] = 0;
1354         if (!read_line_old(f_in, line, sizeof line, 0))
1355                 return -1;
1356
1357         if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1358                 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1359                 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1360                         io_printf(f_out, "@ERROR: invalid early_input length\n");
1361                         return -1;
1362                 }
1363                 early_input = new_array(char, early_input_len);
1364                 read_buf(f_in, early_input, early_input_len);
1365
1366                 if (!read_line_old(f_in, line, sizeof line, 0))
1367                         return -1;
1368         }
1369
1370         if (!*line || strcmp(line, "#list") == 0) {
1371                 rprintf(FLOG, "module-list request from %s (%s)\n",
1372                         host, addr);
1373                 send_listing(f_out);
1374                 return -1;
1375         }
1376
1377         if (*line == '#') {
1378                 /* it's some sort of command that I don't understand */
1379                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1380                 return -1;
1381         }
1382
1383         if ((i = lp_number(line)) < 0) {
1384                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1385                         line, host, addr);
1386                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1387                 return -1;
1388         }
1389
1390 #ifdef HAVE_SIGACTION
1391         sigact.sa_flags = SA_NOCLDSTOP;
1392 #endif
1393         SIGACTION(SIGCHLD, remember_children);
1394
1395         return rsync_module(f_in, f_out, i, addr, host);
1396 }
1397
1398 static void create_pid_file(void)
1399 {
1400         char *pid_file = lp_pid_file();
1401         char pidbuf[32];
1402         STRUCT_STAT st1, st2;
1403         char *fail = NULL;
1404
1405         if (!pid_file || !*pid_file)
1406                 return;
1407
1408 #ifdef O_NOFOLLOW
1409 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1410 #else
1411 #define SAFE_OPEN_FLAGS (O_CREAT)
1412 #endif
1413
1414         /* These tests make sure that a temp-style lock dir is handled safely. */
1415         st1.st_mode = 0;
1416         if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1417                 fail = "unlink";
1418         else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1419                 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1420         else if (!lock_range(pid_file_fd, 0, 4))
1421                 fail = "lock";
1422         else if (do_fstat(pid_file_fd, &st1) < 0)
1423                 fail = "fstat opened";
1424         else if (st1.st_size > (int)sizeof pidbuf)
1425                 fail = "find small";
1426         else if (do_lstat(pid_file, &st2) < 0)
1427                 fail = "lstat";
1428         else if (!S_ISREG(st1.st_mode))
1429                 fail = "avoid file overwrite race for";
1430         else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1431                 fail = "verify stat info for";
1432 #ifdef HAVE_FTRUNCATE
1433         else if (do_ftruncate(pid_file_fd, 0) < 0)
1434                 fail = "truncate";
1435 #endif
1436         else {
1437                 pid_t pid = getpid();
1438                 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1439 #ifndef HAVE_FTRUNCATE
1440                 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1441                 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1442                         pidbuf[len++] = '\n';
1443                 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1444 #endif
1445                 if (write(pid_file_fd, pidbuf, len) != len)
1446                          fail = "write";
1447                 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1448         }
1449
1450         if (fail) {
1451                 char msg[1024];
1452                 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1453                         fail, pid_file, strerror(errno));
1454                 fputs(msg, stderr);
1455                 rprintf(FLOG, "%s", msg);
1456                 exit_cleanup(RERR_FILEIO);
1457         }
1458
1459         /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1460 }
1461
1462 /* Become a daemon, discarding the controlling terminal. */
1463 static void become_daemon(void)
1464 {
1465         int i;
1466         pid_t pid = fork();
1467
1468         if (pid) {
1469                 if (pid < 0) {
1470                         fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1471                         exit_cleanup(RERR_FILEIO);
1472                 }
1473                 _exit(0);
1474         }
1475
1476         create_pid_file();
1477
1478         /* detach from the terminal */
1479 #ifdef HAVE_SETSID
1480         setsid();
1481 #elif defined TIOCNOTTY
1482         i = open("/dev/tty", O_RDWR);
1483         if (i >= 0) {
1484                 ioctl(i, (int)TIOCNOTTY, (char *)0);
1485                 close(i);
1486         }
1487 #endif
1488         /* make sure that stdin, stdout an stderr don't stuff things
1489          * up (library functions, for example) */
1490         for (i = 0; i < 3; i++) {
1491                 close(i);
1492                 open("/dev/null", O_RDWR);
1493         }
1494 }
1495
1496 int daemon_main(void)
1497 {
1498         if (is_a_socket(STDIN_FILENO)) {
1499                 int i;
1500
1501                 /* we are running via inetd - close off stdout and
1502                  * stderr so that library functions (and getopt) don't
1503                  * try to use them. Redirect them to /dev/null */
1504                 for (i = 1; i < 3; i++) {
1505                         close(i);
1506                         open("/dev/null", O_RDWR);
1507                 }
1508
1509                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1510         }
1511
1512         if (!load_config(1)) {
1513                 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1514                 exit_cleanup(RERR_SYNTAX);
1515         }
1516         set_dparams(0);
1517
1518         if (no_detach)
1519                 create_pid_file();
1520         else
1521                 become_daemon();
1522
1523         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1524                 rsync_port = RSYNC_PORT;
1525         if (bind_address == NULL && *lp_bind_address())
1526                 bind_address = lp_bind_address();
1527
1528         log_init(0);
1529
1530         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1531                 rsync_version(), rsync_port);
1532         /* TODO: If listening on a particular address, then show that
1533          * address too.  In fact, why not just do getnameinfo on the
1534          * local address??? */
1535
1536         start_accept_loop(rsync_port, start_daemon);
1537         return -1;
1538 }