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