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