0f924515a5482ceccf88d29fbdc232234f17eded
[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, 2003, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21  */
22
23 #include "rsync.h"
24
25 extern int verbose;
26 extern int quiet;
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 ignore_errors;
35 extern int kluge_around_eof;
36 extern int daemon_over_rsh;
37 extern int sanitize_paths;
38 extern int filesfrom_fd;
39 extern int remote_protocol;
40 extern int protocol_version;
41 extern int io_timeout;
42 extern int no_detach;
43 extern int default_af_hint;
44 extern int logfile_format_has_i;
45 extern int logfile_format_has_o_or_i;
46 extern mode_t orig_umask;
47 extern char *bind_address;
48 extern char *sockopts;
49 extern char *config_file;
50 extern char *logfile_format;
51 extern char *files_from;
52 extern char *tmpdir;
53 extern struct chmod_mode_struct *chmod_modes;
54 extern struct filter_list_struct server_filter_list;
55
56 char *auth_user;
57 int read_only = 0;
58 int module_id = -1;
59 struct chmod_mode_struct *daemon_chmod_modes;
60
61 /* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
62 unsigned int module_dirlen = 0;
63
64 #ifdef HAVE_SIGACTION
65 static struct sigaction sigact;
66 #endif
67
68 /**
69  * Run a client connected to an rsyncd.  The alternative to this
70  * function for remote-shell connections is do_cmd().
71  *
72  * After negotiating which module to use and reading the server's
73  * motd, this hands over to client_run().  Telling the server the
74  * module will cause it to chroot/setuid/etc.
75  *
76  * Instead of doing a transfer, the client may at this stage instead
77  * get a listing of remote modules and exit.
78  *
79  * @return -1 for error in startup, or the result of client_run().
80  * Either way, it eventually gets passed to exit_cleanup().
81  **/
82 int start_socket_client(char *host, char *path, int argc, char *argv[])
83 {
84         int fd, ret;
85         char *p, *user = NULL;
86
87         /* This is redundant with code in start_inband_exchange(), but this
88          * short-circuits a problem in the client before we open a socket,
89          * and the extra check won't hurt. */
90         if (*path == '/') {
91                 rprintf(FERROR,
92                         "ERROR: The remote path must start with a module name not a /\n");
93                 return -1;
94         }
95
96         if ((p = strrchr(host, '@')) != NULL) {
97                 user = host;
98                 host = p+1;
99                 *p = '\0';
100         }
101
102         fd = open_socket_out_wrapped(host, rsync_port, bind_address,
103                                      default_af_hint);
104         if (fd == -1)
105                 exit_cleanup(RERR_SOCKETIO);
106
107         set_socket_options(fd, sockopts);
108
109         ret = start_inband_exchange(user, path, fd, fd, argc);
110
111         return ret ? ret : client_run(fd, fd, -1, argc, argv);
112 }
113
114 int start_inband_exchange(const char *user, char *path, int f_in, int f_out,
115                           int argc)
116 {
117         int i;
118         char *sargs[MAX_ARGS];
119         int sargc = 0;
120         char line[BIGPATHBUFLEN];
121         char *p;
122
123         if (argc == 0 && !am_sender)
124                 list_only |= 1;
125
126         if (*path == '/') {
127                 rprintf(FERROR,
128                         "ERROR: The remote path must start with a module name\n");
129                 return -1;
130         }
131
132         if (!user)
133                 user = getenv("USER");
134         if (!user)
135                 user = getenv("LOGNAME");
136
137         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
138
139         if (!read_line(f_in, line, sizeof line - 1)) {
140                 rprintf(FERROR, "rsync: did not see server greeting\n");
141                 return -1;
142         }
143
144         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
145                 /* note that read_line strips of \n or \r */
146                 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
147                         line);
148                 return -1;
149         }
150         if (protocol_version > remote_protocol)
151                 protocol_version = remote_protocol;
152
153         if (list_only && protocol_version >= 29)
154                 list_only |= 2;
155
156         /* set daemon_over_rsh to false since we need to build the
157          * true set of args passed through the rsh/ssh connection;
158          * this is a no-op for direct-socket-connection mode */
159         daemon_over_rsh = 0;
160         server_options(sargs, &sargc);
161
162         sargs[sargc++] = ".";
163
164         if (path && *path)
165                 sargs[sargc++] = path;
166
167         sargs[sargc] = NULL;
168
169         if (verbose > 1)
170                 print_child_argv(sargs);
171
172         p = strchr(path,'/');
173         if (p) *p = 0;
174         io_printf(f_out, "%s\n", path);
175         if (p) *p = '/';
176
177         /* Old servers may just drop the connection here,
178          rather than sending a proper EXIT command.  Yuck. */
179         kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
180
181         while (1) {
182                 if (!read_line(f_in, line, sizeof line - 1)) {
183                         rprintf(FERROR, "rsync: didn't get server startup line\n");
184                         return -1;
185                 }
186
187                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
188                         auth_client(f_out, user, line+18);
189                         continue;
190                 }
191
192                 if (strcmp(line,"@RSYNCD: OK") == 0)
193                         break;
194
195                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
196                         /* This is sent by recent versions of the
197                          * server to terminate the listing of modules.
198                          * We don't want to go on and transfer
199                          * anything; just exit. */
200                         exit(0);
201                 }
202
203                 if (strncmp(line, "@ERROR", 6) == 0) {
204                         rprintf(FERROR, "%s\n", line);
205                         /* This is always fatal; the server will now
206                          * close the socket. */
207                         return -1;
208                 }
209
210                 /* This might be a MOTD line or a module listing, but there is
211                  * no way to differentiate it.  The manpage mentions this. */
212                 if (output_motd)
213                         rprintf(FINFO, "%s\n", line);
214         }
215         kluge_around_eof = 0;
216
217         for (i = 0; i < sargc; i++) {
218                 io_printf(f_out, "%s\n", sargs[i]);
219         }
220         io_printf(f_out, "\n");
221
222         if (protocol_version < 23) {
223                 if (protocol_version == 22 || !am_sender)
224                         io_start_multiplex_in();
225         }
226
227         return 0;
228 }
229
230 static char *finish_pre_exec(pid_t pid, int fd, char *request,
231                              int argc, char *argv[])
232 {
233         int j, status = -1;
234
235         if (request) {
236                 write_buf(fd, request, strlen(request)+1);
237                 for (j = 0; j < argc; j++)
238                         write_buf(fd, argv[j], strlen(argv[j])+1);
239         }
240
241         write_byte(fd, 0);
242
243         close(fd);
244
245         if (wait_process(pid, &status, 0) < 0
246          || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
247                 char *e;
248                 if (asprintf(&e, "pre-xfer exec returned failure (%d)%s%s\n",
249                              status, status < 0 ? ": " : "",
250                              status < 0 ? strerror(errno) : "") < 0)
251                         out_of_memory("finish_pre_exec");
252                 return e;
253         }
254         return NULL;
255 }
256
257 static int read_arg_from_pipe(int fd, char *buf, int limit)
258 {
259         char *bp = buf, *eob = buf + limit - 1;
260
261         while (1) {
262             if (read(fd, bp, 1) != 1)
263                 return -1;
264             if (*bp == '\0')
265                 break;
266             if (bp < eob)
267                 bp++;
268         }
269         *bp = '\0';
270
271         return bp - buf;
272 }
273
274 static int rsync_module(int f_in, int f_out, int i, char *addr, char *host)
275 {
276         int argc = 0;
277         int maxargs;
278         char **argv;
279         char line[BIGPATHBUFLEN];
280         uid_t uid = (uid_t)-2;  /* canonically "nobody" */
281         gid_t gid = (gid_t)-2;
282         char *p, *err_msg = NULL;
283         char *name = lp_name(i);
284         int use_chroot = lp_use_chroot(i);
285         int start_glob = 0;
286         int ret, pre_exec_fd = -1;
287         pid_t pre_exec_pid = 0;
288         char *request = NULL;
289
290         if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
291                 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
292                         name, host, addr);
293                 if (!lp_list(i))
294                         io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
295                 else {
296                         io_printf(f_out,
297                                   "@ERROR: access denied to %s from %s (%s)\n",
298                                   name, host, addr);
299                 }
300                 return -1;
301         }
302
303         if (am_daemon && am_server) {
304                 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
305                         name, host, addr);
306         }
307
308         if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
309                 if (errno) {
310                         rsyserr(FLOG, errno, "failed to open lock file %s",
311                                 lp_lock_file(i));
312                         io_printf(f_out, "@ERROR: failed to open lock file\n");
313                 } else {
314                         rprintf(FLOG, "max connections (%d) reached\n",
315                                 lp_max_connections(i));
316                         io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
317                                 lp_max_connections(i));
318                 }
319                 return -1;
320         }
321
322         auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
323
324         if (!auth_user) {
325                 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
326                 return -1;
327         }
328
329         module_id = i;
330
331         if (lp_read_only(i))
332                 read_only = 1;
333
334         if (lp_transfer_logging(i) && !logfile_format)
335                 logfile_format = lp_log_format(i);
336         if (log_format_has(logfile_format, 'i'))
337                 logfile_format_has_i = 1;
338         if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
339                 logfile_format_has_o_or_i = 1;
340
341         am_root = (MY_UID() == 0);
342
343         if (am_root) {
344                 p = lp_uid(i);
345                 if (!name_to_uid(p, &uid)) {
346                         if (!isDigit(p)) {
347                                 rprintf(FLOG, "Invalid uid %s\n", p);
348                                 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
349                                 return -1;
350                         }
351                         uid = atoi(p);
352                 }
353
354                 p = lp_gid(i);
355                 if (!name_to_gid(p, &gid)) {
356                         if (!isDigit(p)) {
357                                 rprintf(FLOG, "Invalid gid %s\n", p);
358                                 io_printf(f_out, "@ERROR: invalid gid %s\n", p);
359                                 return -1;
360                         }
361                         gid = atoi(p);
362                 }
363         }
364
365         /* TODO: If we're not root, but the configuration requests
366          * that we change to some uid other than the current one, then
367          * log a warning. */
368
369         /* TODO: Perhaps take a list of gids, and make them into the
370          * supplementary groups. */
371
372         if (use_chroot || (module_dirlen = strlen(lp_path(i))) == 1) {
373                 module_dirlen = 0;
374                 set_filter_dir("/", 1);
375         } else
376                 set_filter_dir(lp_path(i), module_dirlen);
377
378         p = lp_filter(i);
379         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
380                    XFLG_ABS_IF_SLASH);
381
382         p = lp_include_from(i);
383         parse_filter_file(&server_filter_list, p, MATCHFLG_INCLUDE,
384             XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
385
386         p = lp_include(i);
387         parse_rule(&server_filter_list, p,
388                    MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
389                    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
390
391         p = lp_exclude_from(i);
392         parse_filter_file(&server_filter_list, p, 0,
393             XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
394
395         p = lp_exclude(i);
396         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
397                    XFLG_ABS_IF_SLASH | XFLG_OLD_PREFIXES);
398
399         log_init(1);
400
401 #ifdef HAVE_PUTENV
402         if (*lp_prexfer_exec(i) || *lp_postxfer_exec(i)) {
403                 char *modname, *modpath, *hostaddr, *hostname, *username;
404                 int status;
405                 if (asprintf(&modname, "RSYNC_MODULE_NAME=%s", name) < 0
406                  || asprintf(&modpath, "RSYNC_MODULE_PATH=%s", lp_path(i)) < 0
407                  || asprintf(&hostaddr, "RSYNC_HOST_ADDR=%s", addr) < 0
408                  || asprintf(&hostname, "RSYNC_HOST_NAME=%s", host) < 0
409                  || asprintf(&username, "RSYNC_USER_NAME=%s", auth_user) < 0)
410                         out_of_memory("rsync_module");
411                 putenv(modname);
412                 putenv(modpath);
413                 putenv(hostaddr);
414                 putenv(hostname);
415                 putenv(username);
416                 umask(orig_umask);
417                 /* For post-xfer exec, fork a new process to run the rsync
418                  * daemon while this process waits for the exit status and
419                  * runs the indicated command at that point. */
420                 if (*lp_postxfer_exec(i)) {
421                         pid_t pid = fork();
422                         if (pid < 0) {
423                                 rsyserr(FLOG, errno, "fork failed");
424                                 io_printf(f_out, "@ERROR: fork failed\n");
425                                 return -1;
426                         }
427                         if (pid) {
428                                 if (asprintf(&p, "RSYNC_PID=%ld", (long)pid) > 0)
429                                         putenv(p);
430                                 if (wait_process(pid, &status, 0) < 0)
431                                         status = -1;
432                                 if (asprintf(&p, "RSYNC_RAW_STATUS=%d", status) > 0)
433                                         putenv(p);
434                                 if (WIFEXITED(status))
435                                         status = WEXITSTATUS(status);
436                                 else
437                                         status = -1;
438                                 if (asprintf(&p, "RSYNC_EXIT_STATUS=%d", status) > 0)
439                                         putenv(p);
440                                 system(lp_postxfer_exec(i));
441                                 _exit(status);
442                         }
443                 }
444                 /* For pre-xfer exec, fork a child process to run the indicated
445                  * command, though it first waits for the parent process to
446                  * send us the user's request via a pipe. */
447                 if (*lp_prexfer_exec(i)) {
448                         int fds[2];
449                         if (asprintf(&p, "RSYNC_PID=%ld", (long)getpid()) > 0)
450                                 putenv(p);
451                         if (pipe(fds) < 0 || (pre_exec_pid = fork()) < 0) {
452                                 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
453                                 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
454                                 return -1;
455                         }
456                         if (pre_exec_pid == 0) {
457                                 char buf[BIGPATHBUFLEN];
458                                 int j, len;
459                                 close(fds[1]);
460                                 set_blocking(fds[0]);
461                                 len = read_arg_from_pipe(fds[0], buf, BIGPATHBUFLEN);
462                                 if (len <= 0)
463                                         _exit(1);
464                                 if (asprintf(&p, "RSYNC_REQUEST=%s", buf) > 0)
465                                         putenv(p);
466                                 for (j = 0; ; j++) {
467                                         len = read_arg_from_pipe(fds[0], buf,
468                                                                  BIGPATHBUFLEN);
469                                         if (len <= 0) {
470                                                 if (!len)
471                                                         break;
472                                                 _exit(1);
473                                         }
474                                         if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) > 0)
475                                                 putenv(p);
476                                 }
477                                 close(fds[0]);
478                                 close(STDIN_FILENO);
479                                 close(STDOUT_FILENO);
480                                 status = system(lp_prexfer_exec(i));
481                                 if (!WIFEXITED(status))
482                                         _exit(1);
483                                 _exit(WEXITSTATUS(status));
484                         }
485                         close(fds[0]);
486                         set_blocking(fds[1]);
487                         pre_exec_fd = fds[1];
488                 }
489                 umask(0);
490         }
491 #endif
492
493         if (use_chroot) {
494                 /*
495                  * XXX: The 'use chroot' flag is a fairly reliable
496                  * source of confusion, because it fails under two
497                  * important circumstances: running as non-root,
498                  * running on Win32 (or possibly others).  On the
499                  * other hand, if you are running as root, then it
500                  * might be better to always use chroot.
501                  *
502                  * So, perhaps if we can't chroot we should just issue
503                  * a warning, unless a "require chroot" flag is set,
504                  * in which case we fail.
505                  */
506                 if (chroot(lp_path(i))) {
507                         rsyserr(FLOG, errno, "chroot %s failed",
508                                 lp_path(i));
509                         io_printf(f_out, "@ERROR: chroot failed\n");
510                         return -1;
511                 }
512
513                 if (!push_dir("/", 0)) {
514                         rsyserr(FLOG, errno, "chdir %s failed\n",
515                                 lp_path(i));
516                         io_printf(f_out, "@ERROR: chdir failed\n");
517                         return -1;
518                 }
519
520         } else {
521                 if (!push_dir(lp_path(i), 0)) {
522                         rsyserr(FLOG, errno, "chdir %s failed\n",
523                                 lp_path(i));
524                         io_printf(f_out, "@ERROR: chdir failed\n");
525                         return -1;
526                 }
527                 sanitize_paths = 1;
528         }
529
530         if (am_root) {
531                 /* XXXX: You could argue that if the daemon is started
532                  * by a non-root user and they explicitly specify a
533                  * gid, then we should try to change to that gid --
534                  * this could be possible if it's already in their
535                  * supplementary groups. */
536
537                 /* TODO: Perhaps we need to document that if rsyncd is
538                  * started by somebody other than root it will inherit
539                  * all their supplementary groups. */
540
541                 if (setgid(gid)) {
542                         rsyserr(FLOG, errno, "setgid %d failed", (int)gid);
543                         io_printf(f_out, "@ERROR: setgid failed\n");
544                         return -1;
545                 }
546 #ifdef HAVE_SETGROUPS
547                 /* Get rid of any supplementary groups this process
548                  * might have inheristed. */
549                 if (setgroups(1, &gid)) {
550                         rsyserr(FLOG, errno, "setgroups failed");
551                         io_printf(f_out, "@ERROR: setgroups failed\n");
552                         return -1;
553                 }
554 #endif
555
556                 if (setuid(uid)) {
557                         rsyserr(FLOG, errno, "setuid %d failed", (int)uid);
558                         io_printf(f_out, "@ERROR: setuid failed\n");
559                         return -1;
560                 }
561
562                 am_root = (MY_UID() == 0);
563         }
564
565         if (lp_temp_dir(i) && *lp_temp_dir(i)) {
566                 tmpdir = lp_temp_dir(i);
567                 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
568                         rprintf(FLOG,
569                                 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
570                                 name);
571                         tmpdir = NULL;
572                 }
573         }
574
575         io_printf(f_out, "@RSYNCD: OK\n");
576
577         maxargs = MAX_ARGS;
578         if (!(argv = new_array(char *, maxargs)))
579                 out_of_memory("rsync_module");
580         argv[argc++] = "rsyncd";
581
582         while (1) {
583                 if (!read_line(f_in, line, sizeof line - 1))
584                         return -1;
585
586                 if (!*line)
587                         break;
588
589                 p = line;
590
591                 if (argc == maxargs) {
592                         maxargs += MAX_ARGS;
593                         if (!(argv = realloc_array(argv, char *, maxargs)))
594                                 out_of_memory("rsync_module");
595                 }
596                 if (!(argv[argc] = strdup(p)))
597                         out_of_memory("rsync_module");
598
599                 switch (start_glob) {
600                 case 0:
601                         argc++;
602                         if (strcmp(line, ".") == 0)
603                                 start_glob = 1;
604                         break;
605                 case 1:
606                         if (pre_exec_pid) {
607                                 err_msg = finish_pre_exec(pre_exec_pid,
608                                                           pre_exec_fd, p,
609                                                           argc, argv);
610                                 pre_exec_pid = 0;
611                         }
612                         request = strdup(p);
613                         start_glob = 2;
614                         /* FALL THROUGH */
615                 default:
616                         if (!err_msg)
617                                 glob_expand(name, &argv, &argc, &maxargs);
618                         break;
619                 }
620         }
621
622         if (pre_exec_pid) {
623                 err_msg = finish_pre_exec(pre_exec_pid, pre_exec_fd, request,
624                                           argc, argv);
625         }
626
627         verbose = 0; /* future verbosity is controlled by client options */
628         ret = parse_arguments(&argc, (const char ***) &argv, 0);
629         quiet = 0; /* Don't let someone try to be tricky. */
630         if (lp_ignore_errors(module_id))
631                 ignore_errors = 1;
632
633         if (filesfrom_fd == 0)
634                 filesfrom_fd = f_in;
635
636         if (request) {
637                 if (*auth_user) {
638                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
639                                 am_sender ? "on" : "to",
640                                 request, auth_user, host, addr);
641                 } else {
642                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
643                                 am_sender ? "on" : "to",
644                                 request, host, addr);
645                 }
646                 free(request);
647         }
648
649 #ifndef DEBUG
650         /* don't allow the logs to be flooded too fast */
651         if (verbose > lp_max_verbosity(i))
652                 verbose = lp_max_verbosity(i);
653 #endif
654
655         if (protocol_version < 23
656             && (protocol_version == 22 || am_sender))
657                 io_start_multiplex_out();
658         else if (!ret || err_msg) {
659                 /* We have to get I/O multiplexing started so that we can
660                  * get the error back to the client.  This means getting
661                  * the protocol setup finished first in later versions. */
662                 setup_protocol(f_out, f_in);
663                 if (!am_sender) {
664                         /* Since we failed in our option parsing, we may not
665                          * have finished parsing that the client sent us a
666                          * --files-from option, so look for it manually.
667                          * Without this, the socket would be in the wrong
668                          * state for the upcoming error message. */
669                         if (!files_from) {
670                                 int i;
671                                 for (i = 0; i < argc; i++) {
672                                         if (strncmp(argv[i], "--files-from", 12) == 0) {
673                                                 files_from = "";
674                                                 break;
675                                         }
676                                 }
677                         }
678                         if (files_from)
679                                 write_byte(f_out, 0);
680                 }
681                 io_start_multiplex_out();
682         }
683
684         if (!ret || err_msg) {
685                 if (err_msg)
686                         rwrite(FERROR, err_msg, strlen(err_msg));
687                 else
688                         option_error();
689                 msleep(400);
690                 exit_cleanup(RERR_UNSUPPORTED);
691         }
692
693         if (lp_timeout(i) && lp_timeout(i) > io_timeout)
694                 set_io_timeout(lp_timeout(i));
695
696         /* If we have some incoming/outgoing chmod changes, append them to
697          * any user-specified changes (making our changes have priority).
698          * We also get a pointer to just our changes so that a receiver
699          * process can use them separately if --perms wasn't specified. */
700         if (am_sender)
701                 p = lp_outgoing_chmod(i);
702         else
703                 p = lp_incoming_chmod(i);
704         if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
705                 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
706                         am_sender ? "outgo" : "incom", p);
707         }
708
709         start_server(f_in, f_out, argc, argv);
710
711         return 0;
712 }
713
714 /* send a list of available modules to the client. Don't list those
715    with "list = False". */
716 static void send_listing(int fd)
717 {
718         int n = lp_numservices();
719         int i;
720
721         for (i = 0; i < n; i++) {
722                 if (lp_list(i))
723                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
724         }
725
726         if (protocol_version >= 25)
727                 io_printf(fd,"@RSYNCD: EXIT\n");
728 }
729
730 /* this is called when a connection is established to a client
731    and we want to start talking. The setup of the system is done from
732    here */
733 int start_daemon(int f_in, int f_out)
734 {
735         char line[1024];
736         char *motd, *addr, *host;
737         int i;
738
739         io_set_sock_fds(f_in, f_out);
740
741         /* We must load the config file before calling any function that
742          * might cause log-file output to occur.  This ensures that the
743          * "log file" param gets honored for the 2 non-forked use-cases
744          * (when rsync is run by init and run by a remote shell). */
745         if (!lp_load(config_file, 0))
746                 exit_cleanup(RERR_SYNTAX);
747
748         addr = client_addr(f_in);
749         host = client_name(f_in);
750         rprintf(FLOG, "connect from %s (%s)\n", host, addr);
751
752         if (!am_server) {
753                 set_socket_options(f_in, "SO_KEEPALIVE");
754                 if (sockopts)
755                         set_socket_options(f_in, sockopts);
756                 else
757                         set_socket_options(f_in, lp_socket_options());
758                 set_nonblocking(f_in);
759         }
760
761         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
762
763         motd = lp_motd_file();
764         if (motd && *motd) {
765                 FILE *f = fopen(motd,"r");
766                 while (f && !feof(f)) {
767                         int len = fread(line, 1, sizeof line - 1, f);
768                         if (len > 0) {
769                                 line[len] = 0;
770                                 io_printf(f_out, "%s", line);
771                         }
772                 }
773                 if (f)
774                         fclose(f);
775                 io_printf(f_out, "\n");
776         }
777
778         if (!read_line(f_in, line, sizeof line - 1))
779                 return -1;
780
781         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
782                 io_printf(f_out, "@ERROR: protocol startup error\n");
783                 return -1;
784         }
785         if (protocol_version > remote_protocol)
786                 protocol_version = remote_protocol;
787
788         line[0] = 0;
789         if (!read_line(f_in, line, sizeof line - 1))
790                 return -1;
791
792         if (!*line || strcmp(line, "#list") == 0) {
793                 rprintf(FLOG, "module-list request from %s (%s)\n",
794                         host, addr);
795                 send_listing(f_out);
796                 return -1;
797         }
798
799         if (*line == '#') {
800                 /* it's some sort of command that I don't understand */
801                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
802                 return -1;
803         }
804
805         if ((i = lp_number(line)) < 0) {
806                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
807                         line, host, addr);
808                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
809                 return -1;
810         }
811
812 #ifdef HAVE_SIGACTION
813         sigact.sa_flags = SA_NOCLDSTOP;
814 #endif
815         SIGACTION(SIGCHLD, remember_children);
816
817         return rsync_module(f_in, f_out, i, addr, host);
818 }
819
820 int daemon_main(void)
821 {
822         char *pid_file;
823
824         if (is_a_socket(STDIN_FILENO)) {
825                 int i;
826
827                 /* we are running via inetd - close off stdout and
828                  * stderr so that library functions (and getopt) don't
829                  * try to use them. Redirect them to /dev/null */
830                 for (i = 1; i < 3; i++) {
831                         close(i);
832                         open("/dev/null", O_RDWR);
833                 }
834
835                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
836         }
837
838         if (!no_detach)
839                 become_daemon();
840
841         if (!lp_load(config_file, 1))
842                 exit_cleanup(RERR_SYNTAX);
843
844         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
845                 rsync_port = RSYNC_PORT;
846         if (bind_address == NULL && *lp_bind_address())
847                 bind_address = lp_bind_address();
848
849         log_init(0);
850
851         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
852                 RSYNC_VERSION, rsync_port);
853         /* TODO: If listening on a particular address, then show that
854          * address too.  In fact, why not just do inet_ntop on the
855          * local address??? */
856
857         if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
858                 char pidbuf[16];
859                 int fd;
860                 pid_t pid = getpid();
861                 cleanup_set_pid(pid);
862                 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
863                                         0666 & ~orig_umask)) == -1) {
864                         cleanup_set_pid(0);
865                         rsyserr(FLOG, errno, "failed to create pid file %s",
866                                 pid_file);
867                         exit_cleanup(RERR_FILEIO);
868                 }
869                 snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
870                 write(fd, pidbuf, strlen(pidbuf));
871                 close(fd);
872         }
873
874         start_accept_loop(rsync_port, start_daemon);
875         return -1;
876 }