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