5a7c6065ef830d68b5ca2694f50a9e4559e79108
[tinc] / src / net_setup.c
1 /*
2     net_setup.c -- Setup.
3     Copyright (C) 1998-2005 Ivo Timmermans,
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5                   2006      Scott Lamb <slamb@slamb.org>
6                   2010      Brandon Black <blblack@gmail.com>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17
18     You should have received a copy of the GNU General Public License along
19     with this program; if not, write to the Free Software Foundation, Inc.,
20     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
22
23 #include "system.h"
24
25 #include <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                 if(!envname) {
299                         if(strcmp(name + 1, "HOST")) {
300                                 fprintf(stderr, "Invalid Name: environment variable %s does not exist\n", name + 1);
301                                 return false;
302                         }
303                         char envname[32];
304                         if(gethostname(envname, 32)) {
305                                 fprintf(stderr, "Could not get hostname: %s\n", strerror(errno));
306                                 return false;
307                         }
308                         envname[31] = 0;
309                 }
310                 free(name);
311                 name = xstrdup(envname);
312                 for(char *c = name; *c; c++)
313                         if(!isalnum(*c))
314                                 *c = '_';
315         }
316
317         if(!check_id(name)) {
318                 logger(LOG_ERR, "Invalid name for myself!");
319                 free(name);
320                 return false;
321         }
322
323         return name;
324 }
325
326 /*
327   Configure node_t myself and set up the local sockets (listen only)
328 */
329 static bool setup_myself(void) {
330         config_t *cfg;
331         subnet_t *subnet;
332         char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
333         char *fname = NULL;
334         char *address = NULL;
335         char *proxy = NULL;
336         char *space;
337         char *envp[5];
338         struct addrinfo *ai, *aip, hint = {0};
339         bool choice;
340         int i, err;
341         int replaywin_int;
342
343         myself = new_node();
344         myself->connection = new_connection();
345
346         myself->hostname = xstrdup("MYSELF");
347         myself->connection->hostname = xstrdup("MYSELF");
348
349         myself->connection->options = 0;
350         myself->connection->protocol_version = PROT_CURRENT;
351
352         if(!(name = get_name())) {
353                 logger(LOG_ERR, "Name for tinc daemon required!");
354                 return false;
355         }
356
357         myself->name = name;
358         myself->connection->name = xstrdup(name);
359         xasprintf(&fname, "%s/hosts/%s", confbase, name);
360         read_config_options(config_tree, name);
361         read_config_file(config_tree, fname);
362         free(fname);
363
364         if(!read_rsa_private_key())
365                 return false;
366
367         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
368                 myport = xstrdup("655");
369
370         if(!atoi(myport)) {
371                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
372                 sockaddr_t sa;
373                 if(!ai || !ai->ai_addr)
374                         return false;
375                 free(myport);
376                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
377                 sockaddr2str(&sa, NULL, &myport);
378         }
379
380         get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
381         if(proxy) {
382                 if((space = strchr(proxy, ' ')))
383                         *space++ = 0;
384
385                 if(!strcasecmp(proxy, "none")) {
386                         proxytype = PROXY_NONE;
387                 } else if(!strcasecmp(proxy, "socks4")) {
388                         proxytype = PROXY_SOCKS4;
389                 } else if(!strcasecmp(proxy, "socks4a")) {
390                         proxytype = PROXY_SOCKS4A;
391                 } else if(!strcasecmp(proxy, "socks5")) {
392                         proxytype = PROXY_SOCKS5;
393                 } else if(!strcasecmp(proxy, "http")) {
394                         proxytype = PROXY_HTTP;
395                 } else if(!strcasecmp(proxy, "exec")) {
396                         proxytype = PROXY_EXEC;
397                 } else {
398                         logger(LOG_ERR, "Unknown proxy type %s!", proxy);
399                         return false;
400                 }
401
402                 switch(proxytype) {
403                         case PROXY_NONE:
404                         default:
405                                 break;
406
407                         case PROXY_EXEC:
408                                 if(!space || !*space) {
409                                         logger(LOG_ERR, "Argument expected for proxy type exec!");
410                                         return false;
411                                 }
412                                 proxyhost =  xstrdup(space);
413                                 break;
414
415                         case PROXY_SOCKS4:
416                         case PROXY_SOCKS4A:
417                         case PROXY_SOCKS5:
418                         case PROXY_HTTP:
419                                 proxyhost = space;
420                                 if(space && (space = strchr(space, ' ')))
421                                         *space++ = 0, proxyport = space;
422                                 if(space && (space = strchr(space, ' ')))
423                                         *space++ = 0, proxyuser = space;
424                                 if(space && (space = strchr(space, ' ')))
425                                         *space++ = 0, proxypass = space;
426                                 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
427                                         logger(LOG_ERR, "Host and port argument expected for proxy!");
428                                         return false;
429                                 }
430                                 proxyhost = xstrdup(proxyhost);
431                                 proxyport = xstrdup(proxyport);
432                                 if(proxyuser && *proxyuser)
433                                         proxyuser = xstrdup(proxyuser);
434                                 if(proxypass && *proxypass)
435                                         proxypass = xstrdup(proxypass);
436                                 break;
437                 }
438
439                 free(proxy);
440         }
441
442         /* Read in all the subnets specified in the host configuration file */
443
444         cfg = lookup_config(config_tree, "Subnet");
445
446         while(cfg) {
447                 if(!get_config_subnet(cfg, &subnet))
448                         return false;
449
450                 subnet_add(myself, subnet);
451
452                 cfg = lookup_config_next(config_tree, cfg);
453         }
454
455         /* Check some options */
456
457         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
458                 myself->options |= OPTION_INDIRECT;
459
460         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
461                 myself->options |= OPTION_TCPONLY;
462
463         if(myself->options & OPTION_TCPONLY)
464                 myself->options |= OPTION_INDIRECT;
465
466         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
467         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
468         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
469         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
470         strictsubnets |= tunnelserver;
471
472         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
473                 if(!strcasecmp(mode, "router"))
474                         routing_mode = RMODE_ROUTER;
475                 else if(!strcasecmp(mode, "switch"))
476                         routing_mode = RMODE_SWITCH;
477                 else if(!strcasecmp(mode, "hub"))
478                         routing_mode = RMODE_HUB;
479                 else {
480                         logger(LOG_ERR, "Invalid routing mode!");
481                         return false;
482                 }
483                 free(mode);
484         }
485
486         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
487                 if(!strcasecmp(mode, "off"))
488                         forwarding_mode = FMODE_OFF;
489                 else if(!strcasecmp(mode, "internal"))
490                         forwarding_mode = FMODE_INTERNAL;
491                 else if(!strcasecmp(mode, "kernel"))
492                         forwarding_mode = FMODE_KERNEL;
493                 else {
494                         logger(LOG_ERR, "Invalid forwarding mode!");
495                         return false;
496                 }
497                 free(mode);
498         }
499
500         choice = true;
501         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
502         if(choice)
503                 myself->options |= OPTION_PMTU_DISCOVERY;
504
505         choice = true;
506         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
507         if(choice)
508                 myself->options |= OPTION_CLAMP_MSS;
509
510         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
511         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
512         if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
513                 if(!strcasecmp(mode, "no"))
514                         broadcast_mode = BMODE_NONE;
515                 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
516                         broadcast_mode = BMODE_MST;
517                 else if(!strcasecmp(mode, "direct"))
518                         broadcast_mode = BMODE_DIRECT;
519                 else {
520                         logger(LOG_ERR, "Invalid broadcast mode!");
521                         return false;
522                 }
523                 free(mode);
524         }
525
526 #if !defined(SOL_IP) || !defined(IP_TOS)
527         if(priorityinheritance)
528                 logger(LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
529 #endif
530
531         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
532                 macexpire = 600;
533
534         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
535                 if(maxtimeout <= 0) {
536                         logger(LOG_ERR, "Bogus maximum timeout!");
537                         return false;
538                 }
539         } else
540                 maxtimeout = 900;
541
542         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
543                 if(udp_rcvbuf <= 0) {
544                         logger(LOG_ERR, "UDPRcvBuf cannot be negative!");
545                         return false;
546                 }
547         }
548
549         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
550                 if(udp_sndbuf <= 0) {
551                         logger(LOG_ERR, "UDPSndBuf cannot be negative!");
552                         return false;
553                 }
554         }
555
556         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
557                 if(replaywin_int < 0) {
558                         logger(LOG_ERR, "ReplayWindow cannot be negative!");
559                         return false;
560                 }
561                 replaywin = (unsigned)replaywin_int;
562         }
563
564         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
565                 if(!strcasecmp(afname, "IPv4"))
566                         addressfamily = AF_INET;
567                 else if(!strcasecmp(afname, "IPv6"))
568                         addressfamily = AF_INET6;
569                 else if(!strcasecmp(afname, "any"))
570                         addressfamily = AF_UNSPEC;
571                 else {
572                         logger(LOG_ERR, "Invalid address family!");
573                         return false;
574                 }
575                 free(afname);
576         }
577
578         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
579
580         /* Generate packet encryption key */
581
582         if(get_config_string
583            (lookup_config(config_tree, "Cipher"), &cipher)) {
584                 if(!strcasecmp(cipher, "none")) {
585                         myself->incipher = NULL;
586                 } else {
587                         myself->incipher = EVP_get_cipherbyname(cipher);
588
589                         if(!myself->incipher) {
590                                 logger(LOG_ERR, "Unrecognized cipher type!");
591                                 return false;
592                         }
593                 }
594         } else
595                 myself->incipher = EVP_bf_cbc();
596
597         if(myself->incipher)
598                 myself->inkeylength = myself->incipher->key_len + myself->incipher->iv_len;
599         else
600                 myself->inkeylength = 1;
601
602         myself->connection->outcipher = EVP_bf_ofb();
603
604         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
605                 keylifetime = 3600;
606
607         keyexpires = now + keylifetime;
608         
609         /* Check if we want to use message authentication codes... */
610
611         if(get_config_string(lookup_config(config_tree, "Digest"), &digest)) {
612                 if(!strcasecmp(digest, "none")) {
613                         myself->indigest = NULL;
614                 } else {
615                         myself->indigest = EVP_get_digestbyname(digest);
616
617                         if(!myself->indigest) {
618                                 logger(LOG_ERR, "Unrecognized digest type!");
619                                 return false;
620                         }
621                 }
622         } else
623                 myself->indigest = EVP_sha1();
624
625         myself->connection->outdigest = EVP_sha1();
626
627         if(get_config_int(lookup_config(config_tree, "MACLength"), &myself->inmaclength)) {
628                 if(myself->indigest) {
629                         if(myself->inmaclength > myself->indigest->md_size) {
630                                 logger(LOG_ERR, "MAC length exceeds size of digest!");
631                                 return false;
632                         } else if(myself->inmaclength < 0) {
633                                 logger(LOG_ERR, "Bogus MAC length!");
634                                 return false;
635                         }
636                 }
637         } else
638                 myself->inmaclength = 4;
639
640         myself->connection->outmaclength = 0;
641
642         /* Compression */
643
644         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
645                 if(myself->incompression < 0 || myself->incompression > 11) {
646                         logger(LOG_ERR, "Bogus compression level!");
647                         return false;
648                 }
649         } else
650                 myself->incompression = 0;
651
652         myself->connection->outcompression = 0;
653
654         /* Done */
655
656         myself->nexthop = myself;
657         myself->via = myself;
658         myself->status.reachable = true;
659         node_add(myself);
660
661         graph();
662
663         if(strictsubnets)
664                 load_all_subnets();
665
666         /* Open device */
667
668         devops = os_devops;
669
670         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
671                 if(!strcasecmp(type, "dummy"))
672                         devops = dummy_devops;
673                 else if(!strcasecmp(type, "raw_socket"))
674                         devops = raw_socket_devops;
675                 else if(!strcasecmp(type, "multicast"))
676                         devops = multicast_devops;
677 #ifdef ENABLE_UML
678                 else if(!strcasecmp(type, "uml"))
679                         devops = uml_devops;
680 #endif
681 #ifdef ENABLE_VDE
682                 else if(!strcasecmp(type, "vde"))
683                         devops = vde_devops;
684 #endif
685         }
686
687         if(!devops.setup())
688                 return false;
689
690         /* Run tinc-up script to further initialize the tap interface */
691         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
692         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
693         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
694         xasprintf(&envp[3], "NAME=%s", myself->name);
695         envp[4] = NULL;
696
697         execute_script("tinc-up", envp);
698
699         for(i = 0; i < 5; 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];
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         envp[4] = NULL;
900
901         exit_requests();
902         exit_edges();
903         exit_subnets();
904         exit_nodes();
905         exit_connections();
906         exit_events();
907
908         execute_script("tinc-down", envp);
909
910         if(myport) free(myport);
911
912         for(i = 0; i < 4; i++)
913                 free(envp[i]);
914
915         devops.close();
916
917         return;
918 }