Configure minimum reconnect timeouts.
[tinc] / src / net_socket.c
1 /*
2     net_socket.c -- Handle various kinds of sockets.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2014 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 "avl_tree.h"
26 #include "conf.h"
27 #include "connection.h"
28 #include "event.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "netutl.h"
33 #include "protocol.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 /* Needed on Mac OS/X */
38 #ifndef SOL_TCP
39 #define SOL_TCP IPPROTO_TCP
40 #endif
41
42 int addressfamily = AF_UNSPEC;
43 int mintimeout = 0;
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: %s", 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         free(iface);
99
100         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
101         if(status) {
102                 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(errno));
103                 return false;
104         }
105
106 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
107         logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
108 #endif
109
110         return true;
111 }
112
113 int setup_listen_socket(const sockaddr_t *sa) {
114         int nfd;
115         char *addrstr;
116         int option;
117         char *iface;
118
119         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
120
121         if(nfd < 0) {
122                 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
123                 return -1;
124         }
125
126 #ifdef FD_CLOEXEC
127         fcntl(nfd, F_SETFD, FD_CLOEXEC);
128 #endif
129
130         /* Optimize TCP settings */
131
132         option = 1;
133         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
134
135 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
136         if(sa->sa.sa_family == AF_INET6)
137                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
138 #endif
139
140         if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
141 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
142                 struct ifreq ifr;
143
144                 memset(&ifr, 0, sizeof(ifr));
145                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
146                 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
147                 free(iface);
148
149                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
150                         closesocket(nfd);
151                         logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
152                         return -1;
153                 }
154
155 #else
156                 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
157 #endif
158         }
159
160         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
161                 closesocket(nfd);
162                 addrstr = sockaddr2hostname(sa);
163                 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
164                 free(addrstr);
165                 return -1;
166         }
167
168         if(listen(nfd, 3)) {
169                 closesocket(nfd);
170                 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
171                 return -1;
172         }
173
174         return nfd;
175 }
176
177 int setup_vpn_in_socket(const sockaddr_t *sa) {
178         int nfd;
179         char *addrstr;
180         int option;
181
182         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
183
184         if(nfd < 0) {
185                 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
186                 return -1;
187         }
188
189 #ifdef FD_CLOEXEC
190         fcntl(nfd, F_SETFD, FD_CLOEXEC);
191 #endif
192
193 #ifdef O_NONBLOCK
194         {
195                 int flags = fcntl(nfd, F_GETFL);
196
197                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
198                         closesocket(nfd);
199                         logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
200                                    strerror(errno));
201                         return -1;
202                 }
203         }
204 #elif defined(WIN32)
205         {
206                 unsigned long arg = 1;
207                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
208                         closesocket(nfd);
209                         logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
210                         return -1;
211                 }
212         }
213 #endif
214
215         option = 1;
216         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
217         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
218
219         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
220                 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
221
222         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
223                 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
224
225 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
226         if(sa->sa.sa_family == AF_INET6)
227                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
228 #endif
229
230 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
231 #define IP_DONTFRAGMENT IP_DONTFRAG
232 #endif
233
234 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
235         if(myself->options & OPTION_PMTU_DISCOVERY) {
236                 option = IP_PMTUDISC_DO;
237                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
238         }
239 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
240         if(myself->options & OPTION_PMTU_DISCOVERY) {
241                 option = 1;
242                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
243         }
244 #endif
245
246 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
247         if(myself->options & OPTION_PMTU_DISCOVERY) {
248                 option = IPV6_PMTUDISC_DO;
249                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
250         }
251 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
252         if(myself->options & OPTION_PMTU_DISCOVERY) {
253                 option = 1;
254                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
255         }
256 #endif
257
258         if (!bind_to_interface(nfd)) {
259                 closesocket(nfd);
260                 return -1;
261         }
262
263         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
264                 closesocket(nfd);
265                 addrstr = sockaddr2hostname(sa);
266                 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
267                 free(addrstr);
268                 return -1;
269         }
270
271         return nfd;
272 } /* int setup_vpn_in_socket */
273
274 void retry_outgoing(outgoing_t *outgoing) {
275         outgoing->timeout += 5;
276
277         if(outgoing->timeout < mintimeout)
278                 outgoing->timeout = mintimeout;
279
280         if(outgoing->timeout > maxtimeout)
281                 outgoing->timeout = maxtimeout;
282
283         if(outgoing->event)
284                 event_del(outgoing->event);
285         outgoing->event = new_event();
286         outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
287         outgoing->event->time = now + outgoing->timeout;
288         outgoing->event->data = outgoing;
289         event_add(outgoing->event);
290
291         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
292                            "Trying to re-establish outgoing connection in %d seconds",
293                            outgoing->timeout);
294 }
295
296 void finish_connecting(connection_t *c) {
297         ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
298
299         c->last_ping_time = now;
300
301         send_id(c);
302 }
303
304 static void do_outgoing_pipe(connection_t *c, char *command) {
305 #ifndef HAVE_MINGW
306         int fd[2];
307
308         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
309                 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
310                 return;
311         }
312
313         if(fork()) {
314                 c->socket = fd[0];
315                 close(fd[1]);
316                 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
317                 return;
318         }
319
320         close(0);
321         close(1);
322         close(fd[0]);
323         dup2(fd[1], 0);
324         dup2(fd[1], 1);
325         close(fd[1]);
326
327         // Other filedescriptors should be closed automatically by CLOEXEC
328
329         char *host = NULL;
330         char *port = NULL;
331
332         sockaddr2str(&c->address, &host, &port);
333         setenv("REMOTEADDRESS", host, true);
334         setenv("REMOTEPORT", port, true);
335         setenv("NODE", c->name, true);
336         setenv("NAME", myself->name, true);
337         if(netname)
338                 setenv("NETNAME", netname, true);
339
340         int result = system(command);
341         if(result < 0)
342                 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
343         else if(result)
344                 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
345         exit(result);
346 #else
347         logger(LOG_ERR, "Proxy type exec not supported on this platform!");
348         return;
349 #endif
350 }
351
352 void do_outgoing_connection(connection_t *c) {
353         char *address, *port, *space;
354         struct addrinfo *proxyai = NULL;
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                         c->status.remove = true;
368                         retry_outgoing(c->outgoing);
369                         c->outgoing = NULL;
370                         return;
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         if(!proxytype) {
411                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
412         } else if(proxytype == PROXY_EXEC) {
413                 do_outgoing_pipe(c, proxyhost);
414         } else {
415                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
416                 if(!proxyai)
417                         goto begin;
418                 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
419                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
420         }
421
422         if(c->socket == -1) {
423                 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
424                 goto begin;
425         }
426
427         if(proxytype != PROXY_EXEC)
428                 configure_tcp(c);
429
430 #ifdef FD_CLOEXEC
431         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
432 #endif
433
434         if(proxytype != PROXY_EXEC) {
435 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
436                 int option = 1;
437                 if(c->address.sa.sa_family == AF_INET6)
438                         setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
439 #endif
440
441                 bind_to_interface(c->socket);
442         }
443
444         /* Connect */
445
446         if(!proxytype) {
447                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
448         } else if(proxytype == PROXY_EXEC) {
449                 result = 0;
450         } else {
451                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
452                 freeaddrinfo(proxyai);
453         }
454
455         if(result == -1) {
456                 if(sockinprogress(sockerrno)) {
457                         c->status.connecting = true;
458                         return;
459                 }
460
461                 closesocket(c->socket);
462
463                 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
464
465                 goto begin;
466         }
467
468         finish_connecting(c);
469
470         return;
471 }
472
473 void setup_outgoing_connection(outgoing_t *outgoing) {
474         connection_t *c;
475         node_t *n;
476
477         outgoing->event = NULL;
478
479         n = lookup_node(outgoing->name);
480
481         if(n)
482                 if(n->connection) {
483                         ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
484
485                         n->connection->outgoing = outgoing;
486                         return;
487                 }
488
489         c = new_connection();
490         c->name = xstrdup(outgoing->name);
491         c->outcipher = myself->connection->outcipher;
492         c->outdigest = myself->connection->outdigest;
493         c->outmaclength = myself->connection->outmaclength;
494         c->outcompression = myself->connection->outcompression;
495
496         init_configuration(&c->config_tree);
497         read_connection_config(c);
498
499         outgoing->cfg = lookup_config(c->config_tree, "Address");
500
501         if(!outgoing->cfg) {
502                 logger(LOG_ERR, "No address specified for %s", c->name);
503                 free_connection(c);
504                 return;
505         }
506
507         c->outgoing = outgoing;
508         c->last_ping_time = now;
509
510         connection_add(c);
511
512         do_outgoing_connection(c);
513 }
514
515 /*
516   accept a new tcp connect and create a
517   new connection
518 */
519 bool handle_new_meta_connection(int sock) {
520         connection_t *c;
521         sockaddr_t sa;
522         int fd;
523         socklen_t len = sizeof(sa);
524
525         fd = accept(sock, &sa.sa, &len);
526
527         if(fd < 0) {
528                 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
529                 return false;
530         }
531
532         sockaddrunmap(&sa);
533
534         c = new_connection();
535         c->name = xstrdup("<unknown>");
536         c->outcipher = myself->connection->outcipher;
537         c->outdigest = myself->connection->outdigest;
538         c->outmaclength = myself->connection->outmaclength;
539         c->outcompression = myself->connection->outcompression;
540
541         c->address = sa;
542         c->hostname = sockaddr2hostname(&sa);
543         c->socket = fd;
544         c->last_ping_time = now;
545
546         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
547
548         configure_tcp(c);
549
550         connection_add(c);
551
552         c->allow_request = ID;
553         send_id(c);
554
555         return true;
556 }
557
558 static void free_outgoing(outgoing_t *outgoing) {
559         if(outgoing->ai)
560                 freeaddrinfo(outgoing->ai);
561
562         if(outgoing->name)
563                 free(outgoing->name);
564
565         free(outgoing);
566 }
567
568 void try_outgoing_connections(void) {
569         static config_t *cfg = NULL;
570         char *name;
571         outgoing_t *outgoing;
572         
573         outgoing_list = list_alloc((list_action_t)free_outgoing);
574                         
575         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
576                 get_config_string(cfg, &name);
577
578                 if(!check_id(name)) {
579                         logger(LOG_ERR,
580                                    "Invalid name for outgoing connection in %s line %d",
581                                    cfg->file, cfg->line);
582                         free(name);
583                         continue;
584                 }
585
586                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
587                 outgoing->name = name;
588                 list_insert_tail(outgoing_list, outgoing);
589                 setup_outgoing_connection(outgoing);
590         }
591 }