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