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