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