CI: add libgcrypt to sanitizer run
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2021 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2010      Brandon Black <blblack@gmail.com>
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 "cipher.h"
26 #include "conf_net.h"
27 #include "conf.h"
28 #include "connection.h"
29 #include "compression.h"
30 #include "control.h"
31 #include "crypto.h"
32 #include "device.h"
33 #include "digest.h"
34 #include "ecdsa.h"
35 #include "graph.h"
36 #include "logger.h"
37 #include "names.h"
38 #include "net.h"
39 #include "netutl.h"
40 #include "process.h"
41 #include "protocol.h"
42 #include "route.h"
43 #include "script.h"
44 #include "subnet.h"
45 #include "utils.h"
46 #include "xalloc.h"
47 #include "keys.h"
48
49 #ifdef HAVE_MINIUPNPC
50 #include "upnp.h"
51 #endif
52
53 ports_t myport;
54 static io_t device_io;
55 devops_t devops;
56 bool device_standby = false;
57
58 char *proxyhost = NULL;
59 char *proxyport = NULL;
60 char *proxyuser = NULL;
61 char *proxypass = NULL;
62
63 proxytype_t proxytype;
64 bool autoconnect;
65 bool disablebuggypeers;
66
67 char *scriptinterpreter;
68 char *scriptextension;
69
70 bool node_read_ecdsa_public_key(node_t *n) {
71         if(ecdsa_active(n->ecdsa)) {
72                 return true;
73         }
74
75         FILE *fp;
76         char *pubname = NULL;
77         char *p;
78
79         splay_tree_t config;
80         init_configuration(&config);
81
82         if(!read_host_config(&config, n->name, true)) {
83                 goto exit;
84         }
85
86         /* First, check for simple Ed25519PublicKey statement */
87
88         if(get_config_string(lookup_config(&config, "Ed25519PublicKey"), &p)) {
89                 n->ecdsa = ecdsa_set_base64_public_key(p);
90                 free(p);
91                 goto exit;
92         }
93
94         /* Else, check for Ed25519PublicKeyFile statement and read it */
95
96         if(!get_config_string(lookup_config(&config, "Ed25519PublicKeyFile"), &pubname)) {
97                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
98         }
99
100         fp = fopen(pubname, "r");
101
102         if(!fp) {
103                 goto exit;
104         }
105
106         n->ecdsa = ecdsa_read_pem_public_key(fp);
107         fclose(fp);
108
109 exit:
110         splay_empty_tree(&config);
111         free(pubname);
112         return n->ecdsa;
113 }
114
115 static bool read_invitation_key(void) {
116         FILE *fp;
117         char fname[PATH_MAX];
118
119         if(invitation_key) {
120                 ecdsa_free(invitation_key);
121                 invitation_key = NULL;
122         }
123
124         snprintf(fname, sizeof(fname), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
125
126         fp = fopen(fname, "r");
127
128         if(fp) {
129                 invitation_key = ecdsa_read_pem_private_key(fp);
130                 fclose(fp);
131
132                 if(!invitation_key) {
133                         logger(DEBUG_ALWAYS, LOG_ERR, "Reading Ed25519 private key file `%s' failed", fname);
134                 }
135         }
136
137         return invitation_key;
138 }
139
140 #ifndef DISABLE_LEGACY
141 static timeout_t keyexpire_timeout;
142
143 static void keyexpire_handler(void *data) {
144         regenerate_key();
145         timeout_set(data, &(struct timeval) {
146                 keylifetime, jitter()
147         });
148 }
149 #endif
150
151 void regenerate_key(void) {
152         logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
153         send_key_changed();
154
155         for splay_each(node_t, n, &node_tree) {
156                 n->status.validkey_in = false;
157         }
158 }
159
160 void load_all_nodes(void) {
161         DIR *dir;
162         struct dirent *ent;
163         char dname[PATH_MAX];
164
165         snprintf(dname, sizeof(dname), "%s" SLASH "hosts", confbase);
166         dir = opendir(dname);
167
168         if(!dir) {
169                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
170                 return;
171         }
172
173         while((ent = readdir(dir))) {
174                 if(!check_id(ent->d_name)) {
175                         continue;
176                 }
177
178                 node_t *n = lookup_node(ent->d_name);
179
180                 splay_tree_t config;
181                 init_configuration(&config);
182                 read_config_options(&config, ent->d_name);
183                 read_host_config(&config, ent->d_name, true);
184
185                 if(!n) {
186                         n = new_node();
187                         n->name = xstrdup(ent->d_name);
188                         node_add(n);
189                 }
190
191                 if(strictsubnets) {
192                         for(config_t *cfg = lookup_config(&config, "Subnet"); cfg; cfg = lookup_config_next(&config, cfg)) {
193                                 subnet_t *s, *s2;
194
195                                 if(!get_config_subnet(cfg, &s)) {
196                                         continue;
197                                 }
198
199                                 if((s2 = lookup_subnet(n, s))) {
200                                         s2->expires = -1;
201                                         free(s);
202                                 } else {
203                                         subnet_add(n, s);
204                                 }
205                         }
206                 }
207
208                 if(lookup_config(&config, "Address")) {
209                         n->status.has_address = true;
210                 }
211
212                 splay_empty_tree(&config);
213         }
214
215         closedir(dir);
216 }
217
218 char *get_name(void) {
219         char *name = NULL;
220         char *returned_name;
221
222         get_config_string(lookup_config(&config_tree, "Name"), &name);
223
224         if(!name) {
225                 return NULL;
226         }
227
228         returned_name = replace_name(name);
229         free(name);
230         return returned_name;
231 }
232
233 bool setup_myself_reloadable(void) {
234         free(scriptinterpreter);
235         scriptinterpreter = NULL;
236
237         get_config_string(lookup_config(&config_tree, "ScriptsInterpreter"), &scriptinterpreter);
238
239         free(scriptextension);
240
241         if(!get_config_string(lookup_config(&config_tree, "ScriptsExtension"), &scriptextension)) {
242                 scriptextension = xstrdup("");
243         }
244
245         char *proxy = NULL;
246
247         get_config_string(lookup_config(&config_tree, "Proxy"), &proxy);
248
249         if(proxy) {
250                 char *space;
251
252                 if((space = strchr(proxy, ' '))) {
253                         *space++ = 0;
254                 }
255
256                 if(!strcasecmp(proxy, "none")) {
257                         proxytype = PROXY_NONE;
258                 } else if(!strcasecmp(proxy, "socks4")) {
259                         proxytype = PROXY_SOCKS4;
260                 } else if(!strcasecmp(proxy, "socks4a")) {
261                         proxytype = PROXY_SOCKS4A;
262                 } else if(!strcasecmp(proxy, "socks5")) {
263                         proxytype = PROXY_SOCKS5;
264                 } else if(!strcasecmp(proxy, "http")) {
265                         proxytype = PROXY_HTTP;
266                 } else if(!strcasecmp(proxy, "exec")) {
267                         proxytype = PROXY_EXEC;
268                 } else {
269                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
270                         free(proxy);
271                         return false;
272                 }
273
274                 free(proxyhost);
275                 proxyhost = NULL;
276
277                 free(proxyport);
278                 proxyport = NULL;
279
280                 free(proxyuser);
281                 proxyuser = NULL;
282
283                 free(proxypass);
284                 proxypass = NULL;
285
286                 switch(proxytype) {
287                 case PROXY_NONE:
288                 default:
289                         break;
290
291                 case PROXY_EXEC:
292                         if(!space || !*space) {
293                                 logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
294                                 free(proxy);
295                                 return false;
296                         }
297
298                         proxyhost = xstrdup(space);
299                         break;
300
301                 case PROXY_SOCKS4:
302                 case PROXY_SOCKS4A:
303                 case PROXY_SOCKS5:
304                 case PROXY_HTTP:
305                         proxyhost = space;
306
307                         if(space && (space = strchr(space, ' '))) {
308                                 *space++ = 0, proxyport = space;
309                         }
310
311                         if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
312                                 logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
313                                 proxyport = NULL;
314                                 proxyhost = NULL;
315                                 free(proxy);
316                                 return false;
317                         }
318
319                         if(space && (space = strchr(space, ' '))) {
320                                 *space++ = 0, proxyuser = space;
321                         }
322
323                         if(space && (space = strchr(space, ' '))) {
324                                 *space++ = 0, proxypass = space;
325                         }
326
327                         proxyhost = xstrdup(proxyhost);
328                         proxyport = xstrdup(proxyport);
329
330                         if(proxyuser && *proxyuser) {
331                                 proxyuser = xstrdup(proxyuser);
332                         }
333
334                         if(proxypass && *proxypass) {
335                                 proxypass = xstrdup(proxypass);
336                         }
337
338                         break;
339                 }
340
341                 free(proxy);
342         }
343
344         bool choice;
345
346         if(get_config_bool(lookup_config(&config_tree, "IndirectData"), &choice) && choice) {
347                 myself->options |= OPTION_INDIRECT;
348         }
349
350         if(get_config_bool(lookup_config(&config_tree, "TCPOnly"), &choice) && choice) {
351                 myself->options |= OPTION_TCPONLY;
352         }
353
354         if(myself->options & OPTION_TCPONLY) {
355                 myself->options |= OPTION_INDIRECT;
356         }
357
358         get_config_bool(lookup_config(&config_tree, "UDPDiscovery"), &udp_discovery);
359         get_config_int(lookup_config(&config_tree, "UDPDiscoveryKeepaliveInterval"), &udp_discovery_keepalive_interval);
360         get_config_int(lookup_config(&config_tree, "UDPDiscoveryInterval"), &udp_discovery_interval);
361         get_config_int(lookup_config(&config_tree, "UDPDiscoveryTimeout"), &udp_discovery_timeout);
362
363         get_config_int(lookup_config(&config_tree, "MTUInfoInterval"), &mtu_info_interval);
364         get_config_int(lookup_config(&config_tree, "UDPInfoInterval"), &udp_info_interval);
365
366         get_config_bool(lookup_config(&config_tree, "DirectOnly"), &directonly);
367         get_config_bool(lookup_config(&config_tree, "LocalDiscovery"), &localdiscovery);
368
369         char *rmode = NULL;
370
371         if(get_config_string(lookup_config(&config_tree, "Mode"), &rmode)) {
372                 if(!strcasecmp(rmode, "router")) {
373                         routing_mode = RMODE_ROUTER;
374                 } else if(!strcasecmp(rmode, "switch")) {
375                         routing_mode = RMODE_SWITCH;
376                 } else if(!strcasecmp(rmode, "hub")) {
377                         routing_mode = RMODE_HUB;
378                 } else {
379                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
380                         free(rmode);
381                         return false;
382                 }
383
384                 free(rmode);
385         }
386
387         char *fmode = NULL;
388
389         if(get_config_string(lookup_config(&config_tree, "Forwarding"), &fmode)) {
390                 if(!strcasecmp(fmode, "off")) {
391                         forwarding_mode = FMODE_OFF;
392                 } else if(!strcasecmp(fmode, "internal")) {
393                         forwarding_mode = FMODE_INTERNAL;
394                 } else if(!strcasecmp(fmode, "kernel")) {
395                         forwarding_mode = FMODE_KERNEL;
396                 } else {
397                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
398                         free(fmode);
399                         return false;
400                 }
401
402                 free(fmode);
403         }
404
405         choice = !(myself->options & OPTION_TCPONLY);
406         get_config_bool(lookup_config(&config_tree, "PMTUDiscovery"), &choice);
407
408         if(choice) {
409                 myself->options |= OPTION_PMTU_DISCOVERY;
410         }
411
412         choice = true;
413         get_config_bool(lookup_config(&config_tree, "ClampMSS"), &choice);
414
415         if(choice) {
416                 myself->options |= OPTION_CLAMP_MSS;
417         }
418
419         get_config_bool(lookup_config(&config_tree, "PriorityInheritance"), &priorityinheritance);
420         get_config_bool(lookup_config(&config_tree, "DecrementTTL"), &decrement_ttl);
421
422         char *bmode = NULL;
423
424         if(get_config_string(lookup_config(&config_tree, "Broadcast"), &bmode)) {
425                 if(!strcasecmp(bmode, "no")) {
426                         broadcast_mode = BMODE_NONE;
427                 } else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst")) {
428                         broadcast_mode = BMODE_MST;
429                 } else if(!strcasecmp(bmode, "direct")) {
430                         broadcast_mode = BMODE_DIRECT;
431                 } else {
432                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
433                         free(bmode);
434                         return false;
435                 }
436
437                 free(bmode);
438         }
439
440         /* Delete all broadcast subnets before re-adding them */
441
442         for splay_each(subnet_t, s, &subnet_tree) {
443                 if(!s->owner) {
444                         splay_delete_node(&subnet_tree, node);
445                 }
446         }
447
448         const char *const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
449
450         for(size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
451                 subnet_t *s = new_subnet();
452
453                 if(!str2net(s, DEFAULT_BROADCAST_SUBNETS[i])) {
454                         abort();
455                 }
456
457                 subnet_add(NULL, s);
458         }
459
460         for(config_t *cfg = lookup_config(&config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
461                 subnet_t *s;
462
463                 if(!get_config_subnet(cfg, &s)) {
464                         continue;
465                 }
466
467                 subnet_add(NULL, s);
468         }
469
470 #if !defined(IP_TOS)
471
472         if(priorityinheritance) {
473                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv4 connections", "PriorityInheritance");
474         }
475
476 #endif
477
478 #if !defined(IPV6_TCLASS)
479
480         if(priorityinheritance) {
481                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv6 connections", "PriorityInheritance");
482         }
483
484 #endif
485
486         if(!get_config_int(lookup_config(&config_tree, "MACExpire"), &macexpire)) {
487                 macexpire = 600;
488         }
489
490         if(get_config_int(lookup_config(&config_tree, "MaxTimeout"), &maxtimeout)) {
491                 if(maxtimeout <= 0) {
492                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
493                         return false;
494                 }
495         } else {
496                 maxtimeout = 900;
497         }
498
499         char *afname = NULL;
500
501         if(get_config_string(lookup_config(&config_tree, "AddressFamily"), &afname)) {
502                 if(!strcasecmp(afname, "IPv4")) {
503                         addressfamily = AF_INET;
504                 } else if(!strcasecmp(afname, "IPv6")) {
505                         addressfamily = AF_INET6;
506                 } else if(!strcasecmp(afname, "any")) {
507                         addressfamily = AF_UNSPEC;
508                 } else {
509                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
510                         free(afname);
511                         return false;
512                 }
513
514                 free(afname);
515         }
516
517         get_config_bool(lookup_config(&config_tree, "Hostnames"), &hostnames);
518
519         if(!get_config_int(lookup_config(&config_tree, "KeyExpire"), &keylifetime)) {
520                 keylifetime = 3600;
521         }
522
523         if(!get_config_bool(lookup_config(&config_tree, "AutoConnect"), &autoconnect)) {
524                 autoconnect = true;
525         }
526
527         get_config_bool(lookup_config(&config_tree, "DisableBuggyPeers"), &disablebuggypeers);
528
529         if(!get_config_int(lookup_config(&config_tree, "InvitationExpire"), &invitation_lifetime)) {
530                 invitation_lifetime = 604800;        // 1 week
531         }
532
533         read_invitation_key();
534
535         return true;
536 }
537
538 // Get the port that `from_fd` is listening on, and assign it to
539 // `sa` if `sa` has a dynamically allocated (zero) port.
540 static bool assign_static_port(sockaddr_t *sa, int from_fd) {
541         // We cannot get a port from a bad FD. Bail out.
542         if(from_fd <= 0) {
543                 return false;
544         }
545
546         int port = get_bound_port(from_fd);
547
548         if(!port) {
549                 return false;
550         }
551
552         // If the port is non-zero, don't reassign it as it's already static.
553         switch(sa->sa.sa_family) {
554         case AF_INET:
555                 if(!sa->in.sin_port) {
556                         sa->in.sin_port = htons(port);
557                 }
558
559                 return true;
560
561         case AF_INET6:
562                 if(!sa->in6.sin6_port) {
563                         sa->in6.sin6_port = htons(port);
564                 }
565
566                 return true;
567
568         default:
569                 logger(DEBUG_ALWAYS, LOG_ERR, "Unknown address family 0x%x", sa->sa.sa_family);
570                 return false;
571         }
572 }
573
574 typedef int (*bind_fn_t)(const sockaddr_t *);
575
576 static int bind_reusing_port(const sockaddr_t *sa, int from_fd, bind_fn_t setup) {
577         sockaddr_t reuse_sa;
578         memcpy(&reuse_sa, sa, SALEN(sa->sa));
579
580         int fd = -1;
581
582         // Check if the address we've been passed here is using port 0.
583         // If it is, try to get an actual port from an already bound socket, and reuse it here.
584         if(assign_static_port(&reuse_sa, from_fd)) {
585                 fd = setup(&reuse_sa);
586         }
587
588         // If we're binding to a hardcoded non-zero port, or no socket is listening yet,
589         // or binding failed, try the original address.
590         if(fd < 0) {
591                 fd = setup(sa);
592         }
593
594         return fd;
595 }
596
597 /*
598   Add listening sockets.
599 */
600 static bool add_listen_address(char *address, bool bindto) {
601         char *port = myport.tcp;
602
603         if(address) {
604                 char *space = strchr(address, ' ');
605
606                 if(space) {
607                         *space++ = 0;
608                         port = space;
609                 }
610
611                 if(!strcmp(address, "*")) {
612                         *address = 0;
613                 }
614         }
615
616         struct addrinfo *ai, hint = {0};
617
618         hint.ai_family = addressfamily;
619
620         hint.ai_socktype = SOCK_STREAM;
621
622         hint.ai_protocol = IPPROTO_TCP;
623
624         hint.ai_flags = AI_PASSIVE;
625
626 #if HAVE_DECL_RES_INIT
627         res_init();
628
629 #endif
630         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
631
632         free(address);
633
634         if(err || !ai) {
635                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
636                 return false;
637         }
638
639         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
640                 // Ignore duplicate addresses
641                 bool found = false;
642
643                 for(int i = 0; i < listen_sockets; i++)
644                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
645                                 found = true;
646                                 break;
647                         }
648
649                 if(found) {
650                         continue;
651                 }
652
653                 if(listen_sockets >= MAXSOCKETS) {
654                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
655                         freeaddrinfo(ai);
656                         return false;
657                 }
658
659                 const sockaddr_t *sa = (sockaddr_t *) aip->ai_addr;
660                 int from_fd = listen_socket[0].tcp.fd;
661
662                 // If we're binding to a dynamically allocated (zero) port, try to get the actual
663                 // port of the first TCP socket, and use it for this one. If that succeeds, our
664                 // tincd instance will use the same port for all addresses it listens on.
665                 int tcp_fd = bind_reusing_port(sa, from_fd, setup_listen_socket);
666
667                 if(tcp_fd < 0) {
668                         continue;
669                 }
670
671                 // If we just successfully bound the first socket, use it for the UDP procedure below.
672                 // Otherwise, keep using the socket we've obtained from listen_socket[0].
673                 if(!from_fd) {
674                         from_fd = tcp_fd;
675                 }
676
677                 int udp_fd = bind_reusing_port(sa, from_fd, setup_vpn_in_socket);
678
679                 if(udp_fd < 0) {
680                         closesocket(tcp_fd);
681                         continue;
682                 }
683
684                 listen_socket_t *sock = &listen_socket[listen_sockets];
685                 io_add(&sock->tcp, handle_new_meta_connection, sock, tcp_fd, IO_READ);
686                 io_add(&sock->udp, handle_incoming_vpn_data, sock, udp_fd, IO_READ);
687
688                 if(debug_level >= DEBUG_CONNECTIONS) {
689                         int tcp_port = get_bound_port(tcp_fd);
690                         char *hostname = NULL;
691                         sockaddr2str(sa, &hostname, NULL);
692                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s port %d", hostname, tcp_port);
693                         free(hostname);
694                 }
695
696                 sock->bindto = bindto;
697                 memcpy(&sock->sa, aip->ai_addr, aip->ai_addrlen);
698                 listen_sockets++;
699         }
700
701         freeaddrinfo(ai);
702         return true;
703 }
704
705 void device_enable(void) {
706         if(devops.enable) {
707                 devops.enable();
708         }
709
710         /* Run tinc-up script to further initialize the tap interface */
711
712         environment_t env;
713         environment_init(&env);
714         execute_script("tinc-up", &env);
715         environment_exit(&env);
716 }
717
718 void device_disable(void) {
719         environment_t env;
720         environment_init(&env);
721         execute_script("tinc-down", &env);
722         environment_exit(&env);
723
724         if(devops.disable) {
725                 devops.disable();
726         }
727 }
728
729 /*
730   Configure node_t myself and set up the local sockets (listen only)
731 */
732 static bool setup_myself(void) {
733         char *name, *type;
734         char *address = NULL;
735         bool port_specified = false;
736
737         if(!(name = get_name())) {
738                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
739                 return false;
740         }
741
742         myname = xstrdup(name);
743         myself = new_node();
744         myself->connection = new_connection();
745         myself->name = name;
746         myself->connection->name = xstrdup(name);
747         read_host_config(&config_tree, name, true);
748
749         if(!get_config_string(lookup_config(&config_tree, "Port"), &myport.tcp)) {
750                 myport.tcp = xstrdup("655");
751         } else {
752                 port_specified = true;
753         }
754
755         myport.udp = xstrdup(myport.tcp);
756
757         myself->connection->options = 0;
758         myself->connection->protocol_major = PROT_MAJOR;
759         myself->connection->protocol_minor = PROT_MINOR;
760
761         myself->options |= PROT_MINOR << 24;
762
763 #ifdef DISABLE_LEGACY
764         myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
765         experimental = myself->connection->ecdsa != NULL;
766
767         if(!experimental) {
768                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
769                 return false;
770         }
771
772 #else
773
774         if(!get_config_bool(lookup_config(&config_tree, "ExperimentalProtocol"), &experimental)) {
775                 myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
776                 experimental = myself->connection->ecdsa != NULL;
777
778                 if(!experimental) {
779                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
780                 }
781         } else {
782                 if(experimental) {
783                         myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
784
785                         if(!myself->connection->ecdsa) {
786                                 return false;
787                         }
788                 }
789         }
790
791         rsa_t *rsa = read_rsa_private_key(&config_tree, NULL);
792
793         if(rsa) {
794                 myself->connection->legacy = new_legacy_ctx(rsa);
795         } else {
796                 if(experimental) {
797                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
798                 } else {
799                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
800                         return false;
801                 }
802         }
803
804 #endif
805
806         /* Ensure myport is numeric */
807         if(!is_decimal(myport.tcp)) {
808                 uint16_t port = service_to_port(myport.tcp);
809
810                 if(!port) {
811                         return false;
812                 }
813
814                 free(myport.tcp);
815                 myport.tcp = int_to_str(port);
816
817                 free(myport.udp);
818                 myport.udp = xstrdup(myport.tcp);
819         }
820
821         /* Read in all the subnets specified in the host configuration file */
822
823         for(config_t *cfg = lookup_config(&config_tree, "Subnet"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
824                 subnet_t *subnet;
825
826                 if(!get_config_subnet(cfg, &subnet)) {
827                         return false;
828                 }
829
830                 subnet_add(myself, subnet);
831         }
832
833         /* Check some options */
834
835         if(!setup_myself_reloadable()) {
836                 return false;
837         }
838
839         get_config_bool(lookup_config(&config_tree, "StrictSubnets"), &strictsubnets);
840         get_config_bool(lookup_config(&config_tree, "TunnelServer"), &tunnelserver);
841         strictsubnets |= tunnelserver;
842
843         if(get_config_int(lookup_config(&config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
844                 if(max_connection_burst <= 0) {
845                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
846                         return false;
847                 }
848         }
849
850         if(get_config_int(lookup_config(&config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
851                 if(udp_rcvbuf < 0) {
852                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
853                         return false;
854                 }
855
856                 udp_rcvbuf_warnings = true;
857         }
858
859         if(get_config_int(lookup_config(&config_tree, "UDPSndBuf"), &udp_sndbuf)) {
860                 if(udp_sndbuf < 0) {
861                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
862                         return false;
863                 }
864
865                 udp_sndbuf_warnings = true;
866         }
867
868         get_config_int(lookup_config(&config_tree, "FWMark"), &fwmark);
869 #ifndef SO_MARK
870
871         if(fwmark) {
872                 logger(DEBUG_ALWAYS, LOG_ERR, "FWMark not supported on this platform!");
873                 return false;
874         }
875
876 #endif
877
878         int replaywin_int;
879
880         if(get_config_int(lookup_config(&config_tree, "ReplayWindow"), &replaywin_int)) {
881                 if(replaywin_int < 0) {
882                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
883                         return false;
884                 }
885
886                 replaywin = (unsigned)replaywin_int;
887                 sptps_replaywin = replaywin;
888         }
889
890 #ifndef DISABLE_LEGACY
891         /* Generate packet encryption key */
892
893         char *cipher;
894
895         if(!get_config_string(lookup_config(&config_tree, "Cipher"), &cipher)) {
896                 cipher = xstrdup("aes-256-cbc");
897         }
898
899         if(!strcasecmp(cipher, "none")) {
900                 myself->incipher = NULL;
901         } else {
902                 myself->incipher = cipher_alloc();
903
904                 if(!cipher_open_by_name(myself->incipher, cipher)) {
905                         logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
906                         cipher_free(&myself->incipher);
907                         free(cipher);
908                         return false;
909                 }
910         }
911
912         free(cipher);
913
914         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval) {
915                 keylifetime, jitter()
916         });
917
918         /* Check if we want to use message authentication codes... */
919
920         int maclength = 4;
921         get_config_int(lookup_config(&config_tree, "MACLength"), &maclength);
922
923         if(maclength < 0) {
924                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
925                 return false;
926         }
927
928         char *digest;
929
930         if(!get_config_string(lookup_config(&config_tree, "Digest"), &digest)) {
931                 digest = xstrdup("sha256");
932         }
933
934         if(!strcasecmp(digest, "none")) {
935                 myself->indigest = NULL;
936         } else {
937                 myself->indigest = digest_alloc();
938
939                 if(!digest_open_by_name(myself->indigest, digest, maclength)) {
940                         logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
941                         digest_free(&myself->indigest);
942                         free(digest);
943                         return false;
944                 }
945         }
946
947         free(digest);
948 #endif
949
950         /* Compression */
951         int incompression = 0;
952
953         if(get_config_int(lookup_config(&config_tree, "Compression"), &incompression)) {
954                 myself->incompression = incompression;
955
956                 switch(myself->incompression) {
957                 case COMPRESS_LZ4:
958 #ifdef HAVE_LZ4
959                         break;
960 #else
961                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
962                         logger(DEBUG_ALWAYS, LOG_ERR, "LZ4 compression is unavailable on this node.");
963                         return false;
964 #endif
965
966                 case COMPRESS_LZO_HI:
967                 case COMPRESS_LZO_LO:
968 #ifdef HAVE_LZO
969                         break;
970 #else
971                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
972                         logger(DEBUG_ALWAYS, LOG_ERR, "LZO compression is unavailable on this node.");
973                         return false;
974 #endif
975
976                 case COMPRESS_ZLIB_9:
977                 case COMPRESS_ZLIB_8:
978                 case COMPRESS_ZLIB_7:
979                 case COMPRESS_ZLIB_6:
980                 case COMPRESS_ZLIB_5:
981                 case COMPRESS_ZLIB_4:
982                 case COMPRESS_ZLIB_3:
983                 case COMPRESS_ZLIB_2:
984                 case COMPRESS_ZLIB_1:
985 #ifdef HAVE_ZLIB
986                         break;
987 #else
988                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
989                         logger(DEBUG_ALWAYS, LOG_ERR, "ZLIB compression is unavailable on this node.");
990                         return false;
991 #endif
992
993                 case COMPRESS_NONE:
994                         break;
995
996                 default:
997                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
998                         logger(DEBUG_ALWAYS, LOG_ERR, "Compression level %i is unrecognized by this node.", myself->incompression);
999                         return false;
1000                 }
1001         } else {
1002                 myself->incompression = COMPRESS_NONE;
1003         }
1004
1005         /* Done */
1006
1007         myself->nexthop = myself;
1008         myself->via = myself;
1009         myself->status.reachable = true;
1010         myself->last_state_change = now.tv_sec;
1011         myself->status.sptps = experimental;
1012         node_add(myself);
1013
1014         graph();
1015
1016         load_all_nodes();
1017
1018         /* Open device */
1019
1020         devops = os_devops;
1021
1022         if(get_config_string(lookup_config(&config_tree, "DeviceType"), &type)) {
1023                 if(!strcasecmp(type, "dummy")) {
1024                         devops = dummy_devops;
1025                 } else if(!strcasecmp(type, "raw_socket")) {
1026                         devops = raw_socket_devops;
1027                 } else if(!strcasecmp(type, "multicast")) {
1028                         devops = multicast_devops;
1029                 }
1030
1031 #ifdef HAVE_SYS_UN_H
1032                 else if(!strcasecmp(type, "fd")) {
1033                         devops = fd_devops;
1034                 }
1035
1036 #endif
1037 #ifdef ENABLE_UML
1038                 else if(!strcasecmp(type, "uml")) {
1039                         devops = uml_devops;
1040                 }
1041
1042 #endif
1043 #ifdef ENABLE_VDE
1044                 else if(!strcasecmp(type, "vde")) {
1045                         devops = vde_devops;
1046                 }
1047
1048 #endif
1049                 free(type);
1050         }
1051
1052         get_config_bool(lookup_config(&config_tree, "DeviceStandby"), &device_standby);
1053
1054         if(!devops.setup()) {
1055                 return false;
1056         }
1057
1058         if(device_fd >= 0) {
1059                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
1060         }
1061
1062         /* Open sockets */
1063
1064         if(!do_detach && getenv("LISTEN_FDS")) {
1065                 sockaddr_t sa;
1066                 socklen_t salen;
1067
1068                 listen_sockets = atoi(getenv("LISTEN_FDS"));
1069 #ifdef HAVE_UNSETENV
1070                 unsetenv("LISTEN_FDS");
1071 #endif
1072
1073                 if(listen_sockets > MAXSOCKETS) {
1074                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
1075                         return false;
1076                 }
1077
1078                 for(int i = 0; i < listen_sockets; i++) {
1079                         const int tcp_fd = i + 3;
1080                         salen = sizeof(sa);
1081
1082                         if(getsockname(tcp_fd, &sa.sa, &salen) < 0) {
1083                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", tcp_fd, sockstrerror(sockerrno));
1084                                 return false;
1085                         }
1086
1087 #ifdef FD_CLOEXEC
1088                         fcntl(tcp_fd, F_SETFD, FD_CLOEXEC);
1089 #endif
1090
1091                         int udp_fd = setup_vpn_in_socket(&sa);
1092
1093                         if(udp_fd < 0) {
1094                                 return false;
1095                         }
1096
1097                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], tcp_fd, IO_READ);
1098                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1099
1100                         if(debug_level >= DEBUG_CONNECTIONS) {
1101                                 char *hostname = sockaddr2hostname(&sa);
1102                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1103                                 free(hostname);
1104                         }
1105
1106                         memcpy(&listen_socket[i].sa, &sa, salen);
1107                 }
1108         } else {
1109                 listen_sockets = 0;
1110                 int cfgs = 0;
1111
1112                 for(config_t *cfg = lookup_config(&config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1113                         cfgs++;
1114                         get_config_string(cfg, &address);
1115
1116                         if(!add_listen_address(address, true)) {
1117                                 return false;
1118                         }
1119                 }
1120
1121                 for(config_t *cfg = lookup_config(&config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1122                         cfgs++;
1123                         get_config_string(cfg, &address);
1124
1125                         if(!add_listen_address(address, false)) {
1126                                 return false;
1127                         }
1128                 }
1129
1130                 if(!cfgs)
1131                         if(!add_listen_address(address, NULL)) {
1132                                 return false;
1133                         }
1134         }
1135
1136         if(!listen_sockets) {
1137                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1138                 return false;
1139         }
1140
1141         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1142
1143         if(!port_specified || atoi(myport.tcp) == 0) {
1144                 listen_socket_t *sock = &listen_socket[0];
1145
1146                 uint16_t tcp = get_bound_port(sock->tcp.fd);
1147                 free(myport.tcp);
1148                 myport.tcp = int_to_str(tcp);
1149
1150                 uint16_t udp = get_bound_port(sock->udp.fd);
1151                 free(myport.udp);
1152                 myport.udp = int_to_str(udp);
1153         }
1154
1155         xasprintf(&myself->hostname, "MYSELF port %s", myport.tcp);
1156         myself->connection->hostname = xstrdup(myself->hostname);
1157
1158         char *upnp = NULL;
1159         get_config_string(lookup_config(&config_tree, "UPnP"), &upnp);
1160         bool upnp_tcp = false;
1161         bool upnp_udp = false;
1162
1163         if(upnp) {
1164                 if(!strcasecmp(upnp, "yes")) {
1165                         upnp_tcp = upnp_udp = true;
1166                 } else if(!strcasecmp(upnp, "udponly")) {
1167                         upnp_udp = true;
1168                 }
1169
1170                 free(upnp);
1171         }
1172
1173         if(upnp_tcp || upnp_udp) {
1174 #ifdef HAVE_MINIUPNPC
1175                 upnp_init(upnp_tcp, upnp_udp);
1176 #else
1177                 logger(DEBUG_ALWAYS, LOG_WARNING, "UPnP was requested, but tinc isn't built with miniupnpc support!");
1178 #endif
1179         }
1180
1181         /* Done. */
1182
1183         last_config_check = now.tv_sec;
1184
1185         return true;
1186 }
1187
1188 /*
1189   initialize network
1190 */
1191 bool setup_network(void) {
1192         init_connections();
1193         init_subnets();
1194
1195         if(get_config_int(lookup_config(&config_tree, "PingInterval"), &pinginterval)) {
1196                 if(pinginterval < 1) {
1197                         pinginterval = 86400;
1198                 }
1199         } else {
1200                 pinginterval = 60;
1201         }
1202
1203         if(!get_config_int(lookup_config(&config_tree, "PingTimeout"), &pingtimeout)) {
1204                 pingtimeout = 5;
1205         }
1206
1207         if(pingtimeout < 1 || pingtimeout > pinginterval) {
1208                 pingtimeout = pinginterval;
1209         }
1210
1211         if(!get_config_int(lookup_config(&config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1212                 maxoutbufsize = 10 * MTU;
1213         }
1214
1215         if(!setup_myself()) {
1216                 return false;
1217         }
1218
1219         if(!init_control()) {
1220                 return false;
1221         }
1222
1223         if(!device_standby) {
1224                 device_enable();
1225         }
1226
1227         /* Run subnet-up scripts for our own subnets */
1228
1229         subnet_update(myself, NULL, true);
1230
1231         return true;
1232 }
1233
1234 /*
1235   close all open network connections
1236 */
1237 void close_network_connections(void) {
1238         for(list_node_t *node = connection_list.head, *next; node; node = next) {
1239                 next = node->next;
1240                 connection_t *c = node->data;
1241
1242                 /* Keep control connections open until the end, so they know when we really terminated */
1243                 if(c->status.control) {
1244                         c->socket = -1;
1245                 }
1246
1247                 c->outgoing = NULL;
1248                 terminate_connection(c, false);
1249         }
1250
1251         list_empty_list(&outgoing_list);
1252
1253         if(myself && myself->connection) {
1254                 subnet_update(myself, NULL, false);
1255                 free_connection(myself->connection);
1256         }
1257
1258         for(int i = 0; i < listen_sockets; i++) {
1259                 io_del(&listen_socket[i].tcp);
1260                 io_del(&listen_socket[i].udp);
1261                 closesocket(listen_socket[i].tcp.fd);
1262                 closesocket(listen_socket[i].udp.fd);
1263         }
1264
1265         exit_requests();
1266         exit_edges();
1267         exit_subnets();
1268         exit_nodes();
1269         exit_connections();
1270
1271         if(!device_standby) {
1272                 device_disable();
1273         }
1274
1275         free(myport.tcp);
1276         free(myport.udp);
1277
1278         if(device_fd >= 0) {
1279                 io_del(&device_io);
1280         }
1281
1282         if(devops.close) {
1283                 devops.close();
1284         }
1285
1286         exit_control();
1287
1288         free(scriptextension);
1289         free(scriptinterpreter);
1290
1291         return;
1292 }