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