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