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