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