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