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