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