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