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