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