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