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