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