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