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