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