Debian Codegraph @

socket.c

raw symbols SCIP
1 /*
2 * Socket functions used in rsync.
3 *
4 * Copyright (C) 1992-2001 Andrew Tridgell <[email protected]>
5 * Copyright (C) 2001, 2002 Martin Pool <[email protected]>
6 * Copyright (C) 2003-2020 Wayne Davison
7 *
8 * This program is free software; you can redistribute it and/or modify
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.
12 *
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.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
20 */
21
22 /* This file is now converted to use the new-style getaddrinfo()
23 * interface, which supports IPv6 but is also supported on recent
24 * IPv4-only machines. On systems that don't have that interface, we
25 * emulate it using the KAME implementation. */
26
27 #include "rsync.h"
28 #include <poll.h>
29 #include "itypes.h"
30 #include "ifuncs.h"
31 #ifdef HAVE_NETINET_IN_SYSTM_H
32 #include <netinet/in_systm.h>
33 #endif
34 #ifdef HAVE_NETINET_IP_H
35 #include <netinet/ip.h>
36 #endif
37 #include <netinet/tcp.h>
38
39 extern char *bind_address;
40 extern char *sockopts;
41 extern int default_af_hint;
42 extern int connect_timeout;
43 extern int pid_file_fd;
44
45 #ifdef HAVE_SIGACTION
46 static struct sigaction sigact;
47 #endif
48
49 static int sock_exec(const char *prog);
50 static char *shell_quote_connect_host(const char *host);
51
52 #define PROXY_BUF_SIZE 1024
53
54 /* Establish a proxy connection on an open socket to a web proxy by using the
55 * CONNECT method. If proxy_user and proxy_pass are not NULL, they are used to
56 * authenticate to the proxy using the "Basic" proxy-authorization protocol. */
57 static int establish_proxy_connection(int fd, char *host, int port, char *proxy_user, char *proxy_pass)
58 {
59 char *cp, buffer[PROXY_BUF_SIZE + 1];
60 char *authhdr, authbuf[PROXY_BUF_SIZE + 1];
61 int len;
62
63 /* Reject control bytes in the host so they can't be smuggled into the
64 * HTTP CONNECT request line (CRLF header/request injection). */
65 for (cp = host; *cp; cp++) {
66 if ((unsigned char)*cp < 0x20 || (unsigned char)*cp == 0x7f) {
67 rprintf(FERROR, "invalid control character in proxy CONNECT host\n");
68 return -1;
69 }
70 }
71
72 if (proxy_user && proxy_pass) {
73 stringjoin(buffer, PROXY_BUF_SIZE,
74 proxy_user, ":", proxy_pass, NULL);
75 len = strlen(buffer);
76
77 if ((len*8 + 5) / 6 >= PROXY_BUF_SIZE - 3) {
78 rprintf(FERROR,
79 "authentication information is too long\n");
80 return -1;
81 }
82
83 base64_encode(buffer, len, authbuf, 1);
84 authhdr = "\r\nProxy-Authorization: Basic ";
85 } else {
86 *authbuf = '\0';
87 authhdr = "";
88 }
89
90 len = snprintf(buffer, PROXY_BUF_SIZE, "CONNECT %s:%d HTTP/1.0%s%s\r\n\r\n", host, port, authhdr, authbuf);
91 if (len <= 0 || len >= PROXY_BUF_SIZE) {
92 rprintf(FERROR, "proxy CONNECT request too long\n");
93 return -1;
94 }
95 if (write(fd, buffer, len) != len) {
96 rsyserr(FERROR, errno, "failed to write to proxy");
97 return -1;
98 }
99
100 for (cp = buffer; cp < &buffer[PROXY_BUF_SIZE - 1]; cp++) {
101 if (read(fd, cp, 1) != 1) {
102 rsyserr(FERROR, errno, "failed to read from proxy");
103 return -1;
104 }
105 if (*cp == '\n')
106 break;
107 }
108
109 if (cp == &buffer[PROXY_BUF_SIZE - 1]) {
110 rprintf(FERROR, "proxy response line too long\n");
111 return -1;
112 }
113 *cp = '\0';
114 if (cp > buffer && cp[-1] == '\r')
115 cp[-1] = '\0';
116 if (strncmp(buffer, "HTTP/", 5) != 0) {
117 rprintf(FERROR, "bad response from proxy -- %s\n",
118 buffer);
119 return -1;
120 }
121 for (cp = &buffer[5]; isDigit(cp) || *cp == '.'; cp++) {}
122 while (*cp == ' ')
123 cp++;
124 if (*cp != '2') {
125 rprintf(FERROR, "bad response from proxy -- %s\n",
126 buffer);
127 return -1;
128 }
129 /* throw away the rest of the HTTP header */
130 while (1) {
131 for (cp = buffer; cp < &buffer[PROXY_BUF_SIZE - 1]; cp++) {
132 if (read(fd, cp, 1) != 1) {
133 rsyserr(FERROR, errno,
134 "failed to read from proxy");
135 return -1;
136 }
137 if (*cp == '\n')
138 break;
139 }
140 if (cp == &buffer[PROXY_BUF_SIZE - 1]) {
141 rprintf(FERROR, "proxy response header line too long\n");
142 return -1;
143 }
144 if (cp > buffer && *cp == '\n')
145 cp--;
146 if (cp == buffer && (*cp == '\n' || *cp == '\r'))
147 break;
148 }
149 return 0;
150 }
151
152 static char *shell_quote_connect_host(const char *host)
153 {
154 const char *s;
155 char *quoted, *t;
156 size_t len = 2; /* surrounding single quotes */
157
158 for (s = host; *s; s++)
159 len += *s == '\'' ? 4 : 1;
160 quoted = new_array(char, len + 1);
161 t = quoted;
162 *t++ = '\'';
163 for (s = host; *s; s++) {
164 if (*s == '\'') {
165 memcpy(t, "'\\''", 4);
166 t += 4;
167 } else
168 *t++ = *s;
169 }
170 *t++ = '\'';
171 *t = '\0';
172 return quoted;
173 }
174
175 /* %H is substituted into a free-form command string that a shell then runs, and
176 * a hook of the form `sh -c '... %H ...'` re-parses the word in a nested shell
177 * where the quoting we added has already been consumed. Restrict the host to
178 * characters that stay data through such a pass. ('Any shell' is too strong a
179 * claim -- see the leading-'%' note below.)
180 *
181 * The set is deliberately a little wider than a DNS name: RSYNC_CONNECT_PROG
182 * exists for custom transports, where %H may be an alias the program resolves
183 * itself rather than a name the resolver ever sees, so '+' and '~' are allowed
184 * inside the string. '%' is required for an IPv6 zone id (fe80::1%eth0) and is
185 * not special to a POSIX shell.
186 *
187 * The first character is checked separately, because several of the allowed
188 * ones change an argument's MEANING rather than its text, which no amount of
189 * quoting prevents. Mid-word each is literal, which is why the set still
190 * allows them:
191 * '-' and '+' both introduce options to plenty of programs -- `sh +x` is as
192 * real as `sh -x`;
193 * '~' is tilde-expanded by the nested shell, turning ~root into /root;
194 * '%' is expanded by a nested fish, where %self becomes its pid (an IPv6
195 * zone id has its '%' mid-word, so nothing legitimate is lost).
196 * An empty host is refused too: it survives a direct exec as an empty argument
197 * but vanishes entirely when a nested shell re-splits the command, shifting
198 * every argument after it. None of these can begin a real hostname.
199 *
200 * This bounds what a SHELL can do with the value. It cannot bound what the
201 * named program does with it -- something like "host:-rf" arrives intact, and a
202 * program that splits on ':' may reinterpret the tail. That boundary belongs
203 * to whoever writes RSYNC_CONNECT_PROG. */
204 static int shell_unsafe_connect_host(const char *host)
205 {
206 const unsigned char *s;
207
208 if (!*host || strchr("-+~%", *host))
209 return 1;
210
211 for (s = (const unsigned char *)host; *s; s++) {
212 if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z')
213 || (*s >= '0' && *s <= '9') || strchr("._:-%+~", *s)))
214 return 1;
215 }
216 return 0;
217 }
218
219
220 /* Try to set the local address for a newly-created socket.
221 * Return -1 if this fails. */
222 int try_bind_local(int s, int ai_family, int ai_socktype,
223 const char *bind_addr)
224 {
225 int error;
226 struct addrinfo bhints, *bres_all, *r;
227
228 memset(&bhints, 0, sizeof bhints);
229 bhints.ai_family = ai_family;
230 bhints.ai_socktype = ai_socktype;
231 bhints.ai_flags = AI_PASSIVE;
232 if ((error = getaddrinfo(bind_addr, NULL, &bhints, &bres_all))) {
233 rprintf(FERROR, RSYNC_NAME ": getaddrinfo %s: %s\n",
234 bind_addr, gai_strerror(error));
235 return -1;
236 }
237
238 for (r = bres_all; r; r = r->ai_next) {
239 if (bind(s, r->ai_addr, r->ai_addrlen) == -1)
240 continue;
241 freeaddrinfo(bres_all);
242 return s;
243 }
244
245 /* no error message; there might be some problem that allows
246 * creation of the socket but not binding, perhaps if the
247 * machine has no ipv6 address of this name. */
248 freeaddrinfo(bres_all);
249 return -1;
250 }
251
252 /* connect() timeout handler based on alarm() */
253 static void contimeout_handler(UNUSED(int val))
254 {
255 connect_timeout = -1;
256 }
257
258 /* How long each poll() pass waits before re-checking a pending connect(). */
259 #define CONNECT_POLL_SLICE 100
260
261 /* connect() to addr, waiting for completion with poll() rather than blocking
262 * in the kernel. A blocking connect() can sleep forever on a connection that
263 * is already established (seen on OpenBSD, where the socket shows ESTABLISHED
264 * at both ends while connect() never returns); with no timeout set that hangs
265 * rsync for good. Re-checking the socket on each pass costs a loop instead.
266 * Returns 0 on success, -1 with errno set on failure. */
267 static int connect_polled(int s, const struct sockaddr *addr, socklen_t addrlen)
268 {
269 struct pollfd pfd;
270 int save_errno;
271
272 set_nonblocking(s);
273
274 if (connect(s, addr, addrlen) == 0)
275 goto connected;
276 if (errno != EINPROGRESS && errno != EINTR)
277 goto failed;
278
279 pfd.fd = s;
280 pfd.events = POLLOUT;
281 while (1) {
282 int err = 0;
283 socklen_t errlen = sizeof err;
284
285 /* the --contimeout alarm fired: let the caller report it */
286 if (connect_timeout < 0) {
287 errno = ETIMEDOUT;
288 goto failed;
289 }
290 pfd.revents = 0;
291 if (poll(&pfd, 1, CONNECT_POLL_SLICE) < 0) {
292 if (errno == EINTR)
293 continue;
294 goto failed;
295 }
296 /* A finished slice is not a failure: loop so that poll() looks
297 * at the socket again, which is what recovers a missed wakeup. */
298 if (!pfd.revents)
299 continue;
300 if (getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &errlen) < 0)
301 goto failed;
302 if (err) {
303 errno = err;
304 goto failed;
305 }
306 break;
307 }
308
309 connected:
310 set_blocking(s);
311 return 0;
312
313 failed:
314 save_errno = errno;
315 set_blocking(s);
316 errno = save_errno;
317 return -1;
318 }
319
320 /* Open a socket to a tcp remote host with the specified port.
321 *
322 * Based on code from Warren. Proxy support by Stephen Rothwell.
323 * getaddrinfo() rewrite contributed by KAME.net.
324 *
325 * Now that we support IPv6 we need to look up the remote machine's address
326 * first, using af_hint to set a preference for the type of address. Then
327 * depending on whether it has v4 or v6 addresses we try to open a connection.
328 *
329 * The loop allows for machines with some addresses which may not be reachable,
330 * perhaps because we can't e.g. route ipv6 to that network but we can get ip4
331 * packets through.
332 *
333 * bind_addr: local address to use. Normally NULL to bind the wildcard address.
334 *
335 * af_hint: address family, e.g. AF_INET or AF_INET6. */
336 int open_socket_out(char *host, int port, const char *bind_addr, int af_hint)
337 {
338 int type = SOCK_STREAM;
339 int error, s, j, addr_cnt, *errnos;
340 struct addrinfo hints, *res0, *res;
341 char portbuf[10];
342 char *h, *cp;
343 int proxied = 0;
344 char buffer[1024];
345 char *proxy_user = NULL, *proxy_pass = NULL;
346
347 /* if we have a RSYNC_PROXY env variable then redirect our
348 * connection via a web proxy at the given address. */
349 h = getenv("RSYNC_PROXY");
350 proxied = h != NULL && *h != '\0';
351
352 if (proxied) {
353 strlcpy(buffer, h, sizeof buffer);
354
355 /* Is the USER:PASS@ prefix present? */
356 if ((cp = strrchr(buffer, '@')) != NULL) {
357 *cp++ = '\0';
358 /* The remainder is the HOST:PORT part. */
359 h = cp;
360
361 if ((cp = strchr(buffer, ':')) == NULL) {
362 rprintf(FERROR,
363 "invalid proxy specification: should be USER:PASS@HOST:PORT\n");
364 return -1;
365 }
366 *cp++ = '\0';
367
368 proxy_user = buffer;
369 proxy_pass = cp;
370 } else {
371 /* The whole buffer is the HOST:PORT part. */
372 h = buffer;
373 }
374
375 if ((cp = strchr(h, ':')) == NULL) {
376 rprintf(FERROR,
377 "invalid proxy specification: should be HOST:PORT\n");
378 return -1;
379 }
380 *cp++ = '\0';
381 strlcpy(portbuf, cp, sizeof portbuf);
382 if (DEBUG_GTE(CONNECT, 1)) {
383 rprintf(FINFO, "connection via http proxy %s port %s\n",
384 h, portbuf);
385 }
386 } else {
387 snprintf(portbuf, sizeof portbuf, "%d", port);
388 h = host;
389 }
390
391 memset(&hints, 0, sizeof hints);
392 hints.ai_family = af_hint;
393 hints.ai_socktype = type;
394 error = getaddrinfo(h, portbuf, &hints, &res0);
395 if (error) {
396 rprintf(FERROR, RSYNC_NAME ": getaddrinfo: %s %s: %s\n",
397 h, portbuf, gai_strerror(error));
398 return -1;
399 }
400
401 for (res = res0, addr_cnt = 0; res; res = res->ai_next, addr_cnt++) {}
402 errnos = new_array0(int, addr_cnt);
403
404 s = -1;
405 /* Try to connect to all addresses for this machine until we get
406 * through. It might e.g. be multi-homed, or have both IPv4 and IPv6
407 * addresses. We need to create a socket for each record, since the
408 * address record tells us what protocol to use to try to connect. */
409 for (res = res0, j = 0; res; res = res->ai_next, j++) {
410 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
411 if (s < 0)
412 continue;
413
414 if (bind_addr
415 && try_bind_local(s, res->ai_family, type,
416 bind_addr) == -1) {
417 close(s);
418 s = -1;
419 continue;
420 }
421 if (connect_timeout > 0) {
422 SIGACTION(SIGALRM, contimeout_handler);
423 alarm(connect_timeout);
424 }
425
426 set_socket_options(s, sockopts);
427 if (connect_polled(s, res->ai_addr, res->ai_addrlen) < 0) {
428 if (connect_timeout < 0)
429 exit_cleanup(RERR_CONTIMEOUT);
430 /* stash it before close()/alarm() can overwrite errno */
431 errnos[j] = errno;
432 close(s);
433 s = -1;
434 }
435
436 if (connect_timeout > 0)
437 alarm(0);
438
439 if (s < 0)
440 continue;
441
442 if (proxied && establish_proxy_connection(s, host, port, proxy_user, proxy_pass) != 0) {
443 close(s);
444 s = -1;
445 continue;
446 }
447 if (DEBUG_GTE(CONNECT, 2)) {
448 char buf[2048];
449 if ((error = getnameinfo(res->ai_addr, res->ai_addrlen, buf, sizeof buf, NULL, 0, NI_NUMERICHOST)) != 0)
450 snprintf(buf, sizeof buf, "*getnameinfo failure: %s*", gai_strerror(error));
451 rprintf(FINFO, "Connected to %s (%s)\n", h, buf);
452 }
453 break;
454 }
455
456 if (s < 0 || DEBUG_GTE(CONNECT, 2)) {
457 char buf[2048];
458 for (res = res0, j = 0; res; res = res->ai_next, j++) {
459 if (errnos[j] == 0)
460 continue;
461 if ((error = getnameinfo(res->ai_addr, res->ai_addrlen, buf, sizeof buf, NULL, 0, NI_NUMERICHOST)) != 0)
462 snprintf(buf, sizeof buf, "*getnameinfo failure: %s*", gai_strerror(error));
463 rsyserr(FERROR, errnos[j], "failed to connect to %s (%s)", h, buf);
464 }
465 if (s < 0)
466 s = -1;
467 }
468
469 freeaddrinfo(res0);
470 free(errnos);
471
472 return s;
473 }
474
475
476 /* Open an outgoing socket, but allow for it to be intercepted by
477 * $RSYNC_CONNECT_PROG, which will execute a program across a TCP
478 * socketpair rather than really opening a socket.
479 *
480 * We use this primarily in testing to detect TCP flow bugs, but not
481 * cause security problems by really opening remote connections.
482 *
483 * This is based on the Samba LIBSMB_PROG feature.
484 *
485 * bind_addr: local address to use. Normally NULL to get the stack default. */
486 int open_socket_out_wrapped(char *host, int port, const char *bind_addr, int af_hint)
487 {
488 char *prog = getenv("RSYNC_CONNECT_PROG");
489
490 if (prog && strchr(prog, '%')) {
491 if (shell_unsafe_connect_host(host)) {
492 rprintf(FERROR, "unsafe host characters for RSYNC_CONNECT_PROG\n");
493 return -1;
494 }
495 char *qhost = shell_quote_connect_host(host);
496 int hlen = strlen(qhost);
497 int len = strlen(prog) + 1;
498 char *f, *t;
499 for (f = prog; *f; f++) {
500 if (*f != '%')
501 continue;
502 /* Compute more than enough room. */
503 if (f[1] == '%')
504 f++;
505 else
506 len += hlen;
507 }
508 f = prog;
509 prog = new_array(char, len);
510 for (t = prog; *f; f++) {
511 if (*f == '%') {
512 switch (*++f) {
513 case '%':
514 /* Just skips the extra '%'. */
515 break;
516 case 'H':
517 memcpy(t, qhost, hlen);
518 t += hlen;
519 continue;
520 default:
521 f--; /* pass % through */
522 break;
523 }
524 }
525 *t++ = *f;
526 }
527 *t = '\0';
528 free(qhost);
529 }
530
531 if (DEBUG_GTE(CONNECT, 1)) {
532 rprintf(FINFO, "%sopening tcp connection to %s port %d\n",
533 prog ? "Using RSYNC_CONNECT_PROG instead of " : "",
534 host, port);
535 }
536 if (prog)
537 return sock_exec(prog);
538 return open_socket_out(host, port, bind_addr, af_hint);
539 }
540
541
542 /* Open one or more sockets for incoming data using the specified type,
543 * port, and address.
544 *
545 * The getaddrinfo() call may return several address results, e.g. for
546 * the machine's IPv4 and IPv6 name.
547 *
548 * We return an array of file-descriptors to the sockets, with a trailing
549 * -1 value to indicate the end of the list.
550 *
551 * bind_addr: local address to bind, or NULL to allow it to default. */
552 static int *open_socket_in(int type, int port, const char *bind_addr,
553 int af_hint)
554 {
555 int one = 1;
556 int s, *socks, maxs, i, ecnt;
557 struct addrinfo hints, *all_ai, *resp;
558 char portbuf[10], **errmsgs;
559 int error;
560
561 memset(&hints, 0, sizeof hints);
562 hints.ai_family = af_hint;
563 hints.ai_socktype = type;
564 hints.ai_flags = AI_PASSIVE;
565 snprintf(portbuf, sizeof portbuf, "%d", port);
566 error = getaddrinfo(bind_addr, portbuf, &hints, &all_ai);
567 if (error) {
568 rprintf(FERROR, RSYNC_NAME ": getaddrinfo: bind address %s: %s\n",
569 bind_addr, gai_strerror(error));
570 return NULL;
571 }
572
573 /* Count max number of sockets we might open. */
574 for (maxs = 0, resp = all_ai; resp; resp = resp->ai_next, maxs++) {}
575
576 socks = new_array(int, maxs + 1);
577 errmsgs = new_array(char *, maxs);
578
579 /* We may not be able to create the socket, if for example the
580 * machine knows about IPv6 in the C library, but not in the
581 * kernel. */
582 for (resp = all_ai, i = ecnt = 0; resp; resp = resp->ai_next) {
583 s = socket(resp->ai_family, resp->ai_socktype,
584 resp->ai_protocol);
585
586 if (s == -1) {
587 int r = asprintf(&errmsgs[ecnt++],
588 "socket(%d,%d,%d) failed: %s\n",
589 (int)resp->ai_family, (int)resp->ai_socktype,
590 (int)resp->ai_protocol, strerror(errno));
591 if (r < 0)
592 out_of_memory("open_socket_in");
593 /* See if there's another address that will work... */
594 continue;
595 }
596
597 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
598 (char *)&one, sizeof one);
599 if (sockopts)
600 set_socket_options(s, sockopts);
601 else
602 set_socket_options(s, lp_socket_options());
603
604 #ifdef IPV6_V6ONLY
605 if (resp->ai_family == AF_INET6) {
606 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&one, sizeof one) < 0
607 && default_af_hint != AF_INET6) {
608 close(s);
609 continue;
610 }
611 }
612 #endif
613
614 /* Now we've got a socket - we need to bind it. */
615 if (bind(s, resp->ai_addr, resp->ai_addrlen) < 0) {
616 /* Nope, try another */
617 int r = asprintf(&errmsgs[ecnt++],
618 "bind() failed: %s (address-family %d)\n",
619 strerror(errno), (int)resp->ai_family);
620 if (r < 0)
621 out_of_memory("open_socket_in");
622 close(s);
623 continue;
624 }
625
626 socks[i++] = s;
627 }
628 socks[i] = -1;
629
630 if (all_ai)
631 freeaddrinfo(all_ai);
632
633 /* Only output the socket()/bind() messages if we were totally
634 * unsuccessful, or if the daemon is being run with -vv. */
635 for (s = 0; s < ecnt; s++) {
636 if (!i || DEBUG_GTE(BIND, 1))
637 rwrite(FLOG, errmsgs[s], strlen(errmsgs[s]), 0);
638 free(errmsgs[s]);
639 }
640 free(errmsgs);
641
642 if (!i) {
643 rprintf(FERROR,
644 "unable to bind any inbound sockets on port %d\n",
645 port);
646 free(socks);
647 return NULL;
648 }
649 return socks;
650 }
651
652
653 /* Determine if a file descriptor is in fact a socket. */
654 int is_a_socket(int fd)
655 {
656 int v;
657 socklen_t l = sizeof (int);
658
659 /* Parameters to getsockopt, setsockopt etc are very
660 * unstandardized across platforms, so don't be surprised if
661 * there are compiler warnings on e.g. SCO OpenSwerver or AIX.
662 * It seems they all eventually get the right idea.
663 *
664 * Debian says: ``The fifth argument of getsockopt and
665 * setsockopt is in reality an int [*] (and this is what BSD
666 * 4.* and libc4 and libc5 have). Some POSIX confusion
667 * resulted in the present socklen_t. The draft standard has
668 * not been adopted yet, but glibc2 already follows it and
669 * also has socklen_t [*]. See also accept(2).''
670 *
671 * We now return to your regularly scheduled programming. */
672 return getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0;
673 }
674
675
676 static void sigchld_handler(UNUSED(int val))
677 {
678 #ifdef WNOHANG
679 while (waitpid(-1, NULL, WNOHANG) > 0) {}
680 #endif
681 #ifndef HAVE_SIGACTION
682 signal(SIGCHLD, sigchld_handler);
683 #endif
684 }
685
686
687 void start_accept_loop(int port, int (*fn)(int, int))
688 {
689 struct pollfd *pfds;
690 int *sp, nsp, i;
691
692 #ifdef HAVE_SIGACTION
693 sigact.sa_flags = SA_NOCLDSTOP;
694 #endif
695
696 /* open an incoming socket */
697 sp = open_socket_in(SOCK_STREAM, port, bind_address, default_af_hint);
698 if (sp == NULL)
699 exit_cleanup(RERR_SOCKETIO);
700
701 /* ready to listen */
702 for (nsp = 0; sp[nsp] >= 0; nsp++) {}
703 /* poll() rather than select(): a listening fd at or above FD_SETSIZE
704 * would overflow an fd_set, which is undefined behaviour (issue #231). */
705 if (!(pfds = new_array(struct pollfd, nsp ? nsp : 1)))
706 out_of_memory("start_accept_loop");
707 for (i = 0; sp[i] >= 0; i++) {
708 if (listen(sp[i], lp_listen_backlog()) < 0) {
709 rsyserr(FERROR, errno, "listen() on socket failed");
710 #ifdef INET6
711 if (errno == EADDRINUSE && i > 0) {
712 rprintf(FINFO, "Try using --ipv4 or --ipv6 to avoid this listen() error.\n");
713 }
714 #endif
715 exit_cleanup(RERR_SOCKETIO);
716 }
717 pfds[i].fd = sp[i];
718 pfds[i].events = POLLIN;
719 pfds[i].revents = 0;
720 }
721
722 /* now accept incoming connections - forking a new process
723 * for each incoming connection */
724 while (1) {
725 pid_t pid;
726 int fd;
727 struct sockaddr_storage addr;
728 socklen_t addrlen = sizeof addr;
729
730 /* close log file before the potentially very long wait so the
731 * file can be trimmed by another process instead of growing
732 * forever */
733 logfile_close();
734
735 for (i = 0; i < nsp; i++)
736 pfds[i].revents = 0;
737
738 if (poll(pfds, nsp, -1) < 1)
739 continue;
740
741 for (i = 0, fd = -1; i < nsp; i++) {
742 if (pfds[i].revents & (POLLIN | POLLERR | POLLHUP)) {
743 fd = accept(sp[i], (struct sockaddr *)&addr, &addrlen);
744 break;
745 }
746 }
747
748 if (fd < 0)
749 continue;
750
751 SIGACTION(SIGCHLD, sigchld_handler);
752
753 if ((pid = fork()) == 0) {
754 int ret;
755 if (pid_file_fd >= 0)
756 close(pid_file_fd);
757 for (i = 0; sp[i] >= 0; i++)
758 close(sp[i]);
759 /* Re-open log file in child before possibly giving
760 * up privileges (see logfile_close() above). */
761 logfile_reopen();
762 ret = fn(fd, fd);
763 close_all();
764 gcov_flush();
765 _exit(ret);
766 } else if (pid < 0) {
767 rsyserr(FERROR, errno,
768 "could not create child server process");
769 close(fd);
770 /* This might have happened because we're
771 * overloaded. Sleep briefly before trying to
772 * accept again. */
773 sleep(2);
774 } else {
775 /* Parent doesn't need this fd anymore. */
776 close(fd);
777 }
778 }
779 }
780
781
782 enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
783
784 struct
785 {
786 char *name;
787 int level;
788 int option;
789 int value;
790 int opttype;
791 } socket_options[] = {
792 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
793 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
794 #ifdef SO_BROADCAST
795 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
796 #endif
797 #ifdef TCP_NODELAY
798 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
799 #endif
800 #ifdef IPTOS_LOWDELAY
801 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
802 #endif
803 #ifdef IPTOS_THROUGHPUT
804 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
805 #endif
806 #ifdef SO_SNDBUF
807 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
808 #endif
809 #ifdef SO_RCVBUF
810 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
811 #endif
812 #ifdef SO_SNDLOWAT
813 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
814 #endif
815 #ifdef SO_RCVLOWAT
816 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
817 #endif
818 #ifdef SO_SNDTIMEO
819 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
820 #endif
821 #ifdef SO_RCVTIMEO
822 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
823 #endif
824 {NULL,0,0,0,0}
825 };
826
827
828 /* Set user socket options. */
829 void set_socket_options(int fd, char *options)
830 {
831 char *tok;
832
833 if (!options || !*options)
834 return;
835
836 options = strdup(options);
837
838 for (tok = strtok(options, " \t,"); tok; tok = strtok(NULL," \t,")) {
839 int ret=0,i;
840 int value = 1;
841 char *p;
842 int got_value = 0;
843
844 if ((p = strchr(tok,'='))) {
845 *p = 0;
846 value = atoi(p+1);
847 got_value = 1;
848 }
849
850 for (i = 0; socket_options[i].name; i++) {
851 if (strcmp(socket_options[i].name,tok)==0)
852 break;
853 }
854
855 if (!socket_options[i].name) {
856 rprintf(FERROR,"Unknown socket option %s\n",tok);
857 continue;
858 }
859
860 switch (socket_options[i].opttype) {
861 case OPT_BOOL:
862 case OPT_INT:
863 ret = setsockopt(fd,socket_options[i].level,
864 socket_options[i].option,
865 (char *)&value, sizeof (int));
866 break;
867
868 case OPT_ON:
869 if (got_value)
870 rprintf(FERROR,"syntax error -- %s does not take a value\n",tok);
871
872 {
873 int on = socket_options[i].value;
874 ret = setsockopt(fd,socket_options[i].level,
875 socket_options[i].option,
876 (char *)&on, sizeof (int));
877 }
878 break;
879 }
880
881 if (ret != 0) {
882 rsyserr(FERROR, errno,
883 "failed to set socket option %s", tok);
884 }
885 }
886
887 free(options);
888 }
889
890
891 /* How long socketpair_tcp() waits for its own loopback connection (seconds),
892 * and how long each poll() pass waits before re-checking the listen queue. */
893 #define SOCKETPAIR_ACCEPT_TIMEOUT 60
894 #define SOCKETPAIR_ACCEPT_SLICE 100
895
896 /* This is like socketpair but uses tcp. The function guarantees that nobody
897 * else can attach to the socket, or if they do that this function fails and
898 * the socket gets closed. The anti-hijack guarantee is enforced after the
899 * accept() below: a local attacker who races a connection in on the loopback
900 * listener before our own connect() lands would be detected by the peer-vs-
901 * local address comparison and the function fails. Returns 0 on success, -1
902 * on failure. The resulting file descriptors are symmetrical. Currently
903 * only for RSYNC_CONNECT_PROG. */
904 static int socketpair_tcp(int fd[2])
905 {
906 int listener;
907 struct sockaddr_in sock;
908 struct sockaddr_in sock2;
909 socklen_t socklen = sizeof sock;
910 int connect_done = 0;
911 int save_errno;
912
913 fd[0] = fd[1] = -1; /* listener is set by socket() below before any use */
914
915 memset(&sock, 0, sizeof sock);
916
917 if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
918 goto failed;
919
920 memset(&sock2, 0, sizeof sock2);
921 #ifdef HAVE_SOCKADDR_IN_LEN
922 sock2.sin_len = sizeof sock2;
923 #endif
924 sock2.sin_family = PF_INET;
925 sock2.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
926
927 if (bind(listener, (struct sockaddr *)&sock2, sizeof sock2) != 0
928 || listen(listener, 1) != 0
929 || getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0
930 || (fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1)
931 goto failed;
932
933 set_nonblocking(fd[1]);
934
935 sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
936
937 if (connect(fd[1], (struct sockaddr *)&sock, sizeof sock) == -1) {
938 if (errno != EINPROGRESS)
939 goto failed;
940 } else
941 connect_done = 1;
942
943 /* Wait for our own connection with a polled, non-blocking accept()
944 * rather than a blocking one. A blocking accept() here can sleep
945 * forever on a connection the kernel has already completed (seen on
946 * OpenBSD: both ends ESTABLISHED and the connection queued on the
947 * listener, the accept()ing process still asleep), which hangs rsync
948 * with no timeout to break it. Re-checking the queue on each pass
949 * turns a missed wakeup into another loop rather than a hang. */
950 set_nonblocking(listener);
951 {
952 struct pollfd pfd;
953 time_t deadline = time(NULL) + SOCKETPAIR_ACCEPT_TIMEOUT;
954 int ready_but_empty = 0;
955
956 pfd.fd = listener;
957 pfd.events = POLLIN;
958 while ((fd[0] = accept(listener, (struct sockaddr *)&sock2, &socklen)) == -1) {
959 int nready;
960
961 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
962 goto failed;
963 /* Bound the wait by the clock, not by a count of passes: a
964 * signal on every pass must not extend it, and a poll() that
965 * returns at once must not consume it. */
966 if (time(NULL) >= deadline) {
967 errno = ETIMEDOUT;
968 goto failed;
969 }
970 if (ready_but_empty) {
971 /* The listener said ready, yet accept() found nothing
972 * (the peer can reset first). Pause instead of
973 * spinning on a poll() that returns immediately. A
974 * signal only cuts the pause short -- the deadline
975 * above, rechecked every pass, is the bound. */
976 if (poll(NULL, 0, SOCKETPAIR_ACCEPT_SLICE) < 0 && errno != EINTR)
977 goto failed;
978 ready_but_empty = 0;
979 continue;
980 }
981 pfd.revents = 0;
982 nready = poll(&pfd, 1, SOCKETPAIR_ACCEPT_SLICE);
983 if (nready < 0 && errno != EINTR)
984 goto failed;
985 ready_but_empty = nready > 0;
986 }
987 }
988 /* BSD gives the accepted fd the listener's non-blocking flag. */
989 set_blocking(fd[0]);
990
991 close(listener);
992 listener = -1;
993
994 set_blocking(fd[1]);
995
996 if (connect_done == 0) {
997 if (connect(fd[1], (struct sockaddr *)&sock, sizeof sock) != 0 && errno != EISCONN)
998 goto failed;
999 }
1000
1001 /* Confirm that the connection we accepted is the one we just made, and
1002 * not one a local attacker raced in on the loopback listener before our
1003 * own connect() completed. The peer of the accepted end (fd[0]) must be
1004 * the local address of our connecting end (fd[1]), and both must be
1005 * loopback. If they differ, someone else connected first; fail closed. */
1006 {
1007 /* {0}: the analyzer doesn't model getpeername/getsockname filling these. */
1008 struct sockaddr_in accepted_peer = {0}, our_local = {0};
1009 socklen_t plen = sizeof accepted_peer;
1010 socklen_t llen = sizeof our_local;
1011
1012 if (getpeername(fd[0], (struct sockaddr *)&accepted_peer, &plen) != 0
1013 || getsockname(fd[1], (struct sockaddr *)&our_local, &llen) != 0
1014 || accepted_peer.sin_family != AF_INET
1015 || our_local.sin_family != AF_INET
1016 || accepted_peer.sin_addr.s_addr != htonl(INADDR_LOOPBACK)
1017 || our_local.sin_addr.s_addr != htonl(INADDR_LOOPBACK)
1018 || accepted_peer.sin_port != our_local.sin_port) {
1019 errno = EPERM;
1020 goto failed;
1021 }
1022 }
1023
1024 /* all OK! */
1025 return 0;
1026
1027 failed:
1028 save_errno = errno; /* keep it: a failing close() would overwrite it */
1029 if (fd[0] != -1)
1030 close(fd[0]);
1031 if (fd[1] != -1)
1032 close(fd[1]);
1033 if (listener != -1)
1034 close(listener);
1035 errno = save_errno;
1036 return -1;
1037 }
1038
1039
1040 /* Run a program on a local tcp socket, so that we can talk to it's stdin and
1041 * stdout. This is used to fake a connection to a daemon for testing -- not
1042 * for the normal case of running SSH.
1043 *
1044 * Returns a socket which is attached to a subprocess running "prog". stdin and
1045 * stdout are attached. stderr is left attached to the original stderr. */
1046 static int sock_exec(const char *prog)
1047 {
1048 pid_t pid;
1049 int fd[2];
1050
1051 if (socketpair_tcp(fd) != 0) {
1052 rsyserr(FERROR, errno, "socketpair_tcp failed");
1053 return -1;
1054 }
1055 if (DEBUG_GTE(CMD, 1))
1056 rprintf(FINFO, "Running socket program: \"%s\"\n", prog);
1057
1058 pid = fork();
1059 if (pid < 0) {
1060 rsyserr(FERROR, errno, "fork");
1061 exit_cleanup(RERR_IPC);
1062 }
1063
1064 if (pid == 0) {
1065 close(fd[0]);
1066 if (dup2(fd[1], STDIN_FILENO) < 0
1067 || dup2(fd[1], STDOUT_FILENO) < 0) {
1068 fprintf(stderr, "Failed to run \"%s\"\n", prog);
1069 exit(1);
1070 }
1071 exit(shell_exec(prog));
1072 }
1073
1074 close(fd[1]);
1075 return fd[0];
1076 }