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