Avoid splitting a multi-byte character when trimming a name.
[rsync/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-2009 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 rsync_port;
34 extern int protect_args;
35 extern int ignore_errors;
36 extern int preserve_xattrs;
37 extern int kluge_around_eof;
38 extern int daemon_over_rsh;
39 extern int munge_symlinks;
40 extern int sanitize_paths;
41 extern int numeric_ids;
42 extern int filesfrom_fd;
43 extern int remote_protocol;
44 extern int protocol_version;
45 extern int io_timeout;
46 extern int no_detach;
47 extern int write_batch;
48 extern int default_af_hint;
49 extern int logfile_format_has_i;
50 extern int logfile_format_has_o_or_i;
51 extern char *bind_address;
52 extern char *config_file;
53 extern char *logfile_format;
54 extern char *files_from;
55 extern char *tmpdir;
56 extern struct chmod_mode_struct *chmod_modes;
57 extern filter_rule_list daemon_filter_list;
58 #ifdef ICONV_OPTION
59 extern char *iconv_opt;
60 extern iconv_t ic_send, ic_recv;
61 #endif
62
63 #define MAX_GID_LIST 32
64
65 char *auth_user;
66 int read_only = 0;
67 int module_id = -1;
68 struct chmod_mode_struct *daemon_chmod_modes;
69
70 /* module_dirlen is the length of the module_dir string when in daemon
71  * mode and module_dir is not "/"; otherwise 0.  (Note that a chroot-
72  * enabled module can have a non-"/" module_dir these days.) */
73 char *module_dir = NULL;
74 unsigned int module_dirlen = 0;
75
76 char *full_module_path;
77
78 static int rl_nulls = 0;
79
80 #ifdef HAVE_SIGACTION
81 static struct sigaction sigact;
82 #endif
83
84 static gid_t gid_list[MAX_GID_LIST];
85 static int gid_count = 0;
86
87 /* Used when "reverse lookup" is off. */
88 const char undetermined_hostname[] = "UNDETERMINED";
89
90 /**
91  * Run a client connected to an rsyncd.  The alternative to this
92  * function for remote-shell connections is do_cmd().
93  *
94  * After negotiating which module to use and reading the server's
95  * motd, this hands over to client_run().  Telling the server the
96  * module will cause it to chroot/setuid/etc.
97  *
98  * Instead of doing a transfer, the client may at this stage instead
99  * get a listing of remote modules and exit.
100  *
101  * @return -1 for error in startup, or the result of client_run().
102  * Either way, it eventually gets passed to exit_cleanup().
103  **/
104 int start_socket_client(char *host, int remote_argc, char *remote_argv[],
105                         int argc, char *argv[])
106 {
107         int fd, ret;
108         char *p, *user = NULL;
109
110         /* This is redundant with code in start_inband_exchange(), but this
111          * short-circuits a problem in the client before we open a socket,
112          * and the extra check won't hurt. */
113         if (**remote_argv == '/') {
114                 rprintf(FERROR,
115                         "ERROR: The remote path must start with a module name not a /\n");
116                 return -1;
117         }
118
119         if ((p = strrchr(host, '@')) != NULL) {
120                 user = host;
121                 host = p+1;
122                 *p = '\0';
123         }
124
125         fd = open_socket_out_wrapped(host, rsync_port, bind_address,
126                                      default_af_hint);
127         if (fd == -1)
128                 exit_cleanup(RERR_SOCKETIO);
129
130 #ifdef ICONV_CONST
131         setup_iconv();
132 #endif
133
134         ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
135
136         return ret ? ret : client_run(fd, fd, -1, argc, argv);
137 }
138
139 static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
140 {
141         int remote_sub = -1;
142 #if SUBPROTOCOL_VERSION != 0
143         int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
144 #else
145         int our_sub = 0;
146 #endif
147         char *motd;
148
149         io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
150
151         if (!am_client) {
152                 motd = lp_motd_file();
153                 if (motd && *motd) {
154                         FILE *f = fopen(motd,"r");
155                         while (f && !feof(f)) {
156                                 int len = fread(buf, 1, bufsiz - 1, f);
157                                 if (len > 0)
158                                         write_buf(f_out, buf, len);
159                         }
160                         if (f)
161                                 fclose(f);
162                         write_sbuf(f_out, "\n");
163                 }
164         }
165
166         /* This strips the \n. */
167         if (!read_line_old(f_in, buf, bufsiz, 0)) {
168                 if (am_client)
169                         rprintf(FERROR, "rsync: did not see server greeting\n");
170                 return -1;
171         }
172
173         if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
174                 if (am_client)
175                         rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
176                 else
177                         io_printf(f_out, "@ERROR: protocol startup error\n");
178                 return -1;
179         }
180
181         if (remote_sub < 0) {
182                 if (remote_protocol == 30) {
183                         if (am_client)
184                                 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
185                         else
186                                 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
187                         return -1;
188                 }
189                 remote_sub = 0;
190         }
191
192         if (protocol_version > remote_protocol) {
193                 protocol_version = remote_protocol;
194                 if (remote_sub)
195                         protocol_version--;
196         } else if (protocol_version == remote_protocol) {
197                 if (remote_sub != our_sub)
198                         protocol_version--;
199         }
200 #if SUBPROTOCOL_VERSION != 0
201         else if (protocol_version < remote_protocol) {
202                 if (our_sub)
203                         protocol_version--;
204         }
205 #endif
206
207         if (protocol_version >= 30)
208                 rl_nulls = 1;
209
210         return 0;
211 }
212
213 int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
214 {
215         int i, modlen;
216         char line[BIGPATHBUFLEN];
217         char *sargs[MAX_ARGS];
218         int sargc = 0;
219         char *p, *modname;
220
221         assert(argc > 0 && *argv != NULL);
222
223         if (**argv == '/') {
224                 rprintf(FERROR,
225                         "ERROR: The remote path must start with a module name\n");
226                 return -1;
227         }
228
229         if (!(p = strchr(*argv, '/')))
230                 modlen = strlen(*argv);
231         else
232                 modlen = p - *argv;
233
234         if (!(modname = new_array(char, modlen+1+1))) /* room for '/' & '\0' */
235                 out_of_memory("start_inband_exchange");
236         strlcpy(modname, *argv, modlen + 1);
237         modname[modlen] = '/';
238         modname[modlen+1] = '\0';
239
240         if (!user)
241                 user = getenv("USER");
242         if (!user)
243                 user = getenv("LOGNAME");
244
245         if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
246                 return -1;
247
248         /* set daemon_over_rsh to false since we need to build the
249          * true set of args passed through the rsh/ssh connection;
250          * this is a no-op for direct-socket-connection mode */
251         daemon_over_rsh = 0;
252         server_options(sargs, &sargc);
253
254         if (sargc >= MAX_ARGS - 2)
255                 goto arg_overflow;
256
257         sargs[sargc++] = ".";
258
259         while (argc > 0) {
260                 if (sargc >= MAX_ARGS - 1) {
261                   arg_overflow:
262                         rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
263                         exit_cleanup(RERR_SYNTAX);
264                 }
265                 if (strncmp(*argv, modname, modlen) == 0
266                  && argv[0][modlen] == '\0')
267                         sargs[sargc++] = modname; /* we send "modname/" */
268                 else
269                         sargs[sargc++] = *argv;
270                 argv++;
271                 argc--;
272         }
273
274         sargs[sargc] = NULL;
275
276         if (DEBUG_GTE(CMD, 1))
277                 print_child_argv("sending daemon args:", sargs);
278
279         io_printf(f_out, "%.*s\n", modlen, modname);
280
281         /* Old servers may just drop the connection here,
282          rather than sending a proper EXIT command.  Yuck. */
283         kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
284
285         while (1) {
286                 if (!read_line_old(f_in, line, sizeof line, 0)) {
287                         rprintf(FERROR, "rsync: didn't get server startup line\n");
288                         return -1;
289                 }
290
291                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
292                         auth_client(f_out, user, line+18);
293                         continue;
294                 }
295
296                 if (strcmp(line,"@RSYNCD: OK") == 0)
297                         break;
298
299                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
300                         /* This is sent by recent versions of the
301                          * server to terminate the listing of modules.
302                          * We don't want to go on and transfer
303                          * anything; just exit. */
304                         exit(0);
305                 }
306
307                 if (strncmp(line, "@ERROR", 6) == 0) {
308                         rprintf(FERROR, "%s\n", line);
309                         /* This is always fatal; the server will now
310                          * close the socket. */
311                         return -1;
312                 }
313
314                 /* This might be a MOTD line or a module listing, but there is
315                  * no way to differentiate it.  The manpage mentions this. */
316                 if (output_motd)
317                         rprintf(FINFO, "%s\n", line);
318         }
319         kluge_around_eof = 0;
320
321         if (rl_nulls) {
322                 for (i = 0; i < sargc; i++) {
323                         if (!sargs[i]) /* stop at --protect-args NULL */
324                                 break;
325                         write_sbuf(f_out, sargs[i]);
326                         write_byte(f_out, 0);
327                 }
328                 write_byte(f_out, 0);
329         } else {
330                 for (i = 0; i < sargc; i++)
331                         io_printf(f_out, "%s\n", sargs[i]);
332                 write_sbuf(f_out, "\n");
333         }
334
335         if (protect_args)
336                 send_protected_args(f_out, sargs);
337
338         if (protocol_version < 23) {
339                 if (protocol_version == 22 || !am_sender)
340                         io_start_multiplex_in(f_in);
341         }
342
343         free(modname);
344
345         return 0;
346 }
347
348 static char *finish_pre_exec(pid_t pid, int fd, char *request,
349                              char **early_argv, char **argv)
350 {
351         int j = 0, status = -1;
352
353         if (!request)
354                 request = "(NONE)";
355
356         write_buf(fd, request, strlen(request)+1);
357         if (early_argv) {
358                 for ( ; *early_argv; early_argv++)
359                         write_buf(fd, *early_argv, strlen(*early_argv)+1);
360                 j = 1; /* Skip arg0 name in argv. */
361         }
362         for ( ; argv[j]; j++) {
363                 write_buf(fd, argv[j], strlen(argv[j])+1);
364                 if (argv[j][0] == '.' && argv[j][1] == '\0')
365                         break;
366         }
367         write_byte(fd, 0);
368
369         close(fd);
370
371         if (wait_process(pid, &status, 0) < 0
372          || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
373                 char *e;
374                 if (asprintf(&e, "pre-xfer exec returned failure (%d)%s%s\n",
375                              status, status < 0 ? ": " : "",
376                              status < 0 ? strerror(errno) : "") < 0)
377                         out_of_memory("finish_pre_exec");
378                 return e;
379         }
380         return NULL;
381 }
382
383 #ifdef HAVE_PUTENV
384 static int read_arg_from_pipe(int fd, char *buf, int limit)
385 {
386         char *bp = buf, *eob = buf + limit - 1;
387
388         while (1) {
389                 int got = read(fd, bp, 1);
390                 if (got != 1) {
391                         if (got < 0 && errno == EINTR)
392                                 continue;
393                         return -1;
394                 }
395                 if (*bp == '\0')
396                         break;
397                 if (bp < eob)
398                         bp++;
399         }
400         *bp = '\0';
401
402         return bp - buf;
403 }
404 #endif
405
406 static int path_failure(int f_out, const char *dir, BOOL was_chdir)
407 {
408         if (was_chdir)
409                 rsyserr(FLOG, errno, "chdir %s failed\n", dir);
410         else
411                 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
412         io_printf(f_out, "@ERROR: chdir failed\n");
413         return -1;
414 }
415
416 static int add_a_group(int f_out, const char *gname)
417 {
418         gid_t gid;
419         if (!group_to_gid(gname, &gid, True)) {
420                 rprintf(FLOG, "Invalid gid %s\n", gname);
421                 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
422                 return -1;
423         }
424         if (gid_count == MAX_GID_LIST) {
425                 rprintf(FLOG, "Too many groups specified via gid parameter.\n");
426                 io_printf(f_out, "@ERROR: too many groups\n");
427                 return -1;
428         }
429         gid_list[gid_count++] = gid;
430         return 0;
431 }
432
433 #ifdef HAVE_GETGROUPLIST
434 static int want_all_groups(int f_out, uid_t uid)
435 {
436         const char *err;
437         gid_count = MAX_GID_LIST;
438         if ((err = getallgroups(uid, gid_list, &gid_count)) != NULL) {
439                 rsyserr(FLOG, errno, "%s", err);
440                 io_printf(f_out, "@ERROR: %s\n", err);
441                 return -1;
442         }
443         return 0;
444 }
445 #elif defined HAVE_INITGROUPS
446 static struct passwd *want_all_groups(int f_out, uid_t uid)
447 {
448         struct passwd *pw;
449         if ((pw = getpwuid(uid)) == NULL) {
450                 rsyserr(FLOG, errno, "getpwuid failed");
451                 io_printf(f_out, "@ERROR: getpwuid failed\n");
452                 return NULL;
453         }
454         /* Start with the default group and initgroups() will add the reset. */
455         gid_count = 1;
456         gid_list[0] = pw->pw_gid;
457         return pw;
458 }
459 #endif
460
461 static void set_env_str(const char *var, const char *str)
462 {
463 #ifdef HAVE_PUTENV
464         char *mem;
465         if (asprintf(&mem, "%s=%s", var, str) < 0)
466                 out_of_memory("set_env_str");
467         putenv(mem);
468 #endif
469 }
470
471 #ifdef HAVE_PUTENV
472 static void set_env_num(const char *var, long num)
473 {
474         char *mem;
475         if (asprintf(&mem, "%s=%ld", var, num) < 0)
476                 out_of_memory("set_env_num");
477         putenv(mem);
478 }
479 #endif
480
481 static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
482 {
483         int argc;
484         char **argv, **orig_argv, **orig_early_argv, *module_chdir;
485         char line[BIGPATHBUFLEN];
486 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
487         struct passwd *pw = NULL;
488 #endif
489         uid_t uid;
490         int set_uid;
491         char *p, *err_msg = NULL;
492         char *name = lp_name(i);
493         int use_chroot = lp_use_chroot(i);
494         int ret, pre_exec_fd = -1;
495         int save_munge_symlinks;
496         pid_t pre_exec_pid = 0;
497         char *request = NULL;
498
499         set_env_str("RSYNC_MODULE_NAME", name);
500
501 #ifdef ICONV_OPTION
502         iconv_opt = lp_charset(i);
503         if (*iconv_opt)
504                 setup_iconv();
505         iconv_opt = NULL;
506 #endif
507
508         /* If reverse lookup is disabled globally but enabled for this module,
509          * we need to do it now before the access check. */
510         if (host == undetermined_hostname && lp_reverse_lookup(i))
511                 host = client_name(f_in);
512         set_env_str("RSYNC_HOST_NAME", host);
513         set_env_str("RSYNC_HOST_ADDR", addr);
514
515         if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
516                 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
517                         name, host, addr);
518                 if (!lp_list(i))
519                         io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
520                 else {
521                         io_printf(f_out,
522                                   "@ERROR: access denied to %s from %s (%s)\n",
523                                   name, host, addr);
524                 }
525                 return -1;
526         }
527
528         if (am_daemon && am_server) {
529                 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
530                         name, host, addr);
531         }
532
533         if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
534                 if (errno) {
535                         rsyserr(FLOG, errno, "failed to open lock file %s",
536                                 lp_lock_file(i));
537                         io_printf(f_out, "@ERROR: failed to open lock file\n");
538                 } else {
539                         rprintf(FLOG, "max connections (%d) reached\n",
540                                 lp_max_connections(i));
541                         io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
542                                 lp_max_connections(i));
543                 }
544                 return -1;
545         }
546
547         read_only = lp_read_only(i); /* may also be overridden by auth_server() */
548         auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
549
550         if (!auth_user) {
551                 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
552                 return -1;
553         }
554         set_env_str("RSYNC_USER_NAME", auth_user);
555
556         module_id = i;
557
558         if (lp_transfer_logging(i) && !logfile_format)
559                 logfile_format = lp_log_format(i);
560         if (log_format_has(logfile_format, 'i'))
561                 logfile_format_has_i = 1;
562         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
563                 logfile_format_has_o_or_i = 1;
564
565         uid = MY_UID();
566         am_root = (uid == 0);
567
568         p = *lp_uid(i) ? lp_uid(i) : am_root ? NOBODY_USER : NULL;
569         if (p) {
570                 if (!user_to_uid(p, &uid, True)) {
571                         rprintf(FLOG, "Invalid uid %s\n", p);
572                         io_printf(f_out, "@ERROR: invalid uid %s\n", p);
573                         return -1;
574                 }
575                 set_uid = 1;
576         } else
577                 set_uid = 0;
578
579         p = *lp_gid(i) ? strtok(lp_gid(i), ", ") : NULL;
580         if (p) {
581                 /* The "*" gid must be the first item in the list. */
582                 if (strcmp(p, "*") == 0) {
583 #ifdef HAVE_GETGROUPLIST
584                         if (want_all_groups(f_out, uid) < 0)
585                                 return -1;
586 #elif defined HAVE_INITGROUPS
587                         if ((pw = want_all_groups(f_out, uid)) == NULL)
588                                 return -1;
589 #else
590                         rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
591                         io_printf(f_out, "@ERROR: invalid gid setting.\n");
592                         return -1;
593 #endif
594                 } else if (add_a_group(f_out, p) < 0)
595                         return -1;
596                 while ((p = strtok(NULL, ", ")) != NULL) {
597 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
598                         if (pw) {
599                                 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
600                                 io_printf(f_out, "@ERROR: invalid gid setting.\n");
601                                 return -1;
602                         }
603 #endif
604                         if (add_a_group(f_out, p) < 0)
605                                 return -1;
606                 }
607         } else if (am_root) {
608                 if (add_a_group(f_out, NOBODY_GROUP) < 0)
609                         return -1;
610         }
611
612         module_dir = lp_path(i);
613         if (*module_dir == '\0') {
614                 rprintf(FLOG, "No path specified for module %s\n", name);
615                 io_printf(f_out, "@ERROR: no path setting.\n");
616                 return -1;
617         }
618         if (use_chroot) {
619                 if ((p = strstr(module_dir, "/./")) != NULL) {
620                         *p = '\0'; /* Temporary... */
621                         if (!(module_chdir = normalize_path(module_dir, True, NULL)))
622                                 return path_failure(f_out, module_dir, False);
623                         *p = '/';
624                         if (!(p = normalize_path(p + 2, True, &module_dirlen)))
625                                 return path_failure(f_out, strstr(module_dir, "/./"), False);
626                         if (!(full_module_path = normalize_path(module_dir, False, NULL)))
627                                 full_module_path = module_dir;
628                         module_dir = p;
629                 } else {
630                         if (!(module_chdir = normalize_path(module_dir, False, NULL)))
631                                 return path_failure(f_out, module_dir, False);
632                         full_module_path = module_chdir;
633                         module_dir = "/";
634                         module_dirlen = 1;
635                 }
636         } else {
637                 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
638                         return path_failure(f_out, module_dir, False);
639                 full_module_path = module_dir = module_chdir;
640         }
641         set_env_str("RSYNC_MODULE_PATH", full_module_path);
642
643         if (module_dirlen == 1) {
644                 module_dirlen = 0;
645                 set_filter_dir("/", 1);
646         } else
647                 set_filter_dir(module_dir, module_dirlen);
648
649         p = lp_filter(i);
650         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
651                    XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
652
653         p = lp_include_from(i);
654         parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
655             XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
656
657         p = lp_include(i);
658         parse_filter_str(&daemon_filter_list, p,
659                    rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
660                    XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
661
662         p = lp_exclude_from(i);
663         parse_filter_file(&daemon_filter_list, p, rule_template(0),
664             XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
665
666         p = lp_exclude(i);
667         parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
668                    XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
669
670         log_init(1);
671
672 #ifdef HAVE_PUTENV
673         if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
674                 int status;
675
676                 /* For post-xfer exec, fork a new process to run the rsync
677                  * daemon while this process waits for the exit status and
678                  * runs the indicated command at that point. */
679                 if (*lp_postxfer_exec(i)) {
680                         pid_t pid = fork();
681                         if (pid < 0) {
682                                 rsyserr(FLOG, errno, "fork failed");
683                                 io_printf(f_out, "@ERROR: fork failed\n");
684                                 return -1;
685                         }
686                         if (pid) {
687                                 close(f_in);
688                                 if (f_out != f_in)
689                                         close(f_out);
690                                 set_env_num("RSYNC_PID", (long)pid);
691                                 if (wait_process(pid, &status, 0) < 0)
692                                         status = -1;
693                                 set_env_num("RSYNC_RAW_STATUS", status);
694                                 if (WIFEXITED(status))
695                                         status = WEXITSTATUS(status);
696                                 else
697                                         status = -1;
698                                 set_env_num("RSYNC_EXIT_STATUS", status);
699                                 if (system(lp_postxfer_exec(i)) < 0)
700                                         status = -1;
701                                 _exit(status);
702                         }
703                 }
704                 /* For pre-xfer exec, fork a child process to run the indicated
705                  * command, though it first waits for the parent process to
706                  * send us the user's request via a pipe. */
707                 if (*lp_prexfer_exec(i)) {
708                         int fds[2];
709                         set_env_num("RSYNC_PID", (long)getpid());
710                         if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
711                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
712                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
713                                 return -1;
714                         }
715                         if (pre_exec_pid == 0) {
716                                 char buf[BIGPATHBUFLEN];
717                                 int j, len;
718                                 close(fds[1]);
719                                 set_blocking(fds[0]);
720                                 len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
721                                 if (len <= 0)
722                                         _exit(1);
723                                 set_env_str("RSYNC_REQUEST", buf);
724                                 for (j = 0; ; j++) {
725                                         len = read_arg_from_pipe(fds[0], buf,
726                                                                  BIGPATHBUFLEN);
727                                         if (len <= 0) {
728                                                 if (!len)
729                                                         break;
730                                                 _exit(1);
731                                         }
732                                         if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) > 0)
733                                                 putenv(p);
734                                 }
735                                 close(fds[0]);
736                                 close(STDIN_FILENO);
737                                 close(STDOUT_FILENO);
738                                 status = system(lp_prexfer_exec(i));
739                                 if (!WIFEXITED(status))
740                                         _exit(1);
741                                 _exit(WEXITSTATUS(status));
742                         }
743                         close(fds[0]);
744                         set_blocking(fds[1]);
745                         pre_exec_fd = fds[1];
746                 }
747         }
748 #endif
749
750         if (use_chroot) {
751                 /*
752                  * XXX: The 'use chroot' flag is a fairly reliable
753                  * source of confusion, because it fails under two
754                  * important circumstances: running as non-root,
755                  * running on Win32 (or possibly others).  On the
756                  * other hand, if you are running as root, then it
757                  * might be better to always use chroot.
758                  *
759                  * So, perhaps if we can't chroot we should just issue
760                  * a warning, unless a "require chroot" flag is set,
761                  * in which case we fail.
762                  */
763                 if (chroot(module_chdir)) {
764                         rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
765                         io_printf(f_out, "@ERROR: chroot failed\n");
766                         return -1;
767                 }
768                 module_chdir = module_dir;
769         }
770
771         if (!change_dir(module_chdir, CD_NORMAL))
772                 return path_failure(f_out, module_chdir, True);
773         if (module_dirlen || !use_chroot)
774                 sanitize_paths = 1;
775
776         if ((munge_symlinks = lp_munge_symlinks(i)) < 0)
777                 munge_symlinks = !use_chroot || module_dirlen;
778         if (munge_symlinks) {
779                 STRUCT_STAT st;
780                 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
781                 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
782                 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
783                         rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
784                                 prefix);
785                         io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
786                         exit_cleanup(RERR_UNSUPPORTED);
787                 }
788         }
789
790         if (gid_count) {
791                 if (setgid(gid_list[0])) {
792                         rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_list[0]);
793                         io_printf(f_out, "@ERROR: setgid failed\n");
794                         return -1;
795                 }
796 #ifdef HAVE_SETGROUPS
797                 /* Set the group(s) we want to be active. */
798                 if (setgroups(gid_count, gid_list)) {
799                         rsyserr(FLOG, errno, "setgroups failed");
800                         io_printf(f_out, "@ERROR: setgroups failed\n");
801                         return -1;
802                 }
803 #endif
804 #if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
805                 /* pw is set if the user wants all the user's groups. */
806                 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
807                         rsyserr(FLOG, errno, "initgroups failed");
808                         io_printf(f_out, "@ERROR: initgroups failed\n");
809                         return -1;
810                 }
811 #endif
812         }
813
814         if (set_uid) {
815                 if (setuid(uid) < 0
816 #ifdef HAVE_SETEUID
817                  || seteuid(uid) < 0
818 #endif
819                 ) {
820                         rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
821                         io_printf(f_out, "@ERROR: setuid failed\n");
822                         return -1;
823                 }
824
825                 am_root = (MY_UID() == 0);
826         }
827
828         if (lp_temp_dir(i) && *lp_temp_dir(i)) {
829                 tmpdir = lp_temp_dir(i);
830                 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
831                         rprintf(FLOG,
832                                 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
833                                 name);
834                         tmpdir = NULL;
835                 }
836         }
837
838         io_printf(f_out, "@RSYNCD: OK\n");
839
840         read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
841         orig_argv = argv;
842
843         save_munge_symlinks = munge_symlinks;
844
845         reset_output_levels(); /* future verbosity is controlled by client options */
846         ret = parse_arguments(&argc, (const char ***) &argv);
847         if (protect_args && ret) {
848                 orig_early_argv = orig_argv;
849                 protect_args = 2;
850                 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
851                 orig_argv = argv;
852                 ret = parse_arguments(&argc, (const char ***) &argv);
853         } else
854                 orig_early_argv = NULL;
855
856         munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
857
858         if (pre_exec_pid) {
859                 err_msg = finish_pre_exec(pre_exec_pid, pre_exec_fd, request,
860                                           orig_early_argv, orig_argv);
861         }
862
863         if (orig_early_argv)
864                 free(orig_early_argv);
865
866         am_server = 1; /* Don't let someone try to be tricky. */
867         quiet = 0;
868         if (lp_ignore_errors(module_id))
869                 ignore_errors = 1;
870         if (write_batch < 0)
871                 dry_run = 1;
872
873         if (lp_fake_super(i)) {
874                 if (preserve_xattrs > 1)
875                         preserve_xattrs = 1;
876                 am_root = -1;
877         } else if (am_root < 0) /* Treat --fake-super from client as --super. */
878                 am_root = 2;
879
880         if (filesfrom_fd == 0)
881                 filesfrom_fd = f_in;
882
883         if (request) {
884                 if (*auth_user) {
885                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
886                                 am_sender ? "on" : "to",
887                                 request, auth_user, host, addr);
888                 } else {
889                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
890                                 am_sender ? "on" : "to",
891                                 request, host, addr);
892                 }
893                 free(request);
894         }
895
896 #ifndef DEBUG
897         /* don't allow the logs to be flooded too fast */
898         limit_output_verbosity(lp_max_verbosity(i));
899 #endif
900
901         if (protocol_version < 23
902             && (protocol_version == 22 || am_sender))
903                 io_start_multiplex_out(f_out);
904         else if (!ret || err_msg) {
905                 /* We have to get I/O multiplexing started so that we can
906                  * get the error back to the client.  This means getting
907                  * the protocol setup finished first in later versions. */
908                 setup_protocol(f_out, f_in);
909                 if (!am_sender) {
910                         /* Since we failed in our option parsing, we may not
911                          * have finished parsing that the client sent us a
912                          * --files-from option, so look for it manually.
913                          * Without this, the socket would be in the wrong
914                          * state for the upcoming error message. */
915                         if (!files_from) {
916                                 int i;
917                                 for (i = 0; i < argc; i++) {
918                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
919                                                 files_from = "";
920                                                 break;
921                                         }
922                                 }
923                         }
924                         if (files_from)
925                                 write_byte(f_out, 0);
926                 }
927                 io_start_multiplex_out(f_out);
928         }
929
930         if (!ret || err_msg) {
931                 if (err_msg)
932                         rwrite(FERROR, err_msg, strlen(err_msg), 0);
933                 else
934                         option_error();
935                 msleep(400);
936                 exit_cleanup(RERR_UNSUPPORTED);
937         }
938
939 #ifdef ICONV_OPTION
940         if (!iconv_opt) {
941                 if (ic_send != (iconv_t)-1) {
942                         iconv_close(ic_send);
943                         ic_send = (iconv_t)-1;
944                 }
945                 if (ic_recv != (iconv_t)-1) {
946                         iconv_close(ic_recv);
947                         ic_recv = (iconv_t)-1;
948                 }
949         }
950 #endif
951
952         if (!numeric_ids
953          && (use_chroot ? lp_numeric_ids(i) != False : lp_numeric_ids(i) == True))
954                 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
955
956         if (lp_timeout(i) && (!io_timeout || lp_timeout(i) < io_timeout))
957                 set_io_timeout(lp_timeout(i));
958
959         /* If we have some incoming/outgoing chmod changes, append them to
960          * any user-specified changes (making our changes have priority).
961          * We also get a pointer to just our changes so that a receiver
962          * process can use them separately if --perms wasn't specified. */
963         if (am_sender)
964                 p = lp_outgoing_chmod(i);
965         else
966                 p = lp_incoming_chmod(i);
967         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
968                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
969                         am_sender ? "outgo" : "incom", p);
970         }
971
972         start_server(f_in, f_out, argc, argv);
973
974         return 0;
975 }
976
977 /* send a list of available modules to the client. Don't list those
978    with "list = False". */
979 static void send_listing(int fd)
980 {
981         int n = lp_num_modules();
982         int i;
983
984         for (i = 0; i < n; i++) {
985                 if (lp_list(i))
986                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
987         }
988
989         if (protocol_version >= 25)
990                 io_printf(fd,"@RSYNCD: EXIT\n");
991 }
992
993 static int load_config(int globals_only)
994 {
995         if (!config_file) {
996                 if (am_server && am_root <= 0)
997                         config_file = RSYNCD_USERCONF;
998                 else
999                         config_file = RSYNCD_SYSCONF;
1000         }
1001         return lp_load(config_file, globals_only);
1002 }
1003
1004 /* this is called when a connection is established to a client
1005    and we want to start talking. The setup of the system is done from
1006    here */
1007 int start_daemon(int f_in, int f_out)
1008 {
1009         char line[1024];
1010         const char *addr, *host;
1011         int i;
1012
1013         io_set_sock_fds(f_in, f_out);
1014
1015         /* We must load the config file before calling any function that
1016          * might cause log-file output to occur.  This ensures that the
1017          * "log file" param gets honored for the 2 non-forked use-cases
1018          * (when rsync is run by init and run by a remote shell). */
1019         if (!load_config(0))
1020                 exit_cleanup(RERR_SYNTAX);
1021
1022         addr = client_addr(f_in);
1023         host = lp_reverse_lookup(-1) ? client_name(f_in) : undetermined_hostname;
1024         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
1025
1026         if (!am_server) {
1027                 set_socket_options(f_in, "SO_KEEPALIVE");
1028                 set_nonblocking(f_in);
1029         }
1030
1031         if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
1032                 return -1;
1033
1034         line[0] = 0;
1035         if (!read_line_old(f_in, line, sizeof line, 0))
1036                 return -1;
1037
1038         if (!*line || strcmp(line, "#list") == 0) {
1039                 rprintf(FLOG, "module-list request from %s (%s)\n",
1040                         host, addr);
1041                 send_listing(f_out);
1042                 return -1;
1043         }
1044
1045         if (*line == '#') {
1046                 /* it's some sort of command that I don't understand */
1047                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1048                 return -1;
1049         }
1050
1051         if ((i = lp_number(line)) < 0) {
1052                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1053                         line, host, addr);
1054                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1055                 return -1;
1056         }
1057
1058 #ifdef HAVE_SIGACTION
1059         sigact.sa_flags = SA_NOCLDSTOP;
1060 #endif
1061         SIGACTION(SIGCHLD, remember_children);
1062
1063         return rsync_module(f_in, f_out, i, addr, host);
1064 }
1065
1066 static void create_pid_file(void)
1067 {
1068         char *pid_file = lp_pid_file();
1069         char pidbuf[16];
1070         pid_t pid = getpid();
1071         int fd, len;
1072
1073         if (!pid_file || !*pid_file)
1074                 return;
1075
1076         cleanup_set_pid(pid);
1077         if ((fd = do_open(pid_file, O_WRONLY|O_CREAT|O_EXCL, 0666)) == -1) {
1078           failure:
1079                 cleanup_set_pid(0);
1080                 fprintf(stderr, "failed to create pid file %s: %s\n", pid_file, strerror(errno));
1081                 rsyserr(FLOG, errno, "failed to create pid file %s", pid_file);
1082                 exit_cleanup(RERR_FILEIO);
1083         }
1084         snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
1085         len = strlen(pidbuf);
1086         if (write(fd, pidbuf, len) != len)
1087                 goto failure;
1088         close(fd);
1089 }
1090
1091 /* Become a daemon, discarding the controlling terminal. */
1092 static void become_daemon(void)
1093 {
1094         int i;
1095         pid_t pid = fork();
1096
1097         if (pid) {
1098                 if (pid < 0) {
1099                         fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1100                         exit_cleanup(RERR_FILEIO);
1101                 }
1102                 _exit(0);
1103         }
1104
1105         create_pid_file();
1106
1107         /* detach from the terminal */
1108 #ifdef HAVE_SETSID
1109         setsid();
1110 #elif defined TIOCNOTTY
1111         i = open("/dev/tty", O_RDWR);
1112         if (i >= 0) {
1113                 ioctl(i, (int)TIOCNOTTY, (char *)0);
1114                 close(i);
1115         }
1116 #endif
1117         /* make sure that stdin, stdout an stderr don't stuff things
1118          * up (library functions, for example) */
1119         for (i = 0; i < 3; i++) {
1120                 close(i);
1121                 open("/dev/null", O_RDWR);
1122         }
1123 }
1124
1125 int daemon_main(void)
1126 {
1127         if (is_a_socket(STDIN_FILENO)) {
1128                 int i;
1129
1130                 /* we are running via inetd - close off stdout and
1131                  * stderr so that library functions (and getopt) don't
1132                  * try to use them. Redirect them to /dev/null */
1133                 for (i = 1; i < 3; i++) {
1134                         close(i);
1135                         open("/dev/null", O_RDWR);
1136                 }
1137
1138                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
1139         }
1140
1141         if (!load_config(1)) {
1142                 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
1143                 exit_cleanup(RERR_SYNTAX);
1144         }
1145         set_dparams(0);
1146
1147         if (no_detach)
1148                 create_pid_file();
1149         else
1150                 become_daemon();
1151
1152         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1153                 rsync_port = RSYNC_PORT;
1154         if (bind_address == NULL && *lp_bind_address())
1155                 bind_address = lp_bind_address();
1156
1157         log_init(0);
1158
1159         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
1160                 RSYNC_VERSION, rsync_port);
1161         /* TODO: If listening on a particular address, then show that
1162          * address too.  In fact, why not just do inet_ntop on the
1163          * local address??? */
1164
1165         start_accept_loop(rsync_port, start_daemon);
1166         return -1;
1167 }