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