]> git.meshlink.io Git - meshlink/blob - src/net_setup.c
Merge branch 'master' of git://tinc-vpn.org/tinc into 1.1
[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 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/hosts/%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/hosts/%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/hosts/%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/hosts/%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/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 true;
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/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/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/hosts/%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 /*
388   Configure node_t myself and set up the local sockets (listen only)
389 */
390 static bool setup_myself(void) {
391         config_t *cfg;
392         subnet_t *subnet;
393         char *name, *hostname, *mode, *afname, *cipher, *digest, *type;
394         char *fname = NULL;
395         char *address = NULL;
396         char *proxy = NULL;
397         char *space;
398         char *envp[5];
399         struct addrinfo *ai, *aip, hint = {0};
400         bool choice;
401         int i, err;
402         int replaywin_int;
403
404         myself = new_node();
405         myself->connection = new_connection();
406
407         myself->hostname = xstrdup("MYSELF");
408         myself->connection->hostname = xstrdup("MYSELF");
409
410         myself->connection->options = 0;
411         myself->connection->protocol_major = PROT_MAJOR;
412         myself->connection->protocol_minor = PROT_MINOR;
413
414         if(!(name = get_name())) {
415                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
416                 return false;
417         }
418
419         myself->name = name;
420         myself->connection->name = xstrdup(name);
421         xasprintf(&fname, "%s/hosts/%s", confbase, name);
422         read_config_options(config_tree, name);
423         read_config_file(config_tree, fname);
424         free(fname);
425
426         get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental);
427
428         if(experimental && !read_ecdsa_private_key())
429                 return false;
430
431         if(!read_rsa_private_key())
432                 return false;
433
434         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
435                 myport = xstrdup("655");
436
437         if(!atoi(myport)) {
438                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
439                 sockaddr_t sa;
440                 if(!ai || !ai->ai_addr)
441                         return false;
442                 free(myport);
443                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
444                 sockaddr2str(&sa, NULL, &myport);
445         }
446
447         get_config_string(lookup_config(config_tree, "Proxy"), &proxy);
448         if(proxy) {
449                 if((space = strchr(proxy, ' ')))
450                         *space++ = 0;
451
452                 if(!strcasecmp(proxy, "none")) {
453                         proxytype = PROXY_NONE;
454                 } else if(!strcasecmp(proxy, "socks4")) {
455                         proxytype = PROXY_SOCKS4;
456                 } else if(!strcasecmp(proxy, "socks4a")) {
457                         proxytype = PROXY_SOCKS4A;
458                 } else if(!strcasecmp(proxy, "socks5")) {
459                         proxytype = PROXY_SOCKS5;
460                 } else if(!strcasecmp(proxy, "http")) {
461                         proxytype = PROXY_HTTP;
462                 } else if(!strcasecmp(proxy, "exec")) {
463                         proxytype = PROXY_EXEC;
464                 } else {
465                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
466                         return false;
467                 }
468
469                 switch(proxytype) {
470                         case PROXY_NONE:
471                         default:
472                                 break;
473
474                         case PROXY_EXEC:
475                                 if(!space || !*space) {
476                                         logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
477                                         return false;
478                                 }
479                                 proxyhost =  xstrdup(space);
480                                 break;
481
482                         case PROXY_SOCKS4:
483                         case PROXY_SOCKS4A:
484                         case PROXY_SOCKS5:
485                         case PROXY_HTTP:
486                                 proxyhost = space;
487                                 if(space && (space = strchr(space, ' ')))
488                                         *space++ = 0, proxyport = space;
489                                 if(space && (space = strchr(space, ' ')))
490                                         *space++ = 0, proxyuser = space;
491                                 if(space && (space = strchr(space, ' ')))
492                                         *space++ = 0, proxypass = space;
493                                 if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
494                                         logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
495                                         return false;
496                                 }
497                                 proxyhost = xstrdup(proxyhost);
498                                 proxyport = xstrdup(proxyport);
499                                 if(proxyuser && *proxyuser)
500                                         proxyuser = xstrdup(proxyuser);
501                                 if(proxypass && *proxypass)
502                                         proxypass = xstrdup(proxypass);
503                                 break;
504                 }
505
506                 free(proxy);
507         }
508
509         /* Read in all the subnets specified in the host configuration file */
510
511         cfg = lookup_config(config_tree, "Subnet");
512
513         while(cfg) {
514                 if(!get_config_subnet(cfg, &subnet))
515                         return false;
516
517                 subnet_add(myself, subnet);
518
519                 cfg = lookup_config_next(config_tree, cfg);
520         }
521
522         /* Check some options */
523
524         if(get_config_bool(lookup_config(config_tree, "IndirectData"), &choice) && choice)
525                 myself->options |= OPTION_INDIRECT;
526
527         if(get_config_bool(lookup_config(config_tree, "TCPOnly"), &choice) && choice)
528                 myself->options |= OPTION_TCPONLY;
529
530         if(myself->options & OPTION_TCPONLY)
531                 myself->options |= OPTION_INDIRECT;
532
533         get_config_bool(lookup_config(config_tree, "DirectOnly"), &directonly);
534         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
535         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
536         get_config_bool(lookup_config(config_tree, "LocalDiscovery"), &localdiscovery);
537         strictsubnets |= tunnelserver;
538
539         if(get_config_string(lookup_config(config_tree, "Mode"), &mode)) {
540                 if(!strcasecmp(mode, "router"))
541                         routing_mode = RMODE_ROUTER;
542                 else if(!strcasecmp(mode, "switch"))
543                         routing_mode = RMODE_SWITCH;
544                 else if(!strcasecmp(mode, "hub"))
545                         routing_mode = RMODE_HUB;
546                 else {
547                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
548                         return false;
549                 }
550                 free(mode);
551         }
552
553         if(get_config_string(lookup_config(config_tree, "Forwarding"), &mode)) {
554                 if(!strcasecmp(mode, "off"))
555                         forwarding_mode = FMODE_OFF;
556                 else if(!strcasecmp(mode, "internal"))
557                         forwarding_mode = FMODE_INTERNAL;
558                 else if(!strcasecmp(mode, "kernel"))
559                         forwarding_mode = FMODE_KERNEL;
560                 else {
561                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
562                         return false;
563                 }
564                 free(mode);
565         }
566
567         choice = true;
568         get_config_bool(lookup_config(config_tree, "PMTUDiscovery"), &choice);
569         if(choice)
570                 myself->options |= OPTION_PMTU_DISCOVERY;
571
572         choice = true;
573         get_config_bool(lookup_config(config_tree, "ClampMSS"), &choice);
574         if(choice)
575                 myself->options |= OPTION_CLAMP_MSS;
576
577         get_config_bool(lookup_config(config_tree, "PriorityInheritance"), &priorityinheritance);
578         get_config_bool(lookup_config(config_tree, "DecrementTTL"), &decrement_ttl);
579         if(get_config_string(lookup_config(config_tree, "Broadcast"), &mode)) {
580                 if(!strcasecmp(mode, "no"))
581                         broadcast_mode = BMODE_NONE;
582                 else if(!strcasecmp(mode, "yes") || !strcasecmp(mode, "mst"))
583                         broadcast_mode = BMODE_MST;
584                 else if(!strcasecmp(mode, "direct"))
585                         broadcast_mode = BMODE_DIRECT;
586                 else {
587                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
588                         return false;
589                 }
590                 free(mode);
591         }
592
593 #if !defined(SOL_IP) || !defined(IP_TOS)
594         if(priorityinheritance)
595                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
596 #endif
597
598         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
599                 macexpire = 600;
600
601         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
602                 if(maxtimeout <= 0) {
603                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
604                         return false;
605                 }
606         } else
607                 maxtimeout = 900;
608
609         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
610                 if(udp_rcvbuf <= 0) {
611                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
612                         return false;
613                 }
614         }
615
616         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
617                 if(udp_sndbuf <= 0) {
618                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
619                         return false;
620                 }
621         }
622
623         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
624                 if(replaywin_int < 0) {
625                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
626                         return false;
627                 }
628                 replaywin = (unsigned)replaywin_int;
629         }
630
631         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
632                 if(!strcasecmp(afname, "IPv4"))
633                         addressfamily = AF_INET;
634                 else if(!strcasecmp(afname, "IPv6"))
635                         addressfamily = AF_INET6;
636                 else if(!strcasecmp(afname, "any"))
637                         addressfamily = AF_UNSPEC;
638                 else {
639                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
640                         return false;
641                 }
642                 free(afname);
643         }
644
645         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
646
647         /* Generate packet encryption key */
648
649         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
650                 cipher = xstrdup("blowfish");
651
652         if(!cipher_open_by_name(&myself->incipher, cipher)) {
653                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
654                 return false;
655         }
656
657         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
658                 keylifetime = 3600;
659
660         regenerate_key();
661
662         /* Check if we want to use message authentication codes... */
663
664         int maclength = 4;
665         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
666
667         if(maclength < 0) {
668                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
669                 return false;
670         }
671
672         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
673                 digest = xstrdup("sha1");
674
675         if(!digest_open_by_name(&myself->indigest, digest, maclength)) {
676                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
677                 return false;
678         }
679
680         /* Compression */
681
682         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
683                 if(myself->incompression < 0 || myself->incompression > 11) {
684                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
685                         return false;
686                 }
687         } else
688                 myself->incompression = 0;
689
690         myself->connection->outcompression = 0;
691
692         /* Done */
693
694         myself->nexthop = myself;
695         myself->via = myself;
696         myself->status.reachable = true;
697         node_add(myself);
698
699         graph();
700
701         if(strictsubnets)
702                 load_all_subnets();
703
704         /* Open device */
705
706         devops = os_devops;
707
708         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
709                 if(!strcasecmp(type, "dummy"))
710                         devops = dummy_devops;
711                 else if(!strcasecmp(type, "raw_socket"))
712                         devops = raw_socket_devops;
713                 else if(!strcasecmp(type, "multicast"))
714                         devops = multicast_devops;
715 #ifdef ENABLE_UML
716                 else if(!strcasecmp(type, "uml"))
717                         devops = uml_devops;
718 #endif
719 #ifdef ENABLE_VDE
720                 else if(!strcasecmp(type, "vde"))
721                         devops = vde_devops;
722 #endif
723         }
724
725         if(!devops.setup())
726                 return false;
727
728         if(device_fd >= 0) {
729                 event_set(&device_ev, device_fd, EV_READ|EV_PERSIST, handle_device_data, NULL);
730
731                 if (event_add(&device_ev, NULL) < 0) {
732                         logger(DEBUG_ALWAYS, LOG_ERR, "event_add failed: %s", strerror(errno));
733                         devops.close();
734                         return false;
735                 }
736         }
737
738         /* Run tinc-up script to further initialize the tap interface */
739         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
740         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
741         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
742         xasprintf(&envp[3], "NAME=%s", myself->name);
743         envp[4] = NULL;
744
745         execute_script("tinc-up", envp);
746
747         for(i = 0; i < 4; i++)
748                 free(envp[i]);
749
750         /* Run subnet-up scripts for our own subnets */
751
752         subnet_update(myself, NULL, true);
753
754         /* Open sockets */
755
756         if(!do_detach && getenv("LISTEN_FDS")) {
757                 sockaddr_t sa;
758                 socklen_t salen;
759
760                 listen_sockets = atoi(getenv("LISTEN_FDS"));
761 #ifdef HAVE_UNSETENV
762                 unsetenv("LISTEN_FDS");
763 #endif
764
765                 if(listen_sockets > MAXSOCKETS) {
766                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
767                         return false;
768                 }
769
770                 for(i = 0; i < listen_sockets; i++) {
771                         salen = sizeof sa;
772                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
773                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(errno));
774                                 return false;
775                         }
776
777                         listen_socket[i].tcp = i + 3;
778
779 #ifdef FD_CLOEXEC
780                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
781 #endif
782
783                         listen_socket[i].udp = setup_vpn_in_socket(&sa);
784                         if(listen_socket[i].udp < 0)
785                                 return false;
786
787                         event_set(&listen_socket[i].ev_tcp, listen_socket[i].tcp, EV_READ|EV_PERSIST, handle_new_meta_connection, NULL);
788                         if(event_add(&listen_socket[i].ev_tcp, NULL) < 0) {
789                                 logger(DEBUG_ALWAYS, LOG_ERR, "event_add failed: %s", strerror(errno));
790                                 abort();
791                         }
792
793                         event_set(&listen_socket[i].ev_udp, listen_socket[i].udp, EV_READ|EV_PERSIST, handle_incoming_vpn_data, (void *)(intptr_t)listen_sockets);
794                         if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
795                                 logger(DEBUG_ALWAYS, LOG_ERR, "event_add failed: %s", strerror(errno));
796                                 abort();
797                         }
798
799                         if(debug_level >= DEBUG_CONNECTIONS) {
800                                 hostname = sockaddr2hostname(&sa);
801                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
802                                 free(hostname);
803                         }
804
805                         memcpy(&listen_socket[i].sa, &sa, salen);
806                 }
807         } else {
808                 listen_sockets = 0;
809                 cfg = lookup_config(config_tree, "BindToAddress");
810
811                 do {
812                         get_config_string(cfg, &address);
813                         if(cfg)
814                                 cfg = lookup_config_next(config_tree, cfg);
815
816                         char *port = myport;
817
818                         if(address) {
819                                 char *space = strchr(address, ' ');
820                                 if(space) {
821                                         *space++ = 0;
822                                         port = space;
823                                 }
824
825                                 if(!strcmp(address, "*"))
826                                         *address = 0;
827                         }
828
829                         hint.ai_family = addressfamily;
830                         hint.ai_socktype = SOCK_STREAM;
831                         hint.ai_protocol = IPPROTO_TCP;
832                         hint.ai_flags = AI_PASSIVE;
833
834                         err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
835                         free(address);
836
837                         if(err || !ai) {
838                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo",
839                                            gai_strerror(err));
840                                 return false;
841                         }
842
843                         for(aip = ai; aip; aip = aip->ai_next) {
844                                 if(listen_sockets >= MAXSOCKETS) {
845                                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
846                                         return false;
847                                 }
848
849                                 listen_socket[listen_sockets].tcp =
850                                         setup_listen_socket((sockaddr_t *) aip->ai_addr);
851
852                                 if(listen_socket[listen_sockets].tcp < 0)
853                                         continue;
854
855                                 listen_socket[listen_sockets].udp =
856                                         setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
857
858                                 if(listen_socket[listen_sockets].udp < 0) {
859                                         close(listen_socket[listen_sockets].tcp);
860                                         continue;
861                                 }
862
863                                 event_set(&listen_socket[listen_sockets].ev_tcp,
864                                                   listen_socket[listen_sockets].tcp,
865                                                   EV_READ|EV_PERSIST,
866                                                   handle_new_meta_connection, NULL);
867                                 if(event_add(&listen_socket[listen_sockets].ev_tcp, NULL) < 0) {
868                                         logger(DEBUG_ALWAYS, LOG_ERR, "event_add failed: %s", strerror(errno));
869                                         abort();
870                                 }
871
872                                 event_set(&listen_socket[listen_sockets].ev_udp,
873                                                   listen_socket[listen_sockets].udp,
874                                                   EV_READ|EV_PERSIST,
875                                                   handle_incoming_vpn_data, (void *)(intptr_t)listen_sockets);
876                                 if(event_add(&listen_socket[listen_sockets].ev_udp, NULL) < 0) {
877                                         logger(DEBUG_ALWAYS, LOG_ERR, "event_add failed: %s", strerror(errno));
878                                         abort();
879                                 }
880
881                                 if(debug_level >= DEBUG_CONNECTIONS) {
882                                         hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
883                                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
884                                         free(hostname);
885                                 }
886
887                                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
888                                 listen_sockets++;
889                         }
890
891                         freeaddrinfo(ai);
892                 } while(cfg);
893         }
894
895         if(listen_sockets)
896                 logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
897         else {
898                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
899                 return false;
900         }
901
902         return true;
903 }
904
905 /*
906   initialize network
907 */
908 bool setup_network(void) {
909         init_connections();
910         init_subnets();
911         init_nodes();
912         init_edges();
913         init_requests();
914
915         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
916                 if(pinginterval < 1) {
917                         pinginterval = 86400;
918                 }
919         } else
920                 pinginterval = 60;
921
922         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
923                 pingtimeout = 5;
924         if(pingtimeout < 1 || pingtimeout > pinginterval)
925                 pingtimeout = pinginterval;
926
927         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
928                 maxoutbufsize = 10 * MTU;
929
930         if(!setup_myself())
931                 return false;
932
933         return true;
934 }
935
936 /*
937   close all open network connections
938 */
939 void close_network_connections(void) {
940         splay_node_t *node, *next;
941         connection_t *c;
942         char *envp[5];
943         int i;
944
945         for(node = connection_tree->head; node; node = next) {
946                 next = node->next;
947                 c = node->data;
948                 c->outgoing = NULL;
949                 terminate_connection(c, false);
950         }
951
952         list_delete_list(outgoing_list);
953
954         if(myself && myself->connection) {
955                 subnet_update(myself, NULL, false);
956                 terminate_connection(myself->connection, false);
957                 free_connection(myself->connection);
958         }
959
960         for(i = 0; i < listen_sockets; i++) {
961                 event_del(&listen_socket[i].ev_tcp);
962                 event_del(&listen_socket[i].ev_udp);
963                 close(listen_socket[i].tcp);
964                 close(listen_socket[i].udp);
965         }
966
967         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
968         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
969         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
970         xasprintf(&envp[3], "NAME=%s", myself->name);
971         envp[4] = NULL;
972
973         exit_requests();
974         exit_edges();
975         exit_subnets();
976         exit_nodes();
977         exit_connections();
978
979         execute_script("tinc-down", envp);
980
981         if(myport) free(myport);
982
983         for(i = 0; i < 4; i++)
984                 free(envp[i]);
985
986         devops.close();
987
988         return;
989 }