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