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