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