Simplify signal handling.
[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 "compression.h"
30 #include "control.h"
31 #include "device.h"
32 #include "digest.h"
33 #include "ecdsa.h"
34 #include "graph.h"
35 #include "logger.h"
36 #include "names.h"
37 #include "net.h"
38 #include "netutl.h"
39 #include "process.h"
40 #include "protocol.h"
41 #include "route.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         FILE *fp;
75         char *pubname = NULL;
76         char *p;
77
78         splay_tree_t config;
79         init_configuration(&config);
80
81         if(!read_host_config(&config, n->name, true)) {
82                 goto exit;
83         }
84
85         /* First, check for simple Ed25519PublicKey statement */
86
87         if(get_config_string(lookup_config(&config, "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, "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         splay_empty_tree(&config);
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;
180                 init_configuration(&config);
181                 read_config_options(&config, ent->d_name);
182                 read_host_config(&config, 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, "Subnet"); cfg; cfg = lookup_config_next(&config, 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, "Address")) {
208                         n->status.has_address = true;
209                 }
210
211                 splay_empty_tree(&config);
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         if(get_config_int(lookup_config(&config_tree, "Compression"), &myself->incompression)) {
864                 switch(myself->incompression) {
865                 case COMPRESS_LZ4:
866 #ifdef HAVE_LZ4
867                         break;
868 #else
869                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
870                         logger(DEBUG_ALWAYS, LOG_ERR, "LZ4 compression is unavailable on this node.");
871                         return false;
872 #endif
873
874                 case COMPRESS_LZO_HI:
875                 case COMPRESS_LZO_LO:
876 #ifdef HAVE_LZO
877                         break;
878 #else
879                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
880                         logger(DEBUG_ALWAYS, LOG_ERR, "LZO compression is unavailable on this node.");
881                         return false;
882 #endif
883
884                 case COMPRESS_ZLIB_9:
885                 case COMPRESS_ZLIB_8:
886                 case COMPRESS_ZLIB_7:
887                 case COMPRESS_ZLIB_6:
888                 case COMPRESS_ZLIB_5:
889                 case COMPRESS_ZLIB_4:
890                 case COMPRESS_ZLIB_3:
891                 case COMPRESS_ZLIB_2:
892                 case COMPRESS_ZLIB_1:
893 #ifdef HAVE_ZLIB
894                         break;
895 #else
896                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
897                         logger(DEBUG_ALWAYS, LOG_ERR, "ZLIB compression is unavailable on this node.");
898                         return false;
899 #endif
900
901                 case COMPRESS_NONE:
902                         break;
903
904                 default:
905                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
906                         logger(DEBUG_ALWAYS, LOG_ERR, "Compression level %i is unrecognized by this node.", myself->incompression);
907                         return false;
908                 }
909         } else {
910                 myself->incompression = COMPRESS_NONE;
911         }
912
913         myself->connection->outcompression = COMPRESS_NONE;
914
915         /* Done */
916
917         myself->nexthop = myself;
918         myself->via = myself;
919         myself->status.reachable = true;
920         myself->last_state_change = now.tv_sec;
921         myself->status.sptps = experimental;
922         node_add(myself);
923
924         graph();
925
926         load_all_nodes();
927
928         /* Open device */
929
930         devops = os_devops;
931
932         if(get_config_string(lookup_config(&config_tree, "DeviceType"), &type)) {
933                 if(!strcasecmp(type, "dummy")) {
934                         devops = dummy_devops;
935                 } else if(!strcasecmp(type, "raw_socket")) {
936                         devops = raw_socket_devops;
937                 } else if(!strcasecmp(type, "multicast")) {
938                         devops = multicast_devops;
939                 }
940
941 #ifdef HAVE_SYS_UN_H
942                 else if(!strcasecmp(type, "fd")) {
943                         devops = fd_devops;
944                 }
945
946 #endif
947 #ifdef ENABLE_UML
948                 else if(!strcasecmp(type, "uml")) {
949                         devops = uml_devops;
950                 }
951
952 #endif
953 #ifdef ENABLE_VDE
954                 else if(!strcasecmp(type, "vde")) {
955                         devops = vde_devops;
956                 }
957
958 #endif
959                 free(type);
960         }
961
962         get_config_bool(lookup_config(&config_tree, "DeviceStandby"), &device_standby);
963
964         if(!devops.setup()) {
965                 return false;
966         }
967
968         if(device_fd >= 0) {
969                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
970         }
971
972         /* Open sockets */
973
974         if(!do_detach && getenv("LISTEN_FDS")) {
975                 sockaddr_t sa;
976                 socklen_t salen;
977
978                 listen_sockets = atoi(getenv("LISTEN_FDS"));
979 #ifdef HAVE_UNSETENV
980                 unsetenv("LISTEN_FDS");
981 #endif
982
983                 if(listen_sockets > MAXSOCKETS) {
984                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
985                         return false;
986                 }
987
988                 for(int i = 0; i < listen_sockets; i++) {
989                         salen = sizeof(sa);
990
991                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
992                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
993                                 return false;
994                         }
995
996 #ifdef FD_CLOEXEC
997                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
998 #endif
999
1000                         int udp_fd = setup_vpn_in_socket(&sa);
1001
1002                         if(udp_fd < 0) {
1003                                 return false;
1004                         }
1005
1006                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
1007                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
1008
1009                         if(debug_level >= DEBUG_CONNECTIONS) {
1010                                 hostname = sockaddr2hostname(&sa);
1011                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
1012                                 free(hostname);
1013                         }
1014
1015                         memcpy(&listen_socket[i].sa, &sa, salen);
1016                 }
1017         } else {
1018                 listen_sockets = 0;
1019                 int cfgs = 0;
1020
1021                 for(config_t *cfg = lookup_config(&config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1022                         cfgs++;
1023                         get_config_string(cfg, &address);
1024
1025                         if(!add_listen_address(address, true)) {
1026                                 return false;
1027                         }
1028                 }
1029
1030                 for(config_t *cfg = lookup_config(&config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
1031                         cfgs++;
1032                         get_config_string(cfg, &address);
1033
1034                         if(!add_listen_address(address, false)) {
1035                                 return false;
1036                         }
1037                 }
1038
1039                 if(!cfgs)
1040                         if(!add_listen_address(address, NULL)) {
1041                                 return false;
1042                         }
1043         }
1044
1045         if(!listen_sockets) {
1046                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1047                 return false;
1048         }
1049
1050         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1051
1052         if(!port_specified || atoi(myport) == 0) {
1053                 sockaddr_t sa;
1054                 socklen_t salen = sizeof(sa);
1055
1056                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1057                         free(myport);
1058                         sockaddr2str(&sa, NULL, &myport);
1059
1060                         if(!myport) {
1061                                 myport = xstrdup("655");
1062                         }
1063                 }
1064         }
1065
1066         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1067         myself->connection->hostname = xstrdup(myself->hostname);
1068
1069         char *upnp = NULL;
1070         get_config_string(lookup_config(&config_tree, "UPnP"), &upnp);
1071         bool upnp_tcp = false;
1072         bool upnp_udp = false;
1073
1074         if(upnp) {
1075                 if(!strcasecmp(upnp, "yes")) {
1076                         upnp_tcp = upnp_udp = true;
1077                 } else if(!strcasecmp(upnp, "udponly")) {
1078                         upnp_udp = true;
1079                 }
1080
1081                 free(upnp);
1082         }
1083
1084         if(upnp_tcp || upnp_udp) {
1085 #ifdef HAVE_MINIUPNPC
1086                 upnp_init(upnp_tcp, upnp_udp);
1087 #else
1088                 logger(DEBUG_ALWAYS, LOG_WARNING, "UPnP was requested, but tinc isn't built with miniupnpc support!");
1089 #endif
1090         }
1091
1092         /* Done. */
1093
1094         last_config_check = now.tv_sec;
1095
1096         return true;
1097 }
1098
1099 /*
1100   initialize network
1101 */
1102 bool setup_network(void) {
1103         init_connections();
1104         init_subnets();
1105
1106         if(get_config_int(lookup_config(&config_tree, "PingInterval"), &pinginterval)) {
1107                 if(pinginterval < 1) {
1108                         pinginterval = 86400;
1109                 }
1110         } else {
1111                 pinginterval = 60;
1112         }
1113
1114         if(!get_config_int(lookup_config(&config_tree, "PingTimeout"), &pingtimeout)) {
1115                 pingtimeout = 5;
1116         }
1117
1118         if(pingtimeout < 1 || pingtimeout > pinginterval) {
1119                 pingtimeout = pinginterval;
1120         }
1121
1122         if(!get_config_int(lookup_config(&config_tree, "MaxOutputBufferSize"), &maxoutbufsize)) {
1123                 maxoutbufsize = 10 * MTU;
1124         }
1125
1126         if(!setup_myself()) {
1127                 return false;
1128         }
1129
1130         if(!init_control()) {
1131                 return false;
1132         }
1133
1134         if(!device_standby) {
1135                 device_enable();
1136         }
1137
1138         /* Run subnet-up scripts for our own subnets */
1139
1140         subnet_update(myself, NULL, true);
1141
1142         return true;
1143 }
1144
1145 /*
1146   close all open network connections
1147 */
1148 void close_network_connections(void) {
1149         for(list_node_t *node = connection_list.head, *next; node; node = next) {
1150                 next = node->next;
1151                 connection_t *c = node->data;
1152
1153                 /* Keep control connections open until the end, so they know when we really terminated */
1154                 if(c->status.control) {
1155                         c->socket = -1;
1156                 }
1157
1158                 c->outgoing = NULL;
1159                 terminate_connection(c, false);
1160         }
1161
1162         list_empty_list(&outgoing_list);
1163
1164         if(myself && myself->connection) {
1165                 subnet_update(myself, NULL, false);
1166                 free_connection(myself->connection);
1167         }
1168
1169         for(int i = 0; i < listen_sockets; i++) {
1170                 io_del(&listen_socket[i].tcp);
1171                 io_del(&listen_socket[i].udp);
1172                 close(listen_socket[i].tcp.fd);
1173                 close(listen_socket[i].udp.fd);
1174         }
1175
1176         exit_requests();
1177         exit_edges();
1178         exit_subnets();
1179         exit_nodes();
1180         exit_connections();
1181
1182         if(!device_standby) {
1183                 device_disable();
1184         }
1185
1186         free(myport);
1187
1188         if(device_fd >= 0) {
1189                 io_del(&device_io);
1190         }
1191
1192         if(devops.close) {
1193                 devops.close();
1194         }
1195
1196         exit_control();
1197
1198         free(scriptextension);
1199         free(scriptinterpreter);
1200
1201         return;
1202 }