Remove "release-" from displayed git version.
[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
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;
230
231         if(invitation_key) {
232                 ecdsa_free(invitation_key);
233                 invitation_key = NULL;
234         }
235
236         xasprintf(&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         free(fname);
248         return invitation_key;
249 }
250
251 #ifndef DISABLE_LEGACY
252 static bool read_rsa_private_key(void) {
253         FILE *fp;
254         char *fname;
255         char *n, *d;
256
257         /* First, check for simple PrivateKey statement */
258
259         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
260                 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
261                         logger(DEBUG_ALWAYS, LOG_ERR, "PrivateKey used but no PublicKey found!");
262                         free(d);
263                         return false;
264                 }
265                 myself->connection->rsa = rsa_set_hex_private_key(n, "FFFF", d);
266                 free(n);
267                 free(d);
268                 return myself->connection->rsa;
269         }
270
271         /* Else, check for PrivateKeyFile statement and read it */
272
273         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
274                 xasprintf(&fname, "%s" SLASH "rsa_key.priv", confbase);
275
276         fp = fopen(fname, "r");
277
278         if(!fp) {
279                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA private key file `%s': %s",
280                            fname, strerror(errno));
281                 if(errno == ENOENT)
282                         logger(DEBUG_ALWAYS, LOG_INFO, "Create an RSA keypair with `tinc -n %s generate-rsa-keys'.", netname ?: ".");
283                 free(fname);
284                 return false;
285         }
286
287 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
288         struct stat s;
289
290         if(fstat(fileno(fp), &s)) {
291                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
292                 free(fname);
293                 return false;
294         }
295
296         if(s.st_mode & ~0100700)
297                 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
298 #endif
299
300         myself->connection->rsa = rsa_read_pem_private_key(fp);
301         fclose(fp);
302
303         if(!myself->connection->rsa)
304                 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
305         free(fname);
306         return myself->connection->rsa;
307 }
308 #endif
309
310 static timeout_t keyexpire_timeout;
311
312 static void keyexpire_handler(void *data) {
313         regenerate_key();
314         timeout_set(data, &(struct timeval){keylifetime, rand() % 100000});
315 }
316
317 void regenerate_key(void) {
318         logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
319         send_key_changed();
320         for splay_each(node_t, n, node_tree)
321                 n->status.validkey_in = false;
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_int(lookup_config(config_tree, "MTUInfoInterval"), &mtu_info_interval);
519         get_config_int(lookup_config(config_tree, "UDPInfoInterval"), &udp_info_interval);
520
521         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
522         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
523
524         if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
525                 if(!strcasecmp(rmode, "router"))
526                         routing_mode = RMODE_ROUTER;
527                 else if(!strcasecmp(rmode, "switch"))
528                         routing_mode = RMODE_SWITCH;
529                 else if(!strcasecmp(rmode, "hub"))
530                         routing_mode = RMODE_HUB;
531                 else {
532                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
533                         return false;
534                 }
535                 free(rmode);
536         }
537
538         if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
539                 if(!strcasecmp(fmode, "off"))
540                         forwarding_mode = FMODE_OFF;
541                 else if(!strcasecmp(fmode, "internal"))
542                         forwarding_mode = FMODE_INTERNAL;
543                 else if(!strcasecmp(fmode, "kernel"))
544                         forwarding_mode = FMODE_KERNEL;
545                 else {
546                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
547                         return false;
548                 }
549                 free(fmode);
550         }
551
552         choice = true;
553         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
554         if(choice)
555                 myself->options |= OPTION_PMTU_DISCOVERY;
556
557         choice = true;
558         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
559         if(choice)
560                 myself->options |= OPTION_CLAMP_MSS;
561
562         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
563         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
564         if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
565                 if(!strcasecmp(bmode, "no"))
566                         broadcast_mode = BMODE_NONE;
567                 else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst"))
568                         broadcast_mode = BMODE_MST;
569                 else if(!strcasecmp(bmode, "direct"))
570                         broadcast_mode = BMODE_DIRECT;
571                 else {
572                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
573                         return false;
574                 }
575                 free(bmode);
576         }
577
578         const char* const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
579         for (size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
580                 subnet_t *s = new_subnet();
581                 if (!str2net(s, DEFAULT_BROADCAST_SUBNETS[i]))
582                         abort();
583                 subnet_add(NULL, s);
584         }
585         for (config_t* cfg = lookup_config(config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
586                 subnet_t *s;
587                 if (!get_config_subnet(cfg, &s))
588                         continue;
589                 subnet_add(NULL, s);
590         }
591
592 #if !defined(SOL_IP) || !defined(IP_TOS)
593         if(priorityinheritance)
594                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
595 #endif
596
597         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
598                 macexpire = 600;
599
600         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
601                 if(maxtimeout <= 0) {
602                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
603                         return false;
604                 }
605         } else
606                 maxtimeout = 900;
607
608         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
609                 if(!strcasecmp(afname, "IPv4"))
610                         addressfamily = AF_INET;
611                 else if(!strcasecmp(afname, "IPv6"))
612                         addressfamily = AF_INET6;
613                 else if(!strcasecmp(afname, "any"))
614                         addressfamily = AF_UNSPEC;
615                 else {
616                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
617                         return false;
618                 }
619                 free(afname);
620         }
621
622         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
623
624         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
625                 keylifetime = 3600;
626
627         config_t *cfg = lookup_config(config_tree, "AutoConnect");
628         if(cfg) {
629                 if(!get_config_bool(cfg, &autoconnect)) {
630                         // Some backwards compatibility with when this option was an int
631                         int val = 0;
632                         get_config_int(cfg, &val);
633                         autoconnect = val;
634                 }
635         }
636
637         get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
638
639         read_invitation_key();
640
641         return true;
642 }
643
644 /*
645   Add listening sockets.
646 */
647 static bool add_listen_address(char *address, bool bindto) {
648         char *port = myport;
649
650         if(address) {
651                 char *space = strchr(address, ' ');
652                 if(space) {
653                         *space++ = 0;
654                         port = space;
655                 }
656
657                 if(!strcmp(address, "*"))
658                         *address = 0;
659         }
660
661         struct addrinfo *ai, hint = {0};
662         hint.ai_family = addressfamily;
663         hint.ai_socktype = SOCK_STREAM;
664         hint.ai_protocol = IPPROTO_TCP;
665         hint.ai_flags = AI_PASSIVE;
666
667 #if HAVE_DECL_RES_INIT
668         res_init();
669 #endif
670         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
671         free(address);
672
673         if(err || !ai) {
674                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
675                 return false;
676         }
677
678         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
679                 // Ignore duplicate addresses
680                 bool found = false;
681
682                 for(int i = 0; i < listen_sockets; i++)
683                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
684                                 found = true;
685                                 break;
686                         }
687
688                 if(found)
689                         continue;
690
691                 if(listen_sockets >= MAXSOCKETS) {
692                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
693                         return false;
694                 }
695
696                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
697
698                 if(tcp_fd < 0)
699                         continue;
700
701                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
702
703                 if(tcp_fd < 0) {
704                         close(tcp_fd);
705                         continue;
706                 }
707
708                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
709                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
710
711                 if(debug_level >= DEBUG_CONNECTIONS) {
712                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
713                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
714                         free(hostname);
715                 }
716
717                 listen_socket[listen_sockets].bindto = bindto;
718                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
719                 listen_sockets++;
720         }
721
722         freeaddrinfo(ai);
723         return true;
724 }
725
726 void device_enable(void) {
727         if (devops.enable)
728                 devops.enable();
729
730         /* Run tinc-up script to further initialize the tap interface */
731
732         char *envp[5] = {NULL};
733         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
734         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
735         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
736         xasprintf(&envp[3], "NAME=%s", myname);
737
738         execute_script("tinc-up", envp);
739
740         for(int i = 0; i < 4; i++)
741                 free(envp[i]);
742 }
743
744 void device_disable(void) {
745         char *envp[5] = {NULL};
746         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
747         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
748         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
749         xasprintf(&envp[3], "NAME=%s", myname);
750
751         execute_script("tinc-down", envp);
752
753         for(int i = 0; i < 4; i++)
754                 free(envp[i]);
755
756         if (devops.disable)
757                 devops.disable();
758 }
759
760 /*
761   Configure node_t myself and set up the local sockets (listen only)
762 */
763 static bool setup_myself(void) {
764         char *name, *hostname, *cipher, *digest, *type;
765         char *address = NULL;
766         bool port_specified = false;
767
768         if(!(name = get_name())) {
769                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
770                 return false;
771         }
772
773         myname = xstrdup(name);
774         myself = new_node();
775         myself->connection = new_connection();
776         myself->name = name;
777         myself->connection->name = xstrdup(name);
778         read_host_config(config_tree, name);
779
780         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
781                 myport = xstrdup("655");
782         else
783                 port_specified = true;
784
785         myself->connection->options = 0;
786         myself->connection->protocol_major = PROT_MAJOR;
787         myself->connection->protocol_minor = PROT_MINOR;
788
789         myself->options |= PROT_MINOR << 24;
790
791 #ifdef DISABLE_LEGACY
792         experimental = read_ecdsa_private_key();
793         if(!experimental) {
794                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
795                 return false;
796         }
797 #else
798         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
799                 experimental = read_ecdsa_private_key();
800                 if(!experimental)
801                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
802         } else {
803                 if(experimental && !read_ecdsa_private_key())
804                         return false;
805         }
806
807         if(!read_rsa_private_key()) {
808                 if(experimental) {
809                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
810                 } else {
811                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
812                         return false;
813                 }
814         }
815 #endif
816
817         /* Ensure myport is numeric */
818
819         if(!atoi(myport)) {
820                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
821                 sockaddr_t sa;
822                 if(!ai || !ai->ai_addr)
823                         return false;
824                 free(myport);
825                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
826                 sockaddr2str(&sa, NULL, &myport);
827         }
828
829         /* Read in all the subnets specified in the host configuration file */
830
831         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
832                 subnet_t *subnet;
833
834                 if(!get_config_subnet(cfg, &subnet))
835                         return false;
836
837                 subnet_add(myself, subnet);
838         }
839
840         /* Check some options */
841
842         if(!setup_myself_reloadable())
843                 return false;
844
845         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
846         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
847         strictsubnets |= tunnelserver;
848
849         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
850                 if(max_connection_burst <= 0) {
851                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
852                         return false;
853                 }
854         }
855
856         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
857                 if(udp_rcvbuf < 0) {
858                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
859                         return false;
860                 }
861         }
862
863         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
864                 if(udp_sndbuf < 0) {
865                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
866                         return false;
867                 }
868         }
869
870         int replaywin_int;
871         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
872                 if(replaywin_int < 0) {
873                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
874                         return false;
875                 }
876                 replaywin = (unsigned)replaywin_int;
877                 sptps_replaywin = replaywin;
878         }
879
880 #ifndef DISABLE_LEGACY
881         /* Generate packet encryption key */
882
883         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
884                 cipher = xstrdup("blowfish");
885
886         if(!strcasecmp(cipher, "none")) {
887                 myself->incipher = NULL;
888         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
889                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
890                 return false;
891         }
892
893         free(cipher);
894
895         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
896
897         /* Check if we want to use message authentication codes... */
898
899         int maclength = 4;
900         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
901
902         if(maclength < 0) {
903                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
904                 return false;
905         }
906
907         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
908                 digest = xstrdup("sha1");
909
910         if(!strcasecmp(digest, "none")) {
911                 myself->indigest = NULL;
912         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
913                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
914                 return false;
915         }
916
917         free(digest);
918 #endif
919
920         /* Compression */
921
922         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
923                 if(myself->incompression < 0 || myself->incompression > 11) {
924                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
925                         return false;
926                 }
927         } else
928                 myself->incompression = 0;
929
930         myself->connection->outcompression = 0;
931
932         /* Done */
933
934         myself->nexthop = myself;
935         myself->via = myself;
936         myself->status.reachable = true;
937         myself->last_state_change = now.tv_sec;
938         myself->status.sptps = experimental;
939         node_add(myself);
940
941         graph();
942
943         if(strictsubnets)
944                 load_all_subnets();
945         else if(autoconnect)
946                 load_all_nodes();
947
948         /* Open device */
949
950         devops = os_devops;
951
952         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
953                 if(!strcasecmp(type, "dummy"))
954                         devops = dummy_devops;
955                 else if(!strcasecmp(type, "raw_socket"))
956                         devops = raw_socket_devops;
957                 else if(!strcasecmp(type, "multicast"))
958                         devops = multicast_devops;
959 #ifdef ENABLE_UML
960                 else if(!strcasecmp(type, "uml"))
961                         devops = uml_devops;
962 #endif
963 #ifdef ENABLE_VDE
964                 else if(!strcasecmp(type, "vde"))
965                         devops = vde_devops;
966 #endif
967         }
968
969         get_config_bool(lookup_config(config_tree, "DeviceStandby"), &device_standby);
970
971         if(!devops.setup())
972                 return false;
973
974         if(device_fd >= 0)
975                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
976
977         /* Open sockets */
978
979         if(!do_detach && getenv("LISTEN_FDS")) {
980                 sockaddr_t sa;
981                 socklen_t salen;
982
983                 listen_sockets = atoi(getenv("LISTEN_FDS"));
984 #ifdef HAVE_UNSETENV
985                 unsetenv("LISTEN_FDS");
986 #endif
987
988                 if(listen_sockets > MAXSOCKETS) {
989                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
990                         return false;
991                 }
992
993                 for(int i = 0; i < listen_sockets; i++) {
994                         salen = sizeof sa;
995                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
996                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
997                                 return false;
998                         }
999
1000 #ifdef FD_CLOEXEC
1001                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
1002 #endif
1003
1004                         int udp_fd = setup_vpn_in_socket(&sa);
1005                         if(udp_fd < 0)
1006                                 return false;
1007
1008                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
1009                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1010
1011                         if(debug_level >= DEBUG_CONNECTIONS) {
1012                                 hostname = sockaddr2hostname(&sa);
1013                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1014                                 free(hostname);
1015                         }
1016
1017                         memcpy(&listen_socket[i].sa, &sa, salen);
1018                 }
1019         } else {
1020                 listen_sockets = 0;
1021                 int cfgs = 0;
1022
1023                 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1024                         cfgs++;
1025                         get_config_string(cfg, &address);
1026                         if(!add_listen_address(address, true))
1027                                 return false;
1028                 }
1029
1030                 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1031                         cfgs++;
1032                         get_config_string(cfg, &address);
1033                         if(!add_listen_address(address, false))
1034                                 return false;
1035                 }
1036
1037                 if(!cfgs)
1038                         if(!add_listen_address(address, NULL))
1039                                 return false;
1040         }
1041
1042         if(!listen_sockets) {
1043                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1044                 return false;
1045         }
1046
1047         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1048
1049         if(!port_specified || atoi(myport) == 0) {
1050                 sockaddr_t sa;
1051                 socklen_t salen = sizeof sa;
1052                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1053                         free(myport);
1054                         sockaddr2str(&sa, NULL, &myport);
1055                         if(!myport)
1056                                 myport = xstrdup("655");
1057                 }
1058         }
1059
1060         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1061         myself->connection->hostname = xstrdup(myself->hostname);
1062
1063         /* Done. */
1064
1065         last_config_check = now.tv_sec;
1066
1067         return true;
1068 }
1069
1070 /*
1071   initialize network
1072 */
1073 bool setup_network(void) {
1074         init_connections();
1075         init_subnets();
1076         init_nodes();
1077         init_edges();
1078         init_requests();
1079
1080         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1081                 if(pinginterval < 1) {
1082                         pinginterval = 86400;
1083                 }
1084         } else
1085                 pinginterval = 60;
1086
1087         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1088                 pingtimeout = 5;
1089         if(pingtimeout < 1 || pingtimeout > pinginterval)
1090                 pingtimeout = pinginterval;
1091
1092         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
1093                 maxoutbufsize = 10 * MTU;
1094
1095         if(!setup_myself())
1096                 return false;
1097
1098         if(!init_control())
1099                 return false;
1100
1101         if (!device_standby)
1102                 device_enable();
1103
1104         /* Run subnet-up scripts for our own subnets */
1105
1106         subnet_update(myself, NULL, true);
1107
1108         return true;
1109 }
1110
1111 /*
1112   close all open network connections
1113 */
1114 void close_network_connections(void) {
1115         for(list_node_t *node = connection_list->head, *next; node; node = next) {
1116                 next = node->next;
1117                 connection_t *c = node->data;
1118                 /* Keep control connections open until the end, so they know when we really terminated */
1119                 if(c->status.control)
1120                         c->socket = -1;
1121                 c->outgoing = NULL;
1122                 terminate_connection(c, false);
1123         }
1124
1125         if(outgoing_list)
1126                 list_delete_list(outgoing_list);
1127
1128         if(myself && myself->connection) {
1129                 subnet_update(myself, NULL, false);
1130                 terminate_connection(myself->connection, false);
1131                 free_connection(myself->connection);
1132         }
1133
1134         for(int i = 0; i < listen_sockets; i++) {
1135                 io_del(&listen_socket[i].tcp);
1136                 io_del(&listen_socket[i].udp);
1137                 close(listen_socket[i].tcp.fd);
1138                 close(listen_socket[i].udp.fd);
1139         }
1140
1141         exit_requests();
1142         exit_edges();
1143         exit_subnets();
1144         exit_nodes();
1145         exit_connections();
1146
1147         if (!device_standby)
1148                 device_disable();
1149
1150         free(myport);
1151
1152         if (device_fd >= 0)
1153                 io_del(&device_io);
1154         if (devops.close)
1155                 devops.close();
1156
1157         exit_control();
1158
1159         free(myname);
1160         free(scriptextension);
1161         free(scriptinterpreter);
1162
1163         return;
1164 }