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