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