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