+#ifdef HAVE_MINIUPNPC
+#include "upnp.h"
+#endif
+
+ports_t myport;
+static io_t device_io;
+devops_t devops;
+bool device_standby = false;
+
+char *proxyhost = NULL;
+char *proxyport = NULL;
+char *proxyuser = NULL;
+char *proxypass = NULL;
+
+proxytype_t proxytype;
+bool autoconnect;
+bool disablebuggypeers;
+
+char *scriptinterpreter;
+char *scriptextension;
+
+bool node_read_ecdsa_public_key(node_t *n) {
+ if(ecdsa_active(n->ecdsa)) {
+ return true;
+ }
+
+ FILE *fp;
+ char *pubname = NULL;
+ char *p;
+
+ splay_tree_t config;
+ init_configuration(&config);
+
+ if(!read_host_config(&config, n->name, true)) {
+ goto exit;
+ }
+
+ /* First, check for simple Ed25519PublicKey statement */
+
+ if(get_config_string(lookup_config(&config, "Ed25519PublicKey"), &p)) {
+ n->ecdsa = ecdsa_set_base64_public_key(p);
+ free(p);
+ goto exit;
+ }
+
+ /* Else, check for Ed25519PublicKeyFile statement and read it */
+
+ if(!get_config_string(lookup_config(&config, "Ed25519PublicKeyFile"), &pubname)) {
+ xasprintf(&pubname, "%s" SLASH "hosts" SLASH "%s", confbase, n->name);
+ }
+
+ fp = fopen(pubname, "r");
+
+ if(!fp) {
+ goto exit;
+ }
+
+ n->ecdsa = ecdsa_read_pem_public_key(fp);
+ fclose(fp);
+
+exit:
+ splay_empty_tree(&config);
+ free(pubname);
+ return n->ecdsa;
+}
+
+static bool read_invitation_key(void) {
+ FILE *fp;
+ char fname[PATH_MAX];
+
+ if(invitation_key) {
+ ecdsa_free(invitation_key);
+ invitation_key = NULL;
+ }
+
+ snprintf(fname, sizeof(fname), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
+
+ fp = fopen(fname, "r");
+
+ if(fp) {
+ invitation_key = ecdsa_read_pem_private_key(fp);
+ fclose(fp);
+
+ if(!invitation_key) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Reading Ed25519 private key file `%s' failed", fname);
+ }
+ }
+
+ return invitation_key;
+}
+
+#ifndef DISABLE_LEGACY
+static timeout_t keyexpire_timeout;
+
+static void keyexpire_handler(void *data) {
+ regenerate_key();
+ timeout_set(data, &(struct timeval) {
+ keylifetime, jitter()
+ });
+}
+#endif
+
+void regenerate_key(void) {
+ logger(DEBUG_STATUS, LOG_INFO, "Expiring symmetric keys");
+ send_key_changed();
+
+ for splay_each(node_t, n, &node_tree) {
+ n->status.validkey_in = false;
+ }
+}
+
+void load_all_nodes(void) {
+ DIR *dir;
+ struct dirent *ent;
+ char dname[PATH_MAX];
+
+ snprintf(dname, sizeof(dname), "%s" SLASH "hosts", confbase);
+ dir = opendir(dname);
+
+ if(!dir) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
+ return;
+ }
+
+ while((ent = readdir(dir))) {
+ if(!check_id(ent->d_name)) {
+ continue;
+ }
+
+ node_t *n = lookup_node(ent->d_name);
+
+ splay_tree_t config;
+ init_configuration(&config);
+ read_config_options(&config, ent->d_name);
+ read_host_config(&config, ent->d_name, true);
+
+ if(!n) {
+ n = new_node(ent->d_name);
+ node_add(n);
+ }
+
+ if(strictsubnets) {
+ for(config_t *cfg = lookup_config(&config, "Subnet"); cfg; cfg = lookup_config_next(&config, cfg)) {
+ subnet_t *s, *s2;
+
+ if(!get_config_subnet(cfg, &s)) {
+ continue;
+ }
+
+ if((s2 = lookup_subnet(n, s))) {
+ s2->expires = -1;
+ free(s);
+ } else {
+ subnet_add(n, s);
+ }
+ }
+ }
+
+ if(lookup_config(&config, "Address")) {
+ n->status.has_address = true;
+ }
+
+ splay_empty_tree(&config);
+ }
+
+ closedir(dir);
+}
+
+char *get_name(void) {
+ char *name = NULL;
+ char *returned_name;
+
+ get_config_string(lookup_config(&config_tree, "Name"), &name);
+
+ if(!name) {
+ return NULL;
+ }
+
+ returned_name = replace_name(name);
+ free(name);
+ return returned_name;
+}
+
+static void read_interpreter(void) {
+ char *interpreter = NULL;
+ get_config_string(lookup_config(&config_tree, "ScriptsInterpreter"), &interpreter);
+
+ if(!interpreter || (sandbox_can(START_PROCESSES, AFTER_SANDBOX) && sandbox_can(USE_NEW_PATHS, AFTER_SANDBOX))) {
+ free(scriptinterpreter);
+ scriptinterpreter = interpreter;
+ return;
+ }
+
+ if(!string_eq(interpreter, scriptinterpreter)) {
+ logger(DEBUG_ALWAYS, LOG_NOTICE, "Not changing ScriptsInterpreter because of sandbox.");
+ }
+
+ free(interpreter);
+}
+
+bool setup_myself_reloadable(void) {
+ read_interpreter();
+
+ free(scriptextension);
+
+ if(!get_config_string(lookup_config(&config_tree, "ScriptsExtension"), &scriptextension)) {
+ scriptextension = xstrdup("");
+ }
+
+ char *proxy = NULL;
+
+ get_config_string(lookup_config(&config_tree, "Proxy"), &proxy);
+
+ if(proxy) {
+ char *space;
+
+ if((space = strchr(proxy, ' '))) {
+ *space++ = 0;
+ }
+
+ if(!strcasecmp(proxy, "none")) {
+ proxytype = PROXY_NONE;
+ } else if(!strcasecmp(proxy, "socks4")) {
+ proxytype = PROXY_SOCKS4;
+ } else if(!strcasecmp(proxy, "socks4a")) {
+ proxytype = PROXY_SOCKS4A;
+ } else if(!strcasecmp(proxy, "socks5")) {
+ proxytype = PROXY_SOCKS5;
+ } else if(!strcasecmp(proxy, "http")) {
+ proxytype = PROXY_HTTP;
+ } else if(!strcasecmp(proxy, "exec")) {
+ if(sandbox_can(START_PROCESSES, AFTER_SANDBOX)) {
+ proxytype = PROXY_EXEC;
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Cannot use exec proxies with current sandbox level.");
+ return false;
+ }
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type %s!", proxy);
+ free_string(proxy);
+ return false;
+ }
+
+ free(proxyhost);
+ proxyhost = NULL;
+
+ free(proxyport);
+ proxyport = NULL;
+
+ free_string(proxyuser);
+ proxyuser = NULL;
+
+ free_string(proxypass);
+ proxypass = NULL;
+
+ switch(proxytype) {
+ case PROXY_NONE:
+ default:
+ break;
+
+ case PROXY_EXEC:
+ if(!space || !*space) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Argument expected for proxy type exec!");
+ free_string(proxy);
+ return false;
+ }
+
+ if(!sandbox_can(USE_NEW_PATHS, AFTER_SANDBOX)) {
+ logger(DEBUG_ALWAYS, LOG_NOTICE, "Changed exec proxy may fail to work because of sandbox.");
+ }
+
+ proxyhost = xstrdup(space);
+ break;
+
+ case PROXY_SOCKS4:
+ case PROXY_SOCKS4A:
+ case PROXY_SOCKS5:
+ case PROXY_HTTP:
+ proxyhost = space;
+
+ if(space && (space = strchr(space, ' '))) {
+ *space++ = 0, proxyport = space;
+ }
+
+ if(!proxyhost || !*proxyhost || !proxyport || !*proxyport) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Host and port argument expected for proxy!");
+ proxyport = NULL;
+ proxyhost = NULL;
+ free_string(proxy);
+ return false;
+ }
+
+ if(space && (space = strchr(space, ' '))) {
+ *space++ = 0, proxyuser = space;
+ }
+
+ if(space && (space = strchr(space, ' '))) {
+ *space++ = 0, proxypass = space;
+ }
+
+ proxyhost = xstrdup(proxyhost);
+ proxyport = xstrdup(proxyport);
+
+ if(proxyuser && *proxyuser) {
+ proxyuser = xstrdup(proxyuser);
+ }
+
+ if(proxypass && *proxypass) {
+ proxypass = xstrdup(proxypass);
+ }
+
+ break;
+ }
+
+ free_string(proxy);
+ }
+
+ bool choice;
+
+ if(get_config_bool(lookup_config(&config_tree, "IndirectData"), &choice) && choice) {
+ myself->options |= OPTION_INDIRECT;
+ }
+
+ if(get_config_bool(lookup_config(&config_tree, "TCPOnly"), &choice) && choice) {
+ myself->options |= OPTION_TCPONLY;
+ }
+
+ if(myself->options & OPTION_TCPONLY) {
+ myself->options |= OPTION_INDIRECT;
+ }
+
+ get_config_bool(lookup_config(&config_tree, "UDPDiscovery"), &udp_discovery);
+ get_config_int(lookup_config(&config_tree, "UDPDiscoveryKeepaliveInterval"), &udp_discovery_keepalive_interval);
+ get_config_int(lookup_config(&config_tree, "UDPDiscoveryInterval"), &udp_discovery_interval);
+ get_config_int(lookup_config(&config_tree, "UDPDiscoveryTimeout"), &udp_discovery_timeout);
+
+ get_config_int(lookup_config(&config_tree, "MTUInfoInterval"), &mtu_info_interval);
+ get_config_int(lookup_config(&config_tree, "UDPInfoInterval"), &udp_info_interval);
+
+ get_config_bool(lookup_config(&config_tree, "DirectOnly"), &directonly);
+ get_config_bool(lookup_config(&config_tree, "LocalDiscovery"), &localdiscovery);
+
+ char *rmode = NULL;
+
+ if(get_config_string(lookup_config(&config_tree, "Mode"), &rmode)) {
+ if(!strcasecmp(rmode, "router")) {
+ routing_mode = RMODE_ROUTER;
+ } else if(!strcasecmp(rmode, "switch")) {
+ routing_mode = RMODE_SWITCH;
+ } else if(!strcasecmp(rmode, "hub")) {
+ routing_mode = RMODE_HUB;
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Invalid routing mode!");
+ free(rmode);
+ return false;
+ }
+
+ free(rmode);
+ }
+
+ char *fmode = NULL;
+
+ if(get_config_string(lookup_config(&config_tree, "Forwarding"), &fmode)) {
+ if(!strcasecmp(fmode, "off")) {
+ forwarding_mode = FMODE_OFF;
+ } else if(!strcasecmp(fmode, "internal")) {
+ forwarding_mode = FMODE_INTERNAL;
+ } else if(!strcasecmp(fmode, "kernel")) {
+ forwarding_mode = FMODE_KERNEL;
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Invalid forwarding mode!");
+ free(fmode);
+ return false;
+ }
+
+ free(fmode);
+ }
+
+ choice = !(myself->options & OPTION_TCPONLY);
+ get_config_bool(lookup_config(&config_tree, "PMTUDiscovery"), &choice);
+
+ if(choice) {
+ myself->options |= OPTION_PMTU_DISCOVERY;
+ }
+
+ choice = true;
+ get_config_bool(lookup_config(&config_tree, "ClampMSS"), &choice);
+
+ if(choice) {
+ myself->options |= OPTION_CLAMP_MSS;
+ }
+
+ get_config_bool(lookup_config(&config_tree, "PriorityInheritance"), &priorityinheritance);
+ get_config_bool(lookup_config(&config_tree, "DecrementTTL"), &decrement_ttl);
+
+ char *bmode = NULL;
+
+ if(get_config_string(lookup_config(&config_tree, "Broadcast"), &bmode)) {
+ if(!strcasecmp(bmode, "no")) {
+ broadcast_mode = BMODE_NONE;
+ } else if(!strcasecmp(bmode, "yes") || !strcasecmp(bmode, "mst")) {
+ broadcast_mode = BMODE_MST;
+ } else if(!strcasecmp(bmode, "direct")) {
+ broadcast_mode = BMODE_DIRECT;
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Invalid broadcast mode!");
+ free(bmode);
+ return false;
+ }
+
+ free(bmode);
+ }
+
+ /* Delete all broadcast subnets before re-adding them */
+
+ for splay_each(subnet_t, s, &subnet_tree) {
+ if(!s->owner) {
+ splay_delete_node(&subnet_tree, node);
+ }
+ }
+
+ const char *const DEFAULT_BROADCAST_SUBNETS[] = { "ff:ff:ff:ff:ff:ff", "255.255.255.255", "224.0.0.0/4", "ff00::/8" };
+
+ for(size_t i = 0; i < sizeof(DEFAULT_BROADCAST_SUBNETS) / sizeof(*DEFAULT_BROADCAST_SUBNETS); i++) {
+ subnet_t *s = new_subnet();
+
+ if(!str2net(s, DEFAULT_BROADCAST_SUBNETS[i])) {
+ abort();
+ }
+
+ subnet_add(NULL, s);
+ }
+
+ for(config_t *cfg = lookup_config(&config_tree, "BroadcastSubnet"); cfg; cfg = lookup_config_next(&config_tree, cfg)) {
+ subnet_t *s;
+
+ if(!get_config_subnet(cfg, &s)) {
+ continue;
+ }
+
+ subnet_add(NULL, s);
+ }
+
+#if !defined(IP_TOS)
+
+ if(priorityinheritance) {
+ logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv4 connections", "PriorityInheritance");
+ }
+
+#endif
+
+#if !defined(IPV6_TCLASS)
+
+ if(priorityinheritance) {
+ logger(DEBUG_ALWAYS, LOG_WARNING, "%s not supported on this platform for IPv6 connections", "PriorityInheritance");
+ }
+
+#endif
+
+ if(!get_config_int(lookup_config(&config_tree, "MACExpire"), &macexpire)) {
+ macexpire = 600;
+ }
+
+ if(get_config_int(lookup_config(&config_tree, "MaxTimeout"), &maxtimeout)) {
+ if(maxtimeout <= 0) {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Bogus maximum timeout!");
+ return false;
+ }
+ } else {
+ maxtimeout = 900;
+ }
+
+ char *afname = NULL;
+
+ if(get_config_string(lookup_config(&config_tree, "AddressFamily"), &afname)) {
+ if(!strcasecmp(afname, "IPv4")) {
+ addressfamily = AF_INET;
+ } else if(!strcasecmp(afname, "IPv6")) {
+ addressfamily = AF_INET6;
+ } else if(!strcasecmp(afname, "any")) {
+ addressfamily = AF_UNSPEC;
+ } else {
+ logger(DEBUG_ALWAYS, LOG_ERR, "Invalid address family!");
+ free(afname);
+ return false;
+ }
+
+ free(afname);
+ }
+
+ get_config_bool(lookup_config(&config_tree, "Hostnames"), &hostnames);
+
+ if(!get_config_int(lookup_config(&config_tree, "KeyExpire"), &keylifetime)) {
+ keylifetime = 3600;
+ }
+
+ if(!get_config_bool(lookup_config(&config_tree, "AutoConnect"), &autoconnect)) {
+ autoconnect = true;
+ }
+
+ get_config_bool(lookup_config(&config_tree, "DisableBuggyPeers"), &disablebuggypeers);
+
+ if(!get_config_int(lookup_config(&config_tree, "InvitationExpire"), &invitation_lifetime)) {
+ invitation_lifetime = 604800; // 1 week
+ }
+
+ read_invitation_key();
+
+ return true;
+}
+
+// Get the port that `from_fd` is listening on, and assign it to
+// `sa` if `sa` has a dynamically allocated (zero) port.
+static bool assign_static_port(sockaddr_t *sa, int from_fd) {
+ // We cannot get a port from a bad FD. Bail out.
+ if(from_fd <= 0) {
+ return false;
+ }
+
+ int port = get_bound_port(from_fd);
+
+ if(!port) {
+ return false;
+ }
+
+ // If the port is non-zero, don't reassign it as it's already static.
+ switch(sa->sa.sa_family) {
+ case AF_INET:
+ if(!sa->in.sin_port) {
+ sa->in.sin_port = htons(port);
+ }
+
+ return true;
+
+ case AF_INET6:
+ if(!sa->in6.sin6_port) {
+ sa->in6.sin6_port = htons(port);
+ }
+
+ return true;
+
+ default:
+ logger(DEBUG_ALWAYS, LOG_ERR, "Unknown address family 0x%x", sa->sa.sa_family);
+ return false;
+ }
+}
+
+typedef int (*bind_fn_t)(const sockaddr_t *);
+
+static int bind_reusing_port(const sockaddr_t *sa, int from_fd, bind_fn_t setup) {
+ sockaddr_t reuse_sa;
+ memcpy(&reuse_sa, sa, SALEN(sa->sa));
+
+ int fd = -1;
+
+ // Check if the address we've been passed here is using port 0.
+ // If it is, try to get an actual port from an already bound socket, and reuse it here.
+ if(assign_static_port(&reuse_sa, from_fd)) {
+ fd = setup(&reuse_sa);
+ }
+
+ // If we're binding to a hardcoded non-zero port, or no socket is listening yet,
+ // or binding failed, try the original address.
+ if(fd < 0) {
+ fd = setup(sa);
+ }
+
+ return fd;
+}
+
+/*
+ Add listening sockets.
+*/
+static bool add_listen_address(char *address, bool bindto) {
+ char *port = myport.tcp;
+
+ if(address) {
+ char *space = strchr(address, ' ');
+
+ if(space) {
+ *space++ = 0;
+ port = space;
+ }
+
+ if(!strcmp(address, "*")) {
+ *address = 0;
+ }
+ }
+
+ struct addrinfo *ai, hint = {0};
+
+ hint.ai_family = addressfamily;
+
+ hint.ai_socktype = SOCK_STREAM;
+
+ hint.ai_protocol = IPPROTO_TCP;
+
+ hint.ai_flags = AI_PASSIVE;
+
+#if HAVE_DECL_RES_INIT
+ res_init();