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