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