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