Doc.
[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 module_id;
31 extern int read_only;
32 extern int verbose;
33 extern int rsync_port;
34 char *auth_user;
35 extern int sanitize_paths;
36
37 /**
38  * Run a client connected to an rsyncd.  The alternative to this
39  * function for remote-shell connections is do_cmd().
40  *
41  * After initial server startup, hands over to client_run().
42  *
43  * @return -1 for error in startup, or the result of client_run().
44  **/
45 int start_socket_client(char *host, char *path, int argc, char *argv[])
46 {
47         int fd, i;
48         char *sargs[MAX_ARGS];
49         int sargc=0;
50         char line[MAXPATHLEN];
51         char *p, *user=NULL;
52         extern int remote_version;
53         extern int am_sender;
54         extern char *shell_cmd;
55         extern int list_only;
56         extern int kludge_around_eof;
57         extern char *bind_address;
58         extern int default_af_hint;
59        
60         if (argc == 0 && !am_sender) {
61                 extern int list_only;
62                 list_only = 1;
63         }
64
65         /* This is just a friendliness enhancement: if the connection
66          * is to an rsyncd then there is no point specifying the -e option.
67          * Note that this is only set if the -e was explicitly specified,
68          * not if the environment variable just happens to be set.
69          * See http://lists.samba.org/pipermail/rsync/2000-September/002744.html
70          */
71         if (shell_cmd) {
72                 rprintf(FERROR, "WARNING: --rsh or -e option ignored when "
73                         "connecting to rsync daemon\n");
74                 /* continue */
75         }
76         
77         if (*path == '/') {
78                 rprintf(FERROR,"ERROR: The remote path must start with a module name not a /\n");
79                 return -1;
80         }
81
82         p = strchr(host, '@');
83         if (p) {
84                 user = host;
85                 host = p+1;
86                 *p = 0;
87         }
88
89         if (!user) user = getenv("USER");
90         if (!user) user = getenv("LOGNAME");
91
92         if (verbose >= 2) {
93                 /* FIXME: If we're going to use a socket program for
94                  * testing, then this message is wrong.  We need to
95                  * say something like "(except really using %s)" */
96                 rprintf(FINFO, "opening tcp connection to %s port %d\n",
97                         host, rsync_port);
98         }
99         fd = open_socket_out_wrapped (host, rsync_port, bind_address,
100                                       default_af_hint);
101         if (fd == -1) {
102                 exit_cleanup(RERR_SOCKETIO);
103         }
104         
105         server_options(sargs,&sargc);
106
107         sargs[sargc++] = ".";
108
109         if (path && *path) 
110                 sargs[sargc++] = path;
111
112         sargs[sargc] = NULL;
113
114         io_printf(fd,"@RSYNCD: %d\n", PROTOCOL_VERSION);
115
116         if (!read_line(fd, line, sizeof(line)-1)) {
117                 rprintf(FERROR, "rsync: did not see server greeting\n");
118                 return -1;
119         }
120
121         if (sscanf(line,"@RSYNCD: %d", &remote_version) != 1) {
122                 /* note that read_line strips of \n or \r */
123                 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n",
124                         line);
125                 return -1;
126         }
127
128         p = strchr(path,'/');
129         if (p) *p = 0;
130         io_printf(fd,"%s\n",path);
131         if (p) *p = '/';
132
133         /* Old servers may just drop the connection here,
134          rather than sending a proper EXIT command.  Yuck. */
135         kludge_around_eof = list_only && (remote_version < 25);
136
137         while (1) {
138                 if (!read_line(fd, line, sizeof(line)-1)) {
139                         rprintf(FERROR, "rsync: didn't get server startup line\n");
140                         return -1;
141                 }
142
143                 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
144                         auth_client(fd, user, line+18);
145                         continue;
146                 }
147
148                 if (strcmp(line,"@RSYNCD: OK") == 0) break;
149
150                 if (strcmp(line,"@RSYNCD: EXIT") == 0) exit(0);
151
152                 if (strncmp(line, "@ERROR", 6) == 0)
153                         rprintf(FERROR,"%s\n", line);
154                 else
155                         rprintf(FINFO,"%s\n", line);
156         }
157         kludge_around_eof = False;
158
159         for (i=0;i<sargc;i++) {
160                 io_printf(fd,"%s\n", sargs[i]);
161         }
162         io_printf(fd,"\n");
163
164         if (remote_version < 23) {
165                 if (remote_version == 22 || (remote_version > 17 && !am_sender))
166                         io_start_multiplex_in(fd);
167         }
168
169         return client_run(fd, fd, -1, argc, argv);
170 }
171
172
173
174 static int rsync_module(int fd, int i)
175 {
176         int argc=0;
177         char *argv[MAX_ARGS];
178         char **argp;
179         char line[MAXPATHLEN];
180         uid_t uid = (uid_t)-2;  /* canonically "nobody" */
181         gid_t gid = (gid_t)-2;
182         char *p;
183         char *addr = client_addr(fd);
184         char *host = client_name(fd);
185         char *name = lp_name(i);
186         int use_chroot = lp_use_chroot(i);
187         int start_glob=0;
188         int ret;
189         char *request=NULL;
190         extern int am_sender;
191         extern int remote_version;
192         extern int am_root;
193
194         if (!allow_access(addr, host, lp_hosts_allow(i), lp_hosts_deny(i))) {
195                 rprintf(FERROR,"rsync denied on module %s from %s (%s)\n",
196                         name, host, addr);
197                 io_printf(fd,"@ERROR: access denied to %s from %s (%s)\n",
198                           name, host, addr);
199                 return -1;
200         }
201
202         if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
203                 if (errno) {
204                         rprintf(FERROR,"failed to open lock file %s : %s\n",
205                                 lp_lock_file(i), strerror(errno));
206                         io_printf(fd,"@ERROR: failed to open lock file %s : %s\n",
207                                   lp_lock_file(i), strerror(errno));
208                 } else {
209                         rprintf(FERROR,"max connections (%d) reached\n",
210                                 lp_max_connections(i));
211                         io_printf(fd,"@ERROR: max connections (%d) reached - try again later\n", lp_max_connections(i));
212                 }
213                 return -1;
214         }
215
216         
217         auth_user = auth_server(fd, i, addr, "@RSYNCD: AUTHREQD ");
218
219         if (!auth_user) {
220                 rprintf(FERROR,"auth failed on module %s from %s (%s)\n",
221                         name, client_name(fd), client_addr(fd));
222                 io_printf(fd,"@ERROR: auth failed on module %s\n",name);
223                 return -1;              
224         }
225
226         module_id = i;
227
228         am_root = (getuid() == 0);
229
230         if (am_root) {
231                 p = lp_uid(i);
232                 if (!name_to_uid(p, &uid)) {
233                         if (!isdigit(*p)) {
234                                 rprintf(FERROR,"Invalid uid %s\n", p);
235                                 io_printf(fd,"@ERROR: invalid uid %s\n", p);
236                                 return -1;
237                         } 
238                         uid = atoi(p);
239                 }
240
241                 p = lp_gid(i);
242                 if (!name_to_gid(p, &gid)) {
243                         if (!isdigit(*p)) {
244                                 rprintf(FERROR,"Invalid gid %s\n", p);
245                                 io_printf(fd,"@ERROR: invalid gid %s\n", p);
246                                 return -1;
247                         } 
248                         gid = atoi(p);
249                 }
250         }
251         
252         /* TODO: If we're not root, but the configuration requests
253          * that we change to some uid other than the current one, then
254          * log a warning. */
255
256         /* TODO: Perhaps take a list of gids, and make them into the
257          * supplementary groups. */
258
259         p = lp_include_from(i);
260         add_exclude_file(p, 1, 1);
261
262         p = lp_include(i);
263         add_include_line(p);
264
265         p = lp_exclude_from(i);
266         add_exclude_file(p, 1, 0);
267
268         p = lp_exclude(i);
269         add_exclude_line(p);
270
271         log_init();
272
273         if (use_chroot) {
274                 /*
275                  * XXX: The 'use chroot' flag is a fairly reliable
276                  * source of confusion, because it fails under two
277                  * important circumstances: running as non-root,
278                  * running on Win32 (or possibly others).  On the
279                  * other hand, if you are running as root, then it
280                  * might be better to always use chroot.
281                  *
282                  * So, perhaps if we can't chroot we should just issue
283                  * a warning, unless a "require chroot" flag is set,
284                  * in which case we fail.
285                  */
286                 if (chroot(lp_path(i))) {
287                         rsyserr(FERROR, errno, "chroot %s failed", lp_path(i));
288                         io_printf(fd,"@ERROR: chroot failed\n");
289                         return -1;
290                 }
291
292                 if (!push_dir("/", 0)) {
293                         rsyserr(FERROR, errno, "chdir %s failed\n", lp_path(i));
294                         io_printf(fd,"@ERROR: chdir failed\n");
295                         return -1;
296                 }
297
298         } else {
299                 if (!push_dir(lp_path(i), 0)) {
300                         rsyserr(FERROR, errno, "chdir %s failed\n", lp_path(i));
301                         io_printf(fd,"@ERROR: chdir failed\n");
302                         return -1;
303                 }
304                 sanitize_paths = 1;
305         }
306
307         if (am_root) {
308 #ifdef HAVE_SETGROUPS
309                 /* Get rid of any supplementary groups this process
310                  * might have inheristed. */
311                 if (setgroups(0, NULL)) {
312                         rsyserr(FERROR, errno, "setgroups failed");
313                         io_printf(fd, "@ERROR: setgroups failed\n");
314                         return -1;
315                 }
316 #endif
317
318                 /* XXXX: You could argue that if the daemon is started
319                  * by a non-root user and they explicitly specify a
320                  * gid, then we should try to change to that gid --
321                  * this could be possible if it's already in their
322                  * supplementary groups. */
323
324                 /* TODO: Perhaps we need to document that if rsyncd is
325                  * started by somebody other than root it will inherit
326                  * all their supplementary groups. */
327
328                 if (setgid(gid)) {
329                         rsyserr(FERROR, errno, "setgid %d failed", (int) gid);
330                         io_printf(fd,"@ERROR: setgid failed\n");
331                         return -1;
332                 }
333
334                 if (setuid(uid)) {
335                         rsyserr(FERROR, errno, "setuid %d failed", (int) uid);
336                         io_printf(fd,"@ERROR: setuid failed\n");
337                         return -1;
338                 }
339
340                 am_root = (getuid() == 0);
341         }
342
343         io_printf(fd,"@RSYNCD: OK\n");
344
345         argv[argc++] = "rsyncd";
346
347         while (1) {
348                 if (!read_line(fd, line, sizeof(line)-1)) {
349                         return -1;
350                 }
351
352                 if (!*line) break;
353
354                 p = line;
355
356                 argv[argc] = strdup(p);
357                 if (!argv[argc]) {
358                         return -1;
359                 }
360
361                 if (start_glob) {
362                         if (start_glob == 1) {
363                                 request = strdup(p);
364                                 start_glob++;
365                         }
366                         glob_expand(name, argv, &argc, MAX_ARGS);
367                 } else {
368                         argc++;
369                 }
370
371                 if (strcmp(line,".") == 0) {
372                         start_glob = 1;
373                 }
374
375                 if (argc == MAX_ARGS) {
376                         return -1;
377                 }
378         }
379
380         if (sanitize_paths) {
381                 /*
382                  * Note that this is applied to all parameters, whether or not
383                  *    they are filenames, but no other legal parameters contain
384                  *    the forms that need to be sanitized so it doesn't hurt;
385                  *    it is not known at this point which parameters are files
386                  *    and which aren't.
387                  */
388                 for (i = 1; i < argc; i++) {
389                         sanitize_path(argv[i], NULL);
390                 }
391         }
392
393         argp = argv;
394         ret = parse_arguments(&argc, (const char ***) &argp, 0);
395
396         if (request) {
397                 if (*auth_user) {
398                         rprintf(FINFO,"rsync %s %s from %s@%s (%s)\n",
399                                 am_sender?"on":"to",
400                                 request, auth_user, host, addr);
401                 } else {
402                         rprintf(FINFO,"rsync %s %s from %s (%s)\n",
403                                 am_sender?"on":"to",
404                                 request, host, addr);
405                 }
406                 free(request);
407         }
408
409 #ifndef DEBUG
410         /* don't allow the logs to be flooded too fast */
411         if (verbose > 1) verbose = 1;
412 #endif
413
414         if (remote_version < 23) {
415                 if (remote_version == 22 || (remote_version > 17 && am_sender))
416                         io_start_multiplex_out(fd);
417         }
418         
419         /* For later protocol versions, we don't start multiplexing
420          * until we've configured nonblocking in start_server.  That
421          * means we're in a sticky situation now: there's no way to
422          * convey errors to the client. */
423
424         /* FIXME: Hold off on reporting option processing errors until
425          * we've set up nonblocking and multiplexed IO and can get the
426          * message back to them. */
427         if (!ret) {
428                 option_error();
429                 exit_cleanup(RERR_UNSUPPORTED);
430         }
431
432         if (lp_timeout(i)) {
433                 extern int io_timeout;
434                 io_timeout = lp_timeout(i);
435         }
436
437         start_server(fd, fd, argc, argp);
438
439         return 0;
440 }
441
442 /* send a list of available modules to the client. Don't list those
443    with "list = False". */
444 static void send_listing(int fd)
445 {
446         int n = lp_numservices();
447         int i;
448         extern int remote_version;
449
450         for (i=0;i<n;i++)
451                 if (lp_list(i))
452                     io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
453
454         if (remote_version >= 25)
455                 io_printf(fd,"@RSYNCD: EXIT\n");
456 }
457
458 /* this is called when a socket connection is established to a client
459    and we want to start talking. The setup of the system is done from
460    here */
461 static int start_daemon(int fd)
462 {
463         char line[200];
464         char *motd;
465         int i = -1;
466         extern char *config_file;
467         extern int remote_version;
468
469         if (!lp_load(config_file, 0)) {
470                 exit_cleanup(RERR_SYNTAX);
471         }
472
473         set_socket_options(fd,"SO_KEEPALIVE");
474         set_socket_options(fd,lp_socket_options());
475         set_nonblocking(fd);
476
477         io_printf(fd,"@RSYNCD: %d\n", PROTOCOL_VERSION);
478
479         motd = lp_motd_file();
480         if (motd && *motd) {
481                 FILE *f = fopen(motd,"r");
482                 while (f && !feof(f)) {
483                         int len = fread(line, 1, sizeof(line)-1, f);
484                         if (len > 0) {
485                                 line[len] = 0;
486                                 io_printf(fd,"%s", line);
487                         }
488                 }
489                 if (f) fclose(f);
490                 io_printf(fd,"\n");
491         }
492
493         if (!read_line(fd, line, sizeof(line)-1)) {
494                 return -1;
495         }
496
497         if (sscanf(line,"@RSYNCD: %d", &remote_version) != 1) {
498                 io_printf(fd,"@ERROR: protocol startup error\n");
499                 return -1;
500         }       
501
502         while (i == -1) {
503                 line[0] = 0;
504                 if (!read_line(fd, line, sizeof(line)-1)) {
505                         return -1;
506                 }
507
508                 if (!*line || strcmp(line,"#list")==0) {
509                         send_listing(fd);
510                         return -1;
511                 } 
512
513                 if (*line == '#') {
514                         /* it's some sort of command that I don't understand */
515                         io_printf(fd,"@ERROR: Unknown command '%s'\n", line);
516                         return -1;
517                 }
518
519                 i = lp_number(line);
520                 if (i == -1) {
521                         io_printf(fd,"@ERROR: Unknown module '%s'\n", line);
522                         return -1;
523                 }
524         }
525
526         return rsync_module(fd, i);
527 }
528
529
530 int daemon_main(void)
531 {
532         extern char *config_file;
533         extern int orig_umask;
534         char *pid_file;
535         extern int no_detach;
536
537         if (is_a_socket(STDIN_FILENO)) {
538                 int i;
539
540                 /* we are running via inetd - close off stdout and
541                    stderr so that library functions (and getopt) don't
542                    try to use them. Redirect them to /dev/null */
543                 for (i=1;i<3;i++) {
544                         close(i); 
545                         open("/dev/null", O_RDWR);
546                 }
547
548                 return start_daemon(STDIN_FILENO);
549         }
550
551         if (!no_detach)
552             become_daemon();
553
554         if (!lp_load(config_file, 1)) {
555                 exit_cleanup(RERR_SYNTAX);
556         }
557
558         log_init();
559
560         rprintf(FINFO, "rsyncd version %s starting, listening on port %d\n",
561                 RSYNC_VERSION,
562                 rsync_port);
563         /* TODO: If listening on a particular address, then show that
564          * address too.  In fact, why not just do inet_ntop on the
565          * local address??? */
566
567         if (((pid_file = lp_pid_file()) != NULL) && (*pid_file != '\0')) {
568                 char pidbuf[16];
569                 int fd;
570                 int pid = (int) getpid();
571                 cleanup_set_pid(pid);
572                 if ((fd = do_open(lp_pid_file(), O_WRONLY|O_CREAT|O_TRUNC,
573                                         0666 & ~orig_umask)) == -1) {
574                     cleanup_set_pid(0);
575                     rsyserr(FLOG, errno, "failed to create pid file %s", pid_file);
576                     exit_cleanup(RERR_FILEIO);
577                 }
578                 snprintf(pidbuf, sizeof(pidbuf), "%d\n", pid);
579                 write(fd, pidbuf, strlen(pidbuf));
580                 close(fd);
581         }
582
583         start_accept_loop(rsync_port, start_daemon);
584         return -1;
585 }
586