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