static void ipTunnel(Dict* ifaceConf, struct Allocator* tempAlloc, struct Context* ctx) { List* incoming = Dict_getList(ifaceConf, String_CONST("allowedConnections")); Dict* d; for (int i = 0; (d = List_getDict(incoming, i)) != NULL; i++) { String* key = Dict_getString(d, String_CONST("publicKey")); String* ip4 = Dict_getString(d, String_CONST("ip4Address")); String* ip6 = Dict_getString(d, String_CONST("ip6Address")); if (!key) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "'publicKey' required.", i); exit(1); } if (!ip4 && !ip6) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "either ip4Address or ip6Address required.", i); exit(1); } Log_debug(ctx->logger, "Allowing IpTunnel connections from [%s]", key->bytes); Dict_putString(d, String_CONST("publicKeyOfAuthorizedNode"), key, tempAlloc); rpcCall0(String_CONST("IpTunnel_allowConnection"), d, ctx, tempAlloc, true); } List* outgoing = Dict_getList(ifaceConf, String_CONST("outgoingConnections")); String* s; for (int i = 0; (s = List_getString(outgoing, i)) != NULL; i++) { Log_debug(ctx->logger, "Initiating IpTunnel connection to [%s]", s->bytes); Dict requestDict = Dict_CONST(String_CONST("publicKeyOfNodeToConnectTo"), String_OBJ(s), NULL); rpcCall0(String_CONST("IpTunnel_connectTo"), &requestDict, ctx, tempAlloc, true); } }
static void reconf(struct event_base* eventbase, Dict* mainConf, struct Log* logger, struct Allocator* alloc) { Dict* adminConf = Dict_getDict(mainConf, String_CONST("admin")); String* address = Dict_getString(adminConf, String_CONST("bind")); String* password = Dict_getString(adminConf, String_CONST("password")); if (!(address && password)) { Log_critical(logger, "Can't get the admin address and password from conf file."); exit(-1); } struct sockaddr_storage addr; memset(&addr, 0, sizeof(struct sockaddr_storage)); int addrLen = sizeof(struct sockaddr_storage); if (evutil_parse_sockaddr_port(address->bytes, (struct sockaddr*) &addr, &addrLen)) { Log_critical(logger, "Unable to parse [%s] as an ip address port, " "eg: 127.0.0.1:11234", address->bytes); exit(-1); } Configurator_config(mainConf, &addr, addrLen, password, eventbase, logger, alloc); }
static void rpcCall0(String* function, Dict* args, struct Context* ctx, struct Allocator* alloc, bool exitIfError) { struct AdminClient_Result* res = AdminClient_rpcCall(function, args, ctx->client, alloc); if (res->err) { Log_critical(ctx->logger, "Failed to make function call [%s], error: [%s]", AdminClient_errorString(res->err), function->bytes); die(res, ctx, alloc); } String* error = Dict_getString(res->responseDict, String_CONST("error")); if (error && !String_equals(error, String_CONST("none"))) { if (exitIfError) { Log_critical(ctx->logger, "Got error [%s] calling [%s]", error->bytes, function->bytes); die(res, ctx, alloc); } Log_warn(ctx->logger, "Got error [%s] calling [%s], ignoring.", error->bytes, function->bytes); } }
static void authorizedPasswords(List* list, struct Context* ctx) { uint32_t count = List_size(list); for (uint32_t i = 0; i < count; i++) { Dict* d = List_getDict(list, i); Log_info(ctx->logger, "Checking authorized password %d.", i); if (!d) { Log_critical(ctx->logger, "Not a dictionary type %d.", i); exit(-1); } String* passwd = Dict_getString(d, String_CONST("password")); if (!passwd) { Log_critical(ctx->logger, "Must specify a password %d.", i); exit(-1); } } Log_info(ctx->logger, "Flushing existing authorized passwords"); rpcCall(String_CONST("AuthorizedPasswords_flush"), NULL, ctx, ctx->alloc); for (uint32_t i = 0; i < count; i++) { Dict* d = List_getDict(list, i); String* passwd = Dict_getString(d, String_CONST("password")); Log_info(ctx->logger, "Adding authorized password #[%d].", i); Dict args = Dict_CONST( String_CONST("authType"), Int_OBJ(1), Dict_CONST( String_CONST("password"), String_OBJ(passwd), NULL )); struct Allocator* child = ctx->alloc->child(ctx->alloc); rpcCall(String_CONST("AuthorizedPasswords_add"), &args, ctx, child); child->free(child); } }
static int rpcCall0(String* function, Dict* args, struct Context* ctx, struct Allocator* alloc, Dict** resultP, bool exitIfError) { ctx->currentReqAlloc = Allocator_child(alloc); ctx->currentResult = NULL; struct AdminClient_Promise* promise = AdminClient_rpcCall(function, args, ctx->client, alloc); promise->callback = rpcCallback; promise->userData = ctx; EventBase_beginLoop(ctx->base); struct AdminClient_Result* res = ctx->currentResult; Assert_true(res); if (res->err) { Log_critical(ctx->logger, "Failed to make function call [%s], error: [%s]", AdminClient_errorString(res->err), function->bytes); die(res, ctx, alloc); } String* error = Dict_getString(res->responseDict, String_CONST("error")); int ret = 0; if (error && !String_equals(error, String_CONST("none"))) { if (exitIfError) { Log_critical(ctx->logger, "Got error [%s] calling [%s]", error->bytes, function->bytes); die(res, ctx, alloc); } Log_warn(ctx->logger, "Got error [%s] calling [%s], ignoring.", error->bytes, function->bytes); ret = 1; } if (resultP) { *resultP = res->responseDict; } else { Allocator_free(ctx->currentReqAlloc); } ctx->currentReqAlloc = NULL; return ret; }
static void showMsg(struct AdminClient_Result* res, struct Context* ctx) { Log_keys1(ctx->logger, "message bytes = [%s]", res->messageBytes); #ifndef Log_KEYS Log_critical(ctx->logger, "enable Log_LEVEL=KEYS to see message content."); #endif }
static void authorizedPasswords(List* list, struct Context* ctx) { uint32_t count = List_size(list); for (uint32_t i = 0; i < count; i++) { Dict* d = List_getDict(list, i); Log_info(ctx->logger, "Checking authorized password %d.", i); if (!d) { Log_critical(ctx->logger, "Not a dictionary type %d.", i); exit(-1); } String* passwd = Dict_getString(d, String_CONST("password")); if (!passwd) { Log_critical(ctx->logger, "Must specify a password %d.", i); exit(-1); } } for (uint32_t i = 0; i < count; i++) { struct Allocator* child = Allocator_child(ctx->alloc); Dict* d = List_getDict(list, i); String* passwd = Dict_getString(d, String_CONST("password")); String* user = Dict_getString(d, String_CONST("user")); String* displayName = user; if (!displayName) { displayName = String_printf(child, "password [%d]", i); } //String* publicKey = Dict_getString(d, String_CONST("publicKey")); String* ipv6 = Dict_getString(d, String_CONST("ipv6")); Log_info(ctx->logger, "Adding authorized password #[%d] for user [%s].", i, displayName->bytes); Dict *args = Dict_new(child); uint32_t i = 1; Dict_putInt(args, String_CONST("authType"), i, child); Dict_putString(args, String_CONST("password"), passwd, child); if (user) { Dict_putString(args, String_CONST("user"), user, child); } Dict_putString(args, String_CONST("displayName"), displayName, child); if (ipv6) { Log_info(ctx->logger, " This connection password restricted to [%s] only.", ipv6->bytes); Dict_putString(args, String_CONST("ipv6"), ipv6, child); } rpcCall(String_CONST("AuthorizedPasswords_add"), args, ctx, child); Allocator_free(child); } }
static void die(struct AdminClient_Result* res, struct Context* ctx, struct Allocator* alloc) { Log_keys(ctx->logger, "message bytes = [%s]", res->messageBytes); #ifndef Log_KEYS Log_critical(ctx->logger, "enable Log_LEVEL=KEYS to see message content."); #endif Dict d = NULL; struct AdminClient_Result* exitRes = AdminClient_rpcCall(String_CONST("Core_exit"), &d, ctx->client, alloc); if (exitRes->err) { Log_critical(ctx->logger, "Failed to stop the core."); } Log_critical(ctx->logger, "Aborting."); exit(1); }
static void die(struct AdminClient_Result* res, struct Context* ctx, struct Allocator* alloc) { Log_keys(ctx->logger, "message bytes = [%s]", res->messageBytes); #ifndef Log_KEYS Log_critical(ctx->logger, "enable Log_LEVEL=KEYS to see message content."); #endif Dict d = NULL; struct AdminClient_Promise* exitPromise = AdminClient_rpcCall(String_CONST("Core_exit"), &d, ctx->client, alloc); exitPromise->callback = rpcCallback; exitPromise->userData = ctx; EventBase_beginLoop(ctx->base); if (ctx->currentResult->err) { Log_critical(ctx->logger, "Failed to stop the core."); } Log_critical(ctx->logger, "Aborting."); exit(1); }
static void authorizedPasswords(List* list, struct Context* ctx) { uint32_t count = List_size(list); for (uint32_t i = 0; i < count; i++) { Dict* d = List_getDict(list, i); Log_info(ctx->logger, "Checking authorized password %d.", i); if (!d) { Log_critical(ctx->logger, "Not a dictionary type %d.", i); exit(-1); } String* passwd = Dict_getString(d, String_CONST("password")); if (!passwd) { Log_critical(ctx->logger, "Must specify a password %d.", i); exit(-1); } } for (uint32_t i = 0; i < count; i++) { struct Allocator* child = Allocator_child(ctx->alloc); Dict* d = List_getDict(list, i); String* passwd = Dict_getString(d, String_CONST("password")); String* user = Dict_getString(d, String_CONST("user")); if (!user) { user = String_printf(child, "password [%d]", i); } Log_info(ctx->logger, "Adding authorized password #[%d] for user [%s].", i, user->bytes); Dict args = Dict_CONST( String_CONST("authType"), Int_OBJ(1), Dict_CONST( String_CONST("password"), String_OBJ(passwd), Dict_CONST( String_CONST("user"), String_OBJ(user), NULL ))); rpcCall(String_CONST("AuthorizedPasswords_add"), &args, ctx, child); Allocator_free(child); } }
static void udpInterface(Dict* config, struct Context* ctx) { Dict* udp = Dict_getDict(config, String_CONST("UDPInterface")); if (udp) { // Setup the interface. String* bindStr = Dict_getString(udp, String_CONST("bind")); Dict* d = Dict_new(ctx->alloc); if (bindStr) { Dict_putString(d, String_CONST("bindAddress"), bindStr, ctx->alloc); } rpcCall(String_CONST("UDPInterface_new"), d, ctx, ctx->alloc); // Make the connections. Dict* connectTo = Dict_getDict(udp, String_CONST("connectTo")); if (connectTo) { struct Dict_Entry* entry = *connectTo; while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.UDPInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* value = entry->val->as.dictionary; Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); struct Allocator* perCallAlloc = ctx->alloc->child(ctx->alloc); Dict_putString(value, String_CONST("address"), key, perCallAlloc); rpcCall(String_CONST("UDPInterface_beginConnection"), value, ctx, perCallAlloc); perCallAlloc->free(perCallAlloc); entry = entry->next; } } } }
static struct Admin* newAdmin(Dict* mainConf, char* user, struct Log* logger, struct event_base* eventBase, struct Allocator* alloc) { Dict* adminConf = Dict_getDict(mainConf, String_CONST("admin")); String* address = Dict_getString(adminConf, String_CONST("bind")); String* password = Dict_getString(adminConf, String_CONST("password")); struct sockaddr_storage addr; int addrLen = sizeof(struct sockaddr_storage); memset(&addr, 0, sizeof(struct sockaddr_storage)); if (address) { if (evutil_parse_sockaddr_port(address->bytes, (struct sockaddr*) &addr, &addrLen)) { Log_critical(logger, "Unable to parse [%s] as an ip address port, " "eg: 127.0.0.1:11234", address->bytes); exit(-1); } } if (!password) { uint8_t buff[32]; randomBase32(buff); password = String_new((char*)buff, alloc); } struct Admin* admin = Admin_new(&addr, addrLen, password, user, eventBase, AbortHandler_INSTANCE, logger, alloc); return admin; }
int main(int argc, char** argv) { if (argc > 1 && !strcmp("--genconf", argv[argc-1])) { genconf(); return 0; } struct Allocator* alloc = MallocAllocator_new(1<<22); struct EventBase* base = EventBase_new(alloc); struct Writer* logWriter = FileWriter_new(stdout, alloc); struct Log* logger = WriterLog_new(logWriter, alloc); struct Random* rand = Random_new(alloc, logger, NULL); struct Reader* stdinReader = FileReader_new(stdin, alloc); Dict config; if (JsonBencSerializer_get()->parseDictionary(stdinReader, alloc, &config)) { Log_critical(logger, "Failed to parse configuration"); return -1; } Dict* dns = Dict_getDict(&config, String_CONST("dns")); if (!dns) { Log_critical(logger, "No DNS in configuration"); return -1; } struct Sockaddr_storage addr; Assert_true(!Sockaddr_parse("::", &addr)); struct AddrInterface* ifaceB = UDPAddrInterface_new(base, &addr.addr, alloc, NULL, logger); struct RainflyClient* client = RainflyClient_new(ifaceB, base, rand, logger); String* bind = Dict_getString(dns, String_CONST("bind")); Assert_true(!Sockaddr_parse(bind ? bind->bytes : "[::]:5353", &addr)); struct AddrInterface* iface = UDPAddrInterface_new(base, &addr.addr, alloc, NULL, logger); struct DNSServer* dnsServer = DNSServer_new(iface, logger, client); List* auth = Dict_getList(dns, String_CONST("authorities")); for (int i = 0; i < (int)List_size(auth); i++) { String* str = List_getString(auth, i); if (!str) { Log_warn(logger, "Element [%d] in [dns.authorities] list of wrong type", i); continue; } uint8_t key[32] = {0}; if (str->len < 52 || Base32_decode(key, 32, str->bytes, 52) != 32) { Log_warn(logger, "Failed to parse key [%s]", str->bytes); continue; } if (RainflyClient_addKey(client, key)) { Log_warn(logger, "Failed to add key to RainflyClient [%s]", str->bytes); } } List* servers = Dict_getList(dns, String_CONST("servers")); for (int i = 0; i < (int)List_size(servers); i++) { String* str = List_getString(servers, i); if (!str) { Log_warn(logger, "Element [%d] in [dns.servers] list of wrong type", i); continue; } struct Sockaddr_storage node; if (Sockaddr_parse(str->bytes, &node)) { Log_warn(logger, "Failed to parse server name [%s]", str->bytes); continue; } if (RainflyClient_addServer(client, &node.addr)) { Log_warn(logger, "Failed to add server to RainflyClient [%s]", str->bytes); } } List* legacy = Dict_getList(dns, String_CONST("legacy")); for (int i = 0; i < (int)List_size(legacy); i++) { String* str = List_getString(legacy, i); if (!str) { Log_warn(logger, "Element [%d] in [dns.legacy] list of wrong type", i); continue; } struct Sockaddr_storage node; if (Sockaddr_parse(str->bytes, &node)) { Log_warn(logger, "Failed to parse legacy server name [%s]", str->bytes); continue; } if (DNSServer_addServer(dnsServer, &node.addr)) { Log_warn(logger, "Failed to add server to DNSServer [%s]", str->bytes); } } EventBase_beginLoop(base); }
static void udpInterface(Dict* config, struct Context* ctx) { List* ifaces = Dict_getList(config, String_CONST("UDPInterface")); if (!ifaces) { ifaces = List_addDict(ifaces, Dict_getDict(config, String_CONST("UDPInterface")), ctx->alloc); } uint32_t count = List_size(ifaces); for (uint32_t i = 0; i < count; i++) { Dict *udp = List_getDict(ifaces, i); if (!udp) { continue; } // Setup the interface. String* bindStr = Dict_getString(udp, String_CONST("bind")); Dict* d = Dict_new(ctx->alloc); if (bindStr) { Dict_putString(d, String_CONST("bindAddress"), bindStr, ctx->alloc); } rpcCall(String_CONST("UDPInterface_new"), d, ctx, ctx->alloc); // Make the connections. Dict* connectTo = Dict_getDict(udp, String_CONST("connectTo")); if (connectTo) { struct Dict_Entry* entry = *connectTo; struct Allocator* perCallAlloc = Allocator_child(ctx->alloc); while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.UDPInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* value = entry->val->as.dictionary; Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); key = String_clone(key, perCallAlloc); char* lastColon = strrchr(key->bytes, ':'); if (!Sockaddr_parse(key->bytes, NULL)) { // it's a sockaddr, fall through } else if (lastColon) { // try it as a hostname. int port = atoi(lastColon+1); if (!port) { Log_critical(ctx->logger, "Couldn't get port number from [%s]", key->bytes); exit(-1); } *lastColon = '\0'; struct Sockaddr* adr = Sockaddr_fromName(key->bytes, perCallAlloc); if (adr != NULL) { Sockaddr_setPort(adr, port); key = String_new(Sockaddr_print(adr, perCallAlloc), perCallAlloc); } else { Log_warn(ctx->logger, "Failed to lookup hostname [%s]", key->bytes); entry = entry->next; continue; } } Dict_putString(value, String_CONST("address"), key, perCallAlloc); rpcCall(String_CONST("UDPInterface_beginConnection"), value, ctx, perCallAlloc); entry = entry->next; } Allocator_free(perCallAlloc); } } }
static void ethInterface(Dict* config, struct Context* ctx) { List* ifaces = Dict_getList(config, String_CONST("ETHInterface")); if (!ifaces) { ifaces = List_addDict(ifaces, Dict_getDict(config, String_CONST("ETHInterface")), ctx->alloc); } uint32_t count = List_size(ifaces); for (uint32_t i = 0; i < count; i++) { Dict *eth = List_getDict(ifaces, i); if (!eth) { continue; } // Setup the interface. String* deviceStr = Dict_getString(eth, String_CONST("bind")); Log_info(ctx->logger, "Setting up ETHInterface [%d].", i); Dict* d = Dict_new(ctx->alloc); if (deviceStr) { Log_info(ctx->logger, "Binding to device [%s].", deviceStr->bytes); Dict_putString(d, String_CONST("bindDevice"), deviceStr, ctx->alloc); } if (rpcCall0(String_CONST("ETHInterface_new"), d, ctx, ctx->alloc, false)) { Log_warn(ctx->logger, "Failed to create ETHInterface."); continue; } // Make the connections. Dict* connectTo = Dict_getDict(eth, String_CONST("connectTo")); if (connectTo) { Log_info(ctx->logger, "ETHInterface should connect to a specific node."); struct Dict_Entry* entry = *connectTo; while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.ETHInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* value = entry->val->as.dictionary; Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); struct Allocator* perCallAlloc = Allocator_child(ctx->alloc); // Turn the dict from the config into our RPC args dict by filling in all // the arguments, Dict_putString(value, String_CONST("macAddress"), key, perCallAlloc); Dict_putInt(value, String_CONST("interfaceNumber"), i, perCallAlloc); rpcCall(String_CONST("ETHInterface_beginConnection"), value, ctx, perCallAlloc); Allocator_free(perCallAlloc); entry = entry->next; } } int64_t* beaconP = Dict_getInt(eth, String_CONST("beacon")); if (beaconP) { int64_t beacon = *beaconP; if (beacon > 3 || beacon < 0) { Log_error(ctx->logger, "interfaces.ETHInterface.beacon may only be 0, 1,or 2"); } else { // We can cast beacon to an int here because we know it's small enough Log_info(ctx->logger, "Setting beacon mode on ETHInterface to [%d].", (int) beacon); Dict d = Dict_CONST(String_CONST("interfaceNumber"), Int_OBJ(i), Dict_CONST(String_CONST("state"), Int_OBJ(beacon), NULL)); rpcCall(String_CONST("ETHInterface_beacon"), &d, ctx, ctx->alloc); } } } }
static void ethInterface(Dict* config, struct Context* ctx) { List* ifaces = Dict_getList(config, String_CONST("ETHInterface")); if (!ifaces) { ifaces = List_new(ctx->alloc); List_addDict(ifaces, Dict_getDict(config, String_CONST("ETHInterface")), ctx->alloc); } uint32_t count = List_size(ifaces); for (uint32_t i = 0; i < count; i++) { Dict *eth = List_getDict(ifaces, i); if (!eth) { continue; } String* deviceStr = Dict_getString(eth, String_CONST("bind")); if (!deviceStr || !String_equals(String_CONST("all"), deviceStr)) { continue; } Log_info(ctx->logger, "Setting up all ETHInterfaces..."); Dict* res = NULL; Dict* d = Dict_new(ctx->alloc); if (rpcCall0(String_CONST("ETHInterface_listDevices"), d, ctx, ctx->alloc, &res, false)) { Log_info(ctx->logger, "Getting device list failed"); break; } List* devs = Dict_getList(res, String_CONST("devices")); uint32_t devCount = List_size(devs); for (uint32_t j = 0; j < devCount; j++) { Dict* d = Dict_new(ctx->alloc); String* deviceName = List_getString(devs, j); // skip loopback... if (String_equals(String_CONST("lo"), deviceName)) { continue; } Dict_putString(d, String_CONST("bindDevice"), deviceName, ctx->alloc); Dict* resp; Log_info(ctx->logger, "Creating new ETHInterface [%s]", deviceName->bytes); if (rpcCall0(String_CONST("ETHInterface_new"), d, ctx, ctx->alloc, &resp, false)) { Log_warn(ctx->logger, "Failed to create ETHInterface."); continue; } int ifNum = *(Dict_getInt(resp, String_CONST("interfaceNumber"))); ethInterfaceSetBeacon(ifNum, eth, ctx); } return; } for (uint32_t i = 0; i < count; i++) { Dict *eth = List_getDict(ifaces, i); if (!eth) { continue; } // Setup the interface. String* deviceStr = Dict_getString(eth, String_CONST("bind")); Log_info(ctx->logger, "Setting up ETHInterface [%d].", i); Dict* d = Dict_new(ctx->alloc); if (deviceStr) { Log_info(ctx->logger, "Binding to device [%s].", deviceStr->bytes); Dict_putString(d, String_CONST("bindDevice"), deviceStr, ctx->alloc); } Dict* resp = NULL; if (rpcCall0(String_CONST("ETHInterface_new"), d, ctx, ctx->alloc, &resp, false)) { Log_warn(ctx->logger, "Failed to create ETHInterface."); continue; } int ifNum = *(Dict_getInt(resp, String_CONST("interfaceNumber"))); ethInterfaceSetBeacon(ifNum, eth, ctx); // Make the connections. Dict* connectTo = Dict_getDict(eth, String_CONST("connectTo")); if (connectTo) { Log_info(ctx->logger, "ETHInterface should connect to a specific node."); struct Dict_Entry* entry = *connectTo; while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.ETHInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* value = entry->val->as.dictionary; Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); struct Allocator* perCallAlloc = Allocator_child(ctx->alloc); // Turn the dict from the config into our RPC args dict by filling in all // the arguments, Dict_putString(value, String_CONST("macAddress"), key, perCallAlloc); Dict_putInt(value, String_CONST("interfaceNumber"), ifNum, perCallAlloc); rpcCall(String_CONST("ETHInterface_beginConnection"), value, ctx, perCallAlloc); Allocator_free(perCallAlloc); entry = entry->next; } } } }
static void ipTunnel(Dict* ifaceConf, struct Allocator* tempAlloc, struct Context* ctx) { List* incoming = Dict_getList(ifaceConf, String_CONST("allowedConnections")); if (incoming) { Dict* d; for (int i = 0; (d = List_getDict(incoming, i)) != NULL; i++) { String* key = Dict_getString(d, String_CONST("publicKey")); String* ip4 = Dict_getString(d, String_CONST("ip4Address")); // Note that the prefix length has to be a proper int in the config // (not quoted!) int64_t* ip4Prefix = Dict_getInt(d, String_CONST("ip4Prefix")); String* ip6 = Dict_getString(d, String_CONST("ip6Address")); int64_t* ip6Prefix = Dict_getInt(d, String_CONST("ip6Prefix")); if (!key) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "'publicKey' required.", i); exit(1); } if (!ip4 && !ip6) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "either 'ip4Address' or 'ip6Address' required.", i); exit(1); } else if (ip4Prefix && !ip4) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "'ip4Address' required with 'ip4Prefix'.", i); exit(1); } else if (ip6Prefix && !ip6) { Log_critical(ctx->logger, "In router.ipTunnel.allowedConnections[%d]" "'ip6Address' required with 'ip6Prefix'.", i); exit(1); } Log_debug(ctx->logger, "Allowing IpTunnel connections from [%s]", key->bytes); if (ip4) { Log_debug(ctx->logger, "Issue IPv4 address %s", ip4->bytes); if (ip4Prefix) { Log_debug(ctx->logger, "Issue IPv4 netmask/prefix length /%d", (int) *ip4Prefix); } else { Log_debug(ctx->logger, "Use default netmask/prefix length /0"); } } if (ip6) { Log_debug(ctx->logger, "Issue IPv6 address [%s]", ip6->bytes); if (ip6Prefix) { Log_debug(ctx->logger, "Issue IPv6 netmask/prefix length /%d", (int) *ip6Prefix); } else { Log_debug(ctx->logger, "Use default netmask/prefix length /0"); } } Dict_putString(d, String_CONST("publicKeyOfAuthorizedNode"), key, tempAlloc); rpcCall0(String_CONST("IpTunnel_allowConnection"), d, ctx, tempAlloc, NULL, true); } } List* outgoing = Dict_getList(ifaceConf, String_CONST("outgoingConnections")); if (outgoing) { String* s; for (int i = 0; (s = List_getString(outgoing, i)) != NULL; i++) { Log_debug(ctx->logger, "Initiating IpTunnel connection to [%s]", s->bytes); Dict requestDict = Dict_CONST(String_CONST("publicKeyOfNodeToConnectTo"), String_OBJ(s), NULL); rpcCall0(String_CONST("IpTunnel_connectTo"), &requestDict, ctx, tempAlloc, NULL, true); } } }
static void udpInterface(Dict* config, struct Context* ctx) { List* ifaces = Dict_getList(config, String_CONST("UDPInterface")); if (!ifaces) { ifaces = List_new(ctx->alloc); List_addDict(ifaces, Dict_getDict(config, String_CONST("UDPInterface")), ctx->alloc); } uint32_t count = List_size(ifaces); for (uint32_t i = 0; i < count; i++) { Dict *udp = List_getDict(ifaces, i); if (!udp) { continue; } // Setup the interface. String* bindStr = Dict_getString(udp, String_CONST("bind")); Dict* d = Dict_new(ctx->alloc); if (bindStr) { Dict_putString(d, String_CONST("bindAddress"), bindStr, ctx->alloc); } Dict* resp = NULL; rpcCall0(String_CONST("UDPInterface_new"), d, ctx, ctx->alloc, &resp, true); int ifNum = *(Dict_getInt(resp, String_CONST("interfaceNumber"))); // Make the connections. Dict* connectTo = Dict_getDict(udp, String_CONST("connectTo")); if (connectTo) { struct Dict_Entry* entry = *connectTo; struct Allocator* perCallAlloc = Allocator_child(ctx->alloc); while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.UDPInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* all = entry->val->as.dictionary; Dict* value = Dict_new(perCallAlloc); String* pub_d = Dict_getString(all, String_CONST("publicKey")); String* pss_d = Dict_getString(all, String_CONST("password")); String* peerName_d = Dict_getString(all, String_CONST("peerName")); String* login_d = Dict_getString(all, String_CONST("login")); if ( !pub_d || !pss_d ) { const char * error_name = "(unknown)"; if ( !pub_d ) { error_name = "publicKey"; } if ( !pss_d ) { error_name = "password"; } Log_warn(ctx->logger, "Skipping peer: missing %s for peer [%s]", error_name, key->bytes); if (abort_if_invalid_ref) { Assert_failure("Invalid peer reference"); } else { entry = entry->next; continue; } } Dict_putString(value, String_CONST("publicKey"), pub_d, perCallAlloc); Dict_putString(value, String_CONST("password"), pss_d, perCallAlloc); Dict_putString(value, String_CONST("peerName"), peerName_d, perCallAlloc); Dict_putString(value, String_CONST("login"), login_d, perCallAlloc); Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); key = String_clone(key, perCallAlloc); char* lastColon = CString_strrchr(key->bytes, ':'); if (!Sockaddr_parse(key->bytes, NULL)) { // it's a sockaddr, fall through } else if (lastColon) { // try it as a hostname. int port = atoi(lastColon+1); if (!port) { Log_critical(ctx->logger, "Couldn't get port number from [%s]", key->bytes); exit(-1); } *lastColon = '\0'; struct Sockaddr* adr = Sockaddr_fromName(key->bytes, perCallAlloc); if (adr != NULL) { Sockaddr_setPort(adr, port); key = String_new(Sockaddr_print(adr, perCallAlloc), perCallAlloc); } else { Log_warn(ctx->logger, "Failed to lookup hostname [%s]", key->bytes); entry = entry->next; continue; } } struct Allocator* child = Allocator_child(ctx->alloc); struct Message* msg = Message_new(0, AdminClient_MAX_MESSAGE_SIZE + 256, child); int r = BencMessageWriter_writeDictTry(value, msg, NULL); const int max_reference_size = 298; if (r != 0 || msg->length > max_reference_size) { Log_warn(ctx->logger, "Peer skipped:"); Log_warn(ctx->logger, "Too long peer reference for [%s]", key->bytes); if (abort_if_invalid_ref) { Assert_failure("Invalid peer reference"); } else { entry = entry->next; continue; } } Dict_putInt(value, String_CONST("interfaceNumber"), ifNum, perCallAlloc); Dict_putString(value, String_CONST("address"), key, perCallAlloc); rpcCall(String_CONST("UDPInterface_beginConnection"), value, ctx, perCallAlloc); entry = entry->next; } Allocator_free(perCallAlloc); } } }
int main(int argc, char** argv) { #ifdef Log_KEYS fprintf(stderr, "Log_LEVEL = KEYS, EXPECT TO SEE PRIVATE KEYS IN YOUR LOGS!\n"); #endif Crypto_init(); Assert_true(argc > 0); if (argc == 2) { // one argument if (strcmp(argv[1], "--help") == 0) { return usage(argv[0]); } else if (strcmp(argv[1], "--genconf") == 0) { return genconf(); } else if (strcmp(argv[1], "--pidfile") == 0) { // Performed after reading the configuration } else if (strcmp(argv[1], "--reconf") == 0) { // Performed after reading the configuration } else if (strcmp(argv[1], "--bench") == 0) { return benchmark(); } else if (strcmp(argv[1], "--version") == 0) { printf("Version ID: %s\n", RouterModule_gitVersion()); return 0; } else { fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[1]); fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]); return -1; } } else if (argc > 2) { // more than one argument? fprintf(stderr, "%s: too many arguments\n", argv[0]); fprintf(stderr, "Try `%s --help' for more information.\n", argv[0]); return -1; } if (isatty(STDIN_FILENO)) { // We were started from a terminal // The chances an user wants to type in a configuration // bij hand are pretty slim so we show him the usage return usage(argv[0]); } else { // We assume stdin is a configuration file and that we should // start routing } struct event_base* eventBase = event_base_new(); // Allow it to allocate 4MB struct Allocator* allocator = MallocAllocator_new(1<<22); struct Reader* reader = FileReader_new(stdin, allocator); Dict config; if (JsonBencSerializer_get()->parseDictionary(reader, allocator, &config)) { fprintf(stderr, "Failed to parse configuration.\n"); return -1; } // Logging. struct Writer* logwriter = FileWriter_new(stdout, allocator); struct Log* logger = &(struct Log) { .writer = logwriter }; // pid file String* pidFile = Dict_getString(&config, String_CONST("pidFile")); if (pidFile) { if (argc == 2 && strcmp(argv[1], "--pidfile") == 0) { printf("%s", pidFile->bytes); return 0; } Log_info(logger, "Writing pid of process to [%s].\n", pidFile->bytes); FILE* pf = fopen(pidFile->bytes, "w"); if (!pf) { Log_critical(logger, "Failed to open pid file [%s] for writing, errno=%d\n", pidFile->bytes, errno); return -1; } fprintf(pf, "%d", (int) getpid()); fclose(pf); } // re-configure if (argc == 2 && strcmp(argv[1], "--reconf") == 0) { reconf(eventBase, &config, logger, allocator); return 0; } // ca, needed for admin. struct Address myAddr; uint8_t privateKey[32]; parsePrivateKey(&config, &myAddr, privateKey); struct CryptoAuth* cryptoAuth = CryptoAuth_new(&config, allocator, privateKey, eventBase, logger); // Admin char* user = setUser(Dict_getList(&config, String_CONST("security"))); struct Admin* admin = newAdmin(&config, user, logger, eventBase, allocator); struct SwitchCore* switchCore = SwitchCore_new(logger, allocator); struct DHTModuleRegistry* registry = DHTModuleRegistry_new(allocator); ReplyModule_register(registry, allocator); // Router struct Interface* routerIf = NULL; Dict* routerConf = Dict_getDict(&config, String_CONST("router")); Dict* iface = Dict_getDict(routerConf, String_CONST("interface")); if (String_equals(Dict_getString(iface, String_CONST("type")), String_CONST("TUNInterface"))) { String* ifName = Dict_getString(iface, String_CONST("tunDevice")); char assignedTunName[TUNConfigurator_IFNAMSIZ]; void* tunPtr = TUNConfigurator_initTun(((ifName) ? ifName->bytes : NULL), assignedTunName, logger, AbortHandler_INSTANCE); struct Jmp jmp; Jmp_try(jmp) { TUNConfigurator_setIpAddress( assignedTunName, myAddr.ip6.bytes, 8, logger, &jmp.handler); } Jmp_catch { Log_warn(logger, "Unable to configure ip address [%s]", jmp.message); } struct TUNInterface* tun = TUNInterface_new(tunPtr, eventBase, allocator); routerIf = &tun->iface; }
static void fail(void* vSec) { struct Security_pvt* sec = Identity_check((struct Security_pvt*) vSec); Log_critical(sec->log, "Security_setupComplete() not called in time, exiting"); _exit(232); }
static void udpInterface(Dict* config, struct Context* ctx) { List* ifaces = Dict_getList(config, String_CONST("UDPInterface")); if (!ifaces) { ifaces = List_new(ctx->alloc); List_addDict(ifaces, Dict_getDict(config, String_CONST("UDPInterface")), ctx->alloc); } uint32_t count = List_size(ifaces); for (uint32_t i = 0; i < count; i++) { Dict *udp = List_getDict(ifaces, i); if (!udp) { continue; } // Setup the interface. String* bindStr = Dict_getString(udp, String_CONST("bind")); Dict* d = Dict_new(ctx->alloc); if (bindStr) { Dict_putString(d, String_CONST("bindAddress"), bindStr, ctx->alloc); } Dict* resp = NULL; rpcCall0(String_CONST("UDPInterface_new"), d, ctx, ctx->alloc, &resp, true); int ifNum = *(Dict_getInt(resp, String_CONST("interfaceNumber"))); // Make the connections. Dict* connectTo = Dict_getDict(udp, String_CONST("connectTo")); if (connectTo) { struct Dict_Entry* entry = *connectTo; struct Allocator* perCallAlloc = Allocator_child(ctx->alloc); while (entry != NULL) { String* key = (String*) entry->key; if (entry->val->type != Object_DICT) { Log_critical(ctx->logger, "interfaces.UDPInterface.connectTo: entry [%s] " "is not a dictionary type.", key->bytes); exit(-1); } Dict* value = entry->val->as.dictionary; Log_keys(ctx->logger, "Attempting to connect to node [%s].", key->bytes); key = String_clone(key, perCallAlloc); char* lastColon = CString_strrchr(key->bytes, ':'); if (!Sockaddr_parse(key->bytes, NULL)) { // it's a sockaddr, fall through } else if (lastColon) { // try it as a hostname. Log_critical(ctx->logger, "Couldn't add connection [%s], " "hostnames aren't supported.", key->bytes); exit(-1); } Dict_putInt(value, String_CONST("interfaceNumber"), ifNum, perCallAlloc); Dict_putString(value, String_CONST("address"), key, perCallAlloc); rpcCall(String_CONST("UDPInterface_beginConnection"), value, ctx, perCallAlloc); // Make a IPTunnel exception for this node Dict* aed = Dict_new(perCallAlloc); *lastColon = '\0'; Dict_putString(aed, String_CONST("route"), String_new(key->bytes, perCallAlloc), perCallAlloc); *lastColon = ':'; rpcCall(String_CONST("RouteGen_addException"), aed, ctx, perCallAlloc); entry = entry->next; } Allocator_free(perCallAlloc); } } }