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