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