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