Use threads for TCP connections.
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2009      Florian Forster <octo@verplant.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 along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include "splay_tree.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "logger.h"
29 #include "meta.h"
30 #include "net.h"
31 #include "netutl.h"
32 #include "protocol.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 #include <assert.h>
37
38 /* Needed on Mac OS/X */
39 #ifndef SOL_TCP
40 #define SOL_TCP IPPROTO_TCP
41 #endif
42
43 int addressfamily = AF_UNSPEC;
44 int maxtimeout = 900;
45 int seconds_till_retry = 5;
46 int udp_rcvbuf = 0;
47 int udp_sndbuf = 0;
48
49 listen_socket_t listen_socket[MAXSOCKETS];
50 int listen_sockets;
51 list_t *outgoing_list = NULL;
52
53 /* Setup sockets */
54
55 static void configure_tcp(connection_t *c) {
56         int option;
57
58 #if defined(SOL_TCP) && defined(TCP_NODELAY)
59         option = 1;
60         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof option);
61 #endif
62
63 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
64         option = IPTOS_LOWDELAY;
65         setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof option);
66 #endif
67 }
68
69 static bool bind_to_interface(int sd) {
70         char *iface;
71
72 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
73         struct ifreq ifr;
74         int status;
75 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
76
77         if(!get_config_string (lookup_config (config_tree, "BindToInterface"), &iface))
78                 return true;
79
80 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
81         memset(&ifr, 0, sizeof(ifr));
82         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
83         ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
84
85         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
86         if(status) {
87                 logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
88                                 strerror(errno));
89                 return false;
90         }
91 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
92         logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
93 #endif
94
95         return true;
96 }
97
98 static bool bind_to_address(connection_t *c) {
99         char *node;
100         struct addrinfo *ai_list;
101         struct addrinfo *ai_ptr;
102         struct addrinfo ai_hints;
103         int status;
104
105         assert(c != NULL);
106         assert(c->socket >= 0);
107
108         node = NULL;
109         if(!get_config_string(lookup_config(config_tree, "BindToAddress"),
110                                 &node))
111                 return true;
112
113         assert(node != NULL);
114
115         memset(&ai_hints, 0, sizeof(ai_hints));
116         ai_hints.ai_family = c->address.sa.sa_family;
117         /* We're called from `do_outgoing_connection' only. */
118         ai_hints.ai_socktype = SOCK_STREAM;
119         ai_hints.ai_protocol = IPPROTO_TCP;
120
121         ai_list = NULL;
122
123         status = getaddrinfo(node, /* service = */ NULL,
124                         &ai_hints, &ai_list);
125         if(status) {
126                 free(node);
127                 logger(LOG_WARNING, "Error looking up %s port %s: %s",
128                                 node, "any", gai_strerror(status));
129                 return false;
130         }
131         assert(ai_list != NULL);
132
133         status = -1;
134         for(ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) {
135                 status = bind(c->socket,
136                                 ai_list->ai_addr, ai_list->ai_addrlen);
137                 if(!status)
138                         break;
139         }
140
141
142         if(status) {
143                 logger(LOG_ERR, "Can't bind to %s/tcp: %s", node, sockstrerror(sockerrno));
144         } else ifdebug(CONNECTIONS) {
145                 logger(LOG_DEBUG, "Successfully bound outgoing "
146                                 "TCP socket to %s", node);
147         }
148
149         free(node);
150         freeaddrinfo(ai_list);
151
152         return status ? false : true;
153 }
154
155 int setup_listen_socket(const sockaddr_t *sa) {
156         int nfd;
157         char *addrstr;
158         int option;
159         char *iface;
160
161         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
162
163         if(nfd < 0) {
164                 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
165                 return -1;
166         }
167
168         /* Optimize TCP settings */
169
170         option = 1;
171         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
172
173 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
174         if(sa->sa.sa_family == AF_INET6)
175                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
176 #endif
177
178         if(get_config_string
179            (lookup_config(config_tree, "BindToInterface"), &iface)) {
180 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
181                 struct ifreq ifr;
182
183                 memset(&ifr, 0, sizeof ifr);
184                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
185
186                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof ifr)) {
187                         closesocket(nfd);
188                         logger(LOG_ERR, "Can't bind to interface %s: %s", iface,
189                                    strerror(sockerrno));
190                         return -1;
191                 }
192 #else
193                 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
194 #endif
195         }
196
197         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
198                 closesocket(nfd);
199                 addrstr = sockaddr2hostname(sa);
200                 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
201                 free(addrstr);
202                 return -1;
203         }
204
205         if(listen(nfd, 3)) {
206                 closesocket(nfd);
207                 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
208                 return -1;
209         }
210
211         return nfd;
212 }
213
214 int setup_vpn_in_socket(const sockaddr_t *sa) {
215         int nfd;
216         char *addrstr;
217         int option;
218
219         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
220
221         if(nfd < 0) {
222                 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
223                 return -1;
224         }
225
226         option = 1;
227         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
228
229         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
230                 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
231
232         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
233                 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
234
235 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
236         if(sa->sa.sa_family == AF_INET6)
237                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
238 #endif
239
240 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
241 #define IP_DONTFRAGMENT IP_DONTFRAG
242 #endif
243
244 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
245         if(myself->options & OPTION_PMTU_DISCOVERY) {
246                 option = IP_PMTUDISC_DO;
247                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
248         }
249 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
250         if(myself->options & OPTION_PMTU_DISCOVERY) {
251                 option = 1;
252                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
253         }
254 #else
255 #warning No way to disable IPv4 fragmentation
256 #endif
257
258 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
259         if(myself->options & OPTION_PMTU_DISCOVERY) {
260                 option = IPV6_PMTUDISC_DO;
261                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
262         }
263 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
264         if(myself->options & OPTION_PMTU_DISCOVERY) {
265                 option = 1;
266                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
267         }
268 #else
269 #warning No way to disable IPv6 fragmentation
270 #endif
271
272         if (!bind_to_interface(nfd)) {
273                 closesocket(nfd);
274                 return -1;
275         }
276
277         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
278                 closesocket(nfd);
279                 addrstr = sockaddr2hostname(sa);
280                 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
281                 free(addrstr);
282                 return -1;
283         }
284
285         return nfd;
286 } /* int setup_vpn_in_socket */
287
288 static void retry_outgoing_handler(int fd, short events, void *data) {
289         setup_outgoing_connection(data);
290 }
291
292 void retry_outgoing(outgoing_t *outgoing) {
293         outgoing->timeout += 5;
294
295         if(outgoing->timeout > maxtimeout)
296                 outgoing->timeout = maxtimeout;
297
298         timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
299         event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
300
301         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
302                            "Trying to re-establish outgoing connection in %d seconds",
303                            outgoing->timeout);
304 }
305
306 void finish_connecting(connection_t *c) {
307         ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
308
309         configure_tcp(c);
310
311         c->last_ping_time = time(NULL);
312         c->status.connecting = false;
313
314         send_id(c);
315 }
316
317 void do_outgoing_connection(connection_t *c) {
318         char *address, *port, *space;
319         int result;
320
321         if(!c->outgoing) {
322                 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
323                 abort();
324         }
325
326 begin:
327         if(!c->outgoing->ai) {
328                 if(!c->outgoing->cfg) {
329                         ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
330                                            c->name);
331                         retry_outgoing(c->outgoing);
332                         c->outgoing = NULL;
333                         connection_del(c);
334                         return;
335                 }
336
337                 get_config_string(c->outgoing->cfg, &address);
338
339                 space = strchr(address, ' ');
340                 if(space) {
341                         port = xstrdup(space + 1);
342                         *space = 0;
343                 } else {
344                         if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
345                                 port = xstrdup("655");
346                 }
347
348                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
349                 free(address);
350                 free(port);
351
352                 c->outgoing->aip = c->outgoing->ai;
353                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
354         }
355
356         if(!c->outgoing->aip) {
357                 if(c->outgoing->ai)
358                         freeaddrinfo(c->outgoing->ai);
359                 c->outgoing->ai = NULL;
360                 goto begin;
361         }
362
363         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
364         c->outgoing->aip = c->outgoing->aip->ai_next;
365
366         if(c->hostname)
367                 free(c->hostname);
368
369         c->hostname = sockaddr2hostname(&c->address);
370
371         ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
372                            c->hostname);
373
374         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
375
376         if(c->socket == -1) {
377                 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
378                 goto begin;
379         }
380
381 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
382         int option = 1;
383         if(c->address.sa.sa_family == AF_INET6)
384                 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
385 #endif
386
387         bind_to_interface(c->socket);
388         bind_to_address(c);
389
390         /* Optimize TCP settings */
391
392         configure_tcp(c);
393
394         /* Connect */
395
396         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
397
398         if(result == -1) {
399                 if(sockinprogress(sockerrno)) {
400                         c->status.connecting = true;
401                         return;
402                 }
403
404                 closesocket(c->socket);
405
406                 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
407
408                 goto begin;
409         }
410
411         finish_connecting(c);
412
413         return;
414 }
415
416 void handle_meta_read(struct bufferevent *event, void *data) {
417         logger(LOG_ERR, "handle_meta_read() called");
418         abort();
419 }
420
421 void handle_meta_write(struct bufferevent *event, void *data) {
422         ifdebug(META) logger(LOG_DEBUG, "handle_meta_write() called");
423 }
424
425 void handle_meta_connection_error(struct bufferevent *event, short what, void *data) {
426         connection_t *c = data;
427         logger(LOG_ERR, "handle_meta_connection_error() called: %d: %s", what, strerror(errno));
428         terminate_connection(c, c->status.active);
429 }
430
431 void setup_outgoing_connection(outgoing_t *outgoing) {
432         connection_t *c;
433         node_t *n;
434
435         event_del(&outgoing->ev);
436
437         n = lookup_node(outgoing->name);
438
439         if(n)
440                 if(n->connection) {
441                         ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
442
443                         n->connection->outgoing = outgoing;
444                         return;
445                 }
446
447         c = new_connection();
448         c->name = xstrdup(outgoing->name);
449         c->outcipher = myself->connection->outcipher;
450         c->outdigest = myself->connection->outdigest;
451         c->outmaclength = myself->connection->outmaclength;
452         c->outcompression = myself->connection->outcompression;
453
454         init_configuration(&c->config_tree);
455         read_connection_config(c);
456
457         outgoing->cfg = lookup_config(c->config_tree, "Address");
458
459         if(!outgoing->cfg) {
460                 logger(LOG_ERR, "No address specified for %s", c->name);
461                 free_connection(c);
462                 return;
463         }
464
465         c->outgoing = outgoing;
466         c->last_ping_time = time(NULL);
467
468         connection_add(c);
469
470         do_outgoing_connection(c);
471
472         c->buffer = bufferevent_new(c->socket, handle_meta_read, handle_meta_write, handle_meta_connection_error, c);
473         if(!c->buffer) {
474                 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
475                 abort();
476         }
477         bufferevent_disable(c->buffer, EV_READ);
478
479         if(!thread_create(&c->thread, handle_meta_connection_data, c)) {
480                 logger(LOG_ERR, "create_thread() failed: %s", strerror(errno));
481                 abort();
482         }
483 }
484
485 /*
486   accept a new tcp connect and create a
487   new connection
488 */
489 void handle_new_meta_connection(int sock, short events, void *data) {
490         connection_t *c;
491         sockaddr_t sa;
492         int fd;
493         socklen_t len = sizeof sa;
494
495         fd = accept(sock, &sa.sa, &len);
496
497         if(fd < 0) {
498                 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
499                 return;
500         }
501
502         sockaddrunmap(&sa);
503
504         c = new_connection();
505         c->name = xstrdup("<unknown>");
506         c->outcipher = myself->connection->outcipher;
507         c->outdigest = myself->connection->outdigest;
508         c->outmaclength = myself->connection->outmaclength;
509         c->outcompression = myself->connection->outcompression;
510
511         c->address = sa;
512         c->hostname = sockaddr2hostname(&sa);
513         c->socket = fd;
514         c->last_ping_time = time(NULL);
515
516         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
517
518         c->buffer = bufferevent_new(c->socket, NULL, handle_meta_write, handle_meta_connection_error, c);
519         if(!c->buffer) {
520                 logger(LOG_ERR, "bufferevent_new() failed: %s", strerror(errno));
521                 abort();
522         }
523         bufferevent_disable(c->buffer, EV_READ);
524                 
525         configure_tcp(c);
526
527         connection_add(c);
528
529         c->allow_request = ID;
530         send_id(c);
531
532         if(!thread_create(&c->thread, handle_meta_connection_data, c)) {
533                 logger(LOG_ERR, "create_thread() failed: %s", strerror(errno));
534                 abort();
535         }
536 }
537
538 void free_outgoing(outgoing_t *outgoing) {
539         if(outgoing->ai)
540                 freeaddrinfo(outgoing->ai);
541
542         if(outgoing->name)
543                 free(outgoing->name);
544
545         free(outgoing);
546 }
547
548 void try_outgoing_connections(void) {
549         static config_t *cfg = NULL;
550         char *name;
551         outgoing_t *outgoing;
552         
553         outgoing_list = list_alloc((list_action_t)free_outgoing);
554                         
555         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
556                 get_config_string(cfg, &name);
557
558                 if(!check_id(name)) {
559                         logger(LOG_ERR,
560                                    "Invalid name for outgoing connection in %s line %d",
561                                    cfg->file, cfg->line);
562                         free(name);
563                         continue;
564                 }
565
566                 outgoing = xmalloc_and_zero(sizeof *outgoing);
567                 outgoing->name = name;
568                 list_insert_tail(outgoing_list, outgoing);
569                 setup_outgoing_connection(outgoing);
570         }
571 }