Set KillMode=mixed in the systemd service file.
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2017 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2010      Brandon Black <blblack@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include <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            If Cipher is set to none, still use a low level of encryption for the
665            meta protocol.
666         */
667
668         int keylen = myself->incipher ? EVP_CIPHER_key_length(myself->incipher) : 0;
669         if(keylen <= 16)
670                 myself->connection->outcipher = EVP_aes_128_cfb();
671         else if(keylen <= 24)
672                 myself->connection->outcipher = EVP_aes_192_cfb();
673         else
674                 myself->connection->outcipher = EVP_aes_256_cfb();
675
676         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
677                 keylifetime = 3600;
678
679         keyexpires = now + keylifetime;
680         
681         /* Check if we want to use message authentication codes... */
682
683         if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
684                 if(!strcasecmp(digest, "none")) {
685                         myself->indigest = NULL;
686                 } else {
687                         myself->indigest = EVP_get_digestbyname(digest);
688
689                         if(!myself->indigest) {
690                                 logger(LOG_ERR, "Unrecognized digest type!");
691                                 free(digest);
692                                 return false;
693                         }
694                 }
695
696                 free(digest);
697         } else
698                 myself->indigest = EVP_sha256();
699
700         myself->connection->outdigest = EVP_sha256();
701
702         if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
703                 if(myself->indigest) {
704                         if(myself->inmaclength > EVP_MD_size(myself->indigest)) {
705                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
706                                 return false;
707                         } else if(myself->inmaclength < 0) {
708                                 logger(LOG_ERR, "Bogus MAC length!");
709                                 return false;
710                         }
711                 }
712         } else
713                 myself->inmaclength = 4;
714
715         myself->connection->outmaclength = 0;
716
717         /* Compression */
718
719         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
720                 if(myself->incompression < 0 || myself->incompression > 11) {
721                         logger(LOG_ERR, "Bogus compression level!");
722                         return false;
723                 }
724         } else
725                 myself->incompression = 0;
726
727         myself->connection->outcompression = 0;
728
729         /* Done */
730
731         myself->nexthop = myself;
732         myself->via = myself;
733         myself->status.reachable = true;
734         node_add(myself);
735
736         graph();
737
738         if(strictsubnets)
739                 load_all_subnets();
740
741         /* Open device */
742
743         devops = os_devops;
744
745         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
746                 if(!strcasecmp(type, "dummy"))
747                         devops = dummy_devops;
748                 else if(!strcasecmp(type, "raw_socket"))
749                         devops = raw_socket_devops;
750                 else if(!strcasecmp(type, "multicast"))
751                         devops = multicast_devops;
752 #ifdef ENABLE_UML
753                 else if(!strcasecmp(type, "uml"))
754                         devops = uml_devops;
755 #endif
756 #ifdef ENABLE_VDE
757                 else if(!strcasecmp(type, "vde"))
758                         devops = vde_devops;
759 #endif
760                 free(type);
761         }
762
763         if(!devops.setup())
764                 return false;
765
766         /* Run tinc-up script to further initialize the tap interface */
767         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
768         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
769         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
770         xasprintf(&envp[3], "NAME=%s", myself->name);
771
772 #ifdef HAVE_MINGW
773         Sleep(1000);
774 #endif
775 #ifdef HAVE_CYGWIN
776         sleep(1);
777 #endif
778         execute_script("tinc-up", envp);
779
780         for(i = 0; i < 4; i++)
781                 free(envp[i]);
782
783         /* Run subnet-up scripts for our own subnets */
784
785         subnet_update(myself, NULL, true);
786
787         /* Open sockets */
788
789         if(!do_detach && getenv("LISTEN_FDS")) {
790                 sockaddr_t sa;
791                 socklen_t salen;
792
793                 listen_sockets = atoi(getenv("LISTEN_FDS"));
794 #ifdef HAVE_UNSETENV
795                 unsetenv("LISTEN_FDS");
796 #endif
797
798                 if(listen_sockets > MAXSOCKETS) {
799                         logger(LOG_ERR, "Too many listening sockets");
800                         return false;
801                 }
802
803                 for(i = 0; i < listen_sockets; i++) {
804                         salen = sizeof sa;
805                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
806                                 logger(LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
807                                 return false;
808                         }
809
810                         listen_socket[i].tcp = i + 3;
811
812 #ifdef FD_CLOEXEC
813                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
814 #endif
815
816                         listen_socket[i].udp = setup_vpn_in_socket(&sa);
817                         if(listen_socket[i].udp < 0)
818                                 return false;
819
820                         ifdebug(CONNECTIONS) {
821                                 hostname = sockaddr2hostname(&sa);
822                                 logger(LOG_NOTICE, "Listening on %s", hostname);
823                                 free(hostname);
824                         }
825
826                         memcpy(&listen_socket[i].sa, &sa, salen);
827                 }
828         } else {
829                 listen_sockets = 0;
830                 cfg = lookup_config(config_tree, "BindToAddress");
831
832                 do {
833                         get_config_string(cfg, &address);
834                         if(cfg)
835                                 cfg = lookup_config_next(config_tree, cfg);
836
837                         char *port = myport;
838
839                         if(address) {
840                                 char *space = strchr(address, ' ');
841                                 if(space) {
842                                         *space++ = 0;
843                                         port = space;
844                                 }
845
846                                 if(!strcmp(address, "*"))
847                                         *address = 0;
848                         }
849
850                         hint.ai_family = addressfamily;
851                         hint.ai_socktype = SOCK_STREAM;
852                         hint.ai_protocol = IPPROTO_TCP;
853                         hint.ai_flags = AI_PASSIVE;
854
855 #if HAVE_DECL_RES_INIT
856                         // ensure glibc reloads /etc/resolv.conf.
857                         res_init();
858 #endif
859                         err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
860                         free(address);
861
862                         if(err || !ai) {
863                                 logger(LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
864                                            gai_strerror(err));
865                                 return false;
866                         }
867
868                         for(aip = ai; aip; aip = aip->ai_next) {
869                                 if(listen_sockets >= MAXSOCKETS) {
870                                         logger(LOG_ERR, "Too many listening sockets");
871                                         return false;
872                                 }
873
874                                 listen_socket[listen_sockets].tcp =
875                                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
876
877                                 if(listen_socket[listen_sockets].tcp < 0)
878                                         continue;
879
880                                 listen_socket[listen_sockets].udp =
881                                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
882
883                                 if(listen_socket[listen_sockets].udp < 0)
884                                         continue;
885
886                                 ifdebug(CONNECTIONS) {
887                                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
888                                         logger(LOG_NOTICE, "Listening on %s", hostname);
889                                         free(hostname);
890                                 }
891
892                                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
893                                 listen_sockets++;
894                         }
895
896                         freeaddrinfo(ai);
897                 } while(cfg);
898         }
899
900         if(!listen_sockets) {
901                 logger(LOG_ERR, "Unable to create any listening socket!");
902                 return false;
903         }
904
905         /* If no Port option was specified, set myport to the port used by the first listening socket. */
906
907         if(!port_specified) {
908                 sockaddr_t sa;
909                 socklen_t salen = sizeof sa;
910                 if(!getsockname(listen_socket[0].udp, &sa.sa, &salen)) {
911                         free(myport);
912                         sockaddr2str(&sa, NULL, &myport);
913                         if(!myport)
914                                 myport = xstrdup("655");
915                 }
916         }
917
918         /* Done. */
919
920         logger(LOG_NOTICE, "Ready");
921         return true;
922 }
923
924 /*
925   initialize network
926 */
927 bool setup_network(void) {
928         now = time(NULL);
929
930         init_events();
931         init_connections();
932         init_subnets();
933         init_nodes();
934         init_edges();
935         init_requests();
936
937         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
938                 if(pinginterval < 1) {
939                         pinginterval = 86400;
940                 }
941         } else
942                 pinginterval = 60;
943
944         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
945                 pingtimeout = 5;
946         if(pingtimeout < 1 || pingtimeout > pinginterval)
947                 pingtimeout = pinginterval;
948
949         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
950                 maxoutbufsize = 10 * MTU;
951
952         if(!setup_myself())
953                 return false;
954
955         return true;
956 }
957
958 /*
959   close all open network connections
960 */
961 void close_network_connections(void) {
962         avl_node_t *node, *next;
963         connection_t *c;
964         char *envp[5] = {NULL};
965         int i;
966
967         for(node = connection_tree->head; node; node = next) {
968                 next = node->next;
969                 c = node->data;
970                 c->outgoing = NULL;
971                 terminate_connection(c, false);
972         }
973
974         for(list_node_t *node = outgoing_list->head; node; node = node->next) {
975                 outgoing_t *outgoing = node->data;
976
977                 if(outgoing->event)
978                         event_del(outgoing->event);
979         }
980
981         list_delete_list(outgoing_list);
982
983         if(myself && myself->connection) {
984                 subnet_update(myself, NULL, false);
985                 terminate_connection(myself->connection, false);
986                 free_connection(myself->connection);
987         }
988
989         for(i = 0; i < listen_sockets; i++) {
990                 close(listen_socket[i].tcp);
991                 close(listen_socket[i].udp);
992         }
993
994         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
995         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
996         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
997         xasprintf(&envp[3], "NAME=%s", myself->name);
998
999         exit_requests();
1000         exit_edges();
1001         exit_subnets();
1002         exit_nodes();
1003         exit_connections();
1004         exit_events();
1005
1006         execute_script("tinc-down", envp);
1007
1008         if(myport) free(myport);
1009
1010         for(i = 0; i < 4; i++)
1011                 free(envp[i]);
1012
1013         devops.close();
1014
1015         return;
1016 }