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