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