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