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