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