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