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