23dd2521c74b465cdc64405ea79b3f821e3040aa
[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                                 free(s);
368                         } else {
369                                 subnet_add(n, s);
370                         }
371                 }
372
373                 exit_configuration(&config_tree);
374         }
375
376         closedir(dir);
377 }
378
379 void load_all_nodes(void) {
380         DIR *dir;
381         struct dirent *ent;
382         char dname[PATH_MAX];
383
384         snprintf(dname, sizeof dname, "%s" SLASH "hosts", confbase);
385         dir = opendir(dname);
386         if(!dir) {
387                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
388                 return;
389         }
390
391         while((ent = readdir(dir))) {
392                 if(!check_id(ent->d_name))
393                         continue;
394
395                 node_t *n = lookup_node(ent->d_name);
396                 if(n)
397                         continue;
398
399                 n = new_node();
400                 n->name = xstrdup(ent->d_name);
401                 node_add(n);
402         }
403
404         closedir(dir);
405 }
406
407
408 char *get_name(void) {
409         char *name = NULL;
410         char *returned_name;
411
412         get_config_string(lookup_config(config_tree, "Name"), &name);
413
414         if(!name)
415                 return NULL;
416
417         returned_name = replace_name(name);
418         free(name);
419         return returned_name;
420 }
421
422 bool setup_myself_reloadable(void) {
423         char *proxy = NULL;
424         char *rmode = NULL;
425         char *fmode = NULL;
426         char *bmode = NULL;
427         char *afname = NULL;
428         char *space;
429         bool choice;
430
431         free(scriptinterpreter);
432         scriptinterpreter = NULL;
433         get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &scriptinterpreter);
434
435
436         free(scriptextension);
437         if(!get_config_string(lookup_config(config_tree, "ScriptsExtension"), &scriptextension))
438                 scriptextension = xstrdup("");
439
440         get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
441         if(proxy) {
442                 if((space = strchr(proxy, ' ')))
443                         *space++ = 0;
444
445                 if(!strcasecmp(proxy, "none")) {
446                         proxytype = PROXY_NONE;
447                 } else if(!strcasecmp(proxy, "socks4")) {
448                         proxytype = PROXY_SOCKS4;
449                 } else if(!strcasecmp(proxy, "socks4a")) {
450                         proxytype = PROXY_SOCKS4A;
451                 } else if(!strcasecmp(proxy, "socks5")) {
452                         proxytype = PROXY_SOCKS5;
453                 } else if(!strcasecmp(proxy, "http")) {
454                         proxytype = PROXY_HTTP;
455                 } else if(!strcasecmp(proxy, "exec")) {
456                         proxytype = PROXY_EXEC;
457                 } else {
458                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
459                         return false;
460                 }
461
462                 switch(proxytype) {
463                         case PROXY_NONE:
464                         default:
465                                 break;
466
467                         case PROXY_EXEC:
468                                 if(!space || !*space) {
469                                         logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
470                                         return false;
471                                 }
472                                 proxyhost =  xstrdup(space);
473                                 break;
474
475                         case PROXY_SOCKS4:
476                         case PROXY_SOCKS4A:
477                         case PROXY_SOCKS5:
478                         case PROXY_HTTP:
479                                 proxyhost = space;
480                                 if(space && (space = strchr(space, ' ')))
481                                         *space++ = 0, proxyport = space;
482                                 if(space && (space = strchr(space, ' ')))
483                                         *space++ = 0, proxyuser = space;
484                                 if(space && (space = strchr(space, ' ')))
485                                         *space++ = 0, proxypass = space;
486                                 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
487                                         logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
488                                         return false;
489                                 }
490                                 proxyhost = xstrdup(proxyhost);
491                                 proxyport = xstrdup(proxyport);
492                                 if(proxyuser && *proxyuser)
493                                         proxyuser = xstrdup(proxyuser);
494                                 if(proxypass && *proxypass)
495                                         proxypass = xstrdup(proxypass);
496                                 break;
497                 }
498
499                 free(proxy);
500         }
501
502         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
503                 myself->options |= OPTION_INDIRECT;
504
505         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
506                 myself->options |= OPTION_TCPONLY;
507
508         if(myself->options & OPTION_TCPONLY)
509                 myself->options |= OPTION_INDIRECT;
510
511         get_config_bool(lookup_config(config_tree, "UDPDiscovery"), &udp_discovery);
512         get_config_int(lookup_config(config_tree, "UDPDiscoveryKeepaliveInterval"), &udp_discovery_keepalive_interval);
513         get_config_int(lookup_config(config_tree, "UDPDiscoveryInterval"), &udp_discovery_interval);
514         get_config_int(lookup_config(config_tree, "UDPDiscoveryTimeout"), &udp_discovery_timeout);
515
516         get_config_int(lookup_config(config_tree, "MTUInfoInterval"), &mtu_info_interval);
517         get_config_int(lookup_config(config_tree, "UDPInfoInterval"), &udp_info_interval);
518
519         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
520         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
521
522         if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
523                 if(!strcasecmp(rmode, "router"))
524                         routing_mode = RMODE_ROUTER;
525                 else if(!strcasecmp(rmode, "switch"))
526                         routing_mode = RMODE_SWITCH;
527                 else if(!strcasecmp(rmode, "hub"))
528                         routing_mode = RMODE_HUB;
529                 else {
530                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
531                         return false;
532                 }
533                 free(rmode);
534         }
535
536         if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
537                 if(!strcasecmp(fmode, "off"))
538                         forwarding_mode = FMODE_OFF;
539                 else if(!strcasecmp(fmode, "internal"))
540                         forwarding_mode = FMODE_INTERNAL;
541                 else if(!strcasecmp(fmode, "kernel"))
542                         forwarding_mode = FMODE_KERNEL;
543                 else {
544                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
545                         return false;
546                 }
547                 free(fmode);
548         }
549
550         choice = true;
551         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
552         if(choice)
553                 myself->options |= OPTION_PMTU_DISCOVERY;
554
555         choice = true;
556         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
557         if(choice)
558                 myself->options |= OPTION_CLAMP_MSS;
559
560         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
561         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
562         if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
563                 if(!strcasecmp(bmode, "no"))
564                         broadcast_mode = BMODE_NONE;
565                 else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst"))
566                         broadcast_mode = BMODE_MST;
567                 else if(!strcasecmp(bmode, "direct"))
568                         broadcast_mode = BMODE_DIRECT;
569                 else {
570                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
571                         return false;
572                 }
573                 free(bmode);
574         }
575
576         const char* const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
577         for (size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
578                 subnet_t *s = new_subnet();
579                 if (!str2net(s, DEFAULT_BROADCAST_SUBNETS[i]))
580                         abort();
581                 subnet_add(NULL, s);
582         }
583         for (config_t* cfg = lookup_config(config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
584                 subnet_t *s;
585                 if (!get_config_subnet(cfg, &s))
586                         continue;
587                 subnet_add(NULL, s);
588         }
589
590 #if !defined(SOL_IP) || !defined(IP_TOS)
591         if(priorityinheritance)
592                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
593 #endif
594
595         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
596                 macexpire = 600;
597
598         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
599                 if(maxtimeout <= 0) {
600                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
601                         return false;
602                 }
603         } else
604                 maxtimeout = 900;
605
606         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
607                 if(!strcasecmp(afname, "IPv4"))
608                         addressfamily = AF_INET;
609                 else if(!strcasecmp(afname, "IPv6"))
610                         addressfamily = AF_INET6;
611                 else if(!strcasecmp(afname, "any"))
612                         addressfamily = AF_UNSPEC;
613                 else {
614                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
615                         return false;
616                 }
617                 free(afname);
618         }
619
620         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
621
622         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
623                 keylifetime = 3600;
624
625         config_t *cfg = lookup_config(config_tree, "AutoConnect");
626         if(cfg) {
627                 if(!get_config_bool(cfg, &autoconnect)) {
628                         // Some backwards compatibility with when this option was an int
629                         int val = 0;
630                         get_config_int(cfg, &val);
631                         autoconnect = val;
632                 }
633         }
634
635         get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
636
637         read_invitation_key();
638
639         return true;
640 }
641
642 /*
643   Add listening sockets.
644 */
645 static bool add_listen_address(char *address, bool bindto) {
646         char *port = myport;
647
648         if(address) {
649                 char *space = strchr(address, ' ');
650                 if(space) {
651                         *space++ = 0;
652                         port = space;
653                 }
654
655                 if(!strcmp(address, "*"))
656                         *address = 0;
657         }
658
659         struct addrinfo *ai, hint = {0};
660         hint.ai_family = addressfamily;
661         hint.ai_socktype = SOCK_STREAM;
662         hint.ai_protocol = IPPROTO_TCP;
663         hint.ai_flags = AI_PASSIVE;
664
665 #if HAVE_DECL_RES_INIT
666         res_init();
667 #endif
668         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
669         free(address);
670
671         if(err || !ai) {
672                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
673                 return false;
674         }
675
676         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
677                 // Ignore duplicate addresses
678                 bool found = false;
679
680                 for(int i = 0; i < listen_sockets; i++)
681                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
682                                 found = true;
683                                 break;
684                         }
685
686                 if(found)
687                         continue;
688
689                 if(listen_sockets >= MAXSOCKETS) {
690                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
691                         return false;
692                 }
693
694                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
695
696                 if(tcp_fd < 0)
697                         continue;
698
699                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
700
701                 if(tcp_fd < 0) {
702                         close(tcp_fd);
703                         continue;
704                 }
705
706                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
707                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
708
709                 if(debug_level >= DEBUG_CONNECTIONS) {
710                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
711                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
712                         free(hostname);
713                 }
714
715                 listen_socket[listen_sockets].bindto = bindto;
716                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
717                 listen_sockets++;
718         }
719
720         freeaddrinfo(ai);
721         return true;
722 }
723
724 void device_enable(void) {
725         if (devops.enable)
726                 devops.enable();
727
728         /* Run tinc-up script to further initialize the tap interface */
729
730         char *envp[5] = {NULL};
731         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
732         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
733         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
734         xasprintf(&envp[3], "NAME=%s", myname);
735
736         execute_script("tinc-up", envp);
737
738         for(int i = 0; i < 4; i++)
739                 free(envp[i]);
740 }
741
742 void device_disable(void) {
743         char *envp[5] = {NULL};
744         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
745         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
746         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
747         xasprintf(&envp[3], "NAME=%s", myname);
748
749         execute_script("tinc-down", envp);
750
751         for(int i = 0; i < 4; i++)
752                 free(envp[i]);
753
754         if (devops.disable)
755                 devops.disable();
756 }
757
758 /*
759   Configure node_t myself and set up the local sockets (listen only)
760 */
761 static bool setup_myself(void) {
762         char *name, *hostname, *cipher, *digest, *type;
763         char *address = NULL;
764         bool port_specified = false;
765
766         if(!(name = get_name())) {
767                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
768                 return false;
769         }
770
771         myname = xstrdup(name);
772         myself = new_node();
773         myself->connection = new_connection();
774         myself->name = name;
775         myself->connection->name = xstrdup(name);
776         read_host_config(config_tree, name);
777
778         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
779                 myport = xstrdup("655");
780         else
781                 port_specified = true;
782
783         myself->connection->options = 0;
784         myself->connection->protocol_major = PROT_MAJOR;
785         myself->connection->protocol_minor = PROT_MINOR;
786
787         myself->options |= PROT_MINOR << 24;
788
789 #ifdef DISABLE_LEGACY
790         experimental = read_ecdsa_private_key();
791         if(!experimental) {
792                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
793                 return false;
794         }
795 #else
796         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
797                 experimental = read_ecdsa_private_key();
798                 if(!experimental)
799                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
800         } else {
801                 if(experimental && !read_ecdsa_private_key())
802                         return false;
803         }
804
805         if(!read_rsa_private_key()) {
806                 if(experimental) {
807                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
808                 } else {
809                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
810                         return false;
811                 }
812         }
813 #endif
814
815         /* Ensure myport is numeric */
816
817         if(!atoi(myport)) {
818                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
819                 sockaddr_t sa;
820                 if(!ai || !ai->ai_addr)
821                         return false;
822                 free(myport);
823                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
824                 sockaddr2str(&sa, NULL, &myport);
825         }
826
827         /* Read in all the subnets specified in the host configuration file */
828
829         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
830                 subnet_t *subnet;
831
832                 if(!get_config_subnet(cfg, &subnet))
833                         return false;
834
835                 subnet_add(myself, subnet);
836         }
837
838         /* Check some options */
839
840         if(!setup_myself_reloadable())
841                 return false;
842
843         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
844         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
845         strictsubnets |= tunnelserver;
846
847         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
848                 if(max_connection_burst <= 0) {
849                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
850                         return false;
851                 }
852         }
853
854         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
855                 if(udp_rcvbuf < 0) {
856                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
857                         return false;
858                 }
859         }
860
861         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
862                 if(udp_sndbuf < 0) {
863                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
864                         return false;
865                 }
866         }
867
868         int replaywin_int;
869         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
870                 if(replaywin_int < 0) {
871                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
872                         return false;
873                 }
874                 replaywin = (unsigned)replaywin_int;
875                 sptps_replaywin = replaywin;
876         }
877
878 #ifndef DISABLE_LEGACY
879         /* Generate packet encryption key */
880
881         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
882                 cipher = xstrdup("blowfish");
883
884         if(!strcasecmp(cipher, "none")) {
885                 myself->incipher = NULL;
886         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
887                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
888                 return false;
889         }
890
891         free(cipher);
892
893         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
894
895         /* Check if we want to use message authentication codes... */
896
897         int maclength = 4;
898         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
899
900         if(maclength < 0) {
901                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
902                 return false;
903         }
904
905         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
906                 digest = xstrdup("sha1");
907
908         if(!strcasecmp(digest, "none")) {
909                 myself->indigest = NULL;
910         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
911                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
912                 return false;
913         }
914
915         free(digest);
916 #endif
917
918         /* Compression */
919
920         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
921                 if(myself->incompression < 0 || myself->incompression > 11) {
922                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
923                         return false;
924                 }
925         } else
926                 myself->incompression = 0;
927
928         myself->connection->outcompression = 0;
929
930         /* Done */
931
932         myself->nexthop = myself;
933         myself->via = myself;
934         myself->status.reachable = true;
935         myself->last_state_change = now.tv_sec;
936         myself->status.sptps = experimental;
937         node_add(myself);
938
939         graph();
940
941         if(strictsubnets)
942                 load_all_subnets();
943         else if(autoconnect)
944                 load_all_nodes();
945
946         /* Open device */
947
948         devops = os_devops;
949
950         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
951                 if(!strcasecmp(type, "dummy"))
952                         devops = dummy_devops;
953                 else if(!strcasecmp(type, "raw_socket"))
954                         devops = raw_socket_devops;
955                 else if(!strcasecmp(type, "multicast"))
956                         devops = multicast_devops;
957 #ifdef ENABLE_UML
958                 else if(!strcasecmp(type, "uml"))
959                         devops = uml_devops;
960 #endif
961 #ifdef ENABLE_VDE
962                 else if(!strcasecmp(type, "vde"))
963                         devops = vde_devops;
964 #endif
965                 free(type);
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 }