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