John E. Malmberg convinced me to standardize on #ifs for defined
[rsync/rsync.git] / clientserver.c
1 /* -*- c-file-style: "linux"; -*-
2  *
3  * Copyright (C) 1998-2001 by Andrew Tridgell <tridge@samba.org>
4  * Copyright (C) 2001-2002 by Martin Pool <mbp@samba.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 /**
22  * @file
23  *
24  * The socket based protocol for setting up a connection with
25  * rsyncd.
26  **/
27
28 #include "rsync.h"
29
30 extern int am_sender;
31 extern int am_server;
32 extern int am_daemon;
33 extern int am_root;
34 extern int verbose;
35 extern int rsync_port;
36 extern int kludge_around_eof;
37 extern int daemon_over_rsh;
38 extern int list_only;
39 extern int sanitize_paths;
40 extern int filesfrom_fd;
41 extern int remote_protocol;
42 extern int protocol_version;
43 extern int io_timeout;
44 extern int select_timeout;
45 extern int orig_umask;
46 extern int no_detach;
47 extern int default_af_hint;
48 extern char *bind_address;
49 extern struct filter_list_struct server_filter_list;
50 extern char *config_file;
51 extern char *files_from;
52
53 char *auth_user;
54 int read_only = 0;
55 int module_id = -1;
56
57 /* Length of lp_path() string when in daemon mode & not chrooted, else 0. */
58 unsigned int module_dirlen = 0;
59
60 /**
61  * Run a client connected to an rsyncd.  The alternative to this
62  * function for remote-shell connections is do_cmd().
63  *
64  * After negotiating which module to use and reading the server's
65  * motd, this hands over to client_run().  Telling the server the
66  * module will cause it to chroot/setuid/etc.
67  *
68  * Instead of doing a transfer, the client may at this stage instead
69  * get a listing of remote modules and exit.
70  *
71  * @return -1 for error in startup, or the result of client_run().
72  * Either way, it eventually gets passed to exit_cleanup().
73  **/
74 int start_socket_client(char *host, char *path, int argc, char *argv[])
75 {
76         int fd, ret;
77         char *p, *user = NULL;
78
79         /* This is redundant with code in start_inband_exchange(), but this
80          * short-circuits a problem in the client before we open a socket,
81          * and the extra check won't hurt. */
82         if (*path == '/') {
83                 rprintf(FERROR,
84                         "ERROR: The remote path must start with a module name not a /\n");
85                 return -1;
86         }
87
88         if ((p = strchr(host, '@')) != NULL) {
89                 user = host;
90                 host = p+1;
91                 *p = '\0';
92         }
93
94         if (rsync_port == 0)
95                 rsync_port = RSYNC_PORT;
96
97         fd = open_socket_out_wrapped(host, rsync_port, bind_address,
98                                      default_af_hint);
99         if (fd == -1)
100                 exit_cleanup(RERR_SOCKETIO);
101
102         ret = start_inband_exchange(user, path, fd, fd, argc);
103
104         return ret < 0? ret : client_run(fd, fd, -1, argc, argv);
105 }
106
107 int start_inband_exchange(char *user, char *path, int f_in, int f_out, 
108                           int argc)
109 {
110         int i;
111         char *sargs[MAX_ARGS];
112         int sargc = 0;
113         char line[MAXPATHLEN];
114         char *p;
115
116         if (argc == 0 && !am_sender)
117                 list_only |= 1;
118
119         if (*path == '/') {
120                 rprintf(FERROR,
121                         "ERROR: The remote path must start with a module name\n");
122                 return -1;
123         }
124
125         if (!user)
126                 user = getenv("USER");
127         if (!user)
128                 user = getenv("LOGNAME");
129
130         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
131
132         if (!read_line(f_in, line, sizeof line - 1)) {
133                 rprintf(FERROR, "rsync: did not see server greeting\n");
134                 return -1;
135         }
136
137         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
138                 /* note that read_line strips of \n or \r */
139                 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
140                         line);
141                 return -1;
142         }
143         if (protocol_version > remote_protocol)
144                 protocol_version = remote_protocol;
145
146         if (list_only && protocol_version >= 29)
147                 list_only |= 2;
148
149         /* set daemon_over_rsh to false since we need to build the
150          * true set of args passed through the rsh/ssh connection;
151          * this is a no-op for direct-socket-connection mode */
152         daemon_over_rsh = 0;
153         server_options(sargs, &sargc);
154
155         sargs[sargc++] = ".";
156
157         if (path && *path)
158                 sargs[sargc++] = path;
159
160         sargs[sargc] = NULL;
161
162         if (verbose > 1)
163                 print_child_argv(sargs);
164
165         p = strchr(path,'/');
166         if (p) *p = 0;
167         io_printf(f_out, "%s\n", path);
168         if (p) *p = '/';
169
170         /* Old servers may just drop the connection here,
171          rather than sending a proper EXIT command.  Yuck. */
172         kludge_around_eof = list_only && (protocol_version < 25);
173
174         while (1) {
175                 if (!read_line(f_in, line, sizeof line - 1)) {
176                         rprintf(FERROR, "rsync: didn't get server startup line\n");
177                         return -1;
178                 }
179
180                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
181                         auth_client(f_out, user, line+18);
182                         continue;
183                 }
184
185                 if (strcmp(line,"@RSYNCD: OK") == 0)
186                         break;
187
188                 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
189                         /* This is sent by recent versions of the
190                          * server to terminate the listing of modules.
191                          * We don't want to go on and transfer
192                          * anything; just exit. */
193                         exit(0);
194                 }
195
196                 if (strncmp(line, "@ERROR", 6) == 0) {
197                         rprintf(FERROR, "%s\n", line);
198                         /* This is always fatal; the server will now
199                          * close the socket. */
200                         return RERR_STARTCLIENT;
201                 } else {
202                         rprintf(FINFO,"%s\n", line);
203                 }
204         }
205         kludge_around_eof = False;
206
207         for (i = 0; i < sargc; i++) {
208                 io_printf(f_out, "%s\n", sargs[i]);
209         }
210         io_printf(f_out, "\n");
211
212         if (protocol_version < 23) {
213                 if (protocol_version == 22 || !am_sender)
214                         io_start_multiplex_in();
215         }
216
217         return 0;
218 }
219
220
221
222 static int rsync_module(int f_in, int f_out, int i)
223 {
224         int argc = 0;
225         int maxargs;
226         char **argv;
227         char **argp;
228         char line[MAXPATHLEN];
229         uid_t uid = (uid_t)-2;  /* canonically "nobody" */
230         gid_t gid = (gid_t)-2;
231         char *p;
232         char *addr = client_addr(f_in);
233         char *host = client_name(f_in);
234         char *name = lp_name(i);
235         int use_chroot = lp_use_chroot(i);
236         int start_glob = 0;
237         int ret;
238         char *request = NULL;
239
240         if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
241                 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
242                         name, host, addr);
243                 if (!lp_list(i))
244                         io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
245                 else {
246                         io_printf(f_out,
247                                   "@ERROR: access denied to %s from %s (%s)\n",
248                                   name, host, addr);
249                 }
250                 return -1;
251         }
252
253         if (am_daemon && am_server) {
254                 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
255                         name, host, addr);
256         }
257
258         if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
259                 if (errno) {
260                         rsyserr(FLOG, errno, "failed to open lock file %s",
261                                 safe_fname(lp_lock_file(i)));
262                         io_printf(f_out, "@ERROR: failed to open lock file\n");
263                 } else {
264                         rprintf(FLOG, "max connections (%d) reached\n",
265                                 lp_max_connections(i));
266                         io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
267                                 lp_max_connections(i));
268                 }
269                 return -1;
270         }
271
272         auth_user = auth_server(f_in, f_out, i, addr, "@RSYNCD: AUTHREQD ");
273
274         if (!auth_user) {
275                 rprintf(FLOG, "auth failed on module %s from %s (%s)\n",
276                         name, host, addr);
277                 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
278                 return -1;
279         }
280
281         module_id = i;
282
283         if (lp_read_only(i))
284                 read_only = 1;
285
286         am_root = (MY_UID() == 0);
287
288         if (am_root) {
289                 p = lp_uid(i);
290                 if (!name_to_uid(p, &uid)) {
291                         if (!isdigit(*(unsigned char *)p)) {
292                                 rprintf(FLOG, "Invalid uid %s\n", p);
293                                 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
294                                 return -1;
295                         }
296                         uid = atoi(p);
297                 }
298
299                 p = lp_gid(i);
300                 if (!name_to_gid(p, &gid)) {
301                         if (!isdigit(*(unsigned char *)p)) {
302                                 rprintf(FLOG, "Invalid gid %s\n", p);
303                                 io_printf(f_out, "@ERROR: invalid gid %s\n", p);
304                                 return -1;
305                         }
306                         gid = atoi(p);
307                 }
308         }
309
310         /* TODO: If we're not root, but the configuration requests
311          * that we change to some uid other than the current one, then
312          * log a warning. */
313
314         /* TODO: Perhaps take a list of gids, and make them into the
315          * supplementary groups. */
316
317         if (use_chroot) {
318                 module_dirlen = 0;
319                 set_filter_dir("/", 1);
320         } else {
321                 module_dirlen = strlen(lp_path(i));
322                 set_filter_dir(lp_path(i), module_dirlen);
323         }
324
325         p = lp_filter(i);
326         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
327                    XFLG_ANCHORED2ABS);
328
329         p = lp_include_from(i);
330         parse_filter_file(&server_filter_list, p, MATCHFLG_INCLUDE,
331             XFLG_ANCHORED2ABS | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
332
333         p = lp_include(i);
334         parse_rule(&server_filter_list, p,
335                    MATCHFLG_INCLUDE | MATCHFLG_WORD_SPLIT,
336                    XFLG_ANCHORED2ABS | XFLG_OLD_PREFIXES);
337
338         p = lp_exclude_from(i);
339         parse_filter_file(&server_filter_list, p, 0,
340             XFLG_ANCHORED2ABS | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
341
342         p = lp_exclude(i);
343         parse_rule(&server_filter_list, p, MATCHFLG_WORD_SPLIT,
344                    XFLG_ANCHORED2ABS | XFLG_OLD_PREFIXES);
345
346         log_init();
347
348         if (use_chroot) {
349                 /*
350                  * XXX: The 'use chroot' flag is a fairly reliable
351                  * source of confusion, because it fails under two
352                  * important circumstances: running as non-root,
353                  * running on Win32 (or possibly others).  On the
354                  * other hand, if you are running as root, then it
355                  * might be better to always use chroot.
356                  *
357                  * So, perhaps if we can't chroot we should just issue
358                  * a warning, unless a "require chroot" flag is set,
359                  * in which case we fail.
360                  */
361                 if (chroot(lp_path(i))) {
362                         rsyserr(FLOG, errno, "chroot %s failed",
363                                 safe_fname(lp_path(i)));
364                         io_printf(f_out, "@ERROR: chroot failed\n");
365                         return -1;
366                 }
367
368                 if (!push_dir("/")) {
369                         rsyserr(FLOG, errno, "chdir %s failed\n",
370                                 safe_fname(lp_path(i)));
371                         io_printf(f_out, "@ERROR: chdir failed\n");
372                         return -1;
373                 }
374
375         } else {
376                 if (!push_dir(lp_path(i))) {
377                         rsyserr(FLOG, errno, "chdir %s failed\n",
378                                 safe_fname(lp_path(i)));
379                         io_printf(f_out, "@ERROR: chdir failed\n");
380                         return -1;
381                 }
382                 sanitize_paths = 1;
383         }
384
385         if (am_root) {
386                 /* XXXX: You could argue that if the daemon is started
387                  * by a non-root user and they explicitly specify a
388                  * gid, then we should try to change to that gid --
389                  * this could be possible if it's already in their
390                  * supplementary groups. */
391
392                 /* TODO: Perhaps we need to document that if rsyncd is
393                  * started by somebody other than root it will inherit
394                  * all their supplementary groups. */
395
396                 if (setgid(gid)) {
397                         rsyserr(FLOG, errno, "setgid %d failed", (int)gid);
398                         io_printf(f_out, "@ERROR: setgid failed\n");
399                         return -1;
400                 }
401 #ifdef HAVE_SETGROUPS
402                 /* Get rid of any supplementary groups this process
403                  * might have inheristed. */
404                 if (setgroups(1, &gid)) {
405                         rsyserr(FLOG, errno, "setgroups failed");
406                         io_printf(f_out, "@ERROR: setgroups failed\n");
407                         return -1;
408                 }
409 #endif
410
411                 if (setuid(uid)) {
412                         rsyserr(FLOG, errno, "setuid %d failed", (int)uid);
413                         io_printf(f_out, "@ERROR: setuid failed\n");
414                         return -1;
415                 }
416
417                 am_root = (MY_UID() == 0);
418         }
419
420         io_printf(f_out, "@RSYNCD: OK\n");
421
422         maxargs = MAX_ARGS;
423         if (!(argv = new_array(char *, maxargs)))
424                 out_of_memory("rsync_module");
425         argv[argc++] = "rsyncd";
426
427         while (1) {
428                 if (!read_line(f_in, line, sizeof line - 1))
429                         return -1;
430
431                 if (!*line)
432                         break;
433
434                 p = line;
435
436                 if (argc == maxargs) {
437                         maxargs += MAX_ARGS;
438                         if (!(argv = realloc_array(argv, char *, maxargs)))
439                                 out_of_memory("rsync_module");
440                 }
441                 if (!(argv[argc] = strdup(p)))
442                         out_of_memory("rsync_module");
443
444                 if (start_glob) {
445                         if (start_glob == 1) {
446                                 request = strdup(p);
447                                 start_glob++;
448                         }
449                         glob_expand(name, &argv, &argc, &maxargs);
450                 } else
451                         argc++;
452
453                 if (strcmp(line, ".") == 0)
454                         start_glob = 1;
455         }
456
457         verbose = 0; /* future verbosity is controlled by client options */
458         argp = argv;
459         ret = parse_arguments(&argc, (const char ***) &argp, 0);
460
461         if (filesfrom_fd == 0)
462                 filesfrom_fd = f_in;
463
464         if (request) {
465                 if (*auth_user) {
466                         rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
467                                 am_sender ? "on" : "to",
468                                 request, auth_user, host, addr);
469                 } else {
470                         rprintf(FLOG, "rsync %s %s from %s (%s)\n",
471                                 am_sender ? "on" : "to",
472                                 request, host, addr);
473                 }
474                 free(request);
475         }
476
477 #ifndef DEBUG
478         /* don't allow the logs to be flooded too fast */
479         if (verbose > lp_max_verbosity())
480                 verbose = lp_max_verbosity();
481 #endif
482
483         if (protocol_version < 23
484             && (protocol_version == 22 || am_sender))
485                 io_start_multiplex_out();
486         else if (!ret) {
487                 /* We have to get I/O multiplexing started so that we can
488                  * get the error back to the client.  This means getting
489                  * the protocol setup finished first in later versions. */
490                 setup_protocol(f_out, f_in);
491                 if (files_from && !am_sender && strcmp(files_from, "-") != 0)
492                         write_byte(f_out, 0);
493                 io_start_multiplex_out();
494         }
495
496         if (!ret) {
497                 option_error();
498                 msleep(400);
499                 exit_cleanup(RERR_UNSUPPORTED);
500         }
501
502         if (lp_timeout(i)) {
503                 io_timeout = lp_timeout(i);
504                 if (io_timeout < select_timeout)
505                         select_timeout = io_timeout;
506         }
507
508         start_server(f_in, f_out, argc, argp);
509
510         return 0;
511 }
512
513 /* send a list of available modules to the client. Don't list those
514    with "list = False". */
515 static void send_listing(int fd)
516 {
517         int n = lp_numservices();
518         int i;
519
520         for (i = 0; i < n; i++) {
521                 if (lp_list(i))
522                         io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
523         }
524
525         if (protocol_version >= 25)
526                 io_printf(fd,"@RSYNCD: EXIT\n");
527 }
528
529 /* this is called when a connection is established to a client
530    and we want to start talking. The setup of the system is done from
531    here */
532 int start_daemon(int f_in, int f_out)
533 {
534         char line[200];
535         char *motd;
536         int i;
537
538         io_set_sock_fds(f_in, f_out);
539
540         if (!lp_load(config_file, 0))
541                 exit_cleanup(RERR_SYNTAX);
542
543         log_init();
544
545         if (!am_server) {
546                 set_socket_options(f_in, "SO_KEEPALIVE");
547                 set_socket_options(f_in, lp_socket_options());
548                 set_nonblocking(f_in);
549         }
550
551         io_printf(f_out, "@RSYNCD: %d\n", protocol_version);
552
553         motd = lp_motd_file();
554         if (motd && *motd) {
555                 FILE *f = fopen(motd,"r");
556                 while (f && !feof(f)) {
557                         int len = fread(line, 1, sizeof line - 1, f);
558                         if (len > 0) {
559                                 line[len] = 0;
560                                 io_printf(f_out, "%s", line);
561                         }
562                 }
563                 if (f)
564                         fclose(f);
565                 io_printf(f_out, "\n");
566         }
567
568         if (!read_line(f_in, line, sizeof line - 1))
569                 return -1;
570
571         if (sscanf(line,"@RSYNCD: %d", &remote_protocol) != 1) {
572                 io_printf(f_out, "@ERROR: protocol startup error\n");
573                 return -1;
574         }
575         if (protocol_version > remote_protocol)
576                 protocol_version = remote_protocol;
577
578         line[0] = 0;
579         if (!read_line(f_in, line, sizeof line - 1))
580                 return -1;
581
582         if (!*line || strcmp(line, "#list") == 0) {
583                 send_listing(f_out);
584                 return -1;
585         }
586
587         if (*line == '#') {
588                 /* it's some sort of command that I don't understand */
589                 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
590                 return -1;
591         }
592
593         if ((i = lp_number(line)) < 0) {
594                 char *addr = client_addr(f_in);
595                 char *host = client_name(f_in);
596                 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
597                         line, host, addr);
598                 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
599                 return -1;
600         }
601
602         return rsync_module(f_in, f_out, i);
603 }
604
605
606 int daemon_main(void)
607 {
608         char *pid_file;
609
610         if (is_a_socket(STDIN_FILENO)) {
611                 int i;
612
613                 /* we are running via inetd - close off stdout and
614                  * stderr so that library functions (and getopt) don't
615                  * try to use them. Redirect them to /dev/null */
616                 for (i = 1; i < 3; i++) {
617                         close(i);
618                         open("/dev/null", O_RDWR);
619                 }
620
621                 return start_daemon(STDIN_FILENO, STDIN_FILENO);
622         }
623
624         if (!no_detach)
625                 become_daemon();
626
627         if (!lp_load(config_file, 1))
628                 exit_cleanup(RERR_SYNTAX);
629
630         if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
631                 rsync_port = RSYNC_PORT;
632         if (bind_address == NULL && *lp_bind_address())
633                 bind_address = lp_bind_address();
634
635         log_init();
636
637         rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
638                 RSYNC_VERSION, rsync_port);
639         /* TODO: If listening on a particular address, then show that
640          * address too.  In fact, why not just do inet_ntop on the
641          * local address??? */
642
643         if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
644                 char pidbuf[16];
645                 int fd;
646                 pid_t pid = getpid();
647                 cleanup_set_pid(pid);
648                 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
649                                         0666 & ~orig_umask)) == -1) {
650                         cleanup_set_pid(0);
651                         rsyserr(FLOG, errno, "failed to create pid file %s",
652                                 safe_fname(pid_file));
653                         exit_cleanup(RERR_FILEIO);
654                 }
655                 snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
656                 write(fd, pidbuf, strlen(pidbuf));
657                 close(fd);
658         }
659
660         start_accept_loop(rsync_port, start_daemon);
661         return -1;
662 }