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