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