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