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