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