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