Made base64_encode() non-static.
[rsync/rsync.git] / socket.c
... / ...
CommitLineData
1/* -*- c-file-style: "linux" -*-
2
3 rsync -- fast file replication program
4
5 Copyright (C) 1992-2001 by Andrew Tridgell <tridge@samba.org>
6 Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
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 2 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
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21*/
22
23/**
24 * @file socket.c
25 *
26 * Socket functions used in rsync.
27 *
28 * This file is now converted to use the new-style getaddrinfo()
29 * interface, which supports IPv6 but is also supported on recent
30 * IPv4-only machines. On systems that don't have that interface, we
31 * emulate it using the KAME implementation.
32 **/
33
34#include "rsync.h"
35
36
37/**
38 * Establish a proxy connection on an open socket to a web proxy by
39 * using the HTTP CONNECT method.
40 **/
41static int establish_proxy_connection(int fd, char *host, int port)
42{
43 char buffer[1024];
44 char *cp;
45
46 snprintf(buffer, sizeof(buffer), "CONNECT %s:%d HTTP/1.0\r\n\r\n", host, port);
47 if (write(fd, buffer, strlen(buffer)) != (int)strlen(buffer)) {
48 rprintf(FERROR, "failed to write to proxy: %s\n",
49 strerror(errno));
50 return -1;
51 }
52
53 for (cp = buffer; cp < &buffer[sizeof (buffer) - 1]; cp++) {
54 if (read(fd, cp, 1) != 1) {
55 rprintf(FERROR, "failed to read from proxy: %s\n",
56 strerror(errno));
57 return -1;
58 }
59 if (*cp == '\n')
60 break;
61 }
62
63 if (*cp != '\n')
64 cp++;
65 *cp-- = '\0';
66 if (*cp == '\r')
67 *cp = '\0';
68 if (strncmp(buffer, "HTTP/", 5) != 0) {
69 rprintf(FERROR, "bad response from proxy - %s\n",
70 buffer);
71 return -1;
72 }
73 for (cp = &buffer[5]; isdigit(*(uchar*)cp) || *cp == '.'; cp++) {}
74 while (*cp == ' ')
75 cp++;
76 if (*cp != '2') {
77 rprintf(FERROR, "bad response from proxy - %s\n",
78 buffer);
79 return -1;
80 }
81 /* throw away the rest of the HTTP header */
82 while (1) {
83 for (cp = buffer; cp < &buffer[sizeof (buffer) - 1]; cp++) {
84 if (read(fd, cp, 1) != 1) {
85 rprintf(FERROR, "failed to read from proxy: %s\n",
86 strerror(errno));
87 return -1;
88 }
89 if (*cp == '\n')
90 break;
91 }
92 if (cp > buffer && *cp == '\n')
93 cp--;
94 if (cp == buffer && (*cp == '\n' || *cp == '\r'))
95 break;
96 }
97 return 0;
98}
99
100
101/**
102 * Try to set the local address for a newly-created socket. Return -1
103 * if this fails.
104 **/
105int try_bind_local(int s, int ai_family, int ai_socktype,
106 const char *bind_address)
107{
108 int error;
109 struct addrinfo bhints, *bres_all, *r;
110
111 memset(&bhints, 0, sizeof(bhints));
112 bhints.ai_family = ai_family;
113 bhints.ai_socktype = ai_socktype;
114 bhints.ai_flags = AI_PASSIVE;
115 if ((error = getaddrinfo(bind_address, NULL, &bhints, &bres_all))) {
116 rprintf(FERROR, RSYNC_NAME ": getaddrinfo %s: %s\n",
117 bind_address, gai_strerror(error));
118 return -1;
119 }
120
121 for (r = bres_all; r; r = r->ai_next) {
122 if (bind(s, r->ai_addr, r->ai_addrlen) == -1)
123 continue;
124 freeaddrinfo(bres_all);
125 return s;
126 }
127
128 /* no error message; there might be some problem that allows
129 * creation of the socket but not binding, perhaps if the
130 * machine has no ipv6 address of this name. */
131 freeaddrinfo(bres_all);
132 return -1;
133}
134
135
136/**
137 * Open a socket to a tcp remote host with the specified port .
138 *
139 * Based on code from Warren. Proxy support by Stephen Rothwell.
140 * getaddrinfo() rewrite contributed by KAME.net.
141 *
142 * Now that we support IPv6 we need to look up the remote machine's
143 * address first, using @p af_hint to set a preference for the type
144 * of address. Then depending on whether it has v4 or v6 addresses we
145 * try to open a connection.
146 *
147 * The loop allows for machines with some addresses which may not be
148 * reachable, perhaps because we can't e.g. route ipv6 to that network
149 * but we can get ip4 packets through.
150 *
151 * @param bind_address Local address to use. Normally NULL to bind
152 * the wildcard address.
153 *
154 * @param af_hint Address family, e.g. AF_INET or AF_INET6.
155 **/
156int open_socket_out(char *host, int port, const char *bind_address,
157 int af_hint)
158{
159 int type = SOCK_STREAM;
160 int error;
161 int s;
162 struct addrinfo hints, *res0, *res;
163 char portbuf[10];
164 char *h;
165 int proxied = 0;
166 char buffer[1024];
167 char *cp;
168
169 /* if we have a RSYNC_PROXY env variable then redirect our
170 * connetcion via a web proxy at the given address. The format
171 * is hostname:port */
172 h = getenv("RSYNC_PROXY");
173 proxied = h != NULL && *h != '\0';
174
175 if (proxied) {
176 strlcpy(buffer, h, sizeof(buffer));
177 cp = strchr(buffer, ':');
178 if (cp == NULL) {
179 rprintf(FERROR,
180 "invalid proxy specification: should be HOST:PORT\n");
181 return -1;
182 }
183 *cp++ = '\0';
184 strcpy(portbuf, cp);
185 h = buffer;
186 if (verbose >= 2) {
187 rprintf(FINFO, "connection via http proxy %s port %s\n",
188 h, portbuf);
189 }
190 } else {
191 snprintf(portbuf, sizeof(portbuf), "%d", port);
192 h = host;
193 }
194
195 memset(&hints, 0, sizeof(hints));
196 hints.ai_family = af_hint;
197 hints.ai_socktype = type;
198 error = getaddrinfo(h, portbuf, &hints, &res0);
199 if (error) {
200 rprintf(FERROR, RSYNC_NAME ": getaddrinfo: %s %s: %s\n",
201 h, portbuf, gai_strerror(error));
202 return -1;
203 }
204
205 s = -1;
206 /* Try to connect to all addresses for this machine until we get
207 * through. It might e.g. be multi-homed, or have both IPv4 and IPv6
208 * addresses. We need to create a socket for each record, since the
209 * address record tells us what protocol to use to try to connect. */
210 for (res = res0; res; res = res->ai_next) {
211 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
212 if (s < 0)
213 continue;
214
215 if (bind_address)
216 if (try_bind_local(s, res->ai_family, type,
217 bind_address) == -1) {
218 close(s);
219 s = -1;
220 continue;
221 }
222
223 if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
224 close(s);
225 s = -1;
226 continue;
227 }
228 if (proxied &&
229 establish_proxy_connection(s, host, port) != 0) {
230 close(s);
231 s = -1;
232 continue;
233 } else
234 break;
235 }
236 freeaddrinfo(res0);
237 if (s < 0) {
238 rprintf(FERROR, RSYNC_NAME ": failed to connect to %s: %s\n",
239 h, strerror(errno));
240 return -1;
241 }
242 return s;
243}
244
245
246/**
247 * Open an outgoing socket, but allow for it to be intercepted by
248 * $RSYNC_CONNECT_PROG, which will execute a program across a TCP
249 * socketpair rather than really opening a socket.
250 *
251 * We use this primarily in testing to detect TCP flow bugs, but not
252 * cause security problems by really opening remote connections.
253 *
254 * This is based on the Samba LIBSMB_PROG feature.
255 *
256 * @param bind_address Local address to use. Normally NULL to get the stack default.
257 **/
258int open_socket_out_wrapped(char *host, int port, const char *bind_address,
259 int af_hint)
260{
261 char *prog;
262
263 if ((prog = getenv("RSYNC_CONNECT_PROG")) != NULL)
264 return sock_exec(prog);
265 return open_socket_out(host, port, bind_address, af_hint);
266}
267
268
269
270/**
271 * Open a socket of the specified type, port and address for incoming data
272 *
273 * Try to be better about handling the results of getaddrinfo(): when
274 * opening an inbound socket, we might get several address results,
275 * e.g. for the machine's ipv4 and ipv6 name.
276 *
277 * If binding a wildcard, then any one of them should do. If an address
278 * was specified but it's insufficiently specific then that's not our
279 * fault.
280 *
281 * However, some of the advertized addresses may not work because e.g. we
282 * don't have IPv6 support in the kernel. In that case go on and try all
283 * addresses until one succeeds.
284 *
285 * @param bind_address Local address to bind, or NULL to allow it to
286 * default.
287 **/
288static int *open_socket_in(int type, int port, const char *bind_address,
289 int af_hint)
290{
291 int one=1;
292 int s, *sp, *socks, maxs;
293 struct addrinfo hints, *all_ai, *resp;
294 char portbuf[10];
295 int error;
296
297 memset(&hints, 0, sizeof(hints));
298 hints.ai_family = af_hint;
299 hints.ai_socktype = type;
300 hints.ai_flags = AI_PASSIVE;
301 snprintf(portbuf, sizeof(portbuf), "%d", port);
302 error = getaddrinfo(bind_address, portbuf, &hints, &all_ai);
303 if (error) {
304 rprintf(FERROR, RSYNC_NAME ": getaddrinfo: bind address %s: %s\n",
305 bind_address, gai_strerror(error));
306 return NULL;
307 }
308
309 /* Count max number of sockets we might open. */
310 for (maxs = 0, resp = all_ai; resp; resp = resp->ai_next, maxs++) {}
311 socks = new_array(int, maxs + 1);
312 if (!socks) {
313 rprintf(FERROR,
314 RSYNC_NAME "couldn't allocate memory for sockets");
315 return NULL;
316 }
317
318 /* We may not be able to create the socket, if for example the
319 * machine knows about IPv6 in the C library, but not in the
320 * kernel. */
321 sp = socks + 1; /* Leave room for count at start of array. */
322 for (resp = all_ai; resp; resp = resp->ai_next) {
323 s = socket(resp->ai_family, resp->ai_socktype,
324 resp->ai_protocol);
325
326 if (s == -1) {
327 /* See if there's another address that will work... */
328 continue;
329 }
330
331 setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
332 (char *)&one, sizeof one);
333
334#ifdef IPV6_V6ONLY
335 if (resp->ai_family == AF_INET6) {
336 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
337 (char *)&one, sizeof one);
338 }
339#endif
340
341 /* Now we've got a socket - we need to bind it. */
342 if (bind(s, resp->ai_addr, resp->ai_addrlen) < 0) {
343 /* Nope, try another */
344 close(s);
345 continue;
346 }
347
348 *sp++ = s;
349 }
350 *socks = sp - socks - 1; /* Save count. */
351
352 if (all_ai)
353 freeaddrinfo(all_ai);
354
355 if (*socks == 0) {
356 rprintf(FERROR,
357 RSYNC_NAME ": open inbound socket on port %d failed: "
358 "%s\n", port, strerror(errno));
359 free(socks);
360 return NULL;
361 }
362 return socks;
363}
364
365
366/*
367 * Determine if a file descriptor is in fact a socket
368 */
369int is_a_socket(int fd)
370{
371 int v;
372 socklen_t l;
373 l = sizeof(int);
374
375 /* Parameters to getsockopt, setsockopt etc are very
376 * unstandardized across platforms, so don't be surprised if
377 * there are compiler warnings on e.g. SCO OpenSwerver or AIX.
378 * It seems they all eventually get the right idea.
379 *
380 * Debian says: ``The fifth argument of getsockopt and
381 * setsockopt is in reality an int [*] (and this is what BSD
382 * 4.* and libc4 and libc5 have). Some POSIX confusion
383 * resulted in the present socklen_t. The draft standard has
384 * not been adopted yet, but glibc2 already follows it and
385 * also has socklen_t [*]. See also accept(2).''
386 *
387 * We now return to your regularly scheduled programming. */
388 return getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0;
389}
390
391
392static RETSIGTYPE sigchld_handler(UNUSED(int val))
393{
394 signal(SIGCHLD, sigchld_handler);
395#ifdef WNOHANG
396 while (waitpid(-1, NULL, WNOHANG) > 0) {}
397#endif
398}
399
400
401void start_accept_loop(int port, int (*fn)(int, int))
402{
403 fd_set deffds;
404 int *sp, maxfd, i, j;
405 extern char *bind_address;
406 extern int default_af_hint;
407
408 /* open an incoming socket */
409 sp = open_socket_in(SOCK_STREAM, port, bind_address, default_af_hint);
410 if (sp == NULL)
411 exit_cleanup(RERR_SOCKETIO);
412
413 /* ready to listen */
414 FD_ZERO(&deffds);
415 maxfd = -1;
416 for (i = 1; i <= *sp; i++) {
417 if (listen(sp[i], 5) == -1) {
418 for (j = 1; j <= i; j++)
419 close(sp[j]);
420 free(sp);
421 exit_cleanup(RERR_SOCKETIO);
422 }
423 FD_SET(sp[i], &deffds);
424 if (maxfd < sp[i])
425 maxfd = sp[i];
426 }
427
428
429 /* now accept incoming connections - forking a new process
430 for each incoming connection */
431 while (1) {
432 fd_set fds;
433 pid_t pid;
434 int fd;
435 struct sockaddr_storage addr;
436 socklen_t addrlen = sizeof addr;
437
438 /* close log file before the potentially very long select so
439 file can be trimmed by another process instead of growing
440 forever */
441 log_close();
442
443#ifdef FD_COPY
444 FD_COPY(&deffds, &fds);
445#else
446 fds = deffds;
447#endif
448
449 if (select(maxfd + 1, &fds, NULL, NULL, NULL) != 1)
450 continue;
451
452 fd = -1;
453 for (i = 1; i <= *sp; i++) {
454 if (FD_ISSET(sp[i], &fds)) {
455 fd = accept(sp[i], (struct sockaddr *)&addr,
456 &addrlen);
457 break;
458 }
459 }
460
461 if (fd < 0)
462 continue;
463
464 signal(SIGCHLD, sigchld_handler);
465
466 if ((pid = fork()) == 0) {
467 int ret;
468 close(sp[i]);
469 /* open log file in child before possibly giving
470 up privileges */
471 log_open();
472 ret = fn(fd, fd);
473 close_all();
474 _exit(ret);
475 } else if (pid < 0) {
476 rprintf(FERROR,
477 RSYNC_NAME
478 ": could not create child server process: %s\n",
479 strerror(errno));
480 close(fd);
481 /* This might have happened because we're
482 * overloaded. Sleep briefly before trying to
483 * accept again. */
484 sleep(2);
485 } else {
486 /* Parent doesn't need this fd anymore. */
487 close(fd);
488 }
489 }
490 free(sp);
491}
492
493
494enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};
495
496struct
497{
498 char *name;
499 int level;
500 int option;
501 int value;
502 int opttype;
503} socket_options[] = {
504 {"SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE, 0, OPT_BOOL},
505 {"SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR, 0, OPT_BOOL},
506 {"SO_BROADCAST", SOL_SOCKET, SO_BROADCAST, 0, OPT_BOOL},
507#ifdef TCP_NODELAY
508 {"TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY, 0, OPT_BOOL},
509#endif
510#ifdef IPTOS_LOWDELAY
511 {"IPTOS_LOWDELAY", IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY, OPT_ON},
512#endif
513#ifdef IPTOS_THROUGHPUT
514 {"IPTOS_THROUGHPUT", IPPROTO_IP, IP_TOS, IPTOS_THROUGHPUT, OPT_ON},
515#endif
516#ifdef SO_SNDBUF
517 {"SO_SNDBUF", SOL_SOCKET, SO_SNDBUF, 0, OPT_INT},
518#endif
519#ifdef SO_RCVBUF
520 {"SO_RCVBUF", SOL_SOCKET, SO_RCVBUF, 0, OPT_INT},
521#endif
522#ifdef SO_SNDLOWAT
523 {"SO_SNDLOWAT", SOL_SOCKET, SO_SNDLOWAT, 0, OPT_INT},
524#endif
525#ifdef SO_RCVLOWAT
526 {"SO_RCVLOWAT", SOL_SOCKET, SO_RCVLOWAT, 0, OPT_INT},
527#endif
528#ifdef SO_SNDTIMEO
529 {"SO_SNDTIMEO", SOL_SOCKET, SO_SNDTIMEO, 0, OPT_INT},
530#endif
531#ifdef SO_RCVTIMEO
532 {"SO_RCVTIMEO", SOL_SOCKET, SO_RCVTIMEO, 0, OPT_INT},
533#endif
534 {NULL,0,0,0,0}};
535
536
537
538/**
539 * Set user socket options
540 **/
541void set_socket_options(int fd, char *options)
542{
543 char *tok;
544
545 if (!options || !*options)
546 return;
547
548 options = strdup(options);
549
550 if (!options)
551 out_of_memory("set_socket_options");
552
553 for (tok = strtok(options, " \t,"); tok; tok = strtok(NULL," \t,")) {
554 int ret=0,i;
555 int value = 1;
556 char *p;
557 int got_value = 0;
558
559 if ((p = strchr(tok,'='))) {
560 *p = 0;
561 value = atoi(p+1);
562 got_value = 1;
563 }
564
565 for (i = 0; socket_options[i].name; i++) {
566 if (strcmp(socket_options[i].name,tok)==0)
567 break;
568 }
569
570 if (!socket_options[i].name) {
571 rprintf(FERROR,"Unknown socket option %s\n",tok);
572 continue;
573 }
574
575 switch (socket_options[i].opttype) {
576 case OPT_BOOL:
577 case OPT_INT:
578 ret = setsockopt(fd,socket_options[i].level,
579 socket_options[i].option,(char *)&value,sizeof(int));
580 break;
581
582 case OPT_ON:
583 if (got_value)
584 rprintf(FERROR,"syntax error - %s does not take a value\n",tok);
585
586 {
587 int on = socket_options[i].value;
588 ret = setsockopt(fd,socket_options[i].level,
589 socket_options[i].option,(char *)&on,sizeof(int));
590 }
591 break;
592 }
593
594 if (ret != 0)
595 rprintf(FERROR, "failed to set socket option %s: %s\n", tok,
596 strerror(errno));
597 }
598
599 free(options);
600}
601
602/**
603 * Become a daemon, discarding the controlling terminal
604 **/
605void become_daemon(void)
606{
607 int i;
608
609 if (fork()) {
610 _exit(0);
611 }
612
613 /* detach from the terminal */
614#ifdef HAVE_SETSID
615 setsid();
616#else
617#ifdef TIOCNOTTY
618 i = open("/dev/tty", O_RDWR);
619 if (i >= 0) {
620 ioctl(i, (int)TIOCNOTTY, (char *)0);
621 close(i);
622 }
623#endif /* TIOCNOTTY */
624#endif
625 /* make sure that stdin, stdout an stderr don't stuff things
626 up (library functions, for example) */
627 for (i = 0; i < 3; i++) {
628 close(i);
629 open("/dev/null", O_RDWR);
630 }
631}
632
633
634/**
635 * This is like socketpair but uses tcp. It is used by the Samba
636 * regression test code.
637 *
638 * The function guarantees that nobody else can attach to the socket,
639 * or if they do that this function fails and the socket gets closed
640 * returns 0 on success, -1 on failure the resulting file descriptors
641 * are symmetrical.
642 **/
643static int socketpair_tcp(int fd[2])
644{
645 int listener;
646 struct sockaddr_in sock;
647 struct sockaddr_in sock2;
648 socklen_t socklen = sizeof(sock);
649 int connect_done = 0;
650
651 fd[0] = fd[1] = listener = -1;
652
653 memset(&sock, 0, sizeof(sock));
654
655 if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
656 goto failed;
657
658 memset(&sock2, 0, sizeof(sock2));
659#ifdef HAVE_SOCKADDR_LEN
660 sock2.sin_len = sizeof(sock2);
661#endif
662 sock2.sin_family = PF_INET;
663
664 bind(listener, (struct sockaddr *)&sock2, sizeof(sock2));
665
666 if (listen(listener, 1) != 0)
667 goto failed;
668
669 if (getsockname(listener, (struct sockaddr *)&sock, &socklen) != 0)
670 goto failed;
671
672 if ((fd[1] = socket(PF_INET, SOCK_STREAM, 0)) == -1)
673 goto failed;
674
675 set_nonblocking(fd[1]);
676
677 sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
678
679 if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) == -1) {
680 if (errno != EINPROGRESS)
681 goto failed;
682 } else
683 connect_done = 1;
684
685 if ((fd[0] = accept(listener, (struct sockaddr *)&sock, &socklen)) == -1)
686 goto failed;
687
688 close(listener);
689 if (connect_done == 0) {
690 if (connect(fd[1],(struct sockaddr *)&sock,sizeof(sock)) != 0
691 && errno != EISCONN)
692 goto failed;
693 }
694
695 set_blocking(fd[1]);
696
697 /* all OK! */
698 return 0;
699
700 failed:
701 if (fd[0] != -1)
702 close(fd[0]);
703 if (fd[1] != -1)
704 close(fd[1]);
705 if (listener != -1)
706 close(listener);
707 return -1;
708}
709
710
711
712/**
713 * Run a program on a local tcp socket, so that we can talk to it's
714 * stdin and stdout. This is used to fake a connection to a daemon
715 * for testing -- not for the normal case of running SSH.
716 *
717 * @return a socket which is attached to a subprocess running
718 * "prog". stdin and stdout are attached. stderr is left attached to
719 * the original stderr
720 **/
721int sock_exec(const char *prog)
722{
723 int fd[2];
724
725 if (socketpair_tcp(fd) != 0) {
726 rprintf(FERROR, RSYNC_NAME ": socketpair_tcp failed (%s)\n",
727 strerror(errno));
728 return -1;
729 }
730 if (fork() == 0) {
731 close(fd[0]);
732 close(0);
733 close(1);
734 dup(fd[1]);
735 dup(fd[1]);
736 if (verbose > 3) {
737 /* Can't use rprintf because we've forked. */
738 fprintf(stderr,
739 RSYNC_NAME ": execute socket program \"%s\"\n",
740 prog);
741 }
742 exit(system(prog));
743 }
744 close(fd[1]);
745 return fd[0];
746}