]> git.ipfire.org Git - thirdparty/rsync.git/blame - clientserver.c
Send the uid/gid 0 name since not all systems use 0 for root.
[thirdparty/rsync.git] / clientserver.c
CommitLineData
0f78b815
WD
1/*
2 * The socket based protocol for setting up a connection with rsyncd.
4a7144ee 3 *
0f78b815
WD
4 * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5 * Copyright (C) 2001-2002 Martin Pool <mbp@samba.org>
c5fabfb0 6 * Copyright (C) 2002-2020 Wayne Davison
4a7144ee 7 *
a254fd97 8 * This program is free software; you can redistribute it and/or modify
8e41b68e
WD
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
4a7144ee 12 *
a254fd97
MP
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
4a7144ee 17 *
e7c67065 18 * You should have received a copy of the GNU General Public License along
4fd842f9 19 * with this program; if not, visit the http://fsf.org website.
a254fd97 20 */
3591c066 21
3591c066 22#include "rsync.h"
5dd14f0c 23#include "itypes.h"
3591c066 24
53936ef9 25extern int quiet;
5223b786 26extern int dry_run;
9ce7fc38 27extern int output_motd;
c0814b81 28extern int list_only;
6e195fe9
WD
29extern int am_sender;
30extern int am_server;
31extern int am_daemon;
32extern int am_root;
c0268d92 33extern int msgs2stderr;
3591c066 34extern int rsync_port;
53936ef9 35extern int protect_args;
3162ea6f 36extern int ignore_errors;
cbbd8e2e 37extern int preserve_xattrs;
8dad7fc6 38extern int kluge_around_eof;
6e195fe9 39extern int daemon_over_rsh;
41adbcec 40extern int munge_symlinks;
f0e670b4 41extern int open_noatime;
b35d0d8e 42extern int sanitize_paths;
0b52f94d 43extern int numeric_ids;
7c2a9e76 44extern int filesfrom_fd;
daa598df
WD
45extern int remote_protocol;
46extern int protocol_version;
6e195fe9 47extern int io_timeout;
6e195fe9 48extern int no_detach;
5223b786 49extern int write_batch;
6e195fe9 50extern int default_af_hint;
ecc7623e
WD
51extern int logfile_format_has_i;
52extern int logfile_format_has_o_or_i;
6e195fe9 53extern char *bind_address;
6e195fe9 54extern char *config_file;
ecc7623e 55extern char *logfile_format;
bf4679e8 56extern char *files_from;
fed1f3f4 57extern char *tmpdir;
e16b2275 58extern char *early_input_file;
730df9d2 59extern struct chmod_mode_struct *chmod_modes;
7b6c5c77 60extern filter_rule_list daemon_filter_list;
0b52f94d
WD
61#ifdef ICONV_OPTION
62extern char *iconv_opt;
63extern iconv_t ic_send, ic_recv;
64#endif
17b849c9
WD
65extern uid_t our_uid;
66extern gid_t our_gid;
6e195fe9
WD
67
68char *auth_user;
18638730 69int read_only = 0;
211bc43b 70int module_id = -1;
b177311a 71int pid_file_fd = -1;
e16b2275
WD
72int early_input_len = 0;
73char *early_input = NULL;
8840ec0f 74struct chmod_mode_struct *daemon_chmod_modes;
3591c066 75
e16b2275
WD
76#define EARLY_INPUT_CMD "#early_input="
77#define EARLY_INPUT_CMDLEN (sizeof EARLY_INPUT_CMD - 1)
78
33cbd577 79/* module_dirlen is the length of the module_dir string when in daemon
2fe1feea
WD
80 * mode and module_dir is not "/"; otherwise 0. (Note that a chroot-
81 * enabled module can have a non-"/" module_dir these days.) */
33cbd577 82char *module_dir = NULL;
e7bf7c01
WD
83unsigned int module_dirlen = 0;
84
26e21efc
WD
85char *full_module_path;
86
7909e65f
WD
87static int rl_nulls = 0;
88
d749eb68
WD
89#ifdef HAVE_SIGACTION
90static struct sigaction sigact;
91#endif
92
2a7355fb 93static item_list gid_list = EMPTY_ITEM_LIST;
7f367bb1 94
11ef77b7
MM
95/* Used when "reverse lookup" is off. */
96const char undetermined_hostname[] = "UNDETERMINED";
97
be2961da 98/**
bc363ea9 99 * Run a client connected to an rsyncd. The alternative to this
be2961da
MP
100 * function for remote-shell connections is do_cmd().
101 *
fdf88d75
MP
102 * After negotiating which module to use and reading the server's
103 * motd, this hands over to client_run(). Telling the server the
104 * module will cause it to chroot/setuid/etc.
105 *
106 * Instead of doing a transfer, the client may at this stage instead
107 * get a listing of remote modules and exit.
be2961da
MP
108 *
109 * @return -1 for error in startup, or the result of client_run().
d0829892 110 * Either way, it eventually gets passed to exit_cleanup().
be2961da 111 **/
7909e65f
WD
112int start_socket_client(char *host, int remote_argc, char *remote_argv[],
113 int argc, char *argv[])
3591c066 114{
68f40ebb 115 int fd, ret;
2e94e70e 116 char *p, *user = NULL;
4a7144ee 117
1732b6c0
WD
118 /* This is redundant with code in start_inband_exchange(), but this
119 * short-circuits a problem in the client before we open a socket,
120 * and the extra check won't hurt. */
7909e65f 121 if (**remote_argv == '/') {
1732b6c0
WD
122 rprintf(FERROR,
123 "ERROR: The remote path must start with a module name not a /\n");
f98df1d9
AT
124 return -1;
125 }
126
b31c92ed 127 if ((p = strrchr(host, '@')) != NULL) {
bcb7e502
AT
128 user = host;
129 host = p+1;
1732b6c0 130 *p = '\0';
bcb7e502
AT
131 }
132
e63ff70e 133 fd = open_socket_out_wrapped(host, rsync_port, bind_address, default_af_hint);
df5cd107 134 if (fd == -1)
65417579 135 exit_cleanup(RERR_SOCKETIO);
68f40ebb 136
5b3aa802
WD
137#ifdef ICONV_CONST
138 setup_iconv();
139#endif
140
7909e65f 141 ret = start_inband_exchange(fd, fd, user, remote_argc, remote_argv);
68f40ebb 142
180443af 143 return ret ? ret : client_run(fd, fd, -1, argc, argv);
68f40ebb
WD
144}
145
7909e65f
WD
146static int exchange_protocols(int f_in, int f_out, char *buf, size_t bufsiz, int am_client)
147{
148 int remote_sub = -1;
149#if SUBPROTOCOL_VERSION != 0
150 int our_sub = protocol_version < PROTOCOL_VERSION ? 0 : SUBPROTOCOL_VERSION;
151#else
152 int our_sub = 0;
153#endif
7909e65f
WD
154
155 io_printf(f_out, "@RSYNCD: %d.%d\n", protocol_version, our_sub);
7909e65f 156 if (!am_client) {
e16b2275 157 char *motd = lp_motd_file();
7909e65f 158 if (motd && *motd) {
e16b2275 159 FILE *f = fopen(motd, "r");
7909e65f
WD
160 while (f && !feof(f)) {
161 int len = fread(buf, 1, bufsiz - 1, f);
162 if (len > 0)
163 write_buf(f_out, buf, len);
164 }
165 if (f)
166 fclose(f);
167 write_sbuf(f_out, "\n");
168 }
169 }
170
171 /* This strips the \n. */
5ebe9a46 172 if (!read_line_old(f_in, buf, bufsiz, 0)) {
7909e65f
WD
173 if (am_client)
174 rprintf(FERROR, "rsync: did not see server greeting\n");
175 return -1;
176 }
177
178 if (sscanf(buf, "@RSYNCD: %d.%d", &remote_protocol, &remote_sub) < 1) {
179 if (am_client)
180 rprintf(FERROR, "rsync: server sent \"%s\" rather than greeting\n", buf);
181 else
182 io_printf(f_out, "@ERROR: protocol startup error\n");
183 return -1;
184 }
185
186 if (remote_sub < 0) {
187 if (remote_protocol == 30) {
188 if (am_client)
189 rprintf(FERROR, "rsync: server is speaking an incompatible beta of protocol 30\n");
190 else
191 io_printf(f_out, "@ERROR: your client is speaking an incompatible beta of protocol 30\n");
192 return -1;
193 }
194 remote_sub = 0;
195 }
196
197 if (protocol_version > remote_protocol) {
198 protocol_version = remote_protocol;
199 if (remote_sub)
200 protocol_version--;
201 } else if (protocol_version == remote_protocol) {
202 if (remote_sub != our_sub)
203 protocol_version--;
204 }
205#if SUBPROTOCOL_VERSION != 0
206 else if (protocol_version < remote_protocol) {
207 if (our_sub)
208 protocol_version--;
209 }
210#endif
211
212 if (protocol_version >= 30)
213 rl_nulls = 1;
214
215 return 0;
216}
217
218int start_inband_exchange(int f_in, int f_out, const char *user, int argc, char *argv[])
68f40ebb 219{
e844a4a8 220 int i, modlen;
7909e65f 221 char line[BIGPATHBUFLEN];
68f40ebb
WD
222 char *sargs[MAX_ARGS];
223 int sargc = 0;
e844a4a8 224 char *p, *modname;
68f40ebb 225
d4c5cb2b 226 assert(argc > 0 && *argv != NULL);
68f40ebb 227
e844a4a8 228 if (**argv == '/') {
1732b6c0
WD
229 rprintf(FERROR,
230 "ERROR: The remote path must start with a module name\n");
68f40ebb
WD
231 return -1;
232 }
233
e844a4a8
WD
234 if (!(p = strchr(*argv, '/')))
235 modlen = strlen(*argv);
236 else
237 modlen = p - *argv;
238
11eb67ee 239 modname = new_array(char, modlen+1+1); /* room for '/' & '\0' */
e844a4a8
WD
240 strlcpy(modname, *argv, modlen + 1);
241 modname[modlen] = '/';
242 modname[modlen+1] = '\0';
243
2e94e70e
WD
244 if (!user)
245 user = getenv("USER");
246 if (!user)
247 user = getenv("LOGNAME");
68f40ebb 248
7909e65f 249 if (exchange_protocols(f_in, f_out, line, sizeof line, 1) < 0)
3591c066 250 return -1;
3591c066 251
e16b2275
WD
252 if (early_input_file) {
253 STRUCT_STAT st;
254 FILE *f = fopen(early_input_file, "rb");
255 if (!f || do_fstat(fileno(f), &st) < 0) {
256 rsyserr(FERROR, errno, "failed to open %s", early_input_file);
257 return -1;
258 }
259 early_input_len = st.st_size;
662fedd7
WD
260 if (early_input_len > (int)sizeof line) {
261 rprintf(FERROR, "%s is > %d bytes.\n", early_input_file, (int)sizeof line);
e16b2275
WD
262 return -1;
263 }
264 if (early_input_len > 0) {
265 io_printf(f_out, EARLY_INPUT_CMD "%d\n", early_input_len);
266 while (early_input_len > 0) {
267 int len;
268 if (feof(f)) {
269 rprintf(FERROR, "Early EOF in %s\n", early_input_file);
270 return -1;
271 }
662fedd7 272 len = fread(line, 1, early_input_len, f);
e16b2275
WD
273 if (len > 0) {
274 write_buf(f_out, line, len);
275 early_input_len -= len;
276 }
277 }
278 }
279 fclose(f);
280 }
281
9bcb2595
WD
282 /* set daemon_over_rsh to false since we need to build the
283 * true set of args passed through the rsh/ssh connection;
284 * this is a no-op for direct-socket-connection mode */
285 daemon_over_rsh = 0;
286 server_options(sargs, &sargc);
287
7909e65f
WD
288 if (sargc >= MAX_ARGS - 2)
289 goto arg_overflow;
290
9bcb2595
WD
291 sargs[sargc++] = ".";
292
7909e65f
WD
293 while (argc > 0) {
294 if (sargc >= MAX_ARGS - 1) {
295 arg_overflow:
296 rprintf(FERROR, "internal: args[] overflowed in do_cmd()\n");
297 exit_cleanup(RERR_SYNTAX);
298 }
d348d5fd 299 if (strncmp(*argv, modname, modlen) == 0
e844a4a8
WD
300 && argv[0][modlen] == '\0')
301 sargs[sargc++] = modname; /* we send "modname/" */
8f30d215
WD
302 else if (**argv == '-') {
303 if (asprintf(sargs + sargc++, "./%s", *argv) < 0)
304 out_of_memory("start_inband_exchange");
305 } else
e844a4a8
WD
306 sargs[sargc++] = *argv;
307 argv++;
7909e65f
WD
308 argc--;
309 }
9bcb2595
WD
310
311 sargs[sargc] = NULL;
312
951e826b 313 if (DEBUG_GTE(CMD, 1))
0b515981 314 print_child_argv("sending daemon args:", sargs);
9bcb2595 315
e844a4a8 316 io_printf(f_out, "%.*s\n", modlen, modname);
2c91d3d3 317
063393d6
MP
318 /* Old servers may just drop the connection here,
319 rather than sending a proper EXIT command. Yuck. */
8dad7fc6 320 kluge_around_eof = list_only && protocol_version < 25 ? 1 : 0;
7a55d06e 321
063393d6 322 while (1) {
5ebe9a46 323 if (!read_line_old(f_in, line, sizeof line, 0)) {
be2961da 324 rprintf(FERROR, "rsync: didn't get server startup line\n");
3591c066
AT
325 return -1;
326 }
31593dd6 327
31593dd6 328 if (strncmp(line,"@RSYNCD: AUTHREQD ",18) == 0) {
68f40ebb 329 auth_client(f_out, user, line+18);
31593dd6
AT
330 continue;
331 }
31593dd6 332
2e94e70e
WD
333 if (strcmp(line,"@RSYNCD: OK") == 0)
334 break;
8f04bb36 335
cae95647
MP
336 if (strcmp(line,"@RSYNCD: EXIT") == 0) {
337 /* This is sent by recent versions of the
338 * server to terminate the listing of modules.
339 * We don't want to go on and transfer
340 * anything; just exit. */
341 exit(0);
342 }
8f04bb36 343
136ac7ec 344 if (strncmp(line, "@ERROR", 6) == 0) {
1732b6c0 345 rprintf(FERROR, "%s\n", line);
136ac7ec
MP
346 /* This is always fatal; the server will now
347 * close the socket. */
180443af 348 return -1;
136ac7ec 349 }
180443af 350
9ce7fc38
WD
351 /* This might be a MOTD line or a module listing, but there is
352 * no way to differentiate it. The manpage mentions this. */
353 if (output_motd)
354 rprintf(FINFO, "%s\n", line);
3591c066 355 }
8dad7fc6 356 kluge_around_eof = 0;
3591c066 357
7909e65f
WD
358 if (rl_nulls) {
359 for (i = 0; i < sargc; i++) {
53936ef9
WD
360 if (!sargs[i]) /* stop at --protect-args NULL */
361 break;
7909e65f
WD
362 write_sbuf(f_out, sargs[i]);
363 write_byte(f_out, 0);
364 }
365 write_byte(f_out, 0);
366 } else {
367 for (i = 0; i < sargc; i++)
368 io_printf(f_out, "%s\n", sargs[i]);
369 write_sbuf(f_out, "\n");
3591c066 370 }
3591c066 371
53936ef9
WD
372 if (protect_args)
373 send_protected_args(f_out, sargs);
374
daa598df 375 if (protocol_version < 23) {
3f55bd5d 376 if (protocol_version == 22 || !am_sender)
d8587b46 377 io_start_multiplex_in(f_in);
09b7f5db 378 }
8d9dc9f9 379
e844a4a8
WD
380 free(modname);
381
68f40ebb 382 return 0;
3591c066
AT
383}
384
a3377921
WD
385#ifdef HAVE_PUTENV
386static int read_arg_from_pipe(int fd, char *buf, int limit)
387{
388 char *bp = buf, *eob = buf + limit - 1;
389
390 while (1) {
391 int got = read(fd, bp, 1);
392 if (got != 1) {
393 if (got < 0 && errno == EINTR)
394 continue;
395 return -1;
396 }
397 if (*bp == '\0')
398 break;
399 if (bp < eob)
400 bp++;
401 }
402 *bp = '\0';
403
404 return bp - buf;
405}
406#endif
407
408static void set_env_str(const char *var, const char *str)
409{
410#ifdef HAVE_PUTENV
411 char *mem;
412 if (asprintf(&mem, "%s=%s", var, str) < 0)
413 out_of_memory("set_env_str");
414 putenv(mem);
415#endif
416}
417
418#ifdef HAVE_PUTENV
419void set_env_num(const char *var, long num)
420{
421 char *mem;
422 if (asprintf(&mem, "%s=%ld", var, num) < 0)
423 out_of_memory("set_env_num");
424 putenv(mem);
425}
426#endif
427
428/* Used for both early exec & pre-xfer exec */
429static pid_t start_pre_exec(const char *cmd, int *arg_fd_ptr, int *error_fd_ptr)
430{
3c56896d 431 int arg_fds[2], error_fds[2], arg_fd;
a3377921
WD
432 pid_t pid;
433
e16b2275 434 if ((error_fd_ptr && pipe(error_fds) < 0) || pipe(arg_fds) < 0 || (pid = fork()) < 0)
a3377921
WD
435 return (pid_t)-1;
436
437 if (pid == 0) {
438 char buf[BIGPATHBUFLEN];
439 int j, len, status;
440
441 if (error_fd_ptr) {
442 close(error_fds[0]);
3c56896d 443 set_blocking(error_fds[1]);
a3377921
WD
444 }
445
e16b2275
WD
446 close(arg_fds[1]);
447 arg_fd = arg_fds[0];
448 set_blocking(arg_fd);
449
450 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
451 if (len <= 0)
452 _exit(1);
453 set_env_str("RSYNC_REQUEST", buf);
a3377921 454
e16b2275
WD
455 for (j = 0; ; j++) {
456 char *p;
a3377921 457 len = read_arg_from_pipe(arg_fd, buf, BIGPATHBUFLEN);
e16b2275
WD
458 if (len <= 0) {
459 if (!len)
460 break;
a3377921 461 _exit(1);
a3377921 462 }
e16b2275
WD
463 if (asprintf(&p, "RSYNC_ARG%d=%s", j, buf) >= 0)
464 putenv(p);
a3377921
WD
465 }
466
e16b2275
WD
467 dup2(arg_fd, STDIN_FILENO);
468 close(arg_fd);
469
a3377921 470 if (error_fd_ptr) {
3c56896d
WD
471 dup2(error_fds[1], STDOUT_FILENO);
472 close(error_fds[1]);
a3377921
WD
473 }
474
475 status = shell_exec(cmd);
476
477 if (!WIFEXITED(status))
478 _exit(1);
479 _exit(WEXITSTATUS(status));
480 }
481
482 if (error_fd_ptr) {
483 close(error_fds[1]);
3c56896d
WD
484 *error_fd_ptr = error_fds[0];
485 set_blocking(error_fds[0]);
a3377921
WD
486 }
487
e16b2275
WD
488 close(arg_fds[0]);
489 arg_fd = *arg_fd_ptr = arg_fds[1];
490 set_blocking(arg_fd);
a3377921
WD
491
492 return pid;
493}
494
e16b2275 495static void write_pre_exec_args(int write_fd, char *request, char **early_argv, char **argv, int am_early)
c95ca2a2 496{
a3377921 497 int j = 0;
3591c066 498
7909e65f
WD
499 if (!request)
500 request = "(NONE)";
141c6265 501
820f7a7b 502 write_buf(write_fd, request, strlen(request)+1);
53936ef9
WD
503 if (early_argv) {
504 for ( ; *early_argv; early_argv++)
820f7a7b 505 write_buf(write_fd, *early_argv, strlen(*early_argv)+1);
53936ef9
WD
506 j = 1; /* Skip arg0 name in argv. */
507 }
e16b2275
WD
508 if (argv) {
509 for ( ; argv[j]; j++)
510 write_buf(write_fd, argv[j], strlen(argv[j])+1);
511 }
820f7a7b 512 write_byte(write_fd, 0);
141c6265 513
e16b2275
WD
514 if (am_early && early_input_len)
515 write_buf(write_fd, early_input, early_input_len);
516
820f7a7b 517 close(write_fd);
a3377921 518}
820f7a7b 519
a3377921
WD
520static char *finish_pre_exec(const char *desc, pid_t pid, int read_fd)
521{
522 char buf[BIGPATHBUFLEN], *bp, *cr;
523 int j, status = -1, msglen = sizeof buf - 1;
524
525 if (read_fd >= 0) {
526 /* Read the stdout from the program. This it is only displayed
527 * to the user if the script also returns an error status. */
528 for (bp = buf, cr = buf; msglen > 0; msglen -= j) {
529 if ((j = read(read_fd, bp, msglen)) <= 0) {
530 if (j == 0)
531 break;
532 if (errno == EINTR)
533 continue;
534 break; /* Just ignore the read error for now... */
535 }
536 bp[j] = '\0';
537 while (1) {
538 if ((cr = strchr(cr, '\r')) == NULL) {
539 cr = bp + j;
540 break;
541 }
542 if (!cr[1])
543 break; /* wait for more data before we decide what to do */
544 if (cr[1] == '\n') {
545 memmove(cr, cr+1, j - (cr - bp));
546 j--;
547 } else
548 cr++;
549 }
550 bp += j;
820f7a7b 551 }
a3377921 552 *bp = '\0';
820f7a7b 553
a3377921
WD
554 close(read_fd);
555 } else
556 *buf = '\0';
c95ca2a2
WD
557
558 if (wait_process(pid, &status, 0) < 0
559 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
560 char *e;
a3377921
WD
561 if (asprintf(&e, "%s returned failure (%d)%s%s%s\n%s",
562 desc, status, status < 0 ? ": " : "",
d80f7d6c
WD
563 status < 0 ? strerror(errno) : "",
564 *buf ? ":" : "", buf) < 0)
820f7a7b 565 return "out_of_memory in finish_pre_exec\n";
c95ca2a2
WD
566 return e;
567 }
568 return NULL;
569}
3591c066 570
26e21efc
WD
571static int path_failure(int f_out, const char *dir, BOOL was_chdir)
572{
573 if (was_chdir)
881addc9 574 rsyserr(FLOG, errno, "chdir %s failed", dir);
26e21efc
WD
575 else
576 rprintf(FLOG, "normalize_path(%s) failed\n", dir);
577 io_printf(f_out, "@ERROR: chdir failed\n");
578 return -1;
579}
580
7f367bb1
WD
581static int add_a_group(int f_out, const char *gname)
582{
2a7355fb 583 gid_t gid, *gid_p;
56017d31
WD
584 if (!group_to_gid(gname, &gid, True)) {
585 rprintf(FLOG, "Invalid gid %s\n", gname);
586 io_printf(f_out, "@ERROR: invalid gid %s\n", gname);
587 return -1;
7f367bb1 588 }
2a7355fb
WD
589 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
590 *gid_p = gid;
7f367bb1
WD
591 return 0;
592}
593
d7205694
WD
594#ifdef HAVE_GETGROUPLIST
595static int want_all_groups(int f_out, uid_t uid)
596{
597 const char *err;
2a7355fb 598 if ((err = getallgroups(uid, &gid_list)) != NULL) {
d7205694
WD
599 rsyserr(FLOG, errno, "%s", err);
600 io_printf(f_out, "@ERROR: %s\n", err);
601 return -1;
602 }
603 return 0;
604}
605#elif defined HAVE_INITGROUPS
7f367bb1
WD
606static struct passwd *want_all_groups(int f_out, uid_t uid)
607{
7f367bb1 608 struct passwd *pw;
2a7355fb 609 gid_t *gid_p;
7f367bb1
WD
610 if ((pw = getpwuid(uid)) == NULL) {
611 rsyserr(FLOG, errno, "getpwuid failed");
612 io_printf(f_out, "@ERROR: getpwuid failed\n");
613 return NULL;
614 }
2a7355fb
WD
615 /* Start with the default group and initgroups() will add the rest. */
616 gid_p = EXPAND_ITEM_LIST(&gid_list, gid_t, -32);
617 *gid_p = pw->pw_gid;
7f367bb1 618 return pw;
7f367bb1 619}
d7205694 620#endif
7f367bb1 621
df694f72 622static int rsync_module(int f_in, int f_out, int i, const char *addr, const char *host)
3591c066 623{
53936ef9 624 int argc;
433c6753 625 char **argv, **orig_argv, **orig_early_argv, *module_chdir;
20accf4d 626 char line[BIGPATHBUFLEN];
d7205694 627#if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
7f367bb1 628 struct passwd *pw = NULL;
d7205694 629#endif
7f367bb1
WD
630 uid_t uid;
631 int set_uid;
c95ca2a2 632 char *p, *err_msg = NULL;
874895d5 633 char *name = lp_name(i);
8638dd48 634 int use_chroot = lp_use_chroot(i);
820f7a7b 635 int ret, pre_exec_arg_fd = -1, pre_exec_error_fd = -1;
41adbcec 636 int save_munge_symlinks;
c95ca2a2 637 pid_t pre_exec_pid = 0;
2e94e70e 638 char *request = NULL;
56c473b7 639
0a9fbe17
WD
640 set_env_str("RSYNC_MODULE_NAME", name);
641
15dbffc2 642#ifdef ICONV_OPTION
0b52f94d
WD
643 iconv_opt = lp_charset(i);
644 if (*iconv_opt)
645 setup_iconv();
646 iconv_opt = NULL;
647#endif
648
11ef77b7
MM
649 /* If reverse lookup is disabled globally but enabled for this module,
650 * we need to do it now before the access check. */
651 if (host == undetermined_hostname && lp_reverse_lookup(i))
cff0764b 652 host = client_name(client_addr(f_in));
0a9fbe17
WD
653 set_env_str("RSYNC_HOST_NAME", host);
654 set_env_str("RSYNC_HOST_ADDR", addr);
11ef77b7 655
bf4170ad 656 if (!allow_access(addr, &host, i)) {
1732b6c0 657 rprintf(FLOG, "rsync denied on module %s from %s (%s)\n",
31ec50d7 658 name, host, addr);
c0422cea
WD
659 if (!lp_list(i))
660 io_printf(f_out, "@ERROR: Unknown module '%s'\n", name);
661 else {
662 io_printf(f_out,
663 "@ERROR: access denied to %s from %s (%s)\n",
664 name, host, addr);
665 }
56c473b7
AT
666 return -1;
667 }
3591c066 668
c0268d92 669 if (am_daemon > 0) {
9e5a5ddb 670 rprintf(FLOG, "rsync allowed access on module %s from %s (%s)\n",
68f40ebb
WD
671 name, host, addr);
672 }
673
5e71c444 674 if (!claim_connection(lp_lock_file(i), lp_max_connections(i))) {
8d72ef6e 675 if (errno) {
1732b6c0 676 rsyserr(FLOG, errno, "failed to open lock file %s",
45c49b52 677 lp_lock_file(i));
4875d6b6 678 io_printf(f_out, "@ERROR: failed to open lock file\n");
8d72ef6e 679 } else {
1732b6c0 680 rprintf(FLOG, "max connections (%d) reached\n",
5e71c444 681 lp_max_connections(i));
4ccfd96c 682 io_printf(f_out, "@ERROR: max connections (%d) reached -- try again later\n",
837cbad9 683 lp_max_connections(i));
8d72ef6e 684 }
0c515f17
AT
685 return -1;
686 }
687
5ebe9a46 688 read_only = lp_read_only(i); /* may also be overridden by auth_server() */
45c5b903 689 auth_user = auth_server(f_in, f_out, i, host, addr, "@RSYNCD: AUTHREQD ");
d0d56395 690
97cb8dc2 691 if (!auth_user) {
68f40ebb 692 io_printf(f_out, "@ERROR: auth failed on module %s\n", name);
4a7144ee 693 return -1;
d0d56395 694 }
0a9fbe17 695 set_env_str("RSYNC_USER_NAME", auth_user);
d0d56395 696
3591c066
AT
697 module_id = i;
698
f4184849
WD
699 if (lp_transfer_logging(module_id) && !logfile_format)
700 logfile_format = lp_log_format(module_id);
10ae3406
WD
701 if (log_format_has(logfile_format, 'i'))
702 logfile_format_has_i = 1;
703 if (logfile_format_has_i || log_format_has(logfile_format, 'o'))
704 logfile_format_has_o_or_i = 1;
c0814b81 705
7f367bb1
WD
706 uid = MY_UID();
707 am_root = (uid == 0);
8ef4ffd6 708
f4184849 709 p = *lp_uid(module_id) ? lp_uid(module_id) : am_root ? NOBODY_USER : NULL;
7f367bb1 710 if (p) {
56017d31
WD
711 if (!user_to_uid(p, &uid, True)) {
712 rprintf(FLOG, "Invalid uid %s\n", p);
713 io_printf(f_out, "@ERROR: invalid uid %s\n", p);
714 return -1;
716baed7 715 }
7f367bb1
WD
716 set_uid = 1;
717 } else
718 set_uid = 0;
716baed7 719
f4184849 720 p = *lp_gid(module_id) ? conf_strtok(lp_gid(module_id)) : NULL;
7f367bb1
WD
721 if (p) {
722 /* The "*" gid must be the first item in the list. */
723 if (strcmp(p, "*") == 0) {
d7205694
WD
724#ifdef HAVE_GETGROUPLIST
725 if (want_all_groups(f_out, uid) < 0)
726 return -1;
727#elif defined HAVE_INITGROUPS
7f367bb1
WD
728 if ((pw = want_all_groups(f_out, uid)) == NULL)
729 return -1;
d7205694
WD
730#else
731 rprintf(FLOG, "This rsync does not support a gid of \"*\"\n");
732 io_printf(f_out, "@ERROR: invalid gid setting.\n");
733 return -1;
734#endif
7f367bb1
WD
735 } else if (add_a_group(f_out, p) < 0)
736 return -1;
9a12959a 737 while ((p = conf_strtok(NULL)) != NULL) {
7f367bb1
WD
738#if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
739 if (pw) {
740 rprintf(FLOG, "This rsync cannot add groups after \"*\".\n");
741 io_printf(f_out, "@ERROR: invalid gid setting.\n");
716baed7 742 return -1;
4a7144ee 743 }
7f367bb1
WD
744#endif
745 if (add_a_group(f_out, p) < 0)
746 return -1;
716baed7 747 }
7f367bb1
WD
748 } else if (am_root) {
749 if (add_a_group(f_out, NOBODY_GROUP) < 0)
750 return -1;
8ef4ffd6 751 }
3b2b5345 752
f4184849 753 module_dir = lp_path(module_id);
afccb3d3
WD
754 if (*module_dir == '\0') {
755 rprintf(FLOG, "No path specified for module %s\n", name);
756 io_printf(f_out, "@ERROR: no path setting.\n");
757 return -1;
758 }
2fe1feea
WD
759 if (use_chroot) {
760 if ((p = strstr(module_dir, "/./")) != NULL) {
26e21efc
WD
761 *p = '\0'; /* Temporary... */
762 if (!(module_chdir = normalize_path(module_dir, True, NULL)))
763 return path_failure(f_out, module_dir, False);
764 *p = '/';
765 if (!(p = normalize_path(p + 2, True, &module_dirlen)))
766 return path_failure(f_out, strstr(module_dir, "/./"), False);
767 if (!(full_module_path = normalize_path(module_dir, False, NULL)))
768 full_module_path = module_dir;
433c6753
WD
769 module_dir = p;
770 } else {
26e21efc
WD
771 if (!(module_chdir = normalize_path(module_dir, False, NULL)))
772 return path_failure(f_out, module_dir, False);
773 full_module_path = module_chdir;
774 module_dir = "/";
775 module_dirlen = 1;
433c6753 776 }
26e21efc
WD
777 } else {
778 if (!(module_chdir = normalize_path(module_dir, False, &module_dirlen)))
779 return path_failure(f_out, module_dir, False);
780 full_module_path = module_dir = module_chdir;
781 }
0a9fbe17 782 set_env_str("RSYNC_MODULE_PATH", full_module_path);
2fe1feea
WD
783
784 if (module_dirlen == 1) {
e7bf7c01 785 module_dirlen = 0;
7842418b 786 set_filter_dir("/", 1);
46bffd98 787 } else
33cbd577 788 set_filter_dir(module_dir, module_dirlen);
e7bf7c01 789
f4184849 790 p = lp_filter(module_id);
c8fa85b2 791 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
e63ff70e 792 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3);
837cbad9 793
f4184849 794 p = lp_include_from(module_id);
c8fa85b2 795 parse_filter_file(&daemon_filter_list, p, rule_template(FILTRULE_INCLUDE),
e63ff70e 796 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
cd64343a 797
f4184849 798 p = lp_include(module_id);
c8fa85b2 799 parse_filter_str(&daemon_filter_list, p,
e63ff70e
WD
800 rule_template(FILTRULE_INCLUDE | FILTRULE_WORD_SPLIT),
801 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
cd64343a 802
f4184849 803 p = lp_exclude_from(module_id);
c8fa85b2 804 parse_filter_file(&daemon_filter_list, p, rule_template(0),
e63ff70e 805 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES | XFLG_FATAL_ERRORS);
8f3a2d54 806
f4184849 807 p = lp_exclude(module_id);
c8fa85b2 808 parse_filter_str(&daemon_filter_list, p, rule_template(FILTRULE_WORD_SPLIT),
e63ff70e 809 XFLG_ABS_IF_SLASH | XFLG_DIR2WILD3 | XFLG_OLD_PREFIXES);
8f3a2d54 810
6dc9b74b 811 log_init(1);
1a016bfd 812
9d0d18b5 813#ifdef HAVE_PUTENV
f4184849 814 if ((*lp_early_exec(module_id) || *lp_prexfer_exec(module_id) || *lp_postxfer_exec(module_id))
a3377921
WD
815 && !getenv("RSYNC_NO_XFER_EXEC")) {
816 set_env_num("RSYNC_PID", (long)getpid());
2fe1feea 817
c95ca2a2
WD
818 /* For post-xfer exec, fork a new process to run the rsync
819 * daemon while this process waits for the exit status and
820 * runs the indicated command at that point. */
f4184849 821 if (*lp_postxfer_exec(module_id)) {
9d0d18b5
WD
822 pid_t pid = fork();
823 if (pid < 0) {
824 rsyserr(FLOG, errno, "fork failed");
825 io_printf(f_out, "@ERROR: fork failed\n");
826 return -1;
827 }
828 if (pid) {
a3377921 829 int status;
ce571e64
WD
830 close(f_in);
831 if (f_out != f_in)
832 close(f_out);
c95ca2a2
WD
833 if (wait_process(pid, &status, 0) < 0)
834 status = -1;
0a9fbe17 835 set_env_num("RSYNC_RAW_STATUS", status);
9d0d18b5
WD
836 if (WIFEXITED(status))
837 status = WEXITSTATUS(status);
838 else
839 status = -1;
0a9fbe17 840 set_env_num("RSYNC_EXIT_STATUS", status);
f4184849 841 if (shell_exec(lp_postxfer_exec(module_id)) < 0)
94112924 842 status = -1;
9d0d18b5
WD
843 _exit(status);
844 }
845 }
a3377921
WD
846
847 /* For early exec, fork a child process to run the indicated
848 * command and wait for it to exit. */
f4184849 849 if (*lp_early_exec(module_id)) {
e16b2275 850 int arg_fd;
f4184849 851 pid_t pid = start_pre_exec(lp_early_exec(module_id), &arg_fd, NULL);
a3377921
WD
852 if (pid == (pid_t)-1) {
853 rsyserr(FLOG, errno, "early exec preparation failed");
854 io_printf(f_out, "@ERROR: early exec preparation failed\n");
855 return -1;
856 }
e16b2275 857 write_pre_exec_args(arg_fd, NULL, NULL, NULL, 1);
a3377921
WD
858 if (finish_pre_exec("early exec", pid, -1) != NULL) {
859 rsyserr(FLOG, errno, "early exec failed");
860 io_printf(f_out, "@ERROR: early exec failed\n");
861 return -1;
862 }
863 }
864
c95ca2a2
WD
865 /* For pre-xfer exec, fork a child process to run the indicated
866 * command, though it first waits for the parent process to
867 * send us the user's request via a pipe. */
f4184849
WD
868 if (*lp_prexfer_exec(module_id)) {
869 pre_exec_pid = start_pre_exec(lp_prexfer_exec(module_id), &pre_exec_arg_fd, &pre_exec_error_fd);
a3377921 870 if (pre_exec_pid == (pid_t)-1) {
c95ca2a2
WD
871 rsyserr(FLOG, errno, "pre-xfer exec preparation failed");
872 io_printf(f_out, "@ERROR: pre-xfer exec preparation failed\n");
873 return -1;
874 }
c95ca2a2 875 }
9d0d18b5
WD
876 }
877#endif
878
e16b2275
WD
879 if (early_input) {
880 free(early_input);
881 early_input = NULL;
882 }
883
8638dd48 884 if (use_chroot) {
b52c1d9d
MP
885 /*
886 * XXX: The 'use chroot' flag is a fairly reliable
887 * source of confusion, because it fails under two
888 * important circumstances: running as non-root,
889 * running on Win32 (or possibly others). On the
890 * other hand, if you are running as root, then it
891 * might be better to always use chroot.
892 *
893 * So, perhaps if we can't chroot we should just issue
894 * a warning, unless a "require chroot" flag is set,
895 * in which case we fail.
896 */
433c6753
WD
897 if (chroot(module_chdir)) {
898 rsyserr(FLOG, errno, "chroot %s failed", module_chdir);
68f40ebb 899 io_printf(f_out, "@ERROR: chroot failed\n");
8638dd48
DD
900 return -1;
901 }
433c6753 902 module_chdir = module_dir;
716baed7
DD
903 }
904
26e21efc
WD
905 if (!change_dir(module_chdir, CD_NORMAL))
906 return path_failure(f_out, module_chdir, True);
881addc9 907 if (module_dirlen || (!use_chroot && !*lp_daemon_chroot()))
433c6753
WD
908 sanitize_paths = 1;
909
f4184849 910 if ((munge_symlinks = lp_munge_symlinks(module_id)) < 0)
2fe1feea 911 munge_symlinks = !use_chroot || module_dirlen;
9585b276
WD
912 if (munge_symlinks) {
913 STRUCT_STAT st;
41adbcec
WD
914 char prefix[SYMLINK_PREFIX_LEN]; /* NOT +1 ! */
915 strlcpy(prefix, SYMLINK_PREFIX, sizeof prefix); /* trim the trailing slash */
916 if (do_stat(prefix, &st) == 0 && S_ISDIR(st.st_mode)) {
917 rprintf(FLOG, "Symlink munging is unsafe when a %s directory exists.\n",
918 prefix);
9585b276
WD
919 io_printf(f_out, "@ERROR: daemon security issue -- contact admin\n", name);
920 exit_cleanup(RERR_UNSUPPORTED);
921 }
922 }
923
2a7355fb
WD
924 if (gid_list.count) {
925 gid_t *gid_array = gid_list.items;
926 if (setgid(gid_array[0])) {
927 rsyserr(FLOG, errno, "setgid %ld failed", (long)gid_array[0]);
68f40ebb 928 io_printf(f_out, "@ERROR: setgid failed\n");
8638dd48
DD
929 return -1;
930 }
4f5b0756 931#ifdef HAVE_SETGROUPS
7f367bb1 932 /* Set the group(s) we want to be active. */
2a7355fb 933 if (setgroups(gid_list.count, gid_array)) {
1732b6c0 934 rsyserr(FLOG, errno, "setgroups failed");
6969ebcf
WD
935 io_printf(f_out, "@ERROR: setgroups failed\n");
936 return -1;
937 }
938#endif
7f367bb1
WD
939#if defined HAVE_INITGROUPS && !defined HAVE_GETGROUPLIST
940 /* pw is set if the user wants all the user's groups. */
941 if (pw && initgroups(pw->pw_name, pw->pw_gid) < 0) {
942 rsyserr(FLOG, errno, "initgroups failed");
943 io_printf(f_out, "@ERROR: initgroups failed\n");
944 return -1;
945 }
946#endif
17b849c9 947 our_gid = MY_GID();
7f367bb1 948 }
3591c066 949
7f367bb1 950 if (set_uid) {
cece2e3f
WD
951 if (setuid(uid) < 0
952#ifdef HAVE_SETEUID
953 || seteuid(uid) < 0
954#endif
955 ) {
7f367bb1 956 rsyserr(FLOG, errno, "setuid %ld failed", (long)uid);
68f40ebb 957 io_printf(f_out, "@ERROR: setuid failed\n");
8638dd48
DD
958 return -1;
959 }
960
17b849c9
WD
961 our_uid = MY_UID();
962 am_root = (our_uid == 0);
3591c066
AT
963 }
964
f4184849
WD
965 if (lp_temp_dir(module_id) && *lp_temp_dir(module_id)) {
966 tmpdir = lp_temp_dir(module_id);
fed1f3f4
WD
967 if (strlen(tmpdir) >= MAXPATHLEN - 10) {
968 rprintf(FLOG,
969 "the 'temp dir' value for %s is WAY too long -- ignoring.\n",
970 name);
971 tmpdir = NULL;
972 }
973 }
974
68f40ebb 975 io_printf(f_out, "@RSYNCD: OK\n");
3591c066 976
53936ef9
WD
977 read_args(f_in, name, line, sizeof line, rl_nulls, &argv, &argc, &request);
978 orig_argv = argv;
979
41adbcec
WD
980 save_munge_symlinks = munge_symlinks;
981
951e826b 982 reset_output_levels(); /* future verbosity is controlled by client options */
53936ef9
WD
983 ret = parse_arguments(&argc, (const char ***) &argv);
984 if (protect_args && ret) {
985 orig_early_argv = orig_argv;
986 protect_args = 2;
987 read_args(f_in, name, line, sizeof line, 1, &argv, &argc, &request);
988 orig_argv = argv;
989 ret = parse_arguments(&argc, (const char ***) &argv);
990 } else
991 orig_early_argv = NULL;
3591c066 992
565cde84
WD
993 /* The default is to use the user's setting unless the module sets True or False. */
994 if (lp_open_noatime(module_id) >= 0)
995 open_noatime = lp_open_noatime(module_id);
996
41adbcec 997 munge_symlinks = save_munge_symlinks; /* The client mustn't control this. */
f0e670b4 998
c0268d92
WD
999 if (am_daemon > 0)
1000 msgs2stderr = 0; /* A non-rsh-run daemon doesn't have stderr for msgs. */
41adbcec 1001
141c6265 1002 if (pre_exec_pid) {
e16b2275 1003 write_pre_exec_args(pre_exec_arg_fd, request, orig_early_argv, orig_argv, 0);
a3377921 1004 err_msg = finish_pre_exec("pre-xfer exec", pre_exec_pid, pre_exec_error_fd);
141c6265 1005 }
c95ca2a2 1006
53936ef9
WD
1007 if (orig_early_argv)
1008 free(orig_early_argv);
1009
875a13b4 1010 am_server = 1; /* Don't let someone try to be tricky. */
53936ef9 1011 quiet = 0;
3162ea6f
WD
1012 if (lp_ignore_errors(module_id))
1013 ignore_errors = 1;
5223b786
WD
1014 if (write_batch < 0)
1015 dry_run = 1;
3591c066 1016
f4184849 1017 if (lp_fake_super(module_id)) {
cbbd8e2e
WD
1018 if (preserve_xattrs > 1)
1019 preserve_xattrs = 1;
9439c0cb 1020 am_root = -1;
cbbd8e2e 1021 } else if (am_root < 0) /* Treat --fake-super from client as --super. */
9439c0cb
WD
1022 am_root = 2;
1023
7c2a9e76
WD
1024 if (filesfrom_fd == 0)
1025 filesfrom_fd = f_in;
1026
7b372642 1027 if (request) {
97cb8dc2 1028 if (*auth_user) {
9e5a5ddb
WD
1029 rprintf(FLOG, "rsync %s %s from %s@%s (%s)\n",
1030 am_sender ? "on" : "to",
97cb8dc2 1031 request, auth_user, host, addr);
d0d56395 1032 } else {
9e5a5ddb
WD
1033 rprintf(FLOG, "rsync %s %s from %s (%s)\n",
1034 am_sender ? "on" : "to",
d0d56395
AT
1035 request, host, addr);
1036 }
7b372642
AT
1037 free(request);
1038 }
1039
15b7b73d 1040#ifndef DEBUG
3591c066 1041 /* don't allow the logs to be flooded too fast */
f4184849 1042 limit_output_verbosity(lp_max_verbosity(module_id));
0199b05f 1043#endif
3591c066 1044
e63ff70e 1045 if (protocol_version < 23 && (protocol_version == 22 || am_sender))
d8587b46 1046 io_start_multiplex_out(f_out);
c95ca2a2 1047 else if (!ret || err_msg) {
1732b6c0
WD
1048 /* We have to get I/O multiplexing started so that we can
1049 * get the error back to the client. This means getting
1050 * the protocol setup finished first in later versions. */
1051 setup_protocol(f_out, f_in);
b03c719f
WD
1052 if (!am_sender) {
1053 /* Since we failed in our option parsing, we may not
1054 * have finished parsing that the client sent us a
1055 * --files-from option, so look for it manually.
1056 * Without this, the socket would be in the wrong
1057 * state for the upcoming error message. */
1058 if (!files_from) {
1059 int i;
1060 for (i = 0; i < argc; i++) {
1061 if (strncmp(argv[i], "--files-from", 12) == 0) {
1062 files_from = "";
1063 break;
1064 }
1065 }
1066 }
1067 if (files_from)
1068 write_byte(f_out, 0);
1069 }
d8587b46 1070 io_start_multiplex_out(f_out);
554e0a8d 1071 }
15b7b73d 1072
c95ca2a2 1073 if (!ret || err_msg) {
820f7a7b
WD
1074 if (err_msg) {
1075 while ((p = strchr(err_msg, '\n')) != NULL) {
1076 int len = p - err_msg + 1;
1077 rwrite(FERROR, err_msg, len, 0);
1078 err_msg += len;
1079 }
1080 if (*err_msg)
1081 rprintf(FERROR, "%s\n", err_msg);
f60bd811 1082 io_flush(MSG_FLUSH);
820f7a7b 1083 } else
c95ca2a2 1084 option_error();
7e561438 1085 msleep(400);
4a7144ee 1086 exit_cleanup(RERR_UNSUPPORTED);
41979ff8
AT
1087 }
1088
15dbffc2 1089#ifdef ICONV_OPTION
0b52f94d
WD
1090 if (!iconv_opt) {
1091 if (ic_send != (iconv_t)-1) {
1092 iconv_close(ic_send);
1093 ic_send = (iconv_t)-1;
1094 }
1095 if (ic_recv != (iconv_t)-1) {
1096 iconv_close(ic_recv);
1097 ic_recv = (iconv_t)-1;
1098 }
1099 }
15dbffc2 1100#endif
0b52f94d
WD
1101
1102 if (!numeric_ids
f4184849 1103 && (use_chroot ? lp_numeric_ids(module_id) != False : lp_numeric_ids(module_id) == True))
0b52f94d
WD
1104 numeric_ids = -1; /* Set --numeric-ids w/o breaking protocol. */
1105
f4184849
WD
1106 if (lp_timeout(module_id) && (!io_timeout || lp_timeout(module_id) < io_timeout))
1107 set_io_timeout(lp_timeout(module_id));
81791cfc 1108
f041b025
WD
1109 /* If we have some incoming/outgoing chmod changes, append them to
1110 * any user-specified changes (making our changes have priority).
1111 * We also get a pointer to just our changes so that a receiver
1112 * process can use them separately if --perms wasn't specified. */
aaccaa88 1113 if (am_sender)
f4184849 1114 p = lp_outgoing_chmod(module_id);
aaccaa88 1115 else
f4184849 1116 p = lp_incoming_chmod(module_id);
8840ec0f 1117 if (*p && !(daemon_chmod_modes = parse_chmod(p, &chmod_modes))) {
aaccaa88
WD
1118 rprintf(FLOG, "Invalid \"%sing chmod\" directive: %s\n",
1119 am_sender ? "outgo" : "incom", p);
1120 }
730df9d2 1121
c9dc1300 1122 start_server(f_in, f_out, argc, argv);
3591c066
AT
1123
1124 return 0;
1125}
1126
7a6421fa
AT
1127/* send a list of available modules to the client. Don't list those
1128 with "list = False". */
3591c066
AT
1129static void send_listing(int fd)
1130{
b583594a 1131 int n = lp_num_modules();
3591c066 1132 int i;
063393d6 1133
c0422cea 1134 for (i = 0; i < n; i++) {
3591c066 1135 if (lp_list(i))
4a7144ee 1136 io_printf(fd, "%-15s\t%s\n", lp_name(i), lp_comment(i));
c0422cea 1137 }
8f04bb36 1138
daa598df 1139 if (protocol_version >= 25)
063393d6 1140 io_printf(fd,"@RSYNCD: EXIT\n");
3591c066
AT
1141}
1142
d1c06c21
WD
1143static int load_config(int globals_only)
1144{
1145 if (!config_file) {
c0268d92 1146 if (am_daemon < 0 && am_root <= 0)
d1c06c21
WD
1147 config_file = RSYNCD_USERCONF;
1148 else
1149 config_file = RSYNCD_SYSCONF;
1150 }
1151 return lp_load(config_file, globals_only);
1152}
1153
68f40ebb 1154/* this is called when a connection is established to a client
3591c066
AT
1155 and we want to start talking. The setup of the system is done from
1156 here */
68f40ebb 1157int start_daemon(int f_in, int f_out)
3591c066 1158{
20accf4d 1159 char line[1024];
df694f72 1160 const char *addr, *host;
881addc9 1161 char *p;
c0422cea 1162 int i;
4cdf25e4 1163
c0268d92
WD
1164 /* At this point, am_server is only set for a daemon started via rsh.
1165 * Because am_server gets forced on soon, we'll set am_daemon to -1 as
1166 * a flag that can be checked later on to distinguish a normal daemon
1167 * from an rsh-run daemon. */
1168 if (am_server)
1169 am_daemon = -1;
1170
da3478b2
WD
1171 io_set_sock_fds(f_in, f_out);
1172
374c3e12
WD
1173 /* We must load the config file before calling any function that
1174 * might cause log-file output to occur. This ensures that the
1175 * "log file" param gets honored for the 2 non-forked use-cases
08e0a629 1176 * (when rsync is run by init and run by a remote shell). */
d1c06c21 1177 if (!load_config(0))
65417579 1178 exit_cleanup(RERR_SYNTAX);
3591c066 1179
249e28c7 1180 if (lp_proxy_protocol() && !read_proxy_protocol_header(f_in))
cff0764b
WD
1181 return -1;
1182
881addc9
WD
1183 p = lp_daemon_chroot();
1184 if (*p) {
1185 log_init(0); /* Make use we've initialized syslog before chrooting. */
1186 if (chroot(p) < 0 || chdir("/") < 0) {
1187 rsyserr(FLOG, errno, "daemon chroot %s failed", p);
1188 return -1;
1189 }
1190 }
1191 p = lp_daemon_gid();
1192 if (*p) {
1193 gid_t gid;
1194 if (!group_to_gid(p, &gid, True)) {
1195 rprintf(FLOG, "Invalid daemon gid: %s\n", p);
1196 return -1;
1197 }
1198 if (setgid(gid) < 0) {
1199 rsyserr(FLOG, errno, "Unable to set group to daemon gid %ld", (long)gid);
1200 return -1;
1201 }
17b849c9 1202 our_gid = MY_GID();
881addc9
WD
1203 }
1204 p = lp_daemon_uid();
1205 if (*p) {
1206 uid_t uid;
1207 if (!user_to_uid(p, &uid, True)) {
1208 rprintf(FLOG, "Invalid daemon uid: %s\n", p);
1209 return -1;
1210 }
1211 if (setuid(uid) < 0) {
1212 rsyserr(FLOG, errno, "Unable to set user to daemon uid %ld", (long)uid);
1213 return -1;
1214 }
17b849c9
WD
1215 our_uid = MY_UID();
1216 am_root = (our_uid == 0);
881addc9
WD
1217 }
1218
374c3e12 1219 addr = client_addr(f_in);
cff0764b 1220 host = lp_reverse_lookup(-1) ? client_name(addr) : undetermined_hostname;
374c3e12 1221 rprintf(FLOG, "connect from %s (%s)\n", host, addr);
91d324b4 1222
c0268d92 1223 if (am_daemon > 0) {
68f40ebb 1224 set_socket_options(f_in, "SO_KEEPALIVE");
68f40ebb
WD
1225 set_nonblocking(f_in);
1226 }
3591c066 1227
7909e65f 1228 if (exchange_protocols(f_in, f_out, line, sizeof line, 0) < 0)
91eee594 1229 return -1;
91eee594 1230
c0422cea 1231 line[0] = 0;
5ebe9a46 1232 if (!read_line_old(f_in, line, sizeof line, 0))
c0422cea 1233 return -1;
3591c066 1234
e16b2275
WD
1235 if (strncmp(line, EARLY_INPUT_CMD, EARLY_INPUT_CMDLEN) == 0) {
1236 early_input_len = strtol(line + EARLY_INPUT_CMDLEN, NULL, 10);
a7c1690d 1237 if (early_input_len <= 0 || early_input_len > BIGPATHBUFLEN) {
e16b2275
WD
1238 io_printf(f_out, "@ERROR: invalid early_input length\n");
1239 return -1;
1240 }
11eb67ee 1241 early_input = new_array(char, early_input_len);
e16b2275
WD
1242 read_buf(f_in, early_input, early_input_len);
1243
1244 if (!read_line_old(f_in, line, sizeof line, 0))
1245 return -1;
1246 }
1247
c0422cea 1248 if (!*line || strcmp(line, "#list") == 0) {
b3e15181
WD
1249 rprintf(FLOG, "module-list request from %s (%s)\n",
1250 host, addr);
c0422cea
WD
1251 send_listing(f_out);
1252 return -1;
1253 }
3591c066 1254
c0422cea
WD
1255 if (*line == '#') {
1256 /* it's some sort of command that I don't understand */
1257 io_printf(f_out, "@ERROR: Unknown command '%s'\n", line);
1258 return -1;
1259 }
3591c066 1260
c0422cea 1261 if ((i = lp_number(line)) < 0) {
c0422cea
WD
1262 rprintf(FLOG, "unknown module '%s' tried from %s (%s)\n",
1263 line, host, addr);
1264 io_printf(f_out, "@ERROR: Unknown module '%s'\n", line);
1265 return -1;
3591c066
AT
1266 }
1267
d749eb68
WD
1268#ifdef HAVE_SIGACTION
1269 sigact.sa_flags = SA_NOCLDSTOP;
1270#endif
1271 SIGACTION(SIGCHLD, remember_children);
1272
439a198d 1273 return rsync_module(f_in, f_out, i, addr, host);
3591c066
AT
1274}
1275
dd589118 1276static void create_pid_file(void)
a1d2685b
WD
1277{
1278 char *pid_file = lp_pid_file();
b177311a
WD
1279 char pidbuf[32];
1280 STRUCT_STAT st1, st2;
1281 char *fail = NULL;
a1d2685b
WD
1282
1283 if (!pid_file || !*pid_file)
1284 return;
1285
5d7b71b7
WD
1286#ifdef O_NOFOLLOW
1287#define SAFE_OPEN_FLAGS (O_CREAT|O_NOFOLLOW)
1288#else
1289#define SAFE_OPEN_FLAGS (O_CREAT)
1290#endif
1291
b177311a
WD
1292 /* These tests make sure that a temp-style lock dir is handled safely. */
1293 st1.st_mode = 0;
1294 if (do_lstat(pid_file, &st1) == 0 && !S_ISREG(st1.st_mode) && unlink(pid_file) < 0)
1295 fail = "unlink";
5d7b71b7 1296 else if ((pid_file_fd = do_open(pid_file, O_RDWR|SAFE_OPEN_FLAGS, 0664)) < 0)
b177311a
WD
1297 fail = S_ISREG(st1.st_mode) ? "open" : "create";
1298 else if (!lock_range(pid_file_fd, 0, 4))
1299 fail = "lock";
1300 else if (do_fstat(pid_file_fd, &st1) < 0)
1301 fail = "fstat opened";
2c6f0581 1302 else if (st1.st_size > (int)sizeof pidbuf)
b177311a
WD
1303 fail = "find small";
1304 else if (do_lstat(pid_file, &st2) < 0)
1305 fail = "lstat";
1306 else if (!S_ISREG(st1.st_mode))
1307 fail = "avoid file overwrite race for";
1308 else if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
1309 fail = "verify stat info for";
1310#ifdef HAVE_FTRUNCATE
1311 else if (do_ftruncate(pid_file_fd, 0) < 0)
1312 fail = "truncate";
1313#endif
1314 else {
1315 pid_t pid = getpid();
1316 int len = snprintf(pidbuf, sizeof pidbuf, "%d\n", (int)pid);
1317#ifndef HAVE_FTRUNCATE
1318 /* What can we do with a too-long file and no truncate? I guess we'll add extra newlines. */
2c6f0581 1319 while (len < st1.st_size) /* We already verified that st_size chars fits in the buffer. */
b177311a
WD
1320 pidbuf[len++] = '\n';
1321 /* We don't need the buffer to end in a '\0' (and we may not have room to add it). */
1322#endif
1323 if (write(pid_file_fd, pidbuf, len) != len)
1324 fail = "write";
1325 cleanup_set_pid(pid); /* Mark the file for removal on exit, even if the write failed. */
1326 }
1327
1328 if (fail) {
1329 char msg[1024];
1330 snprintf(msg, sizeof msg, "failed to %s pid file %s: %s\n",
1331 fail, pid_file, strerror(errno));
1332 fputs(msg, stderr);
1333 rprintf(FLOG, "%s", msg);
a1d2685b
WD
1334 exit_cleanup(RERR_FILEIO);
1335 }
b177311a
WD
1336
1337 /* The file is left open so that the lock remains valid. It is closed in our forked child procs. */
a1d2685b
WD
1338}
1339
1340/* Become a daemon, discarding the controlling terminal. */
1341static void become_daemon(void)
3591c066 1342{
a1d2685b
WD
1343 int i;
1344 pid_t pid = fork();
1345
1346 if (pid) {
dd589118
WD
1347 if (pid < 0) {
1348 fprintf(stderr, "failed to fork: %s\n", strerror(errno));
1349 exit_cleanup(RERR_FILEIO);
1350 }
a1d2685b
WD
1351 _exit(0);
1352 }
1a016bfd 1353
dd589118
WD
1354 create_pid_file();
1355
a1d2685b
WD
1356 /* detach from the terminal */
1357#ifdef HAVE_SETSID
1358 setsid();
1359#elif defined TIOCNOTTY
1360 i = open("/dev/tty", O_RDWR);
1361 if (i >= 0) {
1362 ioctl(i, (int)TIOCNOTTY, (char *)0);
1363 close(i);
1364 }
1365#endif
1366 /* make sure that stdin, stdout an stderr don't stuff things
1367 * up (library functions, for example) */
1368 for (i = 0; i < 3; i++) {
1369 close(i);
1370 open("/dev/null", O_RDWR);
1371 }
1372}
1373
1374int daemon_main(void)
1375{
3591c066 1376 if (is_a_socket(STDIN_FILENO)) {
41979ff8
AT
1377 int i;
1378
1379 /* we are running via inetd - close off stdout and
4a7144ee
WD
1380 * stderr so that library functions (and getopt) don't
1381 * try to use them. Redirect them to /dev/null */
2e94e70e 1382 for (i = 1; i < 3; i++) {
4a7144ee 1383 close(i);
41979ff8
AT
1384 open("/dev/null", O_RDWR);
1385 }
3eb38818 1386
68f40ebb 1387 return start_daemon(STDIN_FILENO, STDIN_FILENO);
3591c066
AT
1388 }
1389
d1c06c21 1390 if (!load_config(1)) {
a1d2685b 1391 fprintf(stderr, "Failed to parse config file: %s\n", config_file);
65417579 1392 exit_cleanup(RERR_SYNTAX);
a1d2685b 1393 }
2206abf8 1394 set_dparams(0);
a1d2685b
WD
1395
1396 if (no_detach)
dd589118 1397 create_pid_file();
a1d2685b
WD
1398 else
1399 become_daemon();
f9e940ef 1400
0c56b1ad
WD
1401 if (rsync_port == 0 && (rsync_port = lp_rsync_port()) == 0)
1402 rsync_port = RSYNC_PORT;
3dfe6e97 1403 if (bind_address == NULL && *lp_bind_address())
986aaaaa 1404 bind_address = lp_bind_address();
0c56b1ad 1405
6dc9b74b 1406 log_init(0);
f9e940ef 1407
9e5a5ddb 1408 rprintf(FLOG, "rsyncd version %s starting, listening on port %d\n",
4a7144ee
WD
1409 RSYNC_VERSION, rsync_port);
1410 /* TODO: If listening on a particular address, then show that
0a04a80d 1411 * address too. In fact, why not just do getnameinfo on the
4a7144ee 1412 * local address??? */
e42c9458 1413
8ef4ffd6
AT
1414 start_accept_loop(rsync_port, start_daemon);
1415 return -1;
3591c066 1416}