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