GitHub CI: add MSVC jobs
[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 char *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 /*
539   Add listening sockets.
540 */
541 static bool add_listen_address(char *address, bool bindto) {
542         char *port = myport;
543
544         if(address) {
545                 char *space = strchr(address, ' ');
546
547                 if(space) {
548                         *space++ = 0;
549                         port = space;
550                 }
551
552                 if(!strcmp(address, "*")) {
553                         *address = 0;
554                 }
555         }
556
557         struct addrinfo *ai, hint = {0};
558
559         hint.ai_family = addressfamily;
560
561         hint.ai_socktype = SOCK_STREAM;
562
563         hint.ai_protocol = IPPROTO_TCP;
564
565         hint.ai_flags = AI_PASSIVE;
566
567 #if HAVE_DECL_RES_INIT
568         res_init();
569
570 #endif
571         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
572
573         free(address);
574
575         if(err || !ai) {
576                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
577                 return false;
578         }
579
580         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
581                 // Ignore duplicate addresses
582                 bool found = false;
583
584                 for(int i = 0; i < listen_sockets; i++)
585                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
586                                 found = true;
587                                 break;
588                         }
589
590                 if(found) {
591                         continue;
592                 }
593
594                 if(listen_sockets >= MAXSOCKETS) {
595                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
596                         freeaddrinfo(ai);
597                         return false;
598                 }
599
600                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
601
602                 if(tcp_fd < 0) {
603                         continue;
604                 }
605
606                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
607
608                 if(udp_fd < 0) {
609                         close(tcp_fd);
610                         continue;
611                 }
612
613                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
614                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
615
616                 if(debug_level >= DEBUG_CONNECTIONS) {
617                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
618                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
619                         free(hostname);
620                 }
621
622                 listen_socket[listen_sockets].bindto = bindto;
623                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
624                 listen_sockets++;
625         }
626
627         freeaddrinfo(ai);
628         return true;
629 }
630
631 void device_enable(void) {
632         if(devops.enable) {
633                 devops.enable();
634         }
635
636         /* Run tinc-up script to further initialize the tap interface */
637
638         environment_t env;
639         environment_init(&env);
640         execute_script("tinc-up", &env);
641         environment_exit(&env);
642 }
643
644 void device_disable(void) {
645         environment_t env;
646         environment_init(&env);
647         execute_script("tinc-down", &env);
648         environment_exit(&env);
649
650         if(devops.disable) {
651                 devops.disable();
652         }
653 }
654
655 /*
656   Configure node_t myself and set up the local sockets (listen only)
657 */
658 static bool setup_myself(void) {
659         char *name, *hostname, *type;
660         char *address = NULL;
661         bool port_specified = false;
662
663         if(!(name = get_name())) {
664                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
665                 return false;
666         }
667
668         myname = xstrdup(name);
669         myself = new_node();
670         myself->connection = new_connection();
671         myself->name = name;
672         myself->connection->name = xstrdup(name);
673         read_host_config(&config_tree, name, true);
674
675         if(!get_config_string(lookup_config(&config_tree, "Port"), &myport)) {
676                 myport = xstrdup("655");
677         } else {
678                 port_specified = true;
679         }
680
681         myself->connection->options = 0;
682         myself->connection->protocol_major = PROT_MAJOR;
683         myself->connection->protocol_minor = PROT_MINOR;
684
685         myself->options |= PROT_MINOR << 24;
686
687 #ifdef DISABLE_LEGACY
688         myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
689         experimental = myself->connection->ecdsa != NULL;
690
691         if(!experimental) {
692                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
693                 return false;
694         }
695
696 #else
697
698         if(!get_config_bool(lookup_config(&config_tree, "ExperimentalProtocol"), &experimental)) {
699                 myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
700                 experimental = myself->connection->ecdsa != NULL;
701
702                 if(!experimental) {
703                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
704                 }
705         } else {
706                 if(experimental) {
707                         myself->connection->ecdsa = read_ecdsa_private_key(&config_tree, NULL);
708
709                         if(!myself->connection->ecdsa) {
710                                 return false;
711                         }
712                 }
713         }
714
715         myself->connection->rsa = read_rsa_private_key(&config_tree, NULL);
716
717         if(!myself->connection->rsa) {
718                 if(experimental) {
719                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
720                 } else {
721                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
722                         return false;
723                 }
724         }
725
726 #endif
727
728         /* Ensure myport is numeric */
729
730         if(!atoi(myport)) {
731                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
732                 sockaddr_t sa;
733
734                 if(!ai || !ai->ai_addr) {
735                         return false;
736                 }
737
738                 free(myport);
739                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
740                 freeaddrinfo(ai);
741                 sockaddr2str(&sa, NULL, &myport);
742         }
743
744         /* Read in all the subnets specified in the host configuration file */
745
746         for(config_t *cfg = lookup_config(&config_tree, "Subnet"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
747                 subnet_t *subnet;
748
749                 if(!get_config_subnet(cfg, &subnet)) {
750                         return false;
751                 }
752
753                 subnet_add(myself, subnet);
754         }
755
756         /* Check some options */
757
758         if(!setup_myself_reloadable()) {
759                 return false;
760         }
761
762         get_config_bool(lookup_config(&config_tree, "StrictSubnets"), &strictsubnets);
763         get_config_bool(lookup_config(&config_tree, "TunnelServer"), &tunnelserver);
764         strictsubnets |= tunnelserver;
765
766         if(get_config_int(lookup_config(&config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
767                 if(max_connection_burst <= 0) {
768                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
769                         return false;
770                 }
771         }
772
773         if(get_config_int(lookup_config(&config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
774                 if(udp_rcvbuf < 0) {
775                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
776                         return false;
777                 }
778
779                 udp_rcvbuf_warnings = true;
780         }
781
782         if(get_config_int(lookup_config(&config_tree, "UDPSndBuf"), &udp_sndbuf)) {
783                 if(udp_sndbuf < 0) {
784                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
785                         return false;
786                 }
787
788                 udp_sndbuf_warnings = true;
789         }
790
791         get_config_int(lookup_config(&config_tree, "FWMark"), &fwmark);
792 #ifndef SO_MARK
793
794         if(fwmark) {
795                 logger(DEBUG_ALWAYS, LOG_ERR, "FWMark not supported on this platform!");
796                 return false;
797         }
798
799 #endif
800
801         int replaywin_int;
802
803         if(get_config_int(lookup_config(&config_tree, "ReplayWindow"), &replaywin_int)) {
804                 if(replaywin_int < 0) {
805                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
806                         return false;
807                 }
808
809                 replaywin = (unsigned)replaywin_int;
810                 sptps_replaywin = replaywin;
811         }
812
813 #ifndef DISABLE_LEGACY
814         /* Generate packet encryption key */
815
816         char *cipher;
817
818         if(!get_config_string(lookup_config(&config_tree, "Cipher"), &cipher)) {
819                 cipher = xstrdup("aes-256-cbc");
820         }
821
822         if(!strcasecmp(cipher, "none")) {
823                 myself->incipher = NULL;
824         } else {
825                 myself->incipher = cipher_alloc();
826
827                 if(!cipher_open_by_name(myself->incipher, cipher)) {
828                         logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
829                         cipher_free(&myself->incipher);
830                         free(cipher);
831                         return false;
832                 }
833         }
834
835         free(cipher);
836
837         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval) {
838                 keylifetime, jitter()
839         });
840
841         /* Check if we want to use message authentication codes... */
842
843         int maclength = 4;
844         get_config_int(lookup_config(&config_tree, "MACLength"), &maclength);
845
846         if(maclength < 0) {
847                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
848                 return false;
849         }
850
851         char *digest;
852
853         if(!get_config_string(lookup_config(&config_tree, "Digest"), &digest)) {
854                 digest = xstrdup("sha256");
855         }
856
857         if(!strcasecmp(digest, "none")) {
858                 myself->indigest = NULL;
859         } else {
860                 myself->indigest = digest_alloc();
861
862                 if(!digest_open_by_name(myself->indigest, digest, maclength)) {
863                         logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
864                         digest_free(&myself->indigest);
865                         free(digest);
866                         return false;
867                 }
868         }
869
870         free(digest);
871 #endif
872
873         /* Compression */
874         if(get_config_int(lookup_config(&config_tree, "Compression"), &myself->incompression)) {
875                 switch(myself->incompression) {
876                 case COMPRESS_LZ4:
877 #ifdef HAVE_LZ4
878                         break;
879 #else
880                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
881                         logger(DEBUG_ALWAYS, LOG_ERR, "LZ4 compression is unavailable on this node.");
882                         return false;
883 #endif
884
885                 case COMPRESS_LZO_HI:
886                 case COMPRESS_LZO_LO:
887 #ifdef HAVE_LZO
888                         break;
889 #else
890                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
891                         logger(DEBUG_ALWAYS, LOG_ERR, "LZO compression is unavailable on this node.");
892                         return false;
893 #endif
894
895                 case COMPRESS_ZLIB_9:
896                 case COMPRESS_ZLIB_8:
897                 case COMPRESS_ZLIB_7:
898                 case COMPRESS_ZLIB_6:
899                 case COMPRESS_ZLIB_5:
900                 case COMPRESS_ZLIB_4:
901                 case COMPRESS_ZLIB_3:
902                 case COMPRESS_ZLIB_2:
903                 case COMPRESS_ZLIB_1:
904 #ifdef HAVE_ZLIB
905                         break;
906 #else
907                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
908                         logger(DEBUG_ALWAYS, LOG_ERR, "ZLIB compression is unavailable on this node.");
909                         return false;
910 #endif
911
912                 case COMPRESS_NONE:
913                         break;
914
915                 default:
916                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
917                         logger(DEBUG_ALWAYS, LOG_ERR, "Compression level %i is unrecognized by this node.", myself->incompression);
918                         return false;
919                 }
920         } else {
921                 myself->incompression = COMPRESS_NONE;
922         }
923
924         myself->connection->outcompression = COMPRESS_NONE;
925
926         /* Done */
927
928         myself->nexthop = myself;
929         myself->via = myself;
930         myself->status.reachable = true;
931         myself->last_state_change = now.tv_sec;
932         myself->status.sptps = experimental;
933         node_add(myself);
934
935         graph();
936
937         load_all_nodes();
938
939         /* Open device */
940
941         devops = os_devops;
942
943         if(get_config_string(lookup_config(&config_tree, "DeviceType"), &type)) {
944                 if(!strcasecmp(type, "dummy")) {
945                         devops = dummy_devops;
946                 } else if(!strcasecmp(type, "raw_socket")) {
947                         devops = raw_socket_devops;
948                 } else if(!strcasecmp(type, "multicast")) {
949                         devops = multicast_devops;
950                 }
951
952 #ifdef HAVE_SYS_UN_H
953                 else if(!strcasecmp(type, "fd")) {
954                         devops = fd_devops;
955                 }
956
957 #endif
958 #ifdef ENABLE_UML
959                 else if(!strcasecmp(type, "uml")) {
960                         devops = uml_devops;
961                 }
962
963 #endif
964 #ifdef ENABLE_VDE
965                 else if(!strcasecmp(type, "vde")) {
966                         devops = vde_devops;
967                 }
968
969 #endif
970                 free(type);
971         }
972
973         get_config_bool(lookup_config(&config_tree, "DeviceStandby"), &device_standby);
974
975         if(!devops.setup()) {
976                 return false;
977         }
978
979         if(device_fd >= 0) {
980                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
981         }
982
983         /* Open sockets */
984
985         if(!do_detach && getenv("LISTEN_FDS")) {
986                 sockaddr_t sa;
987                 socklen_t salen;
988
989                 listen_sockets = atoi(getenv("LISTEN_FDS"));
990 #ifdef HAVE_UNSETENV
991                 unsetenv("LISTEN_FDS");
992 #endif
993
994                 if(listen_sockets > MAXSOCKETS) {
995                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
996                         return false;
997                 }
998
999                 for(int i = 0; i < listen_sockets; i++) {
1000                         salen = sizeof(sa);
1001
1002                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
1003                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
1004                                 return false;
1005                         }
1006
1007 #ifdef FD_CLOEXEC
1008                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
1009 #endif
1010
1011                         int udp_fd = setup_vpn_in_socket(&sa);
1012
1013                         if(udp_fd < 0) {
1014                                 return false;
1015                         }
1016
1017                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
1018                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1019
1020                         if(debug_level >= DEBUG_CONNECTIONS) {
1021                                 hostname = sockaddr2hostname(&sa);
1022                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1023                                 free(hostname);
1024                         }
1025
1026                         memcpy(&listen_socket[i].sa, &sa, salen);
1027                 }
1028         } else {
1029                 listen_sockets = 0;
1030                 int cfgs = 0;
1031
1032                 for(config_t *cfg = lookup_config(&config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1033                         cfgs++;
1034                         get_config_string(cfg, &address);
1035
1036                         if(!add_listen_address(address, true)) {
1037                                 return false;
1038                         }
1039                 }
1040
1041                 for(config_t *cfg = lookup_config(&config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1042                         cfgs++;
1043                         get_config_string(cfg, &address);
1044
1045                         if(!add_listen_address(address, false)) {
1046                                 return false;
1047                         }
1048                 }
1049
1050                 if(!cfgs)
1051                         if(!add_listen_address(address, NULL)) {
1052                                 return false;
1053                         }
1054         }
1055
1056         if(!listen_sockets) {
1057                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1058                 return false;
1059         }
1060
1061         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1062
1063         if(!port_specified || atoi(myport) == 0) {
1064                 sockaddr_t sa;
1065                 socklen_t salen = sizeof(sa);
1066
1067                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1068                         free(myport);
1069                         sockaddr2str(&sa, NULL, &myport);
1070
1071                         if(!myport) {
1072                                 myport = xstrdup("655");
1073                         }
1074                 }
1075         }
1076
1077         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1078         myself->connection->hostname = xstrdup(myself->hostname);
1079
1080         char *upnp = NULL;
1081         get_config_string(lookup_config(&config_tree, "UPnP"), &upnp);
1082         bool upnp_tcp = false;
1083         bool upnp_udp = false;
1084
1085         if(upnp) {
1086                 if(!strcasecmp(upnp, "yes")) {
1087                         upnp_tcp = upnp_udp = true;
1088                 } else if(!strcasecmp(upnp, "udponly")) {
1089                         upnp_udp = true;
1090                 }
1091
1092                 free(upnp);
1093         }
1094
1095         if(upnp_tcp || upnp_udp) {
1096 #ifdef HAVE_MINIUPNPC
1097                 upnp_init(upnp_tcp, upnp_udp);
1098 #else
1099                 logger(DEBUG_ALWAYS, LOG_WARNING, "UPnP was requested, but tinc isn't built with miniupnpc support!");
1100 #endif
1101         }
1102
1103         /* Done. */
1104
1105         last_config_check = now.tv_sec;
1106
1107         return true;
1108 }
1109
1110 /*
1111   initialize network
1112 */
1113 bool setup_network(void) {
1114         init_connections();
1115         init_subnets();
1116
1117         if(get_config_int(lookup_config(&config_tree, "PingInterval"), &pinginterval)) {
1118                 if(pinginterval < 1) {
1119                         pinginterval = 86400;
1120                 }
1121         } else {
1122                 pinginterval = 60;
1123         }
1124
1125         if(!get_config_int(lookup_config(&config_tree, "PingTimeout"), &pingtimeout)) {
1126                 pingtimeout = 5;
1127         }
1128
1129         if(pingtimeout < 1 || pingtimeout > pinginterval) {
1130                 pingtimeout = pinginterval;
1131         }
1132
1133         if(!get_config_int(lookup_config(&config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1134                 maxoutbufsize = 10 * MTU;
1135         }
1136
1137         if(!setup_myself()) {
1138                 return false;
1139         }
1140
1141         if(!init_control()) {
1142                 return false;
1143         }
1144
1145         if(!device_standby) {
1146                 device_enable();
1147         }
1148
1149         /* Run subnet-up scripts for our own subnets */
1150
1151         subnet_update(myself, NULL, true);
1152
1153         return true;
1154 }
1155
1156 /*
1157   close all open network connections
1158 */
1159 void close_network_connections(void) {
1160         for(list_node_t *node = connection_list.head, *next; node; node = next) {
1161                 next = node->next;
1162                 connection_t *c = node->data;
1163
1164                 /* Keep control connections open until the end, so they know when we really terminated */
1165                 if(c->status.control) {
1166                         c->socket = -1;
1167                 }
1168
1169                 c->outgoing = NULL;
1170                 terminate_connection(c, false);
1171         }
1172
1173         list_empty_list(&outgoing_list);
1174
1175         if(myself && myself->connection) {
1176                 subnet_update(myself, NULL, false);
1177                 free_connection(myself->connection);
1178         }
1179
1180         for(int i = 0; i < listen_sockets; i++) {
1181                 io_del(&listen_socket[i].tcp);
1182                 io_del(&listen_socket[i].udp);
1183                 close(listen_socket[i].tcp.fd);
1184                 close(listen_socket[i].udp.fd);
1185         }
1186
1187         exit_requests();
1188         exit_edges();
1189         exit_subnets();
1190         exit_nodes();
1191         exit_connections();
1192
1193         if(!device_standby) {
1194                 device_disable();
1195         }
1196
1197         free(myport);
1198
1199         if(device_fd >= 0) {
1200                 io_del(&device_io);
1201         }
1202
1203         if(devops.close) {
1204                 devops.close();
1205         }
1206
1207         exit_control();
1208
1209         free(scriptextension);
1210         free(scriptinterpreter);
1211
1212         return;
1213 }