858992c846fa30ae209dd917aba53c99ceefc863
[tinc] / 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 "script.h"
42 #include "subnet.h"
43 #include "utils.h"
44 #include "xalloc.h"
45
46 char *myport;
47 static io_t device_io;
48 devops_t devops;
49
50 char *proxyhost;
51 char *proxyport;
52 char *proxyuser;
53 char *proxypass;
54 proxytype_t proxytype;
55 int autoconnect;
56 bool disablebuggypeers;
57
58 char *scriptinterpreter;
59 char *scriptextension;
60
61 bool node_read_ecdsa_public_key(node_t *n) {
62         if(ecdsa_active(n->ecdsa))
63                 return true;
64
65         splay_tree_t *config_tree;
66         FILE *fp;
67         char *pubname = NULL;
68         char *p;
69
70         init_configuration(&config_tree);
71         if(!read_host_config(config_tree, n->name))
72                 goto exit;
73
74         /* First, check for simple ECDSAPublicKey statement */
75
76         if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
77                 n->ecdsa = ecdsa_set_base64_public_key(p);
78                 free(p);
79                 goto exit;
80         }
81
82         /* Else, check for ECDSAPublicKeyFile statement and read it */
83
84         if(!get_config_string(lookup_config(config_tree, "ECDSAPublicKeyFile"), &pubname))
85                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
86
87         fp = fopen(pubname, "r");
88
89         if(!fp)
90                 goto exit;
91
92         n->ecdsa = ecdsa_read_pem_public_key(fp);
93         fclose(fp);
94
95 exit:
96         exit_configuration(&config_tree);
97         free(pubname);
98         return n->ecdsa;
99 }
100
101 bool read_ecdsa_public_key(connection_t *c) {
102         if(ecdsa_active(c->ecdsa))
103                 return true;
104
105         FILE *fp;
106         char *fname;
107         char *p;
108
109         if(!c->config_tree) {
110                 init_configuration(&c->config_tree);
111                 if(!read_host_config(c->config_tree, c->name))
112                         return false;
113         }
114
115         /* First, check for simple ECDSAPublicKey statement */
116
117         if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
118                 c->ecdsa = ecdsa_set_base64_public_key(p);
119                 free(p);
120                 return c->ecdsa;
121         }
122
123         /* Else, check for ECDSAPublicKeyFile statement and read it */
124
125         if(!get_config_string(lookup_config(c->config_tree, "ECDSAPublicKeyFile"), &fname))
126                 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
127
128         fp = fopen(fname, "r");
129
130         if(!fp) {
131                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA public key file `%s': %s",
132                            fname, strerror(errno));
133                 free(fname);
134                 return false;
135         }
136
137         c->ecdsa = ecdsa_read_pem_public_key(fp);
138         fclose(fp);
139
140         if(!c->ecdsa)
141                 logger(DEBUG_ALWAYS, LOG_ERR, "Parsing ECDSA public key file `%s' failed.", fname);
142         free(fname);
143         return c->ecdsa;
144 }
145
146 bool read_rsa_public_key(connection_t *c) {
147         if(ecdsa_active(c->ecdsa))
148                 return true;
149
150         FILE *fp;
151         char *fname;
152         char *n;
153
154         /* First, check for simple PublicKey statement */
155
156         if(get_config_string(lookup_config(c->config_tree, "PublicKey"), &n)) {
157                 c->rsa = rsa_set_hex_public_key(n, "FFFF");
158                 free(n);
159                 return c->rsa;
160         }
161
162         /* Else, check for PublicKeyFile statement and read it */
163
164         if(!get_config_string(lookup_config(c->config_tree, "PublicKeyFile"), &fname))
165                 xasprintf(&fname, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
166
167         fp = fopen(fname, "r");
168
169         if(!fp) {
170                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA public key file `%s': %s", fname, strerror(errno));
171                 free(fname);
172                 return false;
173         }
174
175         c->rsa = rsa_read_pem_public_key(fp);
176         fclose(fp);
177
178         if(!c->rsa)
179                 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA public key file `%s' failed: %s", fname, strerror(errno));
180         free(fname);
181         return c->rsa;
182 }
183
184 static bool read_ecdsa_private_key(void) {
185         FILE *fp;
186         char *fname;
187
188         /* Check for PrivateKeyFile statement and read it */
189
190         if(!get_config_string(lookup_config(config_tree, "ECDSAPrivateKeyFile"), &fname))
191                 xasprintf(&fname, "%s" SLASH "ecdsa_key.priv", confbase);
192
193         fp = fopen(fname, "r");
194
195         if(!fp) {
196                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading ECDSA private key file `%s': %s", fname, strerror(errno));
197                 if(errno == ENOENT)
198                         logger(DEBUG_ALWAYS, LOG_INFO, "Create an ECDSA keypair with `tinc -n %s generate-ecdsa-keys'.", netname ?: ".");
199                 free(fname);
200                 return false;
201         }
202
203 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
204         struct stat s;
205
206         if(fstat(fileno(fp), &s)) {
207                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat ECDSA private key file `%s': %s'", fname, strerror(errno));
208                 free(fname);
209                 return false;
210         }
211
212         if(s.st_mode & ~0100700)
213                 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for ECDSA private key file `%s'!", fname);
214 #endif
215
216         myself->connection->ecdsa = ecdsa_read_pem_private_key(fp);
217         fclose(fp);
218
219         if(!myself->connection->ecdsa)
220                 logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
221         free(fname);
222         return myself->connection->ecdsa;
223 }
224
225 static bool read_invitation_key(void) {
226         FILE *fp;
227         char *fname;
228
229         if(invitation_key) {
230                 ecdsa_free(invitation_key);
231                 invitation_key = NULL;
232         }
233
234         xasprintf(&fname, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
235
236         fp = fopen(fname, "r");
237
238         if(fp) {
239                 invitation_key = ecdsa_read_pem_private_key(fp);
240                 fclose(fp);
241                 if(!invitation_key)
242                         logger(DEBUG_ALWAYS, LOG_ERR, "Reading ECDSA private key file `%s' failed: %s", fname, strerror(errno));
243         }
244
245         free(fname);
246         return invitation_key;
247 }
248
249 static bool read_rsa_private_key(void) {
250         FILE *fp;
251         char *fname;
252         char *n, *d;
253
254         /* First, check for simple PrivateKey statement */
255
256         if(get_config_string(lookup_config(config_tree, "PrivateKey"), &d)) {
257                 if(!get_config_string(lookup_config(config_tree, "PublicKey"), &n)) {
258                         logger(DEBUG_ALWAYS, LOG_ERR, "PrivateKey used but no PublicKey found!");
259                         free(d);
260                         return false;
261                 }
262                 myself->connection->rsa = rsa_set_hex_private_key(n, "FFFF", d);
263                 free(n);
264                 free(d);
265                 return myself->connection->rsa;
266         }
267
268         /* Else, check for PrivateKeyFile statement and read it */
269
270         if(!get_config_string(lookup_config(config_tree, "PrivateKeyFile"), &fname))
271                 xasprintf(&fname, "%s" SLASH "rsa_key.priv", confbase);
272
273         fp = fopen(fname, "r");
274
275         if(!fp) {
276                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading RSA private key file `%s': %s",
277                            fname, strerror(errno));
278                 free(fname);
279                 return false;
280         }
281
282 #if !defined(HAVE_MINGW) && !defined(HAVE_CYGWIN)
283         struct stat s;
284
285         if(fstat(fileno(fp), &s)) {
286                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not stat RSA private key file `%s': %s'", fname, strerror(errno));
287                 free(fname);
288                 return false;
289         }
290
291         if(s.st_mode & ~0100700)
292                 logger(DEBUG_ALWAYS, LOG_WARNING, "Warning: insecure file permissions for RSA private key file `%s'!", fname);
293 #endif
294
295         myself->connection->rsa = rsa_read_pem_private_key(fp);
296         fclose(fp);
297
298         if(!myself->connection->rsa)
299                 logger(DEBUG_ALWAYS, LOG_ERR, "Reading RSA private key file `%s' failed: %s", fname, strerror(errno));
300         free(fname);
301         return myself->connection->rsa;
302 }
303
304 static timeout_t keyexpire_timeout;
305
306 static void keyexpire_handler(void *data) {
307         regenerate_key();
308         timeout_set(data, &(struct timeval){keylifetime, rand() % 100000});
309 }
310
311 void regenerate_key(void) {
312         logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
313         send_key_changed();
314 }
315
316 /*
317   Read Subnets from all host config files
318 */
319 void load_all_subnets(void) {
320         DIR *dir;
321         struct dirent *ent;
322         char *dname;
323
324         xasprintf(&dname, "%s" SLASH "hosts", confbase);
325         dir = opendir(dname);
326         if(!dir) {
327                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
328                 free(dname);
329                 return;
330         }
331
332         while((ent = readdir(dir))) {
333                 if(!check_id(ent->d_name))
334                         continue;
335
336                 node_t *n = lookup_node(ent->d_name);
337                 #ifdef _DIRENT_HAVE_D_TYPE
338                 //if(ent->d_type != DT_REG)
339                 //      continue;
340                 #endif
341
342                 splay_tree_t *config_tree;
343                 init_configuration(&config_tree);
344                 read_config_options(config_tree, ent->d_name);
345                 read_host_config(config_tree, ent->d_name);
346
347                 if(!n) {
348                         n = new_node();
349                         n->name = xstrdup(ent->d_name);
350                         node_add(n);
351                 }
352
353                 for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
354                         subnet_t *s, *s2;
355
356                         if(!get_config_subnet(cfg, &s))
357                                 continue;
358
359                         if((s2 = lookup_subnet(n, s))) {
360                                 s2->expires = -1;
361                         } else {
362                                 subnet_add(n, s);
363                         }
364                 }
365
366                 exit_configuration(&config_tree);
367         }
368
369         closedir(dir);
370 }
371
372 void load_all_nodes(void) {
373         DIR *dir;
374         struct dirent *ent;
375         char *dname;
376
377         xasprintf(&dname, "%s" SLASH "hosts", confbase);
378         dir = opendir(dname);
379         if(!dir) {
380                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
381                 free(dname);
382                 return;
383         }
384
385         while((ent = readdir(dir))) {
386                 if(!check_id(ent->d_name))
387                         continue;
388
389                 node_t *n = lookup_node(ent->d_name);
390                 if(n)
391                         continue;
392
393                 n = new_node();
394                 n->name = xstrdup(ent->d_name);
395                 node_add(n);
396         }
397
398         closedir(dir);
399 }
400
401
402 char *get_name(void) {
403         char *name = NULL;
404
405         get_config_string(lookup_config(config_tree, "Name"), &name);
406
407         if(!name)
408                 return NULL;
409
410         if(*name == '$') {
411                 char *envname = getenv(name + 1);
412                 char hostname[32] = "";
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                         if(gethostname(hostname, sizeof hostname) || !*hostname) {
419                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", strerror(errno));
420                                 return false;
421                         }
422                         hostname[31] = 0;
423                         envname = hostname;
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         if(autoconnect < 0)
635                 autoconnect = 0;
636
637         get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
638
639         read_invitation_key();
640
641         return true;
642 }
643
644 /*
645   Configure node_t myself and set up the local sockets (listen only)
646 */
647 static bool setup_myself(void) {
648         char *name, *hostname, *cipher, *digest, *type;
649         char *address = NULL;
650         bool port_specified = false;
651
652         if(!(name = get_name())) {
653                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
654                 return false;
655         }
656
657         myself = new_node();
658         myself->connection = new_connection();
659         myself->name = name;
660         myself->connection->name = xstrdup(name);
661         read_host_config(config_tree, name);
662
663         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
664                 myport = xstrdup("655");
665         else
666                 port_specified = true;
667
668         myself->connection->options = 0;
669         myself->connection->protocol_major = PROT_MAJOR;
670         myself->connection->protocol_minor = PROT_MINOR;
671
672         myself->options |= PROT_MINOR << 24;
673
674         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
675                 experimental = read_ecdsa_private_key();
676                 if(!experimental)
677                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
678         } else {
679                 if(experimental && !read_ecdsa_private_key())
680                         return false;
681         }
682
683         if(!read_rsa_private_key())
684                 return false;
685
686         /* Ensure myport is numeric */
687
688         if(!atoi(myport)) {
689                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
690                 sockaddr_t sa;
691                 if(!ai || !ai->ai_addr)
692                         return false;
693                 free(myport);
694                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
695                 sockaddr2str(&sa, NULL, &myport);
696         }
697
698         /* Read in all the subnets specified in the host configuration file */
699
700         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
701                 subnet_t *subnet;
702
703                 if(!get_config_subnet(cfg, &subnet))
704                         return false;
705
706                 subnet_add(myself, subnet);
707         }
708
709         /* Check some options */
710
711         if(!setup_myself_reloadable())
712                 return false;
713
714         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
715         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
716         strictsubnets |= tunnelserver;
717
718         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
719                 if(max_connection_burst <= 0) {
720                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
721                         return false;
722                 }
723         }
724
725         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
726                 if(udp_rcvbuf <= 0) {
727                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
728                         return false;
729                 }
730         }
731
732         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
733                 if(udp_sndbuf <= 0) {
734                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
735                         return false;
736                 }
737         }
738
739         int replaywin_int;
740         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
741                 if(replaywin_int < 0) {
742                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
743                         return false;
744                 }
745                 replaywin = (unsigned)replaywin_int;
746                 sptps_replaywin = replaywin;
747         }
748
749         /* Generate packet encryption key */
750
751         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
752                 cipher = xstrdup("blowfish");
753
754         if(!strcasecmp(cipher, "none")) {
755                 myself->incipher = NULL;
756         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
757                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
758                 return false;
759         }
760
761         free(cipher);
762
763         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
764
765         /* Check if we want to use message authentication codes... */
766
767         int maclength = 4;
768         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
769
770         if(maclength < 0) {
771                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
772                 return false;
773         }
774
775         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
776                 digest = xstrdup("sha1");
777
778         if(!strcasecmp(digest, "none")) {
779                 myself->indigest = NULL;
780         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
781                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
782                 return false;
783         }
784
785         free(digest);
786
787         /* Compression */
788
789         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
790                 if(myself->incompression < 0 || myself->incompression > 11) {
791                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
792                         return false;
793                 }
794         } else
795                 myself->incompression = 0;
796
797         myself->connection->outcompression = 0;
798
799         /* Done */
800
801         myself->nexthop = myself;
802         myself->via = myself;
803         myself->status.reachable = true;
804         myself->last_state_change = now.tv_sec;
805         myself->status.sptps = experimental;
806         node_add(myself);
807
808         graph();
809
810         if(strictsubnets)
811                 load_all_subnets();
812         else if(autoconnect)
813                 load_all_nodes();
814
815         /* Open device */
816
817         devops = os_devops;
818
819         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
820                 if(!strcasecmp(type, "dummy"))
821                         devops = dummy_devops;
822                 else if(!strcasecmp(type, "raw_socket"))
823                         devops = raw_socket_devops;
824                 else if(!strcasecmp(type, "multicast"))
825                         devops = multicast_devops;
826 #ifdef ENABLE_UML
827                 else if(!strcasecmp(type, "uml"))
828                         devops = uml_devops;
829 #endif
830 #ifdef ENABLE_VDE
831                 else if(!strcasecmp(type, "vde"))
832                         devops = vde_devops;
833 #endif
834         }
835
836         if(!devops.setup())
837                 return false;
838
839         if(device_fd >= 0)
840                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
841
842         /* Open sockets */
843
844         if(!do_detach && getenv("LISTEN_FDS")) {
845                 sockaddr_t sa;
846                 socklen_t salen;
847
848                 listen_sockets = atoi(getenv("LISTEN_FDS"));
849 #ifdef HAVE_UNSETENV
850                 unsetenv("LISTEN_FDS");
851 #endif
852
853                 if(listen_sockets > MAXSOCKETS) {
854                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
855                         return false;
856                 }
857
858                 for(int i = 0; i < listen_sockets; i++) {
859                         salen = sizeof sa;
860                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
861                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
862                                 return false;
863                         }
864
865 #ifdef FD_CLOEXEC
866                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
867 #endif
868
869                         int udp_fd = setup_vpn_in_socket(&sa);
870                         if(udp_fd < 0)
871                                 return false;
872
873                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
874                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
875
876                         if(debug_level >= DEBUG_CONNECTIONS) {
877                                 hostname = sockaddr2hostname(&sa);
878                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
879                                 free(hostname);
880                         }
881
882                         memcpy(&listen_socket[i].sa, &sa, salen);
883                 }
884         } else {
885                 listen_sockets = 0;
886                 config_t *cfg = lookup_config(config_tree, "BindToAddress");
887
888                 do {
889                         get_config_string(cfg, &address);
890                         if(cfg)
891                                 cfg = lookup_config_next(config_tree, cfg);
892
893                         char *port = myport;
894
895                         if(address) {
896                                 char *space = strchr(address, ' ');
897                                 if(space) {
898                                         *space++ = 0;
899                                         port = space;
900                                 }
901
902                                 if(!strcmp(address, "*"))
903                                         *address = 0;
904                         }
905
906                         struct addrinfo *ai, hint = {0};
907                         hint.ai_family = addressfamily;
908                         hint.ai_socktype = SOCK_STREAM;
909                         hint.ai_protocol = IPPROTO_TCP;
910                         hint.ai_flags = AI_PASSIVE;
911
912                         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
913                         free(address);
914
915                         if(err || !ai) {
916                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
917                                 return false;
918                         }
919
920                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
921                                 if(listen_sockets >= MAXSOCKETS) {
922                                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
923                                         return false;
924                                 }
925
926                                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
927
928                                 if(tcp_fd < 0)
929                                         continue;
930
931                                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
932
933                                 if(tcp_fd < 0) {
934                                         close(tcp_fd);
935                                         continue;
936                                 }
937
938                                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
939                                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
940
941                                 if(debug_level >= DEBUG_CONNECTIONS) {
942                                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
943                                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
944                                         free(hostname);
945                                 }
946
947                                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
948                                 listen_sockets++;
949                         }
950
951                         freeaddrinfo(ai);
952                 } while(cfg);
953         }
954
955         if(!listen_sockets) {
956                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
957                 return false;
958         }
959
960         /* If no Port option was specified, set myport to the port used by the first listening socket. */
961
962         if(!port_specified) {
963                 sockaddr_t sa;
964                 socklen_t salen = sizeof sa;
965                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
966                         free(myport);
967                         sockaddr2str(&sa, NULL, &myport);
968                         if(!myport)
969                                 myport = xstrdup("655");
970                 }
971         }
972
973         xasprintf(&myself->hostname, "MYSELF port %s", myport);
974         myself->connection->hostname = xstrdup(myself->hostname);
975
976         /* Done. */
977
978         last_config_check = now.tv_sec;
979
980         return true;
981 }
982
983 /*
984   initialize network
985 */
986 bool setup_network(void) {
987         init_connections();
988         init_subnets();
989         init_nodes();
990         init_edges();
991         init_requests();
992
993         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
994                 if(pinginterval < 1) {
995                         pinginterval = 86400;
996                 }
997         } else
998                 pinginterval = 60;
999
1000         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1001                 pingtimeout = 5;
1002         if(pingtimeout < 1 || pingtimeout > pinginterval)
1003                 pingtimeout = pinginterval;
1004
1005         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
1006                 maxoutbufsize = 10 * MTU;
1007
1008         if(!setup_myself())
1009                 return false;
1010
1011         if(!init_control())
1012                 return false;
1013
1014         /* Run tinc-up script to further initialize the tap interface */
1015
1016         char *envp[5] = {NULL};
1017         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
1018         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
1019         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
1020         xasprintf(&envp[3], "NAME=%s", myself->name);
1021
1022         execute_script("tinc-up", envp);
1023
1024         for(int i = 0; i < 4; i++)
1025                 free(envp[i]);
1026
1027         /* Run subnet-up scripts for our own subnets */
1028
1029         subnet_update(myself, NULL, true);
1030
1031         return true;
1032 }
1033
1034 /*
1035   close all open network connections
1036 */
1037 void close_network_connections(void) {
1038         for(list_node_t *node = connection_list->head, *next; node; node = next) {
1039                 next = node->next;
1040                 connection_t *c = node->data;
1041                 /* Keep control connections open until the end, so they know when we really terminated */
1042                 if(c->status.control)
1043                         c->socket = -1;
1044                 c->outgoing = NULL;
1045                 terminate_connection(c, false);
1046         }
1047
1048         list_delete_list(outgoing_list);
1049
1050         if(myself && myself->connection) {
1051                 subnet_update(myself, NULL, false);
1052                 terminate_connection(myself->connection, false);
1053                 free_connection(myself->connection);
1054         }
1055
1056         for(int i = 0; i < listen_sockets; i++) {
1057                 io_del(&listen_socket[i].tcp);
1058                 io_del(&listen_socket[i].udp);
1059                 close(listen_socket[i].tcp.fd);
1060                 close(listen_socket[i].udp.fd);
1061         }
1062
1063         char *envp[5] = {NULL};
1064         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
1065         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
1066         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
1067         xasprintf(&envp[3], "NAME=%s", myself->name);
1068
1069         exit_requests();
1070         exit_edges();
1071         exit_subnets();
1072         exit_nodes();
1073         exit_connections();
1074
1075         execute_script("tinc-down", envp);
1076
1077         if(myport) free(myport);
1078
1079         for(int i = 0; i < 4; i++)
1080                 free(envp[i]);
1081
1082         devops.close();
1083
1084         exit_control();
1085
1086         return;
1087 }