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