2 net_socket.c -- Handle various kinds of sockets.
3 Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "connection.h"
33 /* Needed on Mac OS/X */
35 #define SOL_TCP IPPROTO_TCP
38 int addressfamily = AF_UNSPEC;
40 int seconds_till_retry = 5;
41 int max_connection_burst = 100;
43 listen_socket_t listen_socket[MAXSOCKETS];
45 list_t *outgoing_list = NULL;
49 static void configure_tcp(connection_t *c) {
53 int flags = fcntl(c->socket, F_GETFL);
55 if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
56 logger(DEBUG_ALWAYS, LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
59 unsigned long arg = 1;
61 if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
62 logger(DEBUG_ALWAYS, LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
66 #if defined(SOL_TCP) && defined(TCP_NODELAY)
68 setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
71 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
72 option = IPTOS_LOWDELAY;
73 setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
77 static bool bind_to_address(connection_t *c) {
80 for(int i = 0; i < listen_sockets && listen_socket[i].bindto; i++) {
81 if(listen_socket[i].sa.sa.sa_family != c->address.sa.sa_family)
91 sockaddr_t sa = listen_socket[s].sa;
92 if(sa.sa.sa_family == AF_INET)
94 else if(sa.sa.sa_family == AF_INET6)
97 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
98 logger(DEBUG_CONNECTIONS, LOG_WARNING, "Can't bind outgoing socket: %s", strerror(errno));
105 int setup_listen_socket(const sockaddr_t *sa) {
111 nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
114 logger(DEBUG_STATUS, LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
119 fcntl(nfd, F_SETFD, FD_CLOEXEC);
122 /* Optimize TCP settings */
125 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
127 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
128 if(sa->sa.sa_family == AF_INET6)
129 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
133 (lookup_config(config_tree, "BindToInterface"), &iface)) {
134 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
137 memset(&ifr, 0, sizeof ifr);
138 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
140 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
142 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to interface %s: %s", iface,
143 strerror(sockerrno));
147 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "BindToInterface");
151 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
153 addrstr = sockaddr2hostname(sa);
154 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
161 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
168 int setup_vpn_in_socket(const sockaddr_t *sa) {
173 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
176 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
181 fcntl(nfd, F_SETFD, FD_CLOEXEC);
186 int flags = fcntl(nfd, F_GETFL);
188 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
190 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
197 unsigned long arg = 1;
198 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
200 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
207 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
208 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
210 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
211 if(sa->sa.sa_family == AF_INET6)
212 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
215 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
216 #define IP_DONTFRAGMENT IP_DONTFRAG
219 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
220 if(myself->options & OPTION_PMTU_DISCOVERY) {
221 option = IP_PMTUDISC_DO;
222 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
224 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
225 if(myself->options & OPTION_PMTU_DISCOVERY) {
227 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
230 #warning No way to disable IPv4 fragmentation
233 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
234 if(myself->options & OPTION_PMTU_DISCOVERY) {
235 option = IPV6_PMTUDISC_DO;
236 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
238 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
239 if(myself->options & OPTION_PMTU_DISCOVERY) {
241 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
244 #warning No way to disable IPv6 fragmentation
247 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
249 addrstr = sockaddr2hostname(sa);
250 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
256 } /* int setup_vpn_in_socket */
258 static void retry_outgoing_handler(void *data) {
259 setup_outgoing_connection(data);
262 void retry_outgoing(outgoing_t *outgoing) {
263 outgoing->timeout += 5;
265 if(outgoing->timeout > maxtimeout)
266 outgoing->timeout = maxtimeout;
268 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
270 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
273 void finish_connecting(connection_t *c) {
274 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
276 c->last_ping_time = now.tv_sec;
277 c->status.connecting = false;
282 static void do_outgoing_pipe(connection_t *c, char *command) {
286 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
287 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
294 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
305 // Other filedescriptors should be closed automatically by CLOEXEC
310 sockaddr2str(&c->address, &host, &port);
311 setenv("REMOTEADDRESS", host, true);
312 setenv("REMOTEPORT", port, true);
313 setenv("NODE", c->name, true);
314 setenv("NAME", myself->name, true);
316 int result = system(command);
318 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
320 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
323 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
328 static void handle_meta_write(connection_t *c) {
329 if(c->outbuf.len <= c->outbuf.offset)
332 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
334 if(!errno || errno == EPIPE) {
335 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
336 } else if(sockwouldblock(sockerrno)) {
337 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
340 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not send %d bytes of data to %s (%s): %s", c->outbuf.len - c->outbuf.offset, c->name, c->hostname, strerror(errno));
343 terminate_connection(c, c->status.active);
347 buffer_read(&c->outbuf, outlen);
349 io_set(&c->io, IO_READ);
352 static void handle_meta_io(void *data, int flags) {
353 connection_t *c = data;
355 if(c->status.connecting) {
356 c->status.connecting = false;
359 socklen_t len = sizeof result;
360 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
363 finish_connecting(c);
365 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
366 terminate_connection(c, false);
372 handle_meta_write(c);
374 handle_meta_connection_data(c);
377 bool do_outgoing_connection(outgoing_t *outgoing) {
378 char *address, *port, *space;
379 struct addrinfo *proxyai = NULL;
385 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
386 retry_outgoing(outgoing);
390 get_config_string(outgoing->cfg, &address);
392 space = strchr(address, ' ');
394 port = xstrdup(space + 1);
397 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
398 port = xstrdup("655");
401 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
405 outgoing->aip = outgoing->ai;
406 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
411 freeaddrinfo(outgoing->ai);
416 connection_t *c = new_connection();
417 c->outgoing = outgoing;
419 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
420 outgoing->aip = outgoing->aip->ai_next;
422 c->hostname = sockaddr2hostname(&c->address);
424 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
427 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
429 } else if(proxytype == PROXY_EXEC) {
430 do_outgoing_pipe(c, proxyhost);
432 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
437 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
438 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
442 if(c->socket == -1) {
443 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
449 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
452 if(proxytype != PROXY_EXEC) {
453 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
455 if(c->address.sa.sa_family == AF_INET6)
456 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
465 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
466 } else if(proxytype == PROXY_EXEC) {
469 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
470 freeaddrinfo(proxyai);
473 if(result == -1 && !sockinprogress(sockerrno)) {
474 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
480 /* Now that there is a working socket, fill in the rest and register this connection. */
482 c->status.connecting = true;
483 c->name = xstrdup(outgoing->name);
484 c->outcipher = myself->connection->outcipher;
485 c->outdigest = myself->connection->outdigest;
486 c->outmaclength = myself->connection->outmaclength;
487 c->outcompression = myself->connection->outcompression;
488 c->last_ping_time = now.tv_sec;
492 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
497 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
498 static struct addrinfo *get_known_addresses(node_t *n) {
499 struct addrinfo *ai = NULL;
501 for splay_each(edge_t, e, n->edge_tree) {
506 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
507 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
515 struct addrinfo *nai = xzalloc(sizeof *nai);
519 ai->ai_family = e->reverse->address.sa.sa_family;
520 ai->ai_socktype = SOCK_STREAM;
521 ai->ai_protocol = IPPROTO_TCP;
522 ai->ai_addrlen = SALEN(e->reverse->address.sa);
523 ai->ai_addr = xmalloc(ai->ai_addrlen);
524 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
530 void setup_outgoing_connection(outgoing_t *outgoing) {
531 timeout_del(&outgoing->ev);
533 node_t *n = lookup_node(outgoing->name);
535 if(n && n->connection) {
536 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
538 n->connection->outgoing = outgoing;
542 init_configuration(&outgoing->config_tree);
543 read_host_config(outgoing->config_tree, outgoing->name);
544 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
548 outgoing->aip = outgoing->ai = get_known_addresses(n);
550 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
555 do_outgoing_connection(outgoing);
559 accept a new tcp connect and create a
562 void handle_new_meta_connection(void *data, int flags) {
563 listen_socket_t *l = data;
567 socklen_t len = sizeof sa;
569 fd = accept(l->tcp.fd, &sa.sa, &len);
572 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
578 // Check if we get many connections from the same host
580 static sockaddr_t prev_sa;
581 static int tarpit = -1;
588 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
589 static int samehost_burst;
590 static int samehost_burst_time;
592 if(now.tv_sec - samehost_burst_time > samehost_burst)
595 samehost_burst -= now.tv_sec - samehost_burst_time;
597 samehost_burst_time = now.tv_sec;
600 if(samehost_burst > max_connection_burst) {
606 memcpy(&prev_sa, &sa, sizeof sa);
608 // Check if we get many connections from different hosts
610 static int connection_burst;
611 static int connection_burst_time;
613 if(now.tv_sec - connection_burst_time > connection_burst)
614 connection_burst = 0;
616 connection_burst -= now.tv_sec - connection_burst_time;
618 connection_burst_time = now.tv_sec;
621 if(connection_burst >= max_connection_burst) {
622 connection_burst = max_connection_burst;
627 // Accept the new connection
629 c = new_connection();
630 c->name = xstrdup("<unknown>");
631 c->outcipher = myself->connection->outcipher;
632 c->outdigest = myself->connection->outdigest;
633 c->outmaclength = myself->connection->outmaclength;
634 c->outcompression = myself->connection->outcompression;
637 c->hostname = sockaddr2hostname(&sa);
639 c->last_ping_time = now.tv_sec;
641 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
643 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
649 c->allow_request = ID;
653 static void free_outgoing(outgoing_t *outgoing) {
654 timeout_del(&outgoing->ev);
657 freeaddrinfo(outgoing->ai);
659 if(outgoing->config_tree)
660 exit_configuration(&outgoing->config_tree);
663 free(outgoing->name);
668 void try_outgoing_connections(void) {
669 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
672 outgoing_list = list_alloc((list_action_t)free_outgoing);
674 for list_each(outgoing_t, outgoing, outgoing_list)
675 outgoing->timeout = -1;
678 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
680 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
682 get_config_string(cfg, &name);
684 if(!check_id(name)) {
685 logger(DEBUG_ALWAYS, LOG_ERR,
686 "Invalid name for outgoing connection in %s line %d",
687 cfg->file, cfg->line);
694 for list_each(outgoing_t, outgoing, outgoing_list) {
695 if(!strcmp(outgoing->name, name)) {
697 outgoing->timeout = 0;
703 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
704 outgoing->name = name;
705 list_insert_tail(outgoing_list, outgoing);
706 setup_outgoing_connection(outgoing);
710 /* Terminate any connections whose outgoing_t is to be deleted. */
712 for list_each(connection_t, c, connection_list) {
713 if(c->outgoing && c->outgoing->timeout == -1) {
715 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
716 terminate_connection(c, c->status.active);
720 /* Delete outgoing_ts for which there is no ConnectTo. */
722 for list_each(outgoing_t, outgoing, outgoing_list)
723 if(outgoing->timeout == -1)
724 list_delete_node(outgoing_list, node);