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);
132 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
134 addrstr = sockaddr2hostname(sa);
135 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
142 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
149 int setup_vpn_in_socket(const sockaddr_t *sa) {
154 nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
157 logger(DEBUG_ALWAYS, LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
162 fcntl(nfd, F_SETFD, FD_CLOEXEC);
167 int flags = fcntl(nfd, F_GETFL);
169 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
171 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "fcntl",
178 unsigned long arg = 1;
179 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
181 logger(DEBUG_ALWAYS, LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
188 setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
189 setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof option);
191 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
192 if(sa->sa.sa_family == AF_INET6)
193 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
196 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
197 #define IP_DONTFRAGMENT IP_DONTFRAG
200 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
201 if(myself->options & OPTION_PMTU_DISCOVERY) {
202 option = IP_PMTUDISC_DO;
203 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
205 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
206 if(myself->options & OPTION_PMTU_DISCOVERY) {
208 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
211 #warning No way to disable IPv4 fragmentation
214 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
215 if(myself->options & OPTION_PMTU_DISCOVERY) {
216 option = IPV6_PMTUDISC_DO;
217 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
219 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
220 if(myself->options & OPTION_PMTU_DISCOVERY) {
222 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
225 #warning No way to disable IPv6 fragmentation
228 if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
230 addrstr = sockaddr2hostname(sa);
231 logger(DEBUG_ALWAYS, LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
237 } /* int setup_vpn_in_socket */
239 static void retry_outgoing_handler(void *data) {
240 setup_outgoing_connection(data);
243 void retry_outgoing(outgoing_t *outgoing) {
244 outgoing->timeout += 5;
246 if(outgoing->timeout > maxtimeout)
247 outgoing->timeout = maxtimeout;
249 timeout_add(&outgoing->ev, retry_outgoing_handler, outgoing, &(struct timeval){outgoing->timeout, rand() % 100000});
251 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Trying to re-establish outgoing connection in %d seconds", outgoing->timeout);
254 void finish_connecting(connection_t *c) {
255 logger(DEBUG_CONNECTIONS, LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
257 c->last_ping_time = now.tv_sec;
258 c->status.connecting = false;
263 static void do_outgoing_pipe(connection_t *c, char *command) {
267 if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
268 logger(DEBUG_ALWAYS, LOG_ERR, "Could not create socketpair: %s", strerror(errno));
275 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Using proxy %s", command);
286 // Other filedescriptors should be closed automatically by CLOEXEC
291 sockaddr2str(&c->address, &host, &port);
292 setenv("REMOTEADDRESS", host, true);
293 setenv("REMOTEPORT", port, true);
294 setenv("NODE", c->name, true);
295 setenv("NAME", myself->name, true);
297 int result = system(command);
299 logger(DEBUG_ALWAYS, LOG_ERR, "Could not execute %s: %s", command, strerror(errno));
301 logger(DEBUG_ALWAYS, LOG_ERR, "%s exited with non-zero status %d", command, result);
304 logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type exec not supported on this platform!");
309 static void handle_meta_write(connection_t *c) {
310 if(c->outbuf.len <= c->outbuf.offset)
313 ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
315 if(!errno || errno == EPIPE) {
316 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection closed by %s (%s)", c->name, c->hostname);
317 } else if(sockwouldblock(sockerrno)) {
318 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Sending %d bytes to %s (%s) would block", c->outbuf.len - c->outbuf.offset, c->name, c->hostname);
321 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));
324 terminate_connection(c, c->status.active);
328 buffer_read(&c->outbuf, outlen);
330 io_set(&c->io, IO_READ);
333 static void handle_meta_io(void *data, int flags) {
334 connection_t *c = data;
336 if(c->status.connecting) {
337 c->status.connecting = false;
340 socklen_t len = sizeof result;
341 getsockopt(c->socket, SOL_SOCKET, SO_ERROR, (void *)&result, &len);
344 finish_connecting(c);
346 logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Error while connecting to %s (%s): %s", c->name, c->hostname, sockstrerror(result));
347 terminate_connection(c, false);
353 handle_meta_write(c);
355 handle_meta_connection_data(c);
358 bool do_outgoing_connection(outgoing_t *outgoing) {
359 char *address, *port, *space;
360 struct addrinfo *proxyai = NULL;
366 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not set up a meta connection to %s", outgoing->name);
367 retry_outgoing(outgoing);
371 get_config_string(outgoing->cfg, &address);
373 space = strchr(address, ' ');
375 port = xstrdup(space + 1);
378 // TODO: Only allow Address statements?
379 if(!get_config_string(lookup_config(outgoing->config_tree, "Port"), &port))
380 port = xstrdup("655");
383 outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
387 outgoing->aip = outgoing->ai;
388 outgoing->cfg = lookup_config_next(outgoing->config_tree, outgoing->cfg);
393 freeaddrinfo(outgoing->ai);
398 connection_t *c = new_connection();
399 c->outgoing = outgoing;
401 memcpy(&c->address, outgoing->aip->ai_addr, outgoing->aip->ai_addrlen);
402 outgoing->aip = outgoing->aip->ai_next;
404 c->hostname = sockaddr2hostname(&c->address);
406 logger(DEBUG_CONNECTIONS, LOG_INFO, "Trying to connect to %s (%s)", outgoing->name, c->hostname);
409 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
411 } else if(proxytype == PROXY_EXEC) {
412 do_outgoing_pipe(c, proxyhost);
414 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
419 logger(DEBUG_CONNECTIONS, LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
420 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
424 if(c->socket == -1) {
425 logger(DEBUG_CONNECTIONS, LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
431 fcntl(c->socket, F_SETFD, FD_CLOEXEC);
434 if(proxytype != PROXY_EXEC) {
435 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
437 if(c->address.sa.sa_family == AF_INET6)
438 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
447 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
448 } else if(proxytype == PROXY_EXEC) {
451 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
452 freeaddrinfo(proxyai);
455 if(result == -1 && !sockinprogress(sockerrno)) {
456 logger(DEBUG_CONNECTIONS, LOG_ERR, "Could not connect to %s (%s): %s", outgoing->name, c->hostname, sockstrerror(sockerrno));
462 /* Now that there is a working socket, fill in the rest and register this connection. */
464 c->status.connecting = true;
465 c->name = xstrdup(outgoing->name);
466 c->outcompression = myself->connection->outcompression;
467 c->last_ping_time = now.tv_sec;
471 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ|IO_WRITE);
476 // Find edges pointing to this node, and use them to build a list of unique, known addresses.
477 static struct addrinfo *get_known_addresses(node_t *n) {
478 struct addrinfo *ai = NULL;
480 for splay_each(edge_t, e, n->edge_tree) {
485 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
486 if(!sockaddrcmp(&e->reverse->address, (sockaddr_t *)aip->ai_addr)) {
494 struct addrinfo *nai = xzalloc(sizeof *nai);
498 ai->ai_family = e->reverse->address.sa.sa_family;
499 ai->ai_socktype = SOCK_STREAM;
500 ai->ai_protocol = IPPROTO_TCP;
501 ai->ai_addrlen = SALEN(e->reverse->address.sa);
502 ai->ai_addr = xmalloc(ai->ai_addrlen);
503 memcpy(ai->ai_addr, &e->reverse->address, ai->ai_addrlen);
509 void setup_outgoing_connection(outgoing_t *outgoing) {
510 timeout_del(&outgoing->ev);
512 node_t *n = lookup_node(outgoing->name);
514 if(n && n->connection) {
515 logger(DEBUG_CONNECTIONS, LOG_INFO, "Already connected to %s", outgoing->name);
517 n->connection->outgoing = outgoing;
521 init_configuration(&outgoing->config_tree);
522 read_host_config(outgoing->config_tree, outgoing->name);
523 outgoing->cfg = lookup_config(outgoing->config_tree, "Address");
527 outgoing->aip = outgoing->ai = get_known_addresses(n);
529 logger(DEBUG_ALWAYS, LOG_ERR, "No address known for %s", outgoing->name);
534 do_outgoing_connection(outgoing);
538 accept a new tcp connect and create a
541 void handle_new_meta_connection(void *data, int flags) {
542 listen_socket_t *l = data;
546 socklen_t len = sizeof sa;
548 fd = accept(l->tcp.fd, &sa.sa, &len);
551 logger(DEBUG_ALWAYS, LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
557 // Check if we get many connections from the same host
559 static sockaddr_t prev_sa;
560 static int tarpit = -1;
567 if(!sockaddrcmp_noport(&sa, &prev_sa)) {
568 static int samehost_burst;
569 static int samehost_burst_time;
571 if(now.tv_sec - samehost_burst_time > samehost_burst)
574 samehost_burst -= now.tv_sec - samehost_burst_time;
576 samehost_burst_time = now.tv_sec;
579 if(samehost_burst > max_connection_burst) {
585 memcpy(&prev_sa, &sa, sizeof sa);
587 // Check if we get many connections from different hosts
589 static int connection_burst;
590 static int connection_burst_time;
592 if(now.tv_sec - connection_burst_time > connection_burst)
593 connection_burst = 0;
595 connection_burst -= now.tv_sec - connection_burst_time;
597 connection_burst_time = now.tv_sec;
600 if(connection_burst >= max_connection_burst) {
601 connection_burst = max_connection_burst;
606 // Accept the new connection
608 c = new_connection();
609 c->name = xstrdup("<unknown>");
610 c->outcompression = myself->connection->outcompression;
613 c->hostname = sockaddr2hostname(&sa);
615 c->last_ping_time = now.tv_sec;
617 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection from %s", c->hostname);
619 io_add(&c->io, handle_meta_io, c, c->socket, IO_READ);
625 c->allow_request = ID;
629 static void free_outgoing(outgoing_t *outgoing) {
630 timeout_del(&outgoing->ev);
633 freeaddrinfo(outgoing->ai);
635 if(outgoing->config_tree)
636 exit_configuration(&outgoing->config_tree);
639 free(outgoing->name);
644 void try_outgoing_connections(void) {
645 /* If there is no outgoing list yet, create one. Otherwise, mark all outgoings as deleted. */
648 outgoing_list = list_alloc((list_action_t)free_outgoing);
650 for list_each(outgoing_t, outgoing, outgoing_list)
651 outgoing->timeout = -1;
654 /* Make sure there is one outgoing_t in the list for each ConnectTo. */
656 // TODO: Drop support for ConnectTo since AutoConnect is now always on?
657 for(config_t *cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
659 get_config_string(cfg, &name);
661 if(!check_id(name)) {
662 logger(DEBUG_ALWAYS, LOG_ERR,
663 "Invalid name for outgoing connection in %s line %d",
664 cfg->file, cfg->line);
671 for list_each(outgoing_t, outgoing, outgoing_list) {
672 if(!strcmp(outgoing->name, name)) {
674 outgoing->timeout = 0;
680 outgoing_t *outgoing = xzalloc(sizeof *outgoing);
681 outgoing->name = name;
682 list_insert_tail(outgoing_list, outgoing);
683 setup_outgoing_connection(outgoing);
687 /* Terminate any connections whose outgoing_t is to be deleted. */
689 for list_each(connection_t, c, connection_list) {
690 if(c->outgoing && c->outgoing->timeout == -1) {
692 logger(DEBUG_CONNECTIONS, LOG_INFO, "No more outgoing connection to %s", c->name);
693 terminate_connection(c, c->status.active);
697 /* Delete outgoing_ts for which there is no ConnectTo. */
699 for list_each(outgoing_t, outgoing, outgoing_list)
700 if(outgoing->timeout == -1)
701 list_delete_node(outgoing_list, node);