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