Use a different UDP discovery interval if the tunnel is established.
[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 }
323
324 /*
325   Read Subnets from all host config files
326 */
327 void load_all_subnets(void) {
328         DIR *dir;
329         struct dirent *ent;
330         char *dname;
331
332         xasprintf(&dname, "%s" SLASH "hosts", confbase);
333         dir = opendir(dname);
334         if(!dir) {
335                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
336                 free(dname);
337                 return;
338         }
339
340         while((ent = readdir(dir))) {
341                 if(!check_id(ent->d_name))
342                         continue;
343
344                 node_t *n = lookup_node(ent->d_name);
345                 #ifdef _DIRENT_HAVE_D_TYPE
346                 //if(ent->d_type != DT_REG)
347                 //      continue;
348                 #endif
349
350                 splay_tree_t *config_tree;
351                 init_configuration(&config_tree);
352                 read_config_options(config_tree, ent->d_name);
353                 read_host_config(config_tree, ent->d_name);
354
355                 if(!n) {
356                         n = new_node();
357                         n->name = xstrdup(ent->d_name);
358                         node_add(n);
359                 }
360
361                 for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
362                         subnet_t *s, *s2;
363
364                         if(!get_config_subnet(cfg, &s))
365                                 continue;
366
367                         if((s2 = lookup_subnet(n, s))) {
368                                 s2->expires = -1;
369                         } else {
370                                 subnet_add(n, s);
371                         }
372                 }
373
374                 exit_configuration(&config_tree);
375         }
376
377         closedir(dir);
378 }
379
380 void load_all_nodes(void) {
381         DIR *dir;
382         struct dirent *ent;
383         char *dname;
384
385         xasprintf(&dname, "%s" SLASH "hosts", confbase);
386         dir = opendir(dname);
387         if(!dir) {
388                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
389                 free(dname);
390                 return;
391         }
392
393         while((ent = readdir(dir))) {
394                 if(!check_id(ent->d_name))
395                         continue;
396
397                 node_t *n = lookup_node(ent->d_name);
398                 if(n)
399                         continue;
400
401                 n = new_node();
402                 n->name = xstrdup(ent->d_name);
403                 node_add(n);
404         }
405
406         closedir(dir);
407 }
408
409
410 char *get_name(void) {
411         char *name = NULL;
412         char *returned_name;
413
414         get_config_string(lookup_config(config_tree, "Name"), &name);
415
416         if(!name)
417                 return NULL;
418
419         returned_name = replace_name(name);
420         free(name);
421         return returned_name;
422 }
423
424 bool setup_myself_reloadable(void) {
425         char *proxy = NULL;
426         char *rmode = NULL;
427         char *fmode = NULL;
428         char *bmode = NULL;
429         char *afname = NULL;
430         char *space;
431         bool choice;
432
433         free(scriptinterpreter);
434         scriptinterpreter = NULL;
435         get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &scriptinterpreter);
436
437
438         free(scriptextension);
439         if(!get_config_string(lookup_config(config_tree, "ScriptsExtension"), &scriptextension))
440                 scriptextension = xstrdup("");
441
442         get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
443         if(proxy) {
444                 if((space = strchr(proxy, ' ')))
445                         *space++ = 0;
446
447                 if(!strcasecmp(proxy, "none")) {
448                         proxytype = PROXY_NONE;
449                 } else if(!strcasecmp(proxy, "socks4")) {
450                         proxytype = PROXY_SOCKS4;
451                 } else if(!strcasecmp(proxy, "socks4a")) {
452                         proxytype = PROXY_SOCKS4A;
453                 } else if(!strcasecmp(proxy, "socks5")) {
454                         proxytype = PROXY_SOCKS5;
455                 } else if(!strcasecmp(proxy, "http")) {
456                         proxytype = PROXY_HTTP;
457                 } else if(!strcasecmp(proxy, "exec")) {
458                         proxytype = PROXY_EXEC;
459                 } else {
460                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
461                         return false;
462                 }
463
464                 switch(proxytype) {
465                         case PROXY_NONE:
466                         default:
467                                 break;
468
469                         case PROXY_EXEC:
470                                 if(!space || !*space) {
471                                         logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
472                                         return false;
473                                 }
474                                 proxyhost =  xstrdup(space);
475                                 break;
476
477                         case PROXY_SOCKS4:
478                         case PROXY_SOCKS4A:
479                         case PROXY_SOCKS5:
480                         case PROXY_HTTP:
481                                 proxyhost = space;
482                                 if(space && (space = strchr(space, ' ')))
483                                         *space++ = 0, proxyport = space;
484                                 if(space && (space = strchr(space, ' ')))
485                                         *space++ = 0, proxyuser = space;
486                                 if(space && (space = strchr(space, ' ')))
487                                         *space++ = 0, proxypass = space;
488                                 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
489                                         logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
490                                         return false;
491                                 }
492                                 proxyhost = xstrdup(proxyhost);
493                                 proxyport = xstrdup(proxyport);
494                                 if(proxyuser && *proxyuser)
495                                         proxyuser = xstrdup(proxyuser);
496                                 if(proxypass && *proxypass)
497                                         proxypass = xstrdup(proxypass);
498                                 break;
499                 }
500
501                 free(proxy);
502         }
503
504         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
505                 myself->options |= OPTION_INDIRECT;
506
507         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
508                 myself->options |= OPTION_TCPONLY;
509
510         if(myself->options & OPTION_TCPONLY)
511                 myself->options |= OPTION_INDIRECT;
512
513         get_config_bool(lookup_config(config_tree, "UDPDiscovery"), &udp_discovery);
514         get_config_int(lookup_config(config_tree, "UDPDiscoveryKeepaliveInterval"), &udp_discovery_keepalive_interval);
515         get_config_int(lookup_config(config_tree, "UDPDiscoveryInterval"), &udp_discovery_interval);
516         get_config_int(lookup_config(config_tree, "UDPDiscoveryTimeout"), &udp_discovery_timeout);
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         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
665         free(address);
666
667         if(err || !ai) {
668                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
669                 return false;
670         }
671
672         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
673                 // Ignore duplicate addresses
674                 bool found = false;
675
676                 for(int i = 0; i < listen_sockets; i++)
677                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
678                                 found = true;
679                                 break;
680                         }
681
682                 if(found)
683                         continue;
684
685                 if(listen_sockets >= MAXSOCKETS) {
686                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
687                         return false;
688                 }
689
690                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
691
692                 if(tcp_fd < 0)
693                         continue;
694
695                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
696
697                 if(tcp_fd < 0) {
698                         close(tcp_fd);
699                         continue;
700                 }
701
702                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
703                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
704
705                 if(debug_level >= DEBUG_CONNECTIONS) {
706                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
707                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
708                         free(hostname);
709                 }
710
711                 listen_socket[listen_sockets].bindto = bindto;
712                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
713                 listen_sockets++;
714         }
715
716         freeaddrinfo(ai);
717         return true;
718 }
719
720 void device_enable(void) {
721         if (devops.enable)
722                 devops.enable();
723
724         /* Run tinc-up script to further initialize the tap interface */
725
726         char *envp[5] = {NULL};
727         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
728         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
729         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
730         xasprintf(&envp[3], "NAME=%s", myname);
731
732         execute_script("tinc-up", envp);
733
734         for(int i = 0; i < 4; i++)
735                 free(envp[i]);
736 }
737
738 void device_disable(void) {
739         char *envp[5] = {NULL};
740         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
741         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
742         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
743         xasprintf(&envp[3], "NAME=%s", myname);
744
745         execute_script("tinc-down", envp);
746
747         for(int i = 0; i < 4; i++)
748                 free(envp[i]);
749
750         if (devops.disable)
751                 devops.disable();
752 }
753
754 /*
755   Configure node_t myself and set up the local sockets (listen only)
756 */
757 static bool setup_myself(void) {
758         char *name, *hostname, *cipher, *digest, *type;
759         char *address = NULL;
760         bool port_specified = false;
761
762         if(!(name = get_name())) {
763                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
764                 return false;
765         }
766
767         myname = xstrdup(name);
768         myself = new_node();
769         myself->connection = new_connection();
770         myself->name = name;
771         myself->connection->name = xstrdup(name);
772         read_host_config(config_tree, name);
773
774         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
775                 myport = xstrdup("655");
776         else
777                 port_specified = true;
778
779         myself->connection->options = 0;
780         myself->connection->protocol_major = PROT_MAJOR;
781         myself->connection->protocol_minor = PROT_MINOR;
782
783         myself->options |= PROT_MINOR << 24;
784
785 #ifdef DISABLE_LEGACY
786         experimental = read_ecdsa_private_key();
787         if(!experimental) {
788                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
789                 return false;
790         }
791 #else
792         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
793                 experimental = read_ecdsa_private_key();
794                 if(!experimental)
795                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
796         } else {
797                 if(experimental && !read_ecdsa_private_key())
798                         return false;
799         }
800
801         if(!read_rsa_private_key()) {
802                 if(experimental) {
803                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
804                 } else {
805                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
806                         return false;
807                 }
808         }
809 #endif
810
811         /* Ensure myport is numeric */
812
813         if(!atoi(myport)) {
814                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
815                 sockaddr_t sa;
816                 if(!ai || !ai->ai_addr)
817                         return false;
818                 free(myport);
819                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
820                 sockaddr2str(&sa, NULL, &myport);
821         }
822
823         /* Read in all the subnets specified in the host configuration file */
824
825         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
826                 subnet_t *subnet;
827
828                 if(!get_config_subnet(cfg, &subnet))
829                         return false;
830
831                 subnet_add(myself, subnet);
832         }
833
834         /* Check some options */
835
836         if(!setup_myself_reloadable())
837                 return false;
838
839         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
840         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
841         strictsubnets |= tunnelserver;
842
843         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
844                 if(max_connection_burst <= 0) {
845                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
846                         return false;
847                 }
848         }
849
850         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
851                 if(udp_rcvbuf <= 0) {
852                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
853                         return false;
854                 }
855         }
856
857         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
858                 if(udp_sndbuf <= 0) {
859                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
860                         return false;
861                 }
862         }
863
864         int replaywin_int;
865         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
866                 if(replaywin_int < 0) {
867                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
868                         return false;
869                 }
870                 replaywin = (unsigned)replaywin_int;
871                 sptps_replaywin = replaywin;
872         }
873
874 #ifndef DISABLE_LEGACY
875         /* Generate packet encryption key */
876
877         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
878                 cipher = xstrdup("blowfish");
879
880         if(!strcasecmp(cipher, "none")) {
881                 myself->incipher = NULL;
882         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
883                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
884                 return false;
885         }
886
887         free(cipher);
888
889         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
890
891         /* Check if we want to use message authentication codes... */
892
893         int maclength = 4;
894         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
895
896         if(maclength < 0) {
897                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
898                 return false;
899         }
900
901         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
902                 digest = xstrdup("sha1");
903
904         if(!strcasecmp(digest, "none")) {
905                 myself->indigest = NULL;
906         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
907                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
908                 return false;
909         }
910
911         free(digest);
912 #endif
913
914         /* Compression */
915
916         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
917                 if(myself->incompression < 0 || myself->incompression > 11) {
918                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
919                         return false;
920                 }
921         } else
922                 myself->incompression = 0;
923
924         myself->connection->outcompression = 0;
925
926         /* Done */
927
928         myself->nexthop = myself;
929         myself->via = myself;
930         myself->status.reachable = true;
931         myself->last_state_change = now.tv_sec;
932         myself->status.sptps = experimental;
933         node_add(myself);
934
935         graph();
936
937         if(strictsubnets)
938                 load_all_subnets();
939         else if(autoconnect)
940                 load_all_nodes();
941
942         /* Open device */
943
944         devops = os_devops;
945
946         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
947                 if(!strcasecmp(type, "dummy"))
948                         devops = dummy_devops;
949                 else if(!strcasecmp(type, "raw_socket"))
950                         devops = raw_socket_devops;
951                 else if(!strcasecmp(type, "multicast"))
952                         devops = multicast_devops;
953 #ifdef ENABLE_UML
954                 else if(!strcasecmp(type, "uml"))
955                         devops = uml_devops;
956 #endif
957 #ifdef ENABLE_VDE
958                 else if(!strcasecmp(type, "vde"))
959                         devops = vde_devops;
960 #endif
961         }
962
963         get_config_bool(lookup_config(config_tree, "DeviceStandby"), &device_standby);
964
965         if(!devops.setup())
966                 return false;
967
968         if(device_fd >= 0)
969                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
970
971         /* Open sockets */
972
973         if(!do_detach && getenv("LISTEN_FDS")) {
974                 sockaddr_t sa;
975                 socklen_t salen;
976
977                 listen_sockets = atoi(getenv("LISTEN_FDS"));
978 #ifdef HAVE_UNSETENV
979                 unsetenv("LISTEN_FDS");
980 #endif
981
982                 if(listen_sockets > MAXSOCKETS) {
983                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
984                         return false;
985                 }
986
987                 for(int i = 0; i < listen_sockets; i++) {
988                         salen = sizeof sa;
989                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
990                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
991                                 return false;
992                         }
993
994 #ifdef FD_CLOEXEC
995                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
996 #endif
997
998                         int udp_fd = setup_vpn_in_socket(&sa);
999                         if(udp_fd < 0)
1000                                 return false;
1001
1002                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
1003                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1004
1005                         if(debug_level >= DEBUG_CONNECTIONS) {
1006                                 hostname = sockaddr2hostname(&sa);
1007                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1008                                 free(hostname);
1009                         }
1010
1011                         memcpy(&listen_socket[i].sa, &sa, salen);
1012                 }
1013         } else {
1014                 listen_sockets = 0;
1015                 int cfgs = 0;
1016
1017                 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1018                         cfgs++;
1019                         get_config_string(cfg, &address);
1020                         if(!add_listen_address(address, true))
1021                                 return false;
1022                 }
1023
1024                 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1025                         cfgs++;
1026                         get_config_string(cfg, &address);
1027                         if(!add_listen_address(address, false))
1028                                 return false;
1029                 }
1030
1031                 if(!cfgs)
1032                         if(!add_listen_address(address, NULL))
1033                                 return false;
1034         }
1035
1036         if(!listen_sockets) {
1037                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1038                 return false;
1039         }
1040
1041         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1042
1043         if(!port_specified || atoi(myport) == 0) {
1044                 sockaddr_t sa;
1045                 socklen_t salen = sizeof sa;
1046                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1047                         free(myport);
1048                         sockaddr2str(&sa, NULL, &myport);
1049                         if(!myport)
1050                                 myport = xstrdup("655");
1051                 }
1052         }
1053
1054         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1055         myself->connection->hostname = xstrdup(myself->hostname);
1056
1057         /* Done. */
1058
1059         last_config_check = now.tv_sec;
1060
1061         return true;
1062 }
1063
1064 /*
1065   initialize network
1066 */
1067 bool setup_network(void) {
1068         init_connections();
1069         init_subnets();
1070         init_nodes();
1071         init_edges();
1072         init_requests();
1073
1074         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1075                 if(pinginterval < 1) {
1076                         pinginterval = 86400;
1077                 }
1078         } else
1079                 pinginterval = 60;
1080
1081         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1082                 pingtimeout = 5;
1083         if(pingtimeout < 1 || pingtimeout > pinginterval)
1084                 pingtimeout = pinginterval;
1085
1086         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
1087                 maxoutbufsize = 10 * MTU;
1088
1089         if(!setup_myself())
1090                 return false;
1091
1092         if(!init_control())
1093                 return false;
1094
1095         if (!device_standby)
1096                 device_enable();
1097
1098         /* Run subnet-up scripts for our own subnets */
1099
1100         subnet_update(myself, NULL, true);
1101
1102         return true;
1103 }
1104
1105 /*
1106   close all open network connections
1107 */
1108 void close_network_connections(void) {
1109         for(list_node_t *node = connection_list->head, *next; node; node = next) {
1110                 next = node->next;
1111                 connection_t *c = node->data;
1112                 /* Keep control connections open until the end, so they know when we really terminated */
1113                 if(c->status.control)
1114                         c->socket = -1;
1115                 c->outgoing = NULL;
1116                 terminate_connection(c, false);
1117         }
1118
1119         if(outgoing_list)
1120                 list_delete_list(outgoing_list);
1121
1122         if(myself && myself->connection) {
1123                 subnet_update(myself, NULL, false);
1124                 terminate_connection(myself->connection, false);
1125                 free_connection(myself->connection);
1126         }
1127
1128         for(int i = 0; i < listen_sockets; i++) {
1129                 io_del(&listen_socket[i].tcp);
1130                 io_del(&listen_socket[i].udp);
1131                 close(listen_socket[i].tcp.fd);
1132                 close(listen_socket[i].udp.fd);
1133         }
1134
1135         exit_requests();
1136         exit_edges();
1137         exit_subnets();
1138         exit_nodes();
1139         exit_connections();
1140
1141         if (!device_standby)
1142                 device_disable();
1143
1144         free(myport);
1145
1146         if (device_fd >= 0)
1147                 io_del(&device_io);
1148         if (devops.close)
1149                 devops.close();
1150
1151         exit_control();
1152
1153         free(myname);
1154         free(scriptextension);
1155         free(scriptinterpreter);
1156
1157         return;
1158 }