Allow using key & configuration parser from tincd in tinc.
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2021 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_net.h"
27 #include "conf.h"
28 #include "connection.h"
29 #include "control.h"
30 #include "device.h"
31 #include "digest.h"
32 #include "ecdsa.h"
33 #include "graph.h"
34 #include "logger.h"
35 #include "names.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "process.h"
39 #include "protocol.h"
40 #include "route.h"
41 #include "rsa.h"
42 #include "script.h"
43 #include "subnet.h"
44 #include "utils.h"
45 #include "xalloc.h"
46 #include "keys.h"
47
48 #ifdef HAVE_MINIUPNPC
49 #include "upnp.h"
50 #endif
51
52 char *myport;
53 static io_t device_io;
54 devops_t devops;
55 bool device_standby = false;
56
57 char *proxyhost = NULL;
58 char *proxyport = NULL;
59 char *proxyuser = NULL;
60 char *proxypass = NULL;
61
62 proxytype_t proxytype;
63 bool autoconnect;
64 bool disablebuggypeers;
65
66 char *scriptinterpreter;
67 char *scriptextension;
68
69 bool node_read_ecdsa_public_key(node_t *n) {
70         if(ecdsa_active(n->ecdsa)) {
71                 return true;
72         }
73
74         splay_tree_t *config_tree;
75         FILE *fp;
76         char *pubname = NULL;
77         char *p;
78
79         init_configuration(&config_tree);
80
81         if(!read_host_config(config_tree, n->name, true)) {
82                 goto exit;
83         }
84
85         /* First, check for simple Ed25519PublicKey statement */
86
87         if(get_config_string(lookup_config(config_tree, "Ed25519PublicKey"), &p)) {
88                 n->ecdsa = ecdsa_set_base64_public_key(p);
89                 free(p);
90                 goto exit;
91         }
92
93         /* Else, check for Ed25519PublicKeyFile statement and read it */
94
95         if(!get_config_string(lookup_config(config_tree, "Ed25519PublicKeyFile"), &pubname)) {
96                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
97         }
98
99         fp = fopen(pubname, "r");
100
101         if(!fp) {
102                 goto exit;
103         }
104
105         n->ecdsa = ecdsa_read_pem_public_key(fp);
106         fclose(fp);
107
108 exit:
109         exit_configuration(&config_tree);
110         free(pubname);
111         return n->ecdsa;
112 }
113
114 static bool read_invitation_key(void) {
115         FILE *fp;
116         char fname[PATH_MAX];
117
118         if(invitation_key) {
119                 ecdsa_free(invitation_key);
120                 invitation_key = NULL;
121         }
122
123         snprintf(fname, sizeof(fname), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
124
125         fp = fopen(fname, "r");
126
127         if(fp) {
128                 invitation_key = ecdsa_read_pem_private_key(fp);
129                 fclose(fp);
130
131                 if(!invitation_key) {
132                         logger(DEBUG_ALWAYS, LOG_ERR, "Reading Ed25519 private key file `%s' failed", fname);
133                 }
134         }
135
136         return invitation_key;
137 }
138
139 #ifndef DISABLE_LEGACY
140 static timeout_t keyexpire_timeout;
141
142 static void keyexpire_handler(void *data) {
143         regenerate_key();
144         timeout_set(data, &(struct timeval) {
145                 keylifetime, rand() % 100000
146         });
147 }
148 #endif
149
150 void regenerate_key(void) {
151         logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
152         send_key_changed();
153
154         for splay_each(node_t, n, node_tree) {
155                 n->status.validkey_in = false;
156         }
157 }
158
159 void load_all_nodes(void) {
160         DIR *dir;
161         struct dirent *ent;
162         char dname[PATH_MAX];
163
164         snprintf(dname, sizeof(dname), "%s" SLASH "hosts", confbase);
165         dir = opendir(dname);
166
167         if(!dir) {
168                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
169                 return;
170         }
171
172         while((ent = readdir(dir))) {
173                 if(!check_id(ent->d_name)) {
174                         continue;
175                 }
176
177                 node_t *n = lookup_node(ent->d_name);
178
179                 splay_tree_t *config_tree;
180                 init_configuration(&config_tree);
181                 read_config_options(config_tree, ent->d_name);
182                 read_host_config(config_tree, ent->d_name, true);
183
184                 if(!n) {
185                         n = new_node();
186                         n->name = xstrdup(ent->d_name);
187                         node_add(n);
188                 }
189
190                 if(strictsubnets) {
191                         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
192                                 subnet_t *s, *s2;
193
194                                 if(!get_config_subnet(cfg, &s)) {
195                                         continue;
196                                 }
197
198                                 if((s2 = lookup_subnet(n, s))) {
199                                         s2->expires = -1;
200                                         free(s);
201                                 } else {
202                                         subnet_add(n, s);
203                                 }
204                         }
205                 }
206
207                 if(lookup_config(config_tree, "Address")) {
208                         n->status.has_address = true;
209                 }
210
211                 exit_configuration(&config_tree);
212         }
213
214         closedir(dir);
215 }
216
217 char *get_name(void) {
218         char *name = NULL;
219         char *returned_name;
220
221         get_config_string(lookup_config(config_tree, "Name"), &name);
222
223         if(!name) {
224                 return NULL;
225         }
226
227         returned_name = replace_name(name);
228         free(name);
229         return returned_name;
230 }
231
232 bool setup_myself_reloadable(void) {
233         free(scriptinterpreter);
234         scriptinterpreter = NULL;
235
236         get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &scriptinterpreter);
237
238         free(scriptextension);
239
240         if(!get_config_string(lookup_config(config_tree, "ScriptsExtension"), &scriptextension)) {
241                 scriptextension = xstrdup("");
242         }
243
244         char *proxy = NULL;
245
246         get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
247
248         if(proxy) {
249                 char *space;
250
251                 if((space = strchr(proxy, ' '))) {
252                         *space++ = 0;
253                 }
254
255                 if(!strcasecmp(proxy, "none")) {
256                         proxytype = PROXY_NONE;
257                 } else if(!strcasecmp(proxy, "socks4")) {
258                         proxytype = PROXY_SOCKS4;
259                 } else if(!strcasecmp(proxy, "socks4a")) {
260                         proxytype = PROXY_SOCKS4A;
261                 } else if(!strcasecmp(proxy, "socks5")) {
262                         proxytype = PROXY_SOCKS5;
263                 } else if(!strcasecmp(proxy, "http")) {
264                         proxytype = PROXY_HTTP;
265                 } else if(!strcasecmp(proxy, "exec")) {
266                         proxytype = PROXY_EXEC;
267                 } else {
268                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
269                         free(proxy);
270                         return false;
271                 }
272
273                 free(proxyhost);
274                 proxyhost = NULL;
275
276                 free(proxyport);
277                 proxyport = NULL;
278
279                 free(proxyuser);
280                 proxyuser = NULL;
281
282                 free(proxypass);
283                 proxypass = NULL;
284
285                 switch(proxytype) {
286                 case PROXY_NONE:
287                 default:
288                         break;
289
290                 case PROXY_EXEC:
291                         if(!space || !*space) {
292                                 logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
293                                 free(proxy);
294                                 return false;
295                         }
296
297                         proxyhost = xstrdup(space);
298                         break;
299
300                 case PROXY_SOCKS4:
301                 case PROXY_SOCKS4A:
302                 case PROXY_SOCKS5:
303                 case PROXY_HTTP:
304                         proxyhost = space;
305
306                         if(space && (space = strchr(space, ' '))) {
307                                 *space++ = 0, proxyport = space;
308                         }
309
310                         if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
311                                 logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
312                                 proxyport = NULL;
313                                 proxyhost = NULL;
314                                 free(proxy);
315                                 return false;
316                         }
317
318                         if(space && (space = strchr(space, ' '))) {
319                                 *space++ = 0, proxyuser = space;
320                         }
321
322                         if(space && (space = strchr(space, ' '))) {
323                                 *space++ = 0, proxypass = space;
324                         }
325
326                         proxyhost = xstrdup(proxyhost);
327                         proxyport = xstrdup(proxyport);
328
329                         if(proxyuser && *proxyuser) {
330                                 proxyuser = xstrdup(proxyuser);
331                         }
332
333                         if(proxypass && *proxypass) {
334                                 proxypass = xstrdup(proxypass);
335                         }
336
337                         break;
338                 }
339
340                 free(proxy);
341         }
342
343         bool choice;
344
345         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice) {
346                 myself->options |= OPTION_INDIRECT;
347         }
348
349         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice) {
350                 myself->options |= OPTION_TCPONLY;
351         }
352
353         if(myself->options & OPTION_TCPONLY) {
354                 myself->options |= OPTION_INDIRECT;
355         }
356
357         get_config_bool(lookup_config(config_tree, "UDPDiscovery"), &udp_discovery);
358         get_config_int(lookup_config(config_tree, "UDPDiscoveryKeepaliveInterval"), &udp_discovery_keepalive_interval);
359         get_config_int(lookup_config(config_tree, "UDPDiscoveryInterval"), &udp_discovery_interval);
360         get_config_int(lookup_config(config_tree, "UDPDiscoveryTimeout"), &udp_discovery_timeout);
361
362         get_config_int(lookup_config(config_tree, "MTUInfoInterval"), &mtu_info_interval);
363         get_config_int(lookup_config(config_tree, "UDPInfoInterval"), &udp_info_interval);
364
365         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
366         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
367
368         char *rmode = NULL;
369
370         if(get_config_string(lookup_config(config_tree, "Mode"), &rmode)) {
371                 if(!strcasecmp(rmode, "router")) {
372                         routing_mode = RMODE_ROUTER;
373                 } else if(!strcasecmp(rmode, "switch")) {
374                         routing_mode = RMODE_SWITCH;
375                 } else if(!strcasecmp(rmode, "hub")) {
376                         routing_mode = RMODE_HUB;
377                 } else {
378                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
379                         free(rmode);
380                         return false;
381                 }
382
383                 free(rmode);
384         }
385
386         char *fmode = NULL;
387
388         if(get_config_string(lookup_config(config_tree, "Forwarding"), &fmode)) {
389                 if(!strcasecmp(fmode, "off")) {
390                         forwarding_mode = FMODE_OFF;
391                 } else if(!strcasecmp(fmode, "internal")) {
392                         forwarding_mode = FMODE_INTERNAL;
393                 } else if(!strcasecmp(fmode, "kernel")) {
394                         forwarding_mode = FMODE_KERNEL;
395                 } else {
396                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
397                         free(fmode);
398                         return false;
399                 }
400
401                 free(fmode);
402         }
403
404         choice = !(myself->options & OPTION_TCPONLY);
405         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
406
407         if(choice) {
408                 myself->options |= OPTION_PMTU_DISCOVERY;
409         }
410
411         choice = true;
412         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
413
414         if(choice) {
415                 myself->options |= OPTION_CLAMP_MSS;
416         }
417
418         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
419         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
420
421         char *bmode = NULL;
422
423         if(get_config_string(lookup_config(config_tree, "Broadcast"), &bmode)) {
424                 if(!strcasecmp(bmode, "no")) {
425                         broadcast_mode = BMODE_NONE;
426                 } else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst")) {
427                         broadcast_mode = BMODE_MST;
428                 } else if(!strcasecmp(bmode, "direct")) {
429                         broadcast_mode = BMODE_DIRECT;
430                 } else {
431                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
432                         free(bmode);
433                         return false;
434                 }
435
436                 free(bmode);
437         }
438
439         /* Delete all broadcast subnets before re-adding them */
440
441         for splay_each(subnet_t, s, subnet_tree) {
442                 if(!s->owner) {
443                         splay_delete_node(subnet_tree, node);
444                 }
445         }
446
447         const char *const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
448
449         for(size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
450                 subnet_t *s = new_subnet();
451
452                 if(!str2net(s, DEFAULT_BROADCAST_SUBNETS[i])) {
453                         abort();
454                 }
455
456                 subnet_add(NULL, s);
457         }
458
459         for(config_t *cfg = lookup_config(config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
460                 subnet_t *s;
461
462                 if(!get_config_subnet(cfg, &s)) {
463                         continue;
464                 }
465
466                 subnet_add(NULL, s);
467         }
468
469 #if !defined(IP_TOS)
470
471         if(priorityinheritance) {
472                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv4 connections", "PriorityInheritance");
473         }
474
475 #endif
476
477 #if !defined(IPV6_TCLASS)
478
479         if(priorityinheritance) {
480                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv6 connections", "PriorityInheritance");
481         }
482
483 #endif
484
485         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire)) {
486                 macexpire = 600;
487         }
488
489         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
490                 if(maxtimeout <= 0) {
491                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
492                         return false;
493                 }
494         } else {
495                 maxtimeout = 900;
496         }
497
498         char *afname = NULL;
499
500         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
501                 if(!strcasecmp(afname, "IPv4")) {
502                         addressfamily = AF_INET;
503                 } else if(!strcasecmp(afname, "IPv6")) {
504                         addressfamily = AF_INET6;
505                 } else if(!strcasecmp(afname, "any")) {
506                         addressfamily = AF_UNSPEC;
507                 } else {
508                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
509                         free(afname);
510                         return false;
511                 }
512
513                 free(afname);
514         }
515
516         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
517
518         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime)) {
519                 keylifetime = 3600;
520         }
521
522         if(!get_config_bool(lookup_config(config_tree, "AutoConnect"), &autoconnect)) {
523                 autoconnect = true;
524         }
525
526         get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
527
528         if(!get_config_int(lookup_config(config_tree, "InvitationExpire"), &invitation_lifetime)) {
529                 invitation_lifetime = 604800;        // 1 week
530         }
531
532         read_invitation_key();
533
534         return true;
535 }
536
537 /*
538   Add listening sockets.
539 */
540 static bool add_listen_address(char *address, bool bindto) {
541         char *port = myport;
542
543         if(address) {
544                 char *space = strchr(address, ' ');
545
546                 if(space) {
547                         *space++ = 0;
548                         port = space;
549                 }
550
551                 if(!strcmp(address, "*")) {
552                         *address = 0;
553                 }
554         }
555
556         struct addrinfo *ai, hint = {0};
557
558         hint.ai_family = addressfamily;
559
560         hint.ai_socktype = SOCK_STREAM;
561
562         hint.ai_protocol = IPPROTO_TCP;
563
564         hint.ai_flags = AI_PASSIVE;
565
566 #if HAVE_DECL_RES_INIT
567         res_init();
568
569 #endif
570         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
571
572         free(address);
573
574         if(err || !ai) {
575                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
576                 return false;
577         }
578
579         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
580                 // Ignore duplicate addresses
581                 bool found = false;
582
583                 for(int i = 0; i < listen_sockets; i++)
584                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
585                                 found = true;
586                                 break;
587                         }
588
589                 if(found) {
590                         continue;
591                 }
592
593                 if(listen_sockets >= MAXSOCKETS) {
594                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
595                         freeaddrinfo(ai);
596                         return false;
597                 }
598
599                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
600
601                 if(tcp_fd < 0) {
602                         continue;
603                 }
604
605                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
606
607                 if(udp_fd < 0) {
608                         close(tcp_fd);
609                         continue;
610                 }
611
612                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
613                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
614
615                 if(debug_level >= DEBUG_CONNECTIONS) {
616                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
617                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
618                         free(hostname);
619                 }
620
621                 listen_socket[listen_sockets].bindto = bindto;
622                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
623                 listen_sockets++;
624         }
625
626         freeaddrinfo(ai);
627         return true;
628 }
629
630 void device_enable(void) {
631         if(devops.enable) {
632                 devops.enable();
633         }
634
635         /* Run tinc-up script to further initialize the tap interface */
636
637         environment_t env;
638         environment_init(&env);
639         execute_script("tinc-up", &env);
640         environment_exit(&env);
641 }
642
643 void device_disable(void) {
644         environment_t env;
645         environment_init(&env);
646         execute_script("tinc-down", &env);
647         environment_exit(&env);
648
649         if(devops.disable) {
650                 devops.disable();
651         }
652 }
653
654 /*
655   Configure node_t myself and set up the local sockets (listen only)
656 */
657 static bool setup_myself(void) {
658         char *name, *hostname, *type;
659         char *address = NULL;
660         bool port_specified = false;
661
662         if(!(name = get_name())) {
663                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
664                 return false;
665         }
666
667         myname = xstrdup(name);
668         myself = new_node();
669         myself->connection = new_connection();
670         myself->name = name;
671         myself->connection->name = xstrdup(name);
672         read_host_config(config_tree, name, true);
673
674         if(!get_config_string(lookup_config(config_tree, "Port"), &myport)) {
675                 myport = xstrdup("655");
676         } else {
677                 port_specified = true;
678         }
679
680         myself->connection->options = 0;
681         myself->connection->protocol_major = PROT_MAJOR;
682         myself->connection->protocol_minor = PROT_MINOR;
683
684         myself->options |= PROT_MINOR << 24;
685
686 #ifdef DISABLE_LEGACY
687         myself->connection->ecdsa = read_ecdsa_private_key(config_tree, NULL);
688         experimental = myself->connection->ecdsa != NULL;
689
690         if(!experimental) {
691                 logger(DEBUG_ALWAYS, LOG_ERR, "No private key available, cannot start tinc!");
692                 return false;
693         }
694
695 #else
696
697         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
698                 myself->connection->ecdsa = read_ecdsa_private_key(config_tree, NULL);
699                 experimental = myself->connection->ecdsa != NULL;
700
701                 if(!experimental) {
702                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
703                 }
704         } else {
705                 if(experimental) {
706                         myself->connection->ecdsa = read_ecdsa_private_key(config_tree, NULL);
707
708                         if(!myself->connection->ecdsa) {
709                                 return false;
710                         }
711                 }
712         }
713
714         myself->connection->rsa = read_rsa_private_key(config_tree, NULL);
715
716         if(!myself->connection->rsa) {
717                 if(experimental) {
718                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for legacy protocol disabled.");
719                 } else {
720                         logger(DEBUG_ALWAYS, LOG_ERR, "No private keys available, cannot start tinc!");
721                         return false;
722                 }
723         }
724
725 #endif
726
727         /* Ensure myport is numeric */
728
729         if(!atoi(myport)) {
730                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
731                 sockaddr_t sa;
732
733                 if(!ai || !ai->ai_addr) {
734                         return false;
735                 }
736
737                 free(myport);
738                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
739                 freeaddrinfo(ai);
740                 sockaddr2str(&sa, NULL, &myport);
741         }
742
743         /* Read in all the subnets specified in the host configuration file */
744
745         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
746                 subnet_t *subnet;
747
748                 if(!get_config_subnet(cfg, &subnet)) {
749                         return false;
750                 }
751
752                 subnet_add(myself, subnet);
753         }
754
755         /* Check some options */
756
757         if(!setup_myself_reloadable()) {
758                 return false;
759         }
760
761         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
762         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
763         strictsubnets |= tunnelserver;
764
765         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
766                 if(max_connection_burst <= 0) {
767                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
768                         return false;
769                 }
770         }
771
772         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
773                 if(udp_rcvbuf < 0) {
774                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
775                         return false;
776                 }
777
778                 udp_rcvbuf_warnings = true;
779         }
780
781         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
782                 if(udp_sndbuf < 0) {
783                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
784                         return false;
785                 }
786
787                 udp_sndbuf_warnings = true;
788         }
789
790         get_config_int(lookup_config(config_tree, "FWMark"), &fwmark);
791 #ifndef SO_MARK
792
793         if(fwmark) {
794                 logger(DEBUG_ALWAYS, LOG_ERR, "FWMark not supported on this platform!");
795                 return false;
796         }
797
798 #endif
799
800         int replaywin_int;
801
802         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
803                 if(replaywin_int < 0) {
804                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
805                         return false;
806                 }
807
808                 replaywin = (unsigned)replaywin_int;
809                 sptps_replaywin = replaywin;
810         }
811
812 #ifndef DISABLE_LEGACY
813         /* Generate packet encryption key */
814
815         char *cipher;
816
817         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher)) {
818                 cipher = xstrdup("aes-256-cbc");
819         }
820
821         if(!strcasecmp(cipher, "none")) {
822                 myself->incipher = NULL;
823         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
824                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
825                 free(cipher);
826                 return false;
827         }
828
829         free(cipher);
830
831         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval) {
832                 keylifetime, rand() % 100000
833         });
834
835         /* Check if we want to use message authentication codes... */
836
837         int maclength = 4;
838         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
839
840         if(maclength < 0) {
841                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
842                 return false;
843         }
844
845         char *digest;
846
847         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
848                 digest = xstrdup("sha256");
849         }
850
851         if(!strcasecmp(digest, "none")) {
852                 myself->indigest = NULL;
853         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
854                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
855                 free(digest);
856                 return false;
857         }
858
859         free(digest);
860 #endif
861
862         /* Compression */
863
864         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
865                 switch(myself->incompression) {
866                 case 12:
867 #ifdef HAVE_LZ4
868                         break;
869 #else
870                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
871                         logger(DEBUG_ALWAYS, LOG_ERR, "LZ4 compression is unavailable on this node.");
872                         return false;
873 #endif
874
875                 case 11:
876                 case 10:
877 #ifdef HAVE_LZO
878                         break;
879 #else
880                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
881                         logger(DEBUG_ALWAYS, LOG_ERR, "LZO compression is unavailable on this node.");
882                         return false;
883 #endif
884
885                 case 9:
886                 case 8:
887                 case 7:
888                 case 6:
889                 case 5:
890                 case 4:
891                 case 3:
892                 case 2:
893                 case 1:
894 #ifdef HAVE_ZLIB
895                         break;
896 #else
897                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
898                         logger(DEBUG_ALWAYS, LOG_ERR, "ZLIB compression is unavailable on this node.");
899                         return false;
900 #endif
901
902                 case 0:
903                         break;
904
905                 default:
906                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
907                         logger(DEBUG_ALWAYS, LOG_ERR, "Compression level %i is unrecognized by this node.", myself->incompression);
908                         return false;
909                 }
910         } else {
911                 myself->incompression = 0;
912         }
913
914         myself->connection->outcompression = 0;
915
916         /* Done */
917
918         myself->nexthop = myself;
919         myself->via = myself;
920         myself->status.reachable = true;
921         myself->last_state_change = now.tv_sec;
922         myself->status.sptps = experimental;
923         node_add(myself);
924
925         graph();
926
927         load_all_nodes();
928
929         /* Open device */
930
931         devops = os_devops;
932
933         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
934                 if(!strcasecmp(type, "dummy")) {
935                         devops = dummy_devops;
936                 } else if(!strcasecmp(type, "raw_socket")) {
937                         devops = raw_socket_devops;
938                 } else if(!strcasecmp(type, "multicast")) {
939                         devops = multicast_devops;
940                 }
941
942 #ifdef HAVE_SYS_UN_H
943                 else if(!strcasecmp(type, "fd")) {
944                         devops = fd_devops;
945                 }
946
947 #endif
948 #ifdef ENABLE_UML
949                 else if(!strcasecmp(type, "uml")) {
950                         devops = uml_devops;
951                 }
952
953 #endif
954 #ifdef ENABLE_VDE
955                 else if(!strcasecmp(type, "vde")) {
956                         devops = vde_devops;
957                 }
958
959 #endif
960                 free(type);
961         }
962
963         get_config_bool(lookup_config(config_tree, "DeviceStandby"), &device_standby);
964
965         if(!devops.setup()) {
966                 return false;
967         }
968
969         if(device_fd >= 0) {
970                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
971         }
972
973         /* Open sockets */
974
975         if(!do_detach && getenv("LISTEN_FDS")) {
976                 sockaddr_t sa;
977                 socklen_t salen;
978
979                 listen_sockets = atoi(getenv("LISTEN_FDS"));
980 #ifdef HAVE_UNSETENV
981                 unsetenv("LISTEN_FDS");
982 #endif
983
984                 if(listen_sockets > MAXSOCKETS) {
985                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
986                         return false;
987                 }
988
989                 for(int i = 0; i < listen_sockets; i++) {
990                         salen = sizeof(sa);
991
992                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
993                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
994                                 return false;
995                         }
996
997 #ifdef FD_CLOEXEC
998                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
999 #endif
1000
1001                         int udp_fd = setup_vpn_in_socket(&sa);
1002
1003                         if(udp_fd < 0) {
1004                                 return false;
1005                         }
1006
1007                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
1008                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1009
1010                         if(debug_level >= DEBUG_CONNECTIONS) {
1011                                 hostname = sockaddr2hostname(&sa);
1012                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1013                                 free(hostname);
1014                         }
1015
1016                         memcpy(&listen_socket[i].sa, &sa, salen);
1017                 }
1018         } else {
1019                 listen_sockets = 0;
1020                 int cfgs = 0;
1021
1022                 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1023                         cfgs++;
1024                         get_config_string(cfg, &address);
1025
1026                         if(!add_listen_address(address, true)) {
1027                                 return false;
1028                         }
1029                 }
1030
1031                 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
1032                         cfgs++;
1033                         get_config_string(cfg, &address);
1034
1035                         if(!add_listen_address(address, false)) {
1036                                 return false;
1037                         }
1038                 }
1039
1040                 if(!cfgs)
1041                         if(!add_listen_address(address, NULL)) {
1042                                 return false;
1043                         }
1044         }
1045
1046         if(!listen_sockets) {
1047                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1048                 return false;
1049         }
1050
1051         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1052
1053         if(!port_specified || atoi(myport) == 0) {
1054                 sockaddr_t sa;
1055                 socklen_t salen = sizeof(sa);
1056
1057                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1058                         free(myport);
1059                         sockaddr2str(&sa, NULL, &myport);
1060
1061                         if(!myport) {
1062                                 myport = xstrdup("655");
1063                         }
1064                 }
1065         }
1066
1067         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1068         myself->connection->hostname = xstrdup(myself->hostname);
1069
1070         char *upnp = NULL;
1071         get_config_string(lookup_config(config_tree, "UPnP"), &upnp);
1072         bool upnp_tcp = false;
1073         bool upnp_udp = false;
1074
1075         if(upnp) {
1076                 if(!strcasecmp(upnp, "yes")) {
1077                         upnp_tcp = upnp_udp = true;
1078                 } else if(!strcasecmp(upnp, "udponly")) {
1079                         upnp_udp = true;
1080                 }
1081
1082                 free(upnp);
1083         }
1084
1085         if(upnp_tcp || upnp_udp) {
1086 #ifdef HAVE_MINIUPNPC
1087                 upnp_init(upnp_tcp, upnp_udp);
1088 #else
1089                 logger(DEBUG_ALWAYS, LOG_WARNING, "UPnP was requested, but tinc isn't built with miniupnpc support!");
1090 #endif
1091         }
1092
1093         /* Done. */
1094
1095         last_config_check = now.tv_sec;
1096
1097         return true;
1098 }
1099
1100 /*
1101   initialize network
1102 */
1103 bool setup_network(void) {
1104         init_connections();
1105         init_subnets();
1106         init_nodes();
1107         init_edges();
1108         init_requests();
1109
1110         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1111                 if(pinginterval < 1) {
1112                         pinginterval = 86400;
1113                 }
1114         } else {
1115                 pinginterval = 60;
1116         }
1117
1118         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout)) {
1119                 pingtimeout = 5;
1120         }
1121
1122         if(pingtimeout < 1 || pingtimeout > pinginterval) {
1123                 pingtimeout = pinginterval;
1124         }
1125
1126         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1127                 maxoutbufsize = 10 * MTU;
1128         }
1129
1130         if(!setup_myself()) {
1131                 return false;
1132         }
1133
1134         if(!init_control()) {
1135                 return false;
1136         }
1137
1138         if(!device_standby) {
1139                 device_enable();
1140         }
1141
1142         /* Run subnet-up scripts for our own subnets */
1143
1144         subnet_update(myself, NULL, true);
1145
1146         return true;
1147 }
1148
1149 /*
1150   close all open network connections
1151 */
1152 void close_network_connections(void) {
1153         for(list_node_t *node = connection_list->head, *next; node; node = next) {
1154                 next = node->next;
1155                 connection_t *c = node->data;
1156
1157                 /* Keep control connections open until the end, so they know when we really terminated */
1158                 if(c->status.control) {
1159                         c->socket = -1;
1160                 }
1161
1162                 c->outgoing = NULL;
1163                 terminate_connection(c, false);
1164         }
1165
1166         if(outgoing_list) {
1167                 list_delete_list(outgoing_list);
1168         }
1169
1170         if(myself && myself->connection) {
1171                 subnet_update(myself, NULL, false);
1172                 free_connection(myself->connection);
1173         }
1174
1175         for(int i = 0; i < listen_sockets; i++) {
1176                 io_del(&listen_socket[i].tcp);
1177                 io_del(&listen_socket[i].udp);
1178                 close(listen_socket[i].tcp.fd);
1179                 close(listen_socket[i].udp.fd);
1180         }
1181
1182         exit_requests();
1183         exit_edges();
1184         exit_subnets();
1185         exit_nodes();
1186         exit_connections();
1187
1188         if(!device_standby) {
1189                 device_disable();
1190         }
1191
1192         free(myport);
1193
1194         if(device_fd >= 0) {
1195                 io_del(&device_io);
1196         }
1197
1198         if(devops.close) {
1199                 devops.close();
1200         }
1201
1202         exit_control();
1203
1204         free(scriptextension);
1205         free(scriptinterpreter);
1206
1207         return;
1208 }