Set KillMode=mixed in the systemd service file.
[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-2015 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 "proxy.h"
35 #include "utils.h"
36 #include "xalloc.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 mintimeout = 0;
45 int maxtimeout = 900;
46 int seconds_till_retry = 5;
47 int udp_rcvbuf = 0;
48 int udp_sndbuf = 0;
49
50 listen_socket_t listen_socket[MAXSOCKETS];
51 int listen_sockets;
52 list_t *outgoing_list = NULL;
53
54 /* Setup sockets */
55
56 static void configure_tcp(connection_t *c) {
57         int option;
58
59 #ifdef O_NONBLOCK
60         int flags = fcntl(c->socket, F_GETFL);
61
62         if(fcntl(c->socket, F_SETFL, flags | O_NONBLOCK) < 0) {
63                 logger(LOG_ERR, "fcntl for %s: %s", c->hostname, strerror(errno));
64         }
65 #elif defined(WIN32)
66         unsigned long arg = 1;
67
68         if(ioctlsocket(c->socket, FIONBIO, &arg) != 0) {
69                 logger(LOG_ERR, "ioctlsocket for %s: %s", c->hostname, sockstrerror(sockerrno));
70         }
71 #endif
72
73 #if defined(SOL_TCP) && defined(TCP_NODELAY)
74         option = 1;
75         setsockopt(c->socket, SOL_TCP, TCP_NODELAY, (void *)&option, sizeof(option));
76 #endif
77
78 #if defined(SOL_IP) && defined(IP_TOS) && defined(IPTOS_LOWDELAY)
79         option = IPTOS_LOWDELAY;
80         setsockopt(c->socket, SOL_IP, IP_TOS, (void *)&option, sizeof(option));
81 #endif
82
83 #if defined(IPPROTO_IPV6) && defined(IPV6_TCLASS) && defined(IPTOS_LOWDELAY)
84         option = IPTOS_LOWDELAY;
85         setsockopt(c->socket, IPPROTO_IPV6, IPV6_TCLASS, (void *)&option, sizeof(option));
86 #endif
87 }
88
89 static bool bind_to_interface(int sd) {
90         char *iface;
91
92 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
93         struct ifreq ifr;
94         int status;
95 #endif /* defined(SOL_SOCKET) && defined(SO_BINDTODEVICE) */
96
97         if(!get_config_string(lookup_config (config_tree, "BindToInterface"), &iface))
98                 return true;
99
100 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
101         memset(&ifr, 0, sizeof(ifr));
102         strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
103         ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
104         free(iface);
105
106         status = setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr));
107         if(status) {
108                 logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(errno));
109                 return false;
110         }
111
112 #else /* if !defined(SOL_SOCKET) || !defined(SO_BINDTODEVICE) */
113         logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
114 #endif
115
116         return true;
117 }
118
119 int setup_listen_socket(const sockaddr_t *sa) {
120         int nfd;
121         char *addrstr;
122         int option;
123         char *iface;
124
125         nfd = socket(sa->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
126
127         if(nfd < 0) {
128                 ifdebug(STATUS) logger(LOG_ERR, "Creating metasocket failed: %s", sockstrerror(sockerrno));
129                 return -1;
130         }
131
132 #ifdef FD_CLOEXEC
133         fcntl(nfd, F_SETFD, FD_CLOEXEC);
134 #endif
135
136         /* Optimize TCP settings */
137
138         option = 1;
139         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
140
141 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
142         if(sa->sa.sa_family == AF_INET6)
143                 setsockopt(nfd, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
144 #endif
145
146         if(get_config_string(lookup_config(config_tree, "BindToInterface"), &iface)) {
147 #if defined(SOL_SOCKET) && defined(SO_BINDTODEVICE)
148                 struct ifreq ifr;
149
150                 memset(&ifr, 0, sizeof(ifr));
151                 strncpy(ifr.ifr_ifrn.ifrn_name, iface, IFNAMSIZ);
152                 ifr.ifr_ifrn.ifrn_name[IFNAMSIZ - 1] = 0;
153                 free(iface);
154
155                 if(setsockopt(nfd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr))) {
156                         closesocket(nfd);
157                         logger(LOG_ERR, "Can't bind to interface %s: %s", ifr.ifr_ifrn.ifrn_name, strerror(sockerrno));
158                         return -1;
159                 }
160
161 #else
162                 logger(LOG_WARNING, "%s not supported on this platform", "BindToInterface");
163 #endif
164         }
165
166         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
167                 closesocket(nfd);
168                 addrstr = sockaddr2hostname(sa);
169                 logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
170                 free(addrstr);
171                 return -1;
172         }
173
174         if(listen(nfd, 3)) {
175                 closesocket(nfd);
176                 logger(LOG_ERR, "System call `%s' failed: %s", "listen", sockstrerror(sockerrno));
177                 return -1;
178         }
179
180         return nfd;
181 }
182
183 int setup_vpn_in_socket(const sockaddr_t *sa) {
184         int nfd;
185         char *addrstr;
186         int option;
187
188         nfd = socket(sa->sa.sa_family, SOCK_DGRAM, IPPROTO_UDP);
189
190         if(nfd < 0) {
191                 logger(LOG_ERR, "Creating UDP socket failed: %s", sockstrerror(sockerrno));
192                 return -1;
193         }
194
195 #ifdef FD_CLOEXEC
196         fcntl(nfd, F_SETFD, FD_CLOEXEC);
197 #endif
198
199 #ifdef O_NONBLOCK
200         {
201                 int flags = fcntl(nfd, F_GETFL);
202
203                 if(fcntl(nfd, F_SETFL, flags | O_NONBLOCK) < 0) {
204                         closesocket(nfd);
205                         logger(LOG_ERR, "System call `%s' failed: %s", "fcntl",
206                                    strerror(errno));
207                         return -1;
208                 }
209         }
210 #elif defined(WIN32)
211         {
212                 unsigned long arg = 1;
213                 if(ioctlsocket(nfd, FIONBIO, &arg) != 0) {
214                         closesocket(nfd);
215                         logger(LOG_ERR, "Call to `%s' failed: %s", "ioctlsocket", sockstrerror(sockerrno));
216                         return -1;
217                 }
218         }
219 #endif
220
221         option = 1;
222         setsockopt(nfd, SOL_SOCKET, SO_REUSEADDR, (void *)&option, sizeof(option));
223         setsockopt(nfd, SOL_SOCKET, SO_BROADCAST, (void *)&option, sizeof(option));
224
225         if(udp_rcvbuf && setsockopt(nfd, SOL_SOCKET, SO_RCVBUF, (void *)&udp_rcvbuf, sizeof(udp_rcvbuf)))
226                 logger(LOG_WARNING, "Can't set UDP SO_RCVBUF to %i: %s", udp_rcvbuf, strerror(errno));
227
228         if(udp_sndbuf && setsockopt(nfd, SOL_SOCKET, SO_SNDBUF, (void *)&udp_sndbuf, sizeof(udp_sndbuf)))
229                 logger(LOG_WARNING, "Can't set UDP SO_SNDBUF to %i: %s", udp_sndbuf, strerror(errno));
230
231 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
232         if(sa->sa.sa_family == AF_INET6)
233                 setsockopt(nfd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
234 #endif
235
236 #if defined(IP_DONTFRAG) && !defined(IP_DONTFRAGMENT)
237 #define IP_DONTFRAGMENT IP_DONTFRAG
238 #endif
239
240 #if defined(SOL_IP) && defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO)
241         if(myself->options & OPTION_PMTU_DISCOVERY) {
242                 option = IP_PMTUDISC_DO;
243                 setsockopt(nfd, SOL_IP, IP_MTU_DISCOVER, (void *)&option, sizeof(option));
244         }
245 #elif defined(IPPROTO_IP) && defined(IP_DONTFRAGMENT)
246         if(myself->options & OPTION_PMTU_DISCOVERY) {
247                 option = 1;
248                 setsockopt(nfd, IPPROTO_IP, IP_DONTFRAGMENT, (void *)&option, sizeof(option));
249         }
250 #endif
251
252 #if defined(SOL_IPV6) && defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO)
253         if(myself->options & OPTION_PMTU_DISCOVERY) {
254                 option = IPV6_PMTUDISC_DO;
255                 setsockopt(nfd, SOL_IPV6, IPV6_MTU_DISCOVER, (void *)&option, sizeof(option));
256         }
257 #elif defined(IPPROTO_IPV6) && defined(IPV6_DONTFRAG)
258         if(myself->options & OPTION_PMTU_DISCOVERY) {
259                 option = 1;
260                 setsockopt(nfd, IPPROTO_IPV6, IPV6_DONTFRAG, (void *)&option, sizeof(option));
261         }
262 #endif
263
264         if (!bind_to_interface(nfd)) {
265                 closesocket(nfd);
266                 return -1;
267         }
268
269         if(bind(nfd, &sa->sa, SALEN(sa->sa))) {
270                 closesocket(nfd);
271                 addrstr = sockaddr2hostname(sa);
272                 logger(LOG_ERR, "Can't bind to %s/udp: %s", addrstr, sockstrerror(sockerrno));
273                 free(addrstr);
274                 return -1;
275         }
276
277         return nfd;
278 } /* int setup_vpn_in_socket */
279
280 void retry_outgoing(outgoing_t *outgoing) {
281         outgoing->timeout += 5;
282
283         if(outgoing->timeout < mintimeout)
284                 outgoing->timeout = mintimeout;
285
286         if(outgoing->timeout > maxtimeout)
287                 outgoing->timeout = maxtimeout;
288
289         if(outgoing->event)
290                 event_del(outgoing->event);
291         outgoing->event = new_event();
292         outgoing->event->handler = (event_handler_t) setup_outgoing_connection;
293         outgoing->event->time = now + outgoing->timeout;
294         outgoing->event->data = outgoing;
295         event_add(outgoing->event);
296
297         ifdebug(CONNECTIONS) logger(LOG_NOTICE,
298                            "Trying to re-establish outgoing connection in %d seconds",
299                            outgoing->timeout);
300 }
301
302 void finish_connecting(connection_t *c) {
303         ifdebug(CONNECTIONS) logger(LOG_INFO, "Connected to %s (%s)", c->name, c->hostname);
304
305         c->last_ping_time = now;
306
307         send_id(c);
308 }
309
310 static void do_outgoing_pipe(connection_t *c, char *command) {
311 #ifndef HAVE_MINGW
312         int fd[2];
313
314         if(socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) {
315                 logger(LOG_ERR, "Could not create socketpair: %s\n", strerror(errno));
316                 return;
317         }
318
319         if(fork()) {
320                 c->socket = fd[0];
321                 close(fd[1]);
322                 ifdebug(CONNECTIONS) logger(LOG_DEBUG, "Using proxy %s", command);
323                 return;
324         }
325
326         close(0);
327         close(1);
328         close(fd[0]);
329         dup2(fd[1], 0);
330         dup2(fd[1], 1);
331         close(fd[1]);
332
333         // Other filedescriptors should be closed automatically by CLOEXEC
334
335         char *host = NULL;
336         char *port = NULL;
337
338         sockaddr2str(&c->address, &host, &port);
339         setenv("REMOTEADDRESS", host, true);
340         setenv("REMOTEPORT", port, true);
341         setenv("NODE", c->name, true);
342         setenv("NAME", myself->name, true);
343         if(netname)
344                 setenv("NETNAME", netname, true);
345
346         int result = system(command);
347         if(result < 0)
348                 logger(LOG_ERR, "Could not execute %s: %s\n", command, strerror(errno));
349         else if(result)
350                 logger(LOG_ERR, "%s exited with non-zero status %d", command, result);
351         exit(result);
352 #else
353         logger(LOG_ERR, "Proxy type exec not supported on this platform!");
354         return;
355 #endif
356 }
357
358 static bool is_valid_host_port(const char *host, const char *port) {
359         for(const char *p = host; *p; p++)
360                 if(!isalnum(*p) && *p != '-' && *p != '.')
361                         return false;
362
363         for(const char *p = port; *p; p++)
364                 if(!isalnum(*p))
365                         return false;
366
367         return true;
368 }
369
370 void do_outgoing_connection(connection_t *c) {
371         struct addrinfo *proxyai = NULL;
372         int result;
373
374         if(!c->outgoing) {
375                 logger(LOG_ERR, "do_outgoing_connection() for %s called without c->outgoing", c->name);
376                 abort();
377         }
378
379 begin:
380         if(!c->outgoing->ai) {
381                 if(!c->outgoing->cfg) {
382                         ifdebug(CONNECTIONS) logger(LOG_ERR, "Could not set up a meta connection to %s",
383                                            c->name);
384                         c->status.remove = true;
385                         retry_outgoing(c->outgoing);
386                         c->outgoing = NULL;
387                         return;
388                 }
389
390                 char *address, *port, *space;
391
392                 get_config_string(c->outgoing->cfg, &address);
393
394                 space = strchr(address, ' ');
395                 if(space) {
396                         port = xstrdup(space + 1);
397                         *space = 0;
398                 } else {
399                         if(!get_config_string(lookup_config(c->config_tree, "Port"), &port))
400                                 port = xstrdup("655");
401                 }
402
403                 c->outgoing->ai = str2addrinfo(address, port, SOCK_STREAM);
404
405                 // If we cannot resolve the address, maybe we are using a proxy that can?
406                 if(!c->outgoing->ai && proxytype != PROXY_NONE && is_valid_host_port(address, port)) {
407                         memset(&c->address, 0, sizeof c->address);
408                         c->address.sa.sa_family = AF_UNKNOWN;
409                         c->address.unknown.address = address;
410                         c->address.unknown.port = port;
411                 } else {
412                         free(address);
413                         free(port);
414                 }
415
416                 c->outgoing->aip = c->outgoing->ai;
417                 c->outgoing->cfg = lookup_config_next(c->config_tree, c->outgoing->cfg);
418
419                 if(!c->outgoing->ai && proxytype != PROXY_NONE)
420                         goto connect;
421         }
422
423         if(!c->outgoing->aip) {
424                 if(c->outgoing->ai)
425                         freeaddrinfo(c->outgoing->ai);
426                 c->outgoing->ai = NULL;
427                 goto begin;
428         }
429
430         memcpy(&c->address, c->outgoing->aip->ai_addr, c->outgoing->aip->ai_addrlen);
431         c->outgoing->aip = c->outgoing->aip->ai_next;
432
433 connect:
434         if(c->hostname)
435                 free(c->hostname);
436
437         c->hostname = sockaddr2hostname(&c->address);
438
439         ifdebug(CONNECTIONS) logger(LOG_INFO, "Trying to connect to %s (%s)", c->name,
440                            c->hostname);
441
442         if(!proxytype) {
443                 c->socket = socket(c->address.sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
444         } else if(proxytype == PROXY_EXEC) {
445                 do_outgoing_pipe(c, proxyhost);
446         } else {
447                 proxyai = str2addrinfo(proxyhost, proxyport, SOCK_STREAM);
448                 if(!proxyai)
449                         goto begin;
450                 ifdebug(CONNECTIONS) logger(LOG_INFO, "Using proxy at %s port %s", proxyhost, proxyport);
451                 c->socket = socket(proxyai->ai_family, SOCK_STREAM, IPPROTO_TCP);
452         }
453
454         if(c->socket == -1) {
455                 ifdebug(CONNECTIONS) logger(LOG_ERR, "Creating socket for %s failed: %s", c->hostname, sockstrerror(sockerrno));
456                 goto begin;
457         }
458
459         if(proxytype != PROXY_EXEC)
460                 configure_tcp(c);
461
462 #ifdef FD_CLOEXEC
463         fcntl(c->socket, F_SETFD, FD_CLOEXEC);
464 #endif
465
466         if(proxytype != PROXY_EXEC) {
467 #if defined(SOL_IPV6) && defined(IPV6_V6ONLY)
468                 int option = 1;
469                 if(c->address.sa.sa_family == AF_INET6)
470                         setsockopt(c->socket, SOL_IPV6, IPV6_V6ONLY, (void *)&option, sizeof option);
471 #endif
472
473                 bind_to_interface(c->socket);
474         }
475
476         int b = -1;
477
478         for(int i = 0; i < listen_sockets; i++) {
479                 if(listen_socket[i].sa.sa.sa_family == c->address.sa.sa_family) {
480                         if(b == -1) {
481                                 b = i;
482                         } else  {
483                                 b = -1;
484                                 break;
485                         }
486                 }
487         }
488
489         if(b != -1) {
490                 sockaddr_t sa = listen_socket[b].sa;
491                 if(sa.sa.sa_family == AF_INET)
492                         sa.in.sin_port = 0;
493                 else if(sa.sa.sa_family == AF_INET6)
494                         sa.in6.sin6_port = 0;
495
496                 if(bind(c->socket, &sa.sa, SALEN(sa.sa))) {
497                         char *addrstr = sockaddr2hostname(&sa);
498                         logger(LOG_ERR, "Can't bind to %s/tcp: %s", addrstr, sockstrerror(sockerrno));
499                         free(addrstr);
500                 }
501         }
502
503         /* Connect */
504
505         if(!proxytype) {
506                 result = connect(c->socket, &c->address.sa, SALEN(c->address.sa));
507         } else if(proxytype == PROXY_EXEC) {
508                 result = 0;
509         } else {
510                 result = connect(c->socket, proxyai->ai_addr, proxyai->ai_addrlen);
511                 freeaddrinfo(proxyai);
512         }
513
514         now = time(NULL);
515
516         if(result == -1) {
517                 if(sockinprogress(sockerrno)) {
518                         c->last_ping_time = now;
519                         c->status.connecting = true;
520                         return;
521                 }
522
523                 closesocket(c->socket);
524
525                 ifdebug(CONNECTIONS) logger(LOG_ERR, "%s: %s", c->hostname, sockstrerror(sockerrno));
526
527                 goto begin;
528         }
529
530         finish_connecting(c);
531
532         return;
533 }
534
535 void setup_outgoing_connection(outgoing_t *outgoing) {
536         connection_t *c;
537         node_t *n;
538
539         outgoing->event = NULL;
540
541         n = lookup_node(outgoing->name);
542
543         if(n)
544                 if(n->connection) {
545                         ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);
546
547                         n->connection->outgoing = outgoing;
548                         return;
549                 }
550
551         c = new_connection();
552         c->name = xstrdup(outgoing->name);
553         c->outcipher = myself->connection->outcipher;
554         c->outdigest = myself->connection->outdigest;
555         c->outmaclength = myself->connection->outmaclength;
556         c->outcompression = myself->connection->outcompression;
557
558         init_configuration(&c->config_tree);
559         read_connection_config(c);
560
561         outgoing->cfg = lookup_config(c->config_tree, "Address");
562
563         if(!outgoing->cfg) {
564                 logger(LOG_ERR, "No address specified for %s", c->name);
565                 free_connection(c);
566                 return;
567         }
568
569         c->outgoing = outgoing;
570         c->last_ping_time = now;
571
572         connection_add(c);
573
574         do_outgoing_connection(c);
575 }
576
577 /*
578   accept a new tcp connect and create a
579   new connection
580 */
581 bool handle_new_meta_connection(int sock) {
582         connection_t *c;
583         sockaddr_t sa;
584         int fd;
585         socklen_t len = sizeof(sa);
586
587         fd = accept(sock, &sa.sa, &len);
588
589         if(fd < 0) {
590                 logger(LOG_ERR, "Accepting a new connection failed: %s", sockstrerror(sockerrno));
591                 return false;
592         }
593
594         sockaddrunmap(&sa);
595
596         c = new_connection();
597         c->name = xstrdup("<unknown>");
598         c->outcipher = myself->connection->outcipher;
599         c->outdigest = myself->connection->outdigest;
600         c->outmaclength = myself->connection->outmaclength;
601         c->outcompression = myself->connection->outcompression;
602
603         c->address = sa;
604         c->hostname = sockaddr2hostname(&sa);
605         c->socket = fd;
606         c->last_ping_time = now;
607
608         ifdebug(CONNECTIONS) logger(LOG_NOTICE, "Connection from %s", c->hostname);
609
610         configure_tcp(c);
611
612         connection_add(c);
613
614         c->allow_request = ID;
615         send_id(c);
616
617         return true;
618 }
619
620 static void free_outgoing(outgoing_t *outgoing) {
621         if(outgoing->ai)
622                 freeaddrinfo(outgoing->ai);
623
624         if(outgoing->name)
625                 free(outgoing->name);
626
627         free(outgoing);
628 }
629
630 void try_outgoing_connections(void) {
631         static config_t *cfg = NULL;
632         char *name;
633         outgoing_t *outgoing;
634         
635         outgoing_list = list_alloc((list_action_t)free_outgoing);
636                         
637         for(cfg = lookup_config(config_tree, "ConnectTo"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
638                 get_config_string(cfg, &name);
639
640                 if(!check_id(name)) {
641                         logger(LOG_ERR,
642                                    "Invalid name for outgoing connection in %s line %d",
643                                    cfg->file, cfg->line);
644                         free(name);
645                         continue;
646                 }
647
648                 outgoing = xmalloc_and_zero(sizeof(*outgoing));
649                 outgoing->name = name;
650                 list_insert_tail(outgoing_list, outgoing);
651                 setup_outgoing_connection(outgoing);
652         }
653 }