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