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