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