utils: Refactor get_name's functionality into util for global access
[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 io_t device_io;
48 devops_t devops;
49 bool device_standby = false;
50
51 char *proxyhost;
52 char *proxyport;
53 char *proxyuser;
54 char *proxypass;
55 proxytype_t proxytype;
56 bool autoconnect;
57 bool disablebuggypeers;
58
59 char *scriptinterpreter;
60 char *scriptextension;
61
62 bool node_read_ecdsa_public_key(node_t *n) {
63         if(ecdsa_active(n->ecdsa))
64                 return true;
65
66         splay_tree_t *config_tree;
67         FILE *fp;
68         char *pubname = NULL;
69         char *p;
70
71         init_configuration(&config_tree);
72         if(!read_host_config(config_tree, n->name))
73                 goto exit;
74
75         /* First, check for simple Ed25519PublicKey statement */
76
77         if(get_config_string(lookup_config(config_tree, "Ed25519PublicKey"), &p)) {
78                 n->ecdsa = ecdsa_set_base64_public_key(p);
79                 free(p);
80                 goto exit;
81         }
82
83         /* Else, check for Ed25519PublicKeyFile statement and read it */
84
85         if(!get_config_string(lookup_config(config_tree, "Ed25519PublicKeyFile"), &pubname))
86                 xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
87
88         fp = fopen(pubname, "r");
89
90         if(!fp)
91                 goto exit;
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 Ed25519PublicKey statement */
117
118         if(get_config_string(lookup_config(c->config_tree, "Ed25519PublicKey"), &p)) {
119                 c->ecdsa = ecdsa_set_base64_public_key(p);
120                 free(p);
121                 return c->ecdsa;
122         }
123
124         /* Else, check for Ed25519PublicKeyFile statement and read it */
125
126         if(!get_config_string(lookup_config(c->config_tree, "Ed25519PublicKeyFile"), &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 Ed25519 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 Ed25519 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, "Ed25519PrivateKeyFile"), &fname))
192                 xasprintf(&fname, "%s" SLASH "ed25519_key.priv", confbase);
193
194         fp = fopen(fname, "r");
195
196         if(!fp) {
197                 logger(DEBUG_ALWAYS, LOG_ERR, "Error reading Ed25519 private key file `%s': %s", fname, strerror(errno));
198                 if(errno == ENOENT)
199                         logger(DEBUG_ALWAYS, LOG_INFO, "Create an Ed25519 keypair with `tinc -n %s generate-ed25519-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 Ed25519 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 Ed25519 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 Ed25519 private key file `%s' failed", fname);
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 "ed25519_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 Ed25519 private key file `%s' failed", fname);
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         char *returned_name;
406
407         get_config_string(lookup_config(config_tree, "Name"), &name);
408
409         if(!name)
410                 return NULL;
411
412         returned_name = replace_name(name);
413         free(name);
414         return returned_name;
415 }
416
417 bool setup_myself_reloadable(void) {
418         char *proxy = NULL;
419         char *rmode = NULL;
420         char *fmode = NULL;
421         char *bmode = NULL;
422         char *afname = NULL;
423         char *space;
424         bool choice;
425
426         free(scriptinterpreter);
427         scriptinterpreter = NULL;
428         get_config_string(lookup_config(config_tree, "ScriptsInterpreter"), &scriptinterpreter);
429
430
431         free(scriptextension);
432         if(!get_config_string(lookup_config(config_tree, "ScriptsExtension"), &scriptextension))
433                 scriptextension = xstrdup("");
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         const char* const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
564         for (size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
565                 subnet_t *s = new_subnet();
566                 if (!str2net(s, DEFAULT_BROADCAST_SUBNETS[i]))
567                         abort();
568                 subnet_add(NULL, s);
569         }
570         for (config_t* cfg = lookup_config(config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
571                 subnet_t *s;
572                 if (!get_config_subnet(cfg, &s))
573                         continue;
574                 subnet_add(NULL, s);
575         }
576
577 #if !defined(SOL_IP) || !defined(IP_TOS)
578         if(priorityinheritance)
579                 logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform", "PriorityInheritance");
580 #endif
581
582         if(!get_config_int(lookup_config(config_tree, "MACExpire"), &macexpire))
583                 macexpire = 600;
584
585         if(get_config_int(lookup_config(config_tree, "MaxTimeout"), &maxtimeout)) {
586                 if(maxtimeout <= 0) {
587                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
588                         return false;
589                 }
590         } else
591                 maxtimeout = 900;
592
593         if(get_config_string(lookup_config(config_tree, "AddressFamily"), &afname)) {
594                 if(!strcasecmp(afname, "IPv4"))
595                         addressfamily = AF_INET;
596                 else if(!strcasecmp(afname, "IPv6"))
597                         addressfamily = AF_INET6;
598                 else if(!strcasecmp(afname, "any"))
599                         addressfamily = AF_UNSPEC;
600                 else {
601                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
602                         return false;
603                 }
604                 free(afname);
605         }
606
607         get_config_bool(lookup_config(config_tree, "Hostnames"), &hostnames);
608
609         if(!get_config_int(lookup_config(config_tree, "KeyExpire"), &keylifetime))
610                 keylifetime = 3600;
611
612         config_t *cfg = lookup_config(config_tree, "AutoConnect");
613         if(cfg) {
614                 if(!get_config_bool(cfg, &autoconnect)) {
615                         // Some backwards compatibility with when this option was an int
616                         int val = 0;
617                         get_config_int(cfg, &val);
618                         autoconnect = val;
619                 }
620         }
621
622         get_config_bool(lookup_config(config_tree, "DisableBuggyPeers"), &disablebuggypeers);
623
624         read_invitation_key();
625
626         return true;
627 }
628
629 /*
630   Add listening sockets.
631 */
632 static bool add_listen_address(char *address, bool bindto) {
633         char *port = myport;
634
635         if(address) {
636                 char *space = strchr(address, ' ');
637                 if(space) {
638                         *space++ = 0;
639                         port = space;
640                 }
641
642                 if(!strcmp(address, "*"))
643                         *address = 0;
644         }
645
646         struct addrinfo *ai, hint = {0};
647         hint.ai_family = addressfamily;
648         hint.ai_socktype = SOCK_STREAM;
649         hint.ai_protocol = IPPROTO_TCP;
650         hint.ai_flags = AI_PASSIVE;
651
652         int err = getaddrinfo(address && *address ? address : NULL, port, &hint, &ai);
653         free(address);
654
655         if(err || !ai) {
656                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "getaddrinfo", err == EAI_SYSTEM ? strerror(err) : gai_strerror(err));
657                 return false;
658         }
659
660         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
661                 // Ignore duplicate addresses
662                 bool found = false;
663
664                 for(int i = 0; i < listen_sockets; i++)
665                         if(!memcmp(&listen_socket[i].sa, aip->ai_addr, aip->ai_addrlen)) {
666                                 found = true;
667                                 break;
668                         }
669
670                 if(found)
671                         continue;
672
673                 if(listen_sockets >= MAXSOCKETS) {
674                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
675                         return false;
676                 }
677
678                 int tcp_fd = setup_listen_socket((sockaddr_t *) aip->ai_addr);
679
680                 if(tcp_fd < 0)
681                         continue;
682
683                 int udp_fd = setup_vpn_in_socket((sockaddr_t *) aip->ai_addr);
684
685                 if(tcp_fd < 0) {
686                         close(tcp_fd);
687                         continue;
688                 }
689
690                 io_add(&listen_socket[listen_sockets].tcp, handle_new_meta_connection, &listen_socket[listen_sockets], tcp_fd, IO_READ);
691                 io_add(&listen_socket[listen_sockets].udp, handle_incoming_vpn_data, &listen_socket[listen_sockets], udp_fd, IO_READ);
692
693                 if(debug_level >= DEBUG_CONNECTIONS) {
694                         char *hostname = sockaddr2hostname((sockaddr_t *) aip->ai_addr);
695                         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
696                         free(hostname);
697                 }
698
699                 listen_socket[listen_sockets].bindto = bindto;
700                 memcpy(&listen_socket[listen_sockets].sa, aip->ai_addr, aip->ai_addrlen);
701                 listen_sockets++;
702         }
703
704         freeaddrinfo(ai);
705         return true;
706 }
707
708 void device_enable(void) {
709         if (devops.enable)
710                 devops.enable();
711
712         /* Run tinc-up script to further initialize the tap interface */
713
714         char *envp[5] = {NULL};
715         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
716         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
717         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
718         xasprintf(&envp[3], "NAME=%s", myself->name);
719
720         execute_script("tinc-up", envp);
721
722         for(int i = 0; i < 4; i++)
723                 free(envp[i]);
724 }
725
726 void device_disable(void) {
727         char *envp[5] = {NULL};
728         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
729         xasprintf(&envp[1], "DEVICE=%s", device ? : "");
730         xasprintf(&envp[2], "INTERFACE=%s", iface ? : "");
731         xasprintf(&envp[3], "NAME=%s", myself->name);
732
733         execute_script("tinc-down", envp);
734
735         for(int i = 0; i < 4; i++)
736                 free(envp[i]);
737
738         if (devops.disable)
739                 devops.disable();
740 }
741
742 /*
743   Configure node_t myself and set up the local sockets (listen only)
744 */
745 static bool setup_myself(void) {
746         char *name, *hostname, *cipher, *digest, *type;
747         char *address = NULL;
748         bool port_specified = false;
749
750         if(!(name = get_name())) {
751                 logger(DEBUG_ALWAYS, LOG_ERR, "Name for tinc daemon required!");
752                 return false;
753         }
754
755         myself = new_node();
756         myself->connection = new_connection();
757         myself->name = name;
758         myself->connection->name = xstrdup(name);
759         read_host_config(config_tree, name);
760
761         if(!get_config_string(lookup_config(config_tree, "Port"), &myport))
762                 myport = xstrdup("655");
763         else
764                 port_specified = true;
765
766         myself->connection->options = 0;
767         myself->connection->protocol_major = PROT_MAJOR;
768         myself->connection->protocol_minor = PROT_MINOR;
769
770         myself->options |= PROT_MINOR << 24;
771
772         if(!get_config_bool(lookup_config(config_tree, "ExperimentalProtocol"), &experimental)) {
773                 experimental = read_ecdsa_private_key();
774                 if(!experimental)
775                         logger(DEBUG_ALWAYS, LOG_WARNING, "Support for SPTPS disabled.");
776         } else {
777                 if(experimental && !read_ecdsa_private_key())
778                         return false;
779         }
780
781         if(!read_rsa_private_key())
782                 return false;
783
784         /* Ensure myport is numeric */
785
786         if(!atoi(myport)) {
787                 struct addrinfo *ai = str2addrinfo("localhost", myport, SOCK_DGRAM);
788                 sockaddr_t sa;
789                 if(!ai || !ai->ai_addr)
790                         return false;
791                 free(myport);
792                 memcpy(&sa, ai->ai_addr, ai->ai_addrlen);
793                 sockaddr2str(&sa, NULL, &myport);
794         }
795
796         /* Read in all the subnets specified in the host configuration file */
797
798         for(config_t *cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
799                 subnet_t *subnet;
800
801                 if(!get_config_subnet(cfg, &subnet))
802                         return false;
803
804                 subnet_add(myself, subnet);
805         }
806
807         /* Check some options */
808
809         if(!setup_myself_reloadable())
810                 return false;
811
812         get_config_bool(lookup_config(config_tree, "StrictSubnets"), &strictsubnets);
813         get_config_bool(lookup_config(config_tree, "TunnelServer"), &tunnelserver);
814         strictsubnets |= tunnelserver;
815
816         if(get_config_int(lookup_config(config_tree, "MaxConnectionBurst"), &max_connection_burst)) {
817                 if(max_connection_burst <= 0) {
818                         logger(DEBUG_ALWAYS, LOG_ERR, "MaxConnectionBurst cannot be negative!");
819                         return false;
820                 }
821         }
822
823         if(get_config_int(lookup_config(config_tree, "UDPRcvBuf"), &udp_rcvbuf)) {
824                 if(udp_rcvbuf <= 0) {
825                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPRcvBuf cannot be negative!");
826                         return false;
827                 }
828         }
829
830         if(get_config_int(lookup_config(config_tree, "UDPSndBuf"), &udp_sndbuf)) {
831                 if(udp_sndbuf <= 0) {
832                         logger(DEBUG_ALWAYS, LOG_ERR, "UDPSndBuf cannot be negative!");
833                         return false;
834                 }
835         }
836
837         int replaywin_int;
838         if(get_config_int(lookup_config(config_tree, "ReplayWindow"), &replaywin_int)) {
839                 if(replaywin_int < 0) {
840                         logger(DEBUG_ALWAYS, LOG_ERR, "ReplayWindow cannot be negative!");
841                         return false;
842                 }
843                 replaywin = (unsigned)replaywin_int;
844                 sptps_replaywin = replaywin;
845         }
846
847         /* Generate packet encryption key */
848
849         if(!get_config_string(lookup_config(config_tree, "Cipher"), &cipher))
850                 cipher = xstrdup("blowfish");
851
852         if(!strcasecmp(cipher, "none")) {
853                 myself->incipher = NULL;
854         } else if(!(myself->incipher = cipher_open_by_name(cipher))) {
855                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized cipher type!");
856                 return false;
857         }
858
859         free(cipher);
860
861         timeout_add(&keyexpire_timeout, keyexpire_handler, &keyexpire_timeout, &(struct timeval){keylifetime, rand() % 100000});
862
863         /* Check if we want to use message authentication codes... */
864
865         int maclength = 4;
866         get_config_int(lookup_config(config_tree, "MACLength"), &maclength);
867
868         if(maclength < 0) {
869                 logger(DEBUG_ALWAYS, LOG_ERR, "Bogus MAC length!");
870                 return false;
871         }
872
873         if(!get_config_string(lookup_config(config_tree, "Digest"), &digest))
874                 digest = xstrdup("sha1");
875
876         if(!strcasecmp(digest, "none")) {
877                 myself->indigest = NULL;
878         } else if(!(myself->indigest = digest_open_by_name(digest, maclength))) {
879                 logger(DEBUG_ALWAYS, LOG_ERR, "Unrecognized digest type!");
880                 return false;
881         }
882
883         free(digest);
884
885         /* Compression */
886
887         if(get_config_int(lookup_config(config_tree, "Compression"), &myself->incompression)) {
888                 if(myself->incompression < 0 || myself->incompression > 11) {
889                         logger(DEBUG_ALWAYS, LOG_ERR, "Bogus compression level!");
890                         return false;
891                 }
892         } else
893                 myself->incompression = 0;
894
895         myself->connection->outcompression = 0;
896
897         /* Done */
898
899         myself->nexthop = myself;
900         myself->via = myself;
901         myself->status.reachable = true;
902         myself->last_state_change = now.tv_sec;
903         myself->status.sptps = experimental;
904         node_add(myself);
905
906         graph();
907
908         if(strictsubnets)
909                 load_all_subnets();
910         else if(autoconnect)
911                 load_all_nodes();
912
913         /* Open device */
914
915         devops = os_devops;
916
917         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
918                 if(!strcasecmp(type, "dummy"))
919                         devops = dummy_devops;
920                 else if(!strcasecmp(type, "raw_socket"))
921                         devops = raw_socket_devops;
922                 else if(!strcasecmp(type, "multicast"))
923                         devops = multicast_devops;
924 #ifdef ENABLE_UML
925                 else if(!strcasecmp(type, "uml"))
926                         devops = uml_devops;
927 #endif
928 #ifdef ENABLE_VDE
929                 else if(!strcasecmp(type, "vde"))
930                         devops = vde_devops;
931 #endif
932         }
933
934         get_config_bool(lookup_config(config_tree, "DeviceStandby"), &device_standby);
935
936         if(!devops.setup())
937                 return false;
938
939         if(device_fd >= 0)
940                 io_add(&device_io, handle_device_data, NULL, device_fd, IO_READ);
941
942         /* Open sockets */
943
944         if(!do_detach && getenv("LISTEN_FDS")) {
945                 sockaddr_t sa;
946                 socklen_t salen;
947
948                 listen_sockets = atoi(getenv("LISTEN_FDS"));
949 #ifdef HAVE_UNSETENV
950                 unsetenv("LISTEN_FDS");
951 #endif
952
953                 if(listen_sockets > MAXSOCKETS) {
954                         logger(DEBUG_ALWAYS, LOG_ERR, "Too many listening sockets");
955                         return false;
956                 }
957
958                 for(int i = 0; i < listen_sockets; i++) {
959                         salen = sizeof sa;
960                         if(getsockname(i + 3, &sa.sa, &salen) < 0) {
961                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get address of listen fd %d: %s", i + 3, sockstrerror(sockerrno));
962                                 return false;
963                         }
964
965 #ifdef FD_CLOEXEC
966                         fcntl(i + 3, F_SETFD, FD_CLOEXEC);
967 #endif
968
969                         int udp_fd = setup_vpn_in_socket(&sa);
970                         if(udp_fd < 0)
971                                 return false;
972
973                         io_add(&listen_socket[i].tcp, (io_cb_t)handle_new_meta_connection, &listen_socket[i], i + 3, IO_READ);
974                         io_add(&listen_socket[i].udp, (io_cb_t)handle_incoming_vpn_data, &listen_socket[i], udp_fd, IO_READ);
975
976                         if(debug_level >= DEBUG_CONNECTIONS) {
977                                 hostname = sockaddr2hostname(&sa);
978                                 logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Listening on %s", hostname);
979                                 free(hostname);
980                         }
981
982                         memcpy(&listen_socket[i].sa, &sa, salen);
983                 }
984         } else {
985                 listen_sockets = 0;
986                 int cfgs = 0;
987
988                 for(config_t *cfg = lookup_config(config_tree, "BindToAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
989                         cfgs++;
990                         get_config_string(cfg, &address);
991                         if(!add_listen_address(address, true))
992                                 return false;
993                 }
994
995                 for(config_t *cfg = lookup_config(config_tree, "ListenAddress"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
996                         cfgs++;
997                         get_config_string(cfg, &address);
998                         if(!add_listen_address(address, false))
999                                 return false;
1000                 }
1001
1002                 if(!cfgs)
1003                         if(!add_listen_address(address, NULL))
1004                                 return false;
1005         }
1006
1007         if(!listen_sockets) {
1008                 logger(DEBUG_ALWAYS, LOG_ERR, "Unable to create any listening socket!");
1009                 return false;
1010         }
1011
1012         /* If no Port option was specified, set myport to the port used by the first listening socket. */
1013
1014         if(!port_specified || atoi(myport) == 0) {
1015                 sockaddr_t sa;
1016                 socklen_t salen = sizeof sa;
1017                 if(!getsockname(listen_socket[0].udp.fd, &sa.sa, &salen)) {
1018                         free(myport);
1019                         sockaddr2str(&sa, NULL, &myport);
1020                         if(!myport)
1021                                 myport = xstrdup("655");
1022                 }
1023         }
1024
1025         xasprintf(&myself->hostname, "MYSELF port %s", myport);
1026         myself->connection->hostname = xstrdup(myself->hostname);
1027
1028         /* Done. */
1029
1030         last_config_check = now.tv_sec;
1031
1032         return true;
1033 }
1034
1035 /*
1036   initialize network
1037 */
1038 bool setup_network(void) {
1039         init_connections();
1040         init_subnets();
1041         init_nodes();
1042         init_edges();
1043         init_requests();
1044
1045         if(get_config_int(lookup_config(config_tree, "PingInterval"), &pinginterval)) {
1046                 if(pinginterval < 1) {
1047                         pinginterval = 86400;
1048                 }
1049         } else
1050                 pinginterval = 60;
1051
1052         if(!get_config_int(lookup_config(config_tree, "PingTimeout"), &pingtimeout))
1053                 pingtimeout = 5;
1054         if(pingtimeout < 1 || pingtimeout > pinginterval)
1055                 pingtimeout = pinginterval;
1056
1057         if(!get_config_int(lookup_config(config_tree, "MaxOutputBufferSize"), &maxoutbufsize))
1058                 maxoutbufsize = 10 * MTU;
1059
1060         if(!setup_myself())
1061                 return false;
1062
1063         if(!init_control())
1064                 return false;
1065
1066         if (!device_standby)
1067                 device_enable();
1068
1069         /* Run subnet-up scripts for our own subnets */
1070
1071         subnet_update(myself, NULL, true);
1072
1073         return true;
1074 }
1075
1076 /*
1077   close all open network connections
1078 */
1079 void close_network_connections(void) {
1080         for(list_node_t *node = connection_list->head, *next; node; node = next) {
1081                 next = node->next;
1082                 connection_t *c = node->data;
1083                 /* Keep control connections open until the end, so they know when we really terminated */
1084                 if(c->status.control)
1085                         c->socket = -1;
1086                 c->outgoing = NULL;
1087                 terminate_connection(c, false);
1088         }
1089
1090         if(outgoing_list)
1091                 list_delete_list(outgoing_list);
1092
1093         if(myself && myself->connection) {
1094                 subnet_update(myself, NULL, false);
1095                 terminate_connection(myself->connection, false);
1096                 free_connection(myself->connection);
1097         }
1098
1099         for(int i = 0; i < listen_sockets; i++) {
1100                 io_del(&listen_socket[i].tcp);
1101                 io_del(&listen_socket[i].udp);
1102                 close(listen_socket[i].tcp.fd);
1103                 close(listen_socket[i].udp.fd);
1104         }
1105
1106         exit_requests();
1107         exit_edges();
1108         exit_subnets();
1109         exit_nodes();
1110         exit_connections();
1111
1112         if (!device_standby)
1113                 device_disable();
1114
1115         if(myport) free(myport);
1116
1117         if (device_fd >= 0)
1118                 io_del(&device_io);
1119         if (devops.close)
1120                 devops.close();
1121
1122         exit_control();
1123
1124         return;
1125 }