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