Merge branch 'master' of git://tinc-vpn.org/tinc 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-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                 logger(LOG_WARNING, "Error looking up %s port %s: %s",
141                                 node, "any", gai_strerror(status));
142                 free(node);
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 #ifdef O_NONBLOCK
241         {
242                 int flags = fcntl(nfd, F_GETFL);
243
244                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
245                         closesocket(nfd);
246                         logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
247                                    strerror(errno));
248                         return -1;
249                 }
250         }
251 #elif defined(WIN32)
252         {
253                 unsigned long arg = 1;
254                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
255                         closesocket(nfd);
256                         logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
257                         return -1;
258                 }
259         }
260 #endif
261
262         option = 1;
263         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof option);
264
265         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
266                 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
267
268         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
269                 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
270
271 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
272         if(sa->sa.sa_family == AF_INET6)
273                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
274 #endif
275
276 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
277 #define IP_DONTFRAGMENT IP_DONTFRAG
278 #endif
279
280 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
281         if(myself->options & OPTION_PMTU_DISCOVERY) {
282                 option = IP_PMTUDISC_DO;
283                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
284         }
285 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
286         if(myself->options & OPTION_PMTU_DISCOVERY) {
287                 option = 1;
288                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
289         }
290 #else
291 #warning No way to disable IPv4 fragmentation
292 #endif
293
294 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
295         if(myself->options & OPTION_PMTU_DISCOVERY) {
296                 option = IPV6_PMTUDISC_DO;
297                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
298         }
299 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
300         if(myself->options & OPTION_PMTU_DISCOVERY) {
301                 option = 1;
302                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
303         }
304 #else
305 #warning No way to disable IPv6 fragmentation
306 #endif
307
308         if (!bind_to_interface(nfd)) {
309                 closesocket(nfd);
310                 return -1;
311         }
312
313         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
314                 closesocket(nfd);
315                 addrstr = sockaddr2hostname(sa);
316                 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
317                 free(addrstr);
318                 return -1;
319         }
320
321         return nfd;
322 } /* int setup_vpn_in_socket */
323
324 static void retry_outgoing_handler(int fd, short events, void *data) {
325         setup_outgoing_connection(data);
326 }
327
328 void retry_outgoing(outgoing_t *outgoing) {
329         outgoing->timeout += 5;
330
331         if(outgoing->timeout > maxtimeout)
332                 outgoing->timeout = maxtimeout;
333
334         timeout_set(&outgoing->ev, retry_outgoing_handler, outgoing);
335         event_add(&outgoing->ev, &(struct timeval){outgoing->timeout, 0});
336
337         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
338                            "Trying to re-establish outgoing connection in %d seconds",
339                            outgoing->timeout);
340 }
341
342 void finish_connecting(connection_t *c) {
343         ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
344
345         configure_tcp(c);
346
347         c->last_ping_time = time(NULL);
348         c->status.connecting = false;
349
350         send_id(c);
351 }
352
353 bool do_outgoing_connection(connection_t *c) {
354         char *address, *port, *space;
355         int result;
356
357         if(!c->outgoing) {
358                 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
359                 abort();
360         }
361
362 begin:
363         if(!c->outgoing->ai) {
364                 if(!c->outgoing->cfg) {
365                         ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
366                                            c->name);
367                         retry_outgoing(c->outgoing);
368                         c->outgoing = NULL;
369                         connection_del(c);
370                         return false;
371                 }
372
373                 get_config_string(c->outgoing->cfg, &address);
374
375                 space = strchr(address, ' ');
376                 if(space) {
377                         port = xstrdup(space + 1);
378                         *space = 0;
379                 } else {
380                         if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
381                                 port = xstrdup("655");
382                 }
383
384                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
385                 free(address);
386                 free(port);
387
388                 c->outgoing->aip = c->outgoing->ai;
389                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
390         }
391
392         if(!c->outgoing->aip) {
393                 if(c->outgoing->ai)
394                         freeaddrinfo(c->outgoing->ai);
395                 c->outgoing->ai = NULL;
396                 goto begin;
397         }
398
399         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
400         c->outgoing->aip = c->outgoing->aip->ai_next;
401
402         if(c->hostname)
403                 free(c->hostname);
404
405         c->hostname = sockaddr2hostname(&c->address);
406
407         ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
408                            c->hostname);
409
410         c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
411
412         if(c->socket == -1) {
413                 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
414                 goto begin;
415         }
416
417 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
418         int option = 1;
419         if(c->address.sa.sa_family == AF_INET6)
420                 setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
421 #endif
422
423         bind_to_interface(c->socket);
424         bind_to_address(c);
425
426         /* Optimize TCP settings */
427
428         configure_tcp(c);
429
430         /* Connect */
431
432         result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
433
434         if(result == -1) {
435                 if(sockinprogress(sockerrno)) {
436                         c->status.connecting = true;
437                         return true;
438                 }
439
440                 closesocket(c->socket);
441
442                 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
443
444                 goto begin;
445         }
446
447         finish_connecting(c);
448
449         return true;
450 }
451
452 static void handle_meta_write(int sock, short events, void *data) {
453         ifdebug(META) logger(LOG_DEBUG, "handle_meta_write() called");
454
455         connection_t *c = data;
456
457         ssize_t outlen = send(c->socket, c->outbuf.data + c->outbuf.offset, c->outbuf.len - c->outbuf.offset, 0);
458         if(outlen <= 0) {
459                 logger(LOG_ERR, "Onoes, outlen = %d (%s)", (int)outlen, strerror(errno));
460                 terminate_connection(c, c->status.active);
461                 return;
462         }
463
464         buffer_read(&c->outbuf, outlen);
465         if(!c->outbuf.len && event_initialized(&c->outevent))
466                 event_del(&c->outevent);
467 }
468
469 void setup_outgoing_connection(outgoing_t *outgoing) {
470         connection_t *c;
471         node_t *n;
472
473         if(event_initialized(&outgoing->ev))
474                 event_del(&outgoing->ev);
475
476         n = lookup_node(outgoing->name);
477
478         if(n)
479                 if(n->connection) {
480                         ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
481
482                         n->connection->outgoing = outgoing;
483                         return;
484                 }
485
486         c = new_connection();
487         c->name = xstrdup(outgoing->name);
488         c->outcipher = myself->connection->outcipher;
489         c->outdigest = myself->connection->outdigest;
490         c->outmaclength = myself->connection->outmaclength;
491         c->outcompression = myself->connection->outcompression;
492
493         init_configuration(&c->config_tree);
494         read_connection_config(c);
495
496         outgoing->cfg = lookup_config(c->config_tree, "Address");
497
498         if(!outgoing->cfg) {
499                 logger(LOG_ERR, "No address specified for %s", c->name);
500                 free_connection(c);
501                 return;
502         }
503
504         c->outgoing = outgoing;
505         c->last_ping_time = time(NULL);
506
507         connection_add(c);
508
509         if (do_outgoing_connection(c)) {
510                 event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
511                 event_set(&c->outevent, c->socket, EV_WRITE | EV_PERSIST, handle_meta_write, c);
512                 event_add(&c->inevent, NULL);
513         }
514 }
515
516 /*
517   accept a new tcp connect and create a
518   new connection
519 */
520 void handle_new_meta_connection(int sock, short events, void *data) {
521         connection_t *c;
522         sockaddr_t sa;
523         int fd;
524         socklen_t len = sizeof sa;
525
526         fd = accept(sock, &sa.sa, &len);
527
528         if(fd < 0) {
529                 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
530                 return;
531         }
532
533         sockaddrunmap(&sa);
534
535         c = new_connection();
536         c->name = xstrdup("<unknown>");
537         c->outcipher = myself->connection->outcipher;
538         c->outdigest = myself->connection->outdigest;
539         c->outmaclength = myself->connection->outmaclength;
540         c->outcompression = myself->connection->outcompression;
541
542         c->address = sa;
543         c->hostname = sockaddr2hostname(&sa);
544         c->socket = fd;
545         c->last_ping_time = time(NULL);
546
547         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
548
549         event_set(&c->inevent, c->socket, EV_READ | EV_PERSIST, handle_meta_connection_data, c);
550         event_set(&c->outevent, c->socket, EV_WRITE | EV_PERSIST, handle_meta_write, c);
551         event_add(&c->inevent, NULL);
552                 
553         configure_tcp(c);
554
555         connection_add(c);
556
557         c->allow_request = ID;
558         send_id(c);
559 }
560
561 static void free_outgoing(outgoing_t *outgoing) {
562         if(outgoing->ai)
563                 freeaddrinfo(outgoing->ai);
564
565         if(outgoing->name)
566                 free(outgoing->name);
567
568         free(outgoing);
569 }
570
571 void try_outgoing_connections(void) {
572         static config_t *cfg = NULL;
573         char *name;
574         outgoing_t *outgoing;
575         
576         outgoing_list = list_alloc((list_action_t)free_outgoing);
577                         
578         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
579                 get_config_string(cfg, &name);
580
581                 if(!check_id(name)) {
582                         logger(LOG_ERR,
583                                    "Invalid name for outgoing connection in %s line %d",
584                                    cfg->file, cfg->line);
585                         free(name);
586                         continue;
587                 }
588
589                 outgoing = xmalloc_and_zero(sizeof *outgoing);
590                 outgoing->name = name;
591                 list_insert_tail(outgoing_list, outgoing);
592                 setup_outgoing_connection(outgoing);
593         }
594 }