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