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