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