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