ab559e380b182fa6f985be2bc61ec46d4ac2c44d
[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 open_noatime;
42 extern int sanitize_paths;
43 extern int numeric_ids;
44 extern int filesfrom_fd;
45 extern int remote_protocol;
46 extern int protocol_version;
47 extern int io_timeout;
48 extern int no_detach;
49 extern int write_batch;
50 extern int default_af_hint;
51 extern int logfile_format_has_i;
52 extern int logfile_format_has_o_or_i;
53 extern char *bind_address;
54 extern char *config_file;
55 extern char *logfile_format;
56 extern char *files_from;
57 extern char *tmpdir;
58 extern char *early_input_file;
59 extern struct chmod_mode_struct *chmod_modes;
60 extern filter_rule_list daemon_filter_list;
61 #ifdef ICONV_OPTION
62 extern char *iconv_opt;
63 extern iconv_t ic_send, ic_recv;
64 #endif
65 extern uid_t our_uid;
66 extern gid_t our_gid;
67
68 char *auth_user;
69 int read_only = 0;
70 int module_id = -1;
71 int pid_file_fd = -1;
72 int early_input_len = 0;
73 char *early_input = NULL;
74 struct chmod_mode_struct *daemon_chmod_modes;
75
76 #define EARLY_INPUT_CMD "#early_input="
77 #define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
78
79 /* module_dirlen is the length of the module_dir string when in daemon
80  * mode and module_dir is not "/"; otherwise 0.  (Note that a chroot-
81  * enabled module can have a non-"/" module_dir these days.) */
82 char *module_dir = NULL;
83 unsigned int module_dirlen = 0;
84
85 char *full_module_path;
86
87 static int rl_nulls = 0;
88
89 #ifdef HAVE_SIGACTION
90 static struct sigaction sigact;
91 #endif
92
93 static item_list gid_list = EMPTY_ITEM_LIST;
94
95 /* Used when "reverse lookup" is off. */
96 const char undetermined_hostname[] = "UNDETERMINED";
97
98 /**
99  * Run a client connected to an rsyncd.  The alternative to this
100  * function for remote-shell connections is do_cmd().
101  *
102  * After negotiating which module to use and reading the server's
103  * motd, this hands over to client_run().  Telling the server the
104  * module will cause it to chroot/setuid/etc.
105  *
106  * Instead of doing a transfer, the client may at this stage instead
107  * get a listing of remote modules and exit.
108  *
109  * @return -1 for error in startup, or the result of client_run().
110  * Either way, it eventually gets passed to exit_cleanup().
111  **/
112 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
113                         int argc, char *argv[])
114 {
115         int fd, ret;
116         char *p, *user = NULL;
117
118         /* This is redundant with code in start_inband_exchange(), but this
119          * short-circuits a problem in the client before we open a socket,
120          * and the extra check won't hurt. */
121         if (**remote_argv == '/') {
122                 rprintf(FERROR,
123                         "ERROR: The remote path must start with a module name not a /\n");
124                 return -1;
125         }
126
127         if ((p = strrchr(host, '@')) != NULL) {
128                 user = host;
129                 host = p+1;
130                 *p = '\0';
131         }
132
133         fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
134         if (fd == -1)
135                 exit_cleanup(RERR_SOCKETIO);
136
137 #ifdef ICONV_CONST
138         setup_iconv();
139 #endif
140
141         ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
142
143         return ret ? ret : client_run(fd, fd, -1, argc, argv);
144 }
145
146 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
147 {
148         int remote_sub = -1;
149 #if SUBPROTOCOL_VERSION != 0
150         int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
151 #else
152         int our_sub = 0;
153 #endif
154
155         io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
156         if (!am_client) {
157                 char *motd = lp_motd_file();
158                 if (motd && *motd) {
159                         FILE *f = fopen(motd, "r");
160                         while (f && !feof(f)) {
161                                 int len = fread(buf, 1, bufsiz - 1, f);
162                                 if (len > 0)
163                                         write_buf(f_out, buf, len);
164                         }
165                         if (f)
166                                 fclose(f);
167                         write_sbuf(f_out, "\n");
168                 }
169         }
170
171         /* This strips the \n. */
172         if (!read_line_old(f_in, buf, bufsiz, 0)) {
173                 if (am_client)
174                         rprintf(FERROR, "rsync: did not see server greeting\n");
175                 return -1;
176         }
177
178         if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
179                 if (am_client)
180                         rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
181                 else
182                         io_printf(f_out, "@ERROR: protocol startup error\n");
183                 return -1;
184         }
185
186         if (remote_sub < 0) {
187                 if (remote_protocol == 30) {
188                         if (am_client)
189                                 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
190                         else
191                                 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
192                         return -1;
193                 }
194                 remote_sub = 0;
195         }
196
197         if (protocol_version > remote_protocol) {
198                 protocol_version = remote_protocol;
199                 if (remote_sub)
200                         protocol_version--;
201         } else if (protocol_version == remote_protocol) {
202                 if (remote_sub != our_sub)
203                         protocol_version--;
204         }
205 #if SUBPROTOCOL_VERSION != 0
206         else if (protocol_version < remote_protocol) {
207                 if (our_sub)
208                         protocol_version--;
209         }
210 #endif
211
212         if (protocol_version >= 30)
213                 rl_nulls = 1;
214
215         return 0;
216 }
217
218 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
219 {
220         int i, modlen;
221         char line[BIGPATHBUFLEN];
222         char *sargs[MAX_ARGS];
223         int sargc = 0;
224         char *p, *modname;
225
226         assert(argc > 0 && *argv != NULL);
227
228         if (**argv == '/') {
229                 rprintf(FERROR,
230                         "ERROR: The remote path must start with a module name\n");
231                 return -1;
232         }
233
234         if (!(p = strchr(*argv, '/')))
235                 modlen = strlen(*argv);
236         else
237                 modlen = p - *argv;
238
239         modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
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, 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         open_noatime = lp_open_noatime(module_id);
995
996         if (am_daemon > 0)
997                 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
998
999         if (pre_exec_pid) {
1000                 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
1001                 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
1002         }
1003
1004         if (orig_early_argv)
1005                 free(orig_early_argv);
1006
1007         am_server = 1; /* Don't let someone try to be tricky. */
1008         quiet = 0;
1009         if (lp_ignore_errors(module_id))
1010                 ignore_errors = 1;
1011         if (write_batch < 0)
1012                 dry_run = 1;
1013
1014         if (lp_fake_super(i)) {
1015                 if (preserve_xattrs > 1)
1016                         preserve_xattrs = 1;
1017                 am_root = -1;
1018         } else if (am_root < 0) /* Treat --fake-super from client as --super. */
1019                 am_root = 2;
1020
1021         if (filesfrom_fd == 0)
1022                 filesfrom_fd = f_in;
1023
1024         if (request) {
1025                 if (*auth_user) {
1026                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1027                                 am_sender ? "on" : "to",
1028                                 request, auth_user, host, addr);
1029                 } else {
1030                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1031                                 am_sender ? "on" : "to",
1032                                 request, host, addr);
1033                 }
1034                 free(request);
1035         }
1036
1037 #ifndef DEBUG
1038         /* don't allow the logs to be flooded too fast */
1039         limit_output_verbosity(lp_max_verbosity(i));
1040 #endif
1041
1042         if (protocol_version < 23 && (protocol_version == 22 || am_sender))
1043                 io_start_multiplex_out(f_out);
1044         else if (!ret || err_msg) {
1045                 /* We have to get I/O multiplexing started so that we can
1046                  * get the error back to the client.  This means getting
1047                  * the protocol setup finished first in later versions. */
1048                 setup_protocol(f_out, f_in);
1049                 if (!am_sender) {
1050                         /* Since we failed in our option parsing, we may not
1051                          * have finished parsing that the client sent us a
1052                          * --files-from option, so look for it manually.
1053                          * Without this, the socket would be in the wrong
1054                          * state for the upcoming error message. */
1055                         if (!files_from) {
1056                                 int i;
1057                                 for (i = 0; i < argc; i++) {
1058                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
1059                                                 files_from = "";
1060                                                 break;
1061                                         }
1062                                 }
1063                         }
1064                         if (files_from)
1065                                 write_byte(f_out, 0);
1066                 }
1067                 io_start_multiplex_out(f_out);
1068         }
1069
1070         if (!ret || err_msg) {
1071                 if (err_msg) {
1072                         while ((p = strchr(err_msg, '\n')) != NULL) {
1073                                 int len = p - err_msg + 1;
1074                                 rwrite(FERROR, err_msg, len, 0);
1075                                 err_msg += len;
1076                         }
1077                         if (*err_msg)
1078                                 rprintf(FERROR, "%s\n", err_msg);
1079                         io_flush(MSG_FLUSH);
1080                 } else
1081                         option_error();
1082                 msleep(400);
1083                 exit_cleanup(RERR_UNSUPPORTED);
1084         }
1085
1086 #ifdef ICONV_OPTION
1087         if (!iconv_opt) {
1088                 if (ic_send != (iconv_t)-1) {
1089                         iconv_close(ic_send);
1090                         ic_send = (iconv_t)-1;
1091                 }
1092                 if (ic_recv != (iconv_t)-1) {
1093                         iconv_close(ic_recv);
1094                         ic_recv = (iconv_t)-1;
1095                 }
1096         }
1097 #endif
1098
1099         if (!numeric_ids
1100          && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
1101                 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1102
1103         if (lp_timeout(i) && (!io_timeout || lp_timeout(i) < io_timeout))
1104                 set_io_timeout(lp_timeout(i));
1105
1106         /* If we have some incoming/outgoing chmod changes, append them to
1107          * any user-specified changes (making our changes have priority).
1108          * We also get a pointer to just our changes so that a receiver
1109          * process can use them separately if --perms wasn't specified. */
1110         if (am_sender)
1111                 p = lp_outgoing_chmod(i);
1112         else
1113                 p = lp_incoming_chmod(i);
1114         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
1115                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1116                         am_sender ? "outgo" : "incom", p);
1117         }
1118
1119         start_server(f_in, f_out, argc, argv);
1120
1121         return 0;
1122 }
1123
1124 /* send a list of available modules to the client. Don't list those
1125    with "list = False". */
1126 static void send_listing(int fd)
1127 {
1128         int n = lp_num_modules();
1129         int i;
1130
1131         for (i = 0; i < n; i++) {
1132                 if (lp_list(i))
1133                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
1134         }
1135
1136         if (protocol_version >= 25)
1137                 io_printf(fd,"@RSYNCD: EXIT\n");
1138 }
1139
1140 static int load_config(int globals_only)
1141 {
1142         if (!config_file) {
1143                 if (am_daemon < 0 && am_root <= 0)
1144                         config_file = RSYNCD_USERCONF;
1145                 else
1146                         config_file = RSYNCD_SYSCONF;
1147         }
1148         return lp_load(config_file, globals_only);
1149 }
1150
1151 /* this is called when a connection is established to a client
1152    and we want to start talking. The setup of the system is done from
1153    here */
1154 int start_daemon(int f_in, int f_out)
1155 {
1156         char line[1024];
1157         const char *addr, *host;
1158         char *p;
1159         int i;
1160
1161         /* At this point, am_server is only set for a daemon started via rsh.
1162          * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1163          * a flag that can be checked later on to distinguish a normal daemon
1164          * from an rsh-run daemon. */
1165         if (am_server)
1166                 am_daemon = -1;
1167
1168         io_set_sock_fds(f_in, f_out);
1169
1170         /* We must load the config file before calling any function that
1171          * might cause log-file output to occur.  This ensures that the
1172          * "log file" param gets honored for the 2 non-forked use-cases
1173          * (when rsync is run by init and run by a remote shell). */
1174         if (!load_config(0))
1175                 exit_cleanup(RERR_SYNTAX);
1176
1177         if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
1178                 return -1;
1179
1180         p = lp_daemon_chroot();
1181         if (*p) {
1182                 log_init(0); /* Make use we've initialized syslog before chrooting. */
1183                 if (chroot(p) < 0 || chdir("/") < 0) {
1184                         rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1185                         return -1;
1186                 }
1187         }
1188         p = lp_daemon_gid();
1189         if (*p) {
1190                 gid_t gid;
1191                 if (!group_to_gid(p, &gid, True)) {
1192                         rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1193                         return -1;
1194                 }
1195                 if (setgid(gid) < 0) {
1196                         rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1197                         return -1;
1198                 }
1199                 our_gid = MY_GID();
1200         }
1201         p = lp_daemon_uid();
1202         if (*p) {
1203                 uid_t uid;
1204                 if (!user_to_uid(p, &uid, True)) {
1205                         rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1206                         return -1;
1207                 }
1208                 if (setuid(uid) < 0) {
1209                         rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1210                         return -1;
1211                 }
1212                 our_uid = MY_UID();
1213                 am_root = (our_uid == 0);
1214         }
1215
1216         addr = client_addr(f_in);
1217         host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
1218         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1219
1220         if (am_daemon > 0) {
1221                 set_socket_options(f_in, "SO_KEEPALIVE");
1222                 set_nonblocking(f_in);
1223         }
1224
1225         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1226                 return -1;
1227
1228         line[0] = 0;
1229         if (!read_line_old(f_in, line, sizeof line, 0))
1230                 return -1;
1231
1232         if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1233                 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
1234                 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
1235                         io_printf(f_out, "@ERROR: invalid early_input length\n");
1236                         return -1;
1237                 }
1238                 early_input = new_array(char, early_input_len);
1239                 read_buf(f_in, early_input, early_input_len);
1240
1241                 if (!read_line_old(f_in, line, sizeof line, 0))
1242                         return -1;
1243         }
1244
1245         if (!*line || strcmp(line, "#list") == 0) {
1246                 rprintf(FLOG, "module-list request from %s (%s)\n",
1247                         host, addr);
1248                 send_listing(f_out);
1249                 return -1;
1250         }
1251
1252         if (*line == '#') {
1253                 /* it's some sort of command that I don't understand */
1254                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1255                 return -1;
1256         }
1257
1258         if ((i = lp_number(line)) < 0) {
1259                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1260                         line, host, addr);
1261                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1262                 return -1;
1263         }
1264
1265 #ifdef HAVE_SIGACTION
1266         sigact.sa_flags = SA_NOCLDSTOP;
1267 #endif
1268         SIGACTION(SIGCHLD, remember_children);
1269
1270         return rsync_module(f_in, f_out, i, addr, host);
1271 }
1272
1273 static void create_pid_file(void)
1274 {
1275         char *pid_file = lp_pid_file();
1276         char pidbuf[32];
1277         STRUCT_STAT st1, st2;
1278         char *fail = NULL;
1279
1280         if (!pid_file || !*pid_file)
1281                 return;
1282
1283 #ifdef O_NOFOLLOW
1284 #define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1285 #else
1286 #define SAFE_OPEN_FLAGS (O_CREAT)
1287 #endif
1288
1289         /* These tests make sure that a temp-style lock dir is handled safely. */
1290         st1.st_mode = 0;
1291         if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1292                 fail = "unlink";
1293         else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
1294                 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1295         else if (!lock_range(pid_file_fd, 0, 4))
1296                 fail = "lock";
1297         else if (do_fstat(pid_file_fd, &st1) < 0)
1298                 fail = "fstat opened";
1299         else if (st1.st_size > (int)sizeof pidbuf)
1300                 fail = "find small";
1301         else if (do_lstat(pid_file, &st2) < 0)
1302                 fail = "lstat";
1303         else if (!S_ISREG(st1.st_mode))
1304                 fail = "avoid file overwrite race for";
1305         else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1306                 fail = "verify stat info for";
1307 #ifdef HAVE_FTRUNCATE
1308         else if (do_ftruncate(pid_file_fd, 0) < 0)
1309                 fail = "truncate";
1310 #endif
1311         else {
1312                 pid_t pid = getpid();
1313                 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1314 #ifndef HAVE_FTRUNCATE
1315                 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
1316                 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
1317                         pidbuf[len++] = '\n';
1318                 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1319 #endif
1320                 if (write(pid_file_fd, pidbuf, len) != len)
1321                          fail = "write";
1322                 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1323         }
1324
1325         if (fail) {
1326                 char msg[1024];
1327                 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1328                         fail, pid_file, strerror(errno));
1329                 fputs(msg, stderr);
1330                 rprintf(FLOG, "%s", msg);
1331                 exit_cleanup(RERR_FILEIO);
1332         }
1333
1334         /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
1335 }
1336
1337 /* Become a daemon, discarding the controlling terminal. */
1338 static void become_daemon(void)
1339 {
1340         int i;
1341         pid_t pid = fork();
1342
1343         if (pid) {
1344                 if (pid < 0) {
1345                         fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1346                         exit_cleanup(RERR_FILEIO);
1347                 }
1348                 _exit(0);
1349         }
1350
1351         create_pid_file();
1352
1353         /* detach from the terminal */
1354 #ifdef HAVE_SETSID
1355         setsid();
1356 #elif defined TIOCNOTTY
1357         i = open("/dev/tty", O_RDWR);
1358         if (i >= 0) {
1359                 ioctl(i, (int)TIOCNOTTY, (char *)0);
1360                 close(i);
1361         }
1362 #endif
1363         /* make sure that stdin, stdout an stderr don't stuff things
1364          * up (library functions, for example) */
1365         for (i = 0; i < 3; i++) {
1366                 close(i);
1367                 open("/dev/null", O_RDWR);
1368         }
1369 }
1370
1371 int daemon_main(void)
1372 {
1373         if (is_a_socket(STDIN_FILENO)) {
1374                 int i;
1375
1376                 /* we are running via inetd - close off stdout and
1377                  * stderr so that library functions (and getopt) don't
1378                  * try to use them. Redirect them to /dev/null */
1379                 for (i = 1; i < 3; i++) {
1380                         close(i);
1381                         open("/dev/null", O_RDWR);
1382                 }
1383
1384                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1385         }
1386
1387         if (!load_config(1)) {
1388                 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1389                 exit_cleanup(RERR_SYNTAX);
1390         }
1391         set_dparams(0);
1392
1393         if (no_detach)
1394                 create_pid_file();
1395         else
1396                 become_daemon();
1397
1398         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1399                 rsync_port = RSYNC_PORT;
1400         if (bind_address == NULL && *lp_bind_address())
1401                 bind_address = lp_bind_address();
1402
1403         log_init(0);
1404
1405         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1406                 RSYNC_VERSION, rsync_port);
1407         /* TODO: If listening on a particular address, then show that
1408          * address too.  In fact, why not just do getnameinfo on the
1409          * local address??? */
1410
1411         start_accept_loop(rsync_port, start_daemon);
1412         return -1;
1413 }