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