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