Parcourir la source

Removed a bunch of dead files

Caleb James DeLisle il y a 9 ans
Parent
commit
21884c3bab
40 fichiers modifiés avec 23 ajouts et 4269 suppressions
  1. 0 33
      admin/angel/Cjdns.c
  2. 0 76
      admin/test/Admin_test_disabled.c
  3. 0 178
      admin/testframework/AdminTestFramework.c
  4. 0 42
      admin/testframework/AdminTestFramework.h
  5. 0 148
      crypto/CryptoAuth_benchmark.c
  6. 0 28
      crypto/CryptoAuth_benchmark.h
  7. 3 1
      crypto/random/randombytes.c
  8. 1 1
      crypto/test/CryptoAuth_unit_test.c
  9. 0 102
      dht/DHTCoreInterface.c
  10. 0 38
      dht/DHTCoreInterface.h
  11. 0 456
      dht/dhtcore/test/NodeStore_test_disabled.c
  12. 0 75
      dht/dhtcore/test/TestFramework.h
  13. 0 134
      doc/FutureHeaders.h
  14. 0 73
      interface/Aligner.c
  15. 0 30
      interface/Aligner.h
  16. 0 1
      interface/DNSServer.c
  17. 1 1
      interface/Iface.h
  18. 0 91
      interface/Interface.h
  19. 0 36
      interface/InterfaceConnector.c
  20. 0 32
      interface/InterfaceConnector.h
  21. 0 36
      interface/InterfaceWrapper.h
  22. 0 73
      interface/addressable/AddrInterfaceAdapter.c
  23. 0 24
      interface/addressable/AddrInterfaceAdapter.h
  24. 1 1
      interface/tuntap/test/TUNTools.c
  25. 0 1048
      net/Ducttape.c
  26. 0 95
      net/Ducttape.h
  27. 0 107
      net/Ducttape_pvt.h
  28. 1 1
      net/SessionManager.c
  29. 0 225
      net/SessionTable.c
  30. 0 112
      net/SessionTable.h
  31. 6 2
      node_build/Codestyle.js
  32. 9 4
      test/RootTest.h
  33. 0 102
      test/cjdroute_injection_test_disabled.c
  34. 0 107
      test/cjdroute_routerPing_test_disabled.c
  35. 0 270
      test/threeNodes_test_disabled.c
  36. 0 108
      util/events/libuv/FakeUDPAddrInterface.c
  37. 0 297
      util/events/libuv/UDPAddrInterface.c
  38. 0 33
      util/platform/clock_gettime.h
  39. 1 1
      util/version/Version.h
  40. 0 47
      wire/BridgeHeader.h

+ 0 - 33
admin/angel/Cjdns.c

@@ -1,33 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#define string_strlen // some systems implement strcmp as a macro using strlen.
-#include "admin/angel/AngelInit.h"
-#include "admin/angel/Core.h"
-
-#include <stdio.h>
-#include <unistd.h>
-
-int main(int argc, char** argv)
-{
-    if (isatty(STDIN_FILENO) || argc < 2) {
-        // Fall through.
-    } else if (!CString_strcmp("angel", argv[1])) {
-        return AngelInit_main(argc, argv);
-    } else if (!CString_strcmp("core", argv[1])) {
-        return Core_main(argc, argv);
-    }
-    printf("This is internal to cjdns, it should not be started manually.\n");
-    return -1;
-}

+ 0 - 76
admin/test/Admin_test_disabled.c

@@ -1,76 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "admin/testframework/AdminTestFramework.h"
-#include "benc/Dict.h"
-#include "benc/String.h"
-#include "benc/Int.h"
-#include "memory/Allocator.h"
-#include "util/Assert.h"
-
-#include <stdio.h>
-
-struct Context {
-    struct AdminTestFramework* framework;
-
-    bool called;
-};
-
-static void adminFunc(Dict* input, void* vcontext, String* txid, struct Allocator* requestAlloc)
-{
-    struct Context* ctx = vcontext;
-    ctx->called = true;
-    Dict d = Dict_CONST(String_CONST("called!"), Int_OBJ(1), NULL);
-    Admin_sendMessage(&d, txid, ctx->framework->admin);
-}
-
-static void standardClientCallback(struct AdminClient_Promise* p, struct AdminClient_Result* res)
-{
-    struct Context* ctx = p->userData;
-    //printf("%d\n", res->err);
-    Assert_true(!res->err);
-    Assert_true(Dict_getInt(res->responseDict, String_CONST("called!")));
-    Assert_true(ctx->called);
-
-    EventBase_endLoop(ctx->framework->eventBase);
-}
-
-static void standardClient(struct Context* ctx)
-{
-    ctx->called = false;
-    struct AdminClient_Promise* promise =
-        AdminClient_rpcCall(String_CONST("adminFunc"),
-                            NULL,
-                            ctx->framework->client,
-                            ctx->framework->alloc);
-
-    promise->callback = standardClientCallback;
-    promise->userData = ctx;
-
-    EventBase_beginLoop(ctx->framework->eventBase);
-}
-
-int main(int argc, char** argv)
-{
-    struct AdminTestFramework* framework = AdminTestFramework_setUp(argc, argv, "Admin_test");
-    struct Context ctx = {
-        .framework = framework
-    };
-    Admin_registerFunction("adminFunc", adminFunc, &ctx, true, NULL, framework->admin);
-
-    standardClient(&ctx);
-
-    AdminTestFramework_tearDown(framework);
-    return 0;
-}

+ 0 - 178
admin/testframework/AdminTestFramework.c

@@ -1,178 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "admin/Admin.h"
-#include "admin/AdminClient.h"
-#include "admin/angel/AngelInit.h"
-#include "admin/angel/InterfaceWaiter.h"
-#include "admin/testframework/AdminTestFramework.h"
-#include "benc/String.h"
-#include "benc/Int.h"
-#include "benc/serialization/standard/BencMessageWriter.h"
-#include "crypto/random/Random.h"
-#include "memory/Allocator.h"
-#include "memory/MallocAllocator.h"
-#include "io/FileWriter.h"
-#include "io/Writer.h"
-#include "util/events/EventBase.h"
-#include "util/events/UDPAddrIface.h"
-#include "util/events/Pipe.h"
-#include "util/events/Process.h"
-#include "util/Assert.h"
-#include "util/log/Log.h"
-#include "util/log/WriterLog.h"
-
-#include <unistd.h>
-#include <stdlib.h>
-
-static void spawnAngel(char* testName,
-                       char* asClientPipeName,
-                       struct EventBase* base,
-                       struct Allocator* alloc)
-{
-    char* args[] = { testName, "angel", asClientPipeName, NULL };
-
-    struct Allocator* tempAlloc = Allocator_child(alloc);
-    char* path = Process_getPath(tempAlloc);
-    Assert_true(path);
-    Process_spawn(path, args, base, alloc);
-    Allocator_free(tempAlloc);
-}
-
-/** @return a string representing the address and port to connect to. */
-static void initAngel(struct Pipe* asClientPipe,
-                      struct Iface* asCoreIface,
-                      char* asCorePipeName,
-                      struct EventBase* eventBase,
-                      struct Log* logger,
-                      struct Allocator* alloc,
-                      struct Random* rand)
-{
-    Dict admin = Dict_CONST(
-        String_CONST("bind"), String_OBJ(String_CONST("127.0.0.1")), Dict_CONST(
-        String_CONST("corePipeName"), String_OBJ(String_CONST(asCorePipeName)), Dict_CONST(
-        String_CONST("pass"), String_OBJ(String_CONST("abcd")), NULL
-    )));
-    Dict message = Dict_CONST(
-        String_CONST("admin"), Dict_OBJ(&admin), NULL
-    );
-
-    struct Allocator* tempAlloc = Allocator_child(alloc);
-
-    struct Message* toAngel = Message_new(0, 1024, tempAlloc);
-    BencMessageWriter_write(&message, toAngel, NULL);
-
-    Log_info(logger, "Writing intial configuration to angel on [%s]", asClientPipe->name);
-    Interface_sendMessage(&asClientPipe->iface, toAngel);
-
-    // This is client->angel->core data, we can throw this away.
-    //struct Message* angelToCore =
-    InterfaceWaiter_waitForData(asCoreIface, eventBase, tempAlloc, NULL);
-
-    // unterminated string
-    //Log_info(logger, "Init message from angel to core: [%s]", angelToCore->bytes);
-
-    // Send response on behalf of core.
-    Dict* coreToAngelResp = Dict_new(tempAlloc);
-    Dict_putString(coreToAngelResp, String_CONST("error"), String_CONST("none"), tempAlloc);
-    struct Message* coreToAngelMsg = Message_new(0, 256, tempAlloc);
-    BencMessageWriter_write(coreToAngelResp, coreToAngelMsg, NULL);
-    Interface_sendMessage(asCoreIface, coreToAngelMsg);
-
-    // This is angel->client data, it will tell us which port was bound.
-    struct Message* angelToClient =
-        InterfaceWaiter_waitForData(&asClientPipe->iface, eventBase, tempAlloc, NULL);
-
-    uint8_t lastByte = angelToClient->bytes[angelToClient->length-1];
-    angelToClient->bytes[angelToClient->length-1] = '\0';
-    printf("Response from angel to client: [%s%c]\n", angelToClient->bytes, (char)lastByte);
-
-    Allocator_free(tempAlloc);
-
-    return;
-}
-
-/**
- * This spawns itself as the Angel process which spawns itself again as the core process.
- * The "core process" pipes all of its inputs back to the originating process
- */
-
-struct AdminTestFramework* AdminTestFramework_setUp(int argc, char** argv, char* testName)
-{
-    if (argc > 2 && !CString_strcmp(testName, argv[1]) && !CString_strcmp("angel", argv[2])) {
-        exit(AngelInit_main(argc-1, &argv[1]));
-    }
-
-    struct Allocator* alloc = MallocAllocator_new(1<<20);
-
-    struct Writer* logwriter = FileWriter_new(stdout, alloc);
-    Assert_true(logwriter);
-    struct Log* logger = WriterLog_new(logwriter, alloc);
-
-    struct EventBase* eventBase = EventBase_new(alloc);
-    struct Random* rand = Random_new(alloc, logger, NULL);
-
-
-    char asClientPipeName[32] = {0};
-    Random_base32(rand, (uint8_t*)asClientPipeName, 31);
-    struct Pipe* asClientPipe = Pipe_named(asClientPipeName, eventBase, NULL, alloc);
-    asClientPipe->logger = logger;
-
-    char asCorePipeName[32] = {0};
-    Random_base32(rand, (uint8_t*)asCorePipeName, 31);
-    struct Pipe* asCorePipe = Pipe_named(asCorePipeName, eventBase, NULL, alloc);
-    asCorePipe->logger = logger;
-    struct Iface* asCoreIface = FramingInterface_new(65535, &asCorePipe->iface, alloc);
-
-    spawnAngel(testName, asClientPipeName, eventBase, alloc);
-
-    Log_info(logger, "Initializing Angel");
-    initAngel(asClientPipe, asCoreIface, (char*)asCorePipe->name, eventBase, logger, alloc, rand);
-
-    struct Sockaddr_storage addr;
-    Assert_true(!Sockaddr_parse("127.0.0.1", &addr));
-
-    Log_info(logger, "Binding UDP admin socket");
-    struct AddrIface* udpAdmin = UDPAddrIface_new(eventBase, &addr.addr, alloc, NULL, logger);
-
-    String* password = String_new("abcd", alloc);
-    struct Admin* admin = Admin_new(udpAdmin, alloc, logger, eventBase, password);
-
-    // Now setup the client.
-
-    struct AdminClient* client =
-        AdminClient_new(udpAdmin->addr, password, eventBase, logger, alloc);
-
-    Assert_true(client);
-
-    return Allocator_clone(alloc, (&(struct AdminTestFramework) {
-        .admin = admin,
-        .client = client,
-        .alloc = alloc,
-        .eventBase = eventBase,
-        .logger = logger,
-        .addr = Sockaddr_clone(udpAdmin->addr, alloc),
-        .angelInterface = asCoreIface
-    }));
-}
-
-void AdminTestFramework_tearDown(struct AdminTestFramework* framework)
-{
-    Dict* exitCmd = Dict_new(framework->alloc);
-    Dict_putString(exitCmd, String_CONST("q"), String_CONST("Angel_exit"), framework->alloc);
-    struct Message* msg = Message_new(0, 256, framework->alloc);
-    BencMessageWriter_write(exitCmd, msg, NULL);
-    Interface_sendMessage(framework->angelInterface, msg);
-    Allocator_free(framework->alloc);
-}

+ 0 - 42
admin/testframework/AdminTestFramework.h

@@ -1,42 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef AdminTestFramework_H
-#define AdminTestFramework_H
-
-#include "admin/Admin.h"
-#include "admin/AdminClient.h"
-#include "memory/Allocator.h"
-#include "util/log/Log.h"
-#include "util/platform/Sockaddr.h"
-#include "util/events/EventBase.h"
-#include "util/Linker.h"
-Linker_require("admin/testframework/AdminTestFramework.c")
-
-#error poisoned
-
-struct AdminTestFramework
-{
-    struct Admin* admin;
-    struct AdminClient* client;
-    struct Allocator* alloc;
-    struct EventBase* eventBase;
-    struct Log* logger;
-    struct Sockaddr* addr;
-    struct Iface* angelInterface;
-};
-
-struct AdminTestFramework* AdminTestFramework_setUp(int argc, char** argv, char* testName);
-void AdminTestFramework_tearDown(struct AdminTestFramework* framework);
-#endif

+ 0 - 148
crypto/CryptoAuth_benchmark.c

@@ -1,148 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "crypto/random/Random.h"
-#include "crypto/CryptoAuth.h"
-#include "io/FileWriter.h"
-#include "benc/Object.h"
-#include "memory/MallocAllocator.h"
-#include "util/Bits.h"
-#include "util/Hex.h"
-#include "util/Endian.h"
-#include "util/events/Time.h"
-#include "util/events/EventBase.h"
-#include "wire/Error.h"
-
-#include "util/Assert.h"
-#include <stdio.h>
-
-static const uint8_t* privateKey = (uint8_t*)
-    "\x20\xca\x45\xd9\x5b\xbf\xca\xe7\x35\x3c\xd2\xdf\xfa\x12\x84\x4b"
-    "\x4e\xff\xbe\x7d\x39\xd8\x4d\x8e\x14\x2b\x9d\x21\x89\x5b\x38\x09";
-
-static const uint8_t* publicKey = (uint8_t*)
-    "\x51\xaf\x8d\xd9\x35\xe8\x61\x86\x3e\x94\x2b\x1b\x6d\x21\x22\xe0"
-    "\x2f\xb2\xd0\x88\x20\xbb\xf3\xf0\x6f\xcd\xe5\x85\x30\xe0\x08\x34";
-
-struct Context
-{
-    uint8_t padding[256];
-    uint8_t buffer[2048];
-    struct Message message;
-    struct CryptoAuth* ca1;
-    struct CryptoAuth* ca2;
-
-    struct Iface if1;
-    struct Iface* cif1;
-    struct Message* if1Incoming;
-
-    struct Iface if2;
-    struct Iface* cif2;
-    struct Message* if2Incoming;
-
-    struct EventBase* base;
-    Identity
-};
-
-static Iface_DEFUN transferMessage1(struct Message* message, struct Iface* iface)
-{
-    struct Context* ctx = Identity_containerOf(iface, struct Context, if1);
-    return otherIface->receiveMessage(message, otherIface);
-}
-
-static Iface_DEFUN transferMessage2(struct Message* message, struct Iface* iface)
-{
-    struct Context* ctx = Identity_containerOf(iface, struct Context, if2);
-// XXX
-    Iface_next(&ctx->if1, message);
-    return 0;
-}
-
-static inline void setupMessage(struct Context* ctx, uint16_t length)
-{
-    ctx->message.bytes = ctx->buffer;
-    ctx->message.padding = 256;
-    ctx->message.length = length;
-}
-
-static const char* KEY = "key";
-static const char* HELLO = "hello";
-static const char* TRAFFIC = "data";
-
-static inline void sendMessages(struct Context* ctx,
-                                int count,
-                                int size,
-                                const char* type)
-{
-    printf("Test sending %d %d byte\t%s packets\n", count, size, type);
-
-    ctx->cif2 = CryptoAuth_wrapInterface(&ctx->if2, NULL, NULL, false, "cif2", ctx->ca2);
-    ctx->cif1 = CryptoAuth_wrapInterface(&ctx->if1, publicKey, NULL, false, "cif1", ctx->ca1);
-    uint64_t startTime = Time_hrtime();
-    if (type != HELLO) {
-        setupMessage(ctx, size);
-        ctx->cif1->sendMessage(&ctx->message, ctx->cif1);
-        if (type == TRAFFIC) {
-            setupMessage(ctx, size);
-            ctx->cif2->sendMessage(&ctx->message, ctx->cif2);
-        }
-    }
-    for (int i = 0; i < count; i++) {
-        setupMessage(ctx, size);
-        if (type == KEY) {
-            ctx->cif2->sendMessage(&ctx->message, ctx->cif2);
-        } else {
-            ctx->cif1->sendMessage(&ctx->message, ctx->cif1);
-        }
-    }
-    uint64_t endTimes = Time_hrtime();
-    uint64_t time = (endTimes - startTime) / 1000000;
-    uint64_t kbSent = (size * count * 8) / 1024;
-
-    // same as kbSent / (time / 1024) (converting time to seconds)
-    uint64_t kbps = (kbSent * 1024) / time;
-
-    printf("\tFinished in %dms. %d Kb/s\n\n", (int)time, (int)kbps);
-}
-
-void CryptoAuth_benchmark(struct EventBase* base,
-                          struct Log* logger,
-                          struct Allocator* alloc)
-{
-    struct Random* rand = Random_new(alloc, logger, NULL);
-    struct Context ctx = {
-        .ca1 = CryptoAuth_new(alloc, NULL, base, NULL, rand),
-        .ca2 = CryptoAuth_new(alloc, privateKey, base, NULL, rand),
-        .if1 = {
-            .send = transferMessage1
-        },
-        .if2 = {
-            .send = transferMessage2
-        },
-        .base = base
-    };
-    printf("These metrics are speed of encryption and decryption similar to the usage pattern\n"
-           "when decrypting a packet, switching it, and re-encrypting it with another key.\n");
-
-    sendMessages(&ctx, 1000, 64, HELLO);
-    sendMessages(&ctx, 1000, 1500, HELLO);
-
-    sendMessages(&ctx, 1000, 64, KEY);
-    sendMessages(&ctx, 1000, 1500, KEY);
-
-    sendMessages(&ctx, 100000, 64, TRAFFIC);
-
-    printf("This is the switch configuration so this indicates expected switch throughput:\n");
-    sendMessages(&ctx, 100000, 1500, TRAFFIC);
-}

+ 0 - 28
crypto/CryptoAuth_benchmark.h

@@ -1,28 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef CryptoAuth_benchmark_H
-#define CryptoAuth_benchmark_H
-
-#include "memory/Allocator.h"
-#include "util/log/Log.h"
-#include "util/events/EventBase.h"
-#include "util/Linker.h"
-Linker_require("crypto/CryptoAuth_benchmark.c")
-
-void CryptoAuth_benchmark(struct EventBase* base,
-                          struct Log* logger,
-                          struct Allocator* alloc);
-
-#endif

+ 3 - 1
crypto/random/randombytes.c

@@ -28,8 +28,10 @@ int main()
         uint8_t buff[4096];
     } str;
 
+    size_t out = 0;
     for (;;) {
         Random_bytes(rand, str.buff, 4096);
-        write(STDOUT_FILENO, str.buff, 4096);
+        out = write(STDOUT_FILENO, str.buff, 4096);
     }
+    return (out == 4096) ? 0 : -1;
 }

+ 1 - 1
crypto/test/CryptoAuth_unit_test.c

@@ -143,7 +143,7 @@ static void receiveHelloWithNoAuth()
     struct Allocator* alloc = MallocAllocator_new(1<<20);
     struct Context* ctx = setUp(PRIVATEKEY, NULL, NULL, alloc);
     struct Message* msg = Message_new(132, 0, alloc);
-    Assert_true(Hex_decode(msg->bytes, msg->length, 
+    Assert_true(Hex_decode(msg->bytes, msg->length,
         "0000000000ffffffffffffff7fffffffffffffffffffffffffffffffffffffff"
         "ffffffffffffffff847c0d2c375234f365e660955187a3735a0f7613d1609d3a"
         "6a4d8c53aeaa5a22ea9cf275eee0185edf7f211192f12e8e642a325ed76925fe"

+ 0 - 102
dht/DHTCoreInterface.c

@@ -1,102 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "dht/DHTModule.h"
-#include "dht/Address.h"
-#include "net/SessionManager.h"
-#include "wire/DataHeader.h"
-#include "wire/RouteHeader.h"
-
-///////////////////// [ Address ][ content... ]
-
-struct DHTCoreInterface_pvt
-{
-    struct DHTCoreInterface pub;
-    struct DHTModule module;
-    struct Allocator* alloc;
-    struct Log* log;
-    struct DHTModuleRegistry* registry;
-    Identity
-};
-
-static int incomingFromDHT(struct DHTMessage* dmessage, void* vcim)
-{
-    struct DHTCoreInterface_pvt* cim = Identity_check((struct DHTCoreInterface_pvt*) vcim);
-    struct Message* msg = dmessage->binMessage;
-    struct Address* addr = dmessage->address;
-
-    // Sanity check (make sure the addr was actually calculated)
-    Assert_true(addr->ip6.bytes[0] == 0xfc && addr->padding == 0);
-
-    Message_shift(msg, RouteHeader_SIZE + DataHeader_SIZE, NULL);
-    struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
-    struct DataHeader* dh = (struct DataHeader*) &hdr[1];
-
-    Bits_memset(dh, 0, DataHeader_SIZE);
-    DataHeader_setVersion(dh, DataHeader_CURRENT_VERSION);
-    DataHeader_setContentType(dh, ContentType_CJDHT);
-
-    Bits_memcpyConst(hdr->ip6, addr->ip6.bytes, 16);
-    hdr->version_be = Endian_hostToBigEndian32(addr->protocolVersion);
-    Bits_memset(&hdr->sh, 0, SwitchHeader_SIZE);
-    hdr->sh.label_be = Endian_hostToBigEndian64(addr->path);
-    Bits_memcpyConst(hdr->publicKey, addr->key, 32);
-
-    Log_debug(cim->log, "Outgoing DHT");
-
-    return Iface_send(&cim->pub.coreIf, msg);
-}
-
-static Iface_DEFUN incomingFromCore(struct Message* msg, struct Iface* coreIf)
-{
-    struct DHTCoreInterface_pvt* cim = Identity_check((struct DHTCoreInterface_pvt*) coreIf);
-
-    struct Address addr;
-    struct RouteHeader* hdr = (struct RouteHeader*) msg->bytes;
-    Message_shift(msg, -(RouteHeader_SIZE + DataHeader_SIZE), NULL);
-    Bits_memcpyConst(addr.ip6.bytes, hdr->ip6, 16);
-    Bits_memcpyConst(addr.key, hdr->publicKey, 32);
-    addr.protocolVersion = Endian_bigEndianToHost32(hdr->version_be);
-    addr.padding = 0;
-    addr.path = Endian_bigEndianToHost64(hdr->sh.label_be);
-
-    Log_debug(cim->log, "Incoming DHT");
-
-    struct DHTMessage dht = {
-        .address = &addr,
-        .binMessage = msg,
-        .allocator = msg->alloc
-    };
-
-    DHTModuleRegistry_handleIncoming(&dht, cim->registry);
-
-    return 0;
-}
-
-struct DHTCoreInterface* DHTCoreInterface_register(struct Allocator* alloc,
-                                                   struct Log* logger,
-                                                   struct DHTModuleRegistry* registry)
-{
-    struct DHTCoreInterface_pvt* cim =
-        Allocator_calloc(alloc, sizeof(struct DHTCoreInterface_pvt), 1);
-    cim->alloc = alloc;
-    cim->log = logger;
-    cim->registry = registry;
-    cim->pub.coreIf.send = incomingFromCore;
-    cim->module.context = cim;
-    cim->module.handleOutgoing = incomingFromDHT;
-    Assert_true(!DHTModuleRegistry_register(&cim->module, cim->registry));
-    Identity_set(cim);
-    return &cim->pub;
-}

+ 0 - 38
dht/DHTCoreInterface.h

@@ -1,38 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef DHTCoreInterface_H
-#define DHTCoreInterface_H
-
-#include "dht/DHTModuleRegistry.h"
-#include "interface/Iface.h"
-#include "memory/Allocator.h"
-#include "util/log/Log.h"
-#include "util/Linker.h"
-Linker_require("dht/DHTCoreInterface.c")
-
-struct DHTCoreInterface
-{
-    /**
-     * Communicates with the core.
-     * Content: [ struct Address ][ content... ]
-     */
-    struct Iface coreIf;
-};
-
-struct DHTCoreInterface* DHTCoreInterface_register(struct Allocator* alloc,
-                                                   struct Log* logger,
-                                                   struct DHTModuleRegistry* registry);
-
-#endif

+ 0 - 456
dht/dhtcore/test/NodeStore_test_disabled.c

@@ -1,456 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "memory/MallocAllocator.h"
-#include "crypto/random/Random.h"
-#include "crypto/AddressCalc.h"
-#include "dht/Address.h"
-#include "dht/dhtcore/Node.h"
-#include "dht/dhtcore/NodeList.h"
-#include "dht/dhtcore/NodeStore.h"
-#include "io/FileWriter.h"
-#include "switch/LabelSplicer.h"
-#include "util/Assert.h"
-#include "util/Endian.h"
-#include "util/log/WriterLog.h"
-#include "util/version/Version.h"
-
-#include "crypto_scalarmult_curve25519.h"
-
-#include <stddef.h>
-#include <stdio.h>
-
-static struct Allocator* alloc = NULL;
-static struct Random* rand = NULL;
-static struct Log* logger = NULL;
-static bool genKeys = 0;
-static int nextKey = 0;
-
-static char* KEYS[] = {
-    #include "dht/dhtcore/test/TestKeys.data"
-};
-
-static struct NodeStore* setUp(struct Address* myAddress, uint32_t capacity)
-{
-    return NodeStore_new(myAddress, capacity, alloc, logger, rand);
-}
-
-static void missingKey()
-{
-    printf("mismatching key, run this:\n"
-           "head ./dht/dhtcore/NodeStore.c -n 14 > ./TestKeys.data && "
-           "./build_linux/testcjdroute NodeStore_test --genkeys | sed -ne "
-           "'s/^created new key: \\[\\(.\\{32\\}\\)\\(.\\{32\\}\\)\\]$/\"\\1\"\\n\"\\2\",/p' "
-           "| sed 's/\\([0-9a-f]\\{2\\}\\)/\\\\x\\1/g' >> TestKeys.data && "
-           "mv ./TestKeys.data ./dht/dhtcore/test/\n");
-    Assert_true(false);
-}
-
-static uint64_t getPath(int* hops)
-{
-    int i;
-    uint64_t out = 0;
-    for (i = 0; hops[i] != 1; i++) ;
-    for (; i >= 0; i--) {
-        int bits = NumberCompress_bitsUsedForNumber(hops[i]);
-        out <<= bits;
-        out |= NumberCompress_getCompressed(hops[i], bits);
-    }
-    return out;
-}
-
-static struct Address* createAddress(int mostSignificantAddressSpaceByte, int* hops)
-{
-    uint64_t path = getPath(hops);
-    struct Address address = { .path = 0 };
-
-    if (!genKeys) {
-        if ((int)(sizeof(KEYS) / sizeof(*KEYS)) < (nextKey + 1)) {
-            missingKey();
-        }
-        Bits_memcpyConst(address.key, KEYS[nextKey], 32);
-        if (AddressCalc_addressForPublicKey(address.ip6.bytes, address.key)
-            && (mostSignificantAddressSpaceByte == -1
-                || address.ip6.bytes[8] == mostSignificantAddressSpaceByte))
-        {
-            nextKey++;
-            uint8_t publicKeyHex[65];
-            Hex_encode(publicKeyHex, 65, address.key, 32);
-            printf("created new key: [%s]\n", publicKeyHex);
-
-            address.path = path;
-            return Allocator_clone(alloc, &address);
-        } else {
-            uint8_t publicKeyHex[65];
-            Hex_encode(publicKeyHex, 65, address.key, 32);
-            printf("bad key: [%s]\n", publicKeyHex);
-            if (address.ip6.ints.three) {
-                uint8_t printedAddr[40];
-                AddrTools_printIp(printedAddr, address.ip6.bytes);
-                printf("addr: [%s]\n", printedAddr);
-            }
-                missingKey();
-        }
-    }
-
-    for (;;) {
-        Random_bytes(rand, address.key, 32);
-        // Brute force for keys until one matches FC00:/8
-        if (AddressCalc_addressForPublicKey(address.ip6.bytes, address.key)
-            && (mostSignificantAddressSpaceByte == -1
-                || address.ip6.bytes[8] == mostSignificantAddressSpaceByte))
-        {
-
-            uint8_t publicKeyHex[65];
-            Hex_encode(publicKeyHex, 65, address.key, 32);
-            printf("created new key: [%s]\n", publicKeyHex);
-
-            address.path = path;
-            return Allocator_clone(alloc, &address);
-        }
-    }
-}
-
-static struct Address* randomIp(int* hops)
-{
-    return createAddress(-1, hops);
-}
-
-// This creates a random address which is a peer
-static struct Address* randomAddress()
-{
-    return randomIp((int[]){0,1}/*0x13*/);
-}
-
-static void test_addNode()
-{
-    struct Address* myAddr = randomAddress();
-    struct NodeStore* store = setUp(myAddr, 2);
-    // adding ourselves should be null
-    Assert_true(NodeStore_addNode(store, myAddr, 1, Version_CURRENT_PROTOCOL) == NULL);
-
-    // adding a random node with no peer should be null
-    Assert_true(
-        !NodeStore_addNode(store, randomIp((int[]){2,2,1}/*0x155*/), 1, Version_CURRENT_PROTOCOL)
-    );
-
-    // adding a peer should be non-null
-    Assert_true(
-        NodeStore_addNode(store, randomIp((int[]){2,1}/*0x15*/), 1, Version_CURRENT_PROTOCOL)
-    );
-
-    // adding a node behind our peer should also be non-null
-    Assert_true(
-        NodeStore_addNode(store, randomIp((int[]){2,2,1}/*0x155*/), 1, Version_CURRENT_PROTOCOL)
-    );
-
-    // test at capacity and verify worst path is replaced
-    NodeStore_addNode(store, randomIp((int[]){3,2,1}/*0x157*/), 1, Version_CURRENT_PROTOCOL);
-    struct Node* node =
-        NodeStore_addNode(store, randomIp((int[]){0,1}/*0x13*/), 1, Version_CURRENT_PROTOCOL);
-    Assert_true( Address_isSameIp(&node->address, &NodeStore_dumpTable(store,1)->address) );
-}
-
-static void test_getNodesByAddr()
-{
-    struct Address* myAddr = randomAddress();
-    struct NodeStore* store = setUp(myAddr, 8);
-    struct Address* otherAddr = randomIp((int[]){0,1}/*0x13*/);
-
-    // make sure we can add an addr and get it back
-    NodeStore_addNode(store, otherAddr, 1, Version_CURRENT_PROTOCOL);
-    struct NodeList* list = NodeStore_getNodesByAddr(otherAddr, 1, alloc, store);
-    Assert_true(list->size == 1);
-    Assert_true(Address_isSameIp(&list->nodes[0]->address, otherAddr));
-
-    // try for two
-    otherAddr->path = getPath((int[]){2,1}) /*0x15*/;
-    NodeStore_addNode(store, otherAddr, 1, Version_CURRENT_PROTOCOL);
-    list = NodeStore_getNodesByAddr(otherAddr, 2, alloc, store);
-    Assert_true(list->size == 2);
-    Assert_true(Address_isSameIp(&list->nodes[0]->address, otherAddr));
-    Assert_true(Address_isSameIp(&list->nodes[1]->address, otherAddr));
-
-    // make sure 1 still works
-    list = NodeStore_getNodesByAddr(otherAddr, 1, alloc, store);
-    Assert_true(list->size == 1);
-}
-
-static void test_getPeers()
-{
-    // mucking around with switch labels...
-    // see switch/NumberCompress.h
-    struct Address* myAddr = createAddress(0x99, (int[]){1}/*0x01*/);   // 0001
-    struct NodeStore* store = setUp(myAddr, 8);
-    uint64_t target = getPath((int[]){7,1})/*0x1f*/;
-    struct Address* oneHop1 = createAddress(0x02, (int[]){3,1}/*0x17*/);
-    struct Address* oneHop2 = createAddress(0x01, (int[]){2,1}/*0x15*/);
-    struct Address* oneHop3 = createAddress(0x04, (int[]){6,1}/*0x1d*/);
-    struct Address* twoHop = createAddress(0x03, (int[]){2,2,1}/*0x155*/);
-
-    // using variable scheme, 4 bits (suffix 1).
-    /* specific to v3x5x8
-        Assert_true(NumberCompress_bitsUsedForLabel(target) == 4);
-        Assert_true(NumberCompress_bitsUsedForLabel(oneHop1->path) == 4);
-        Assert_true(NumberCompress_bitsUsedForLabel(oneHop2->path) == 4);
-        Assert_true(NumberCompress_bitsUsedForLabel(oneHop3->path) == 4);
-        Assert_true(NumberCompress_bitsUsedForLabel(twoHop->path) == 4);
-    */
-
-    // verify we setup our test data correctly.
-    Assert_true(LabelSplicer_isOneHop(oneHop1->path));
-    Assert_true(LabelSplicer_isOneHop(oneHop2->path));
-    Assert_true(LabelSplicer_isOneHop(oneHop3->path));
-    Assert_true(!LabelSplicer_isOneHop(twoHop->path));
-
-    // verify empty case, should always return a NodeList
-    struct NodeList* list = NodeStore_getPeers(target, 1, alloc, store);
-    Assert_true(list != NULL);
-    Assert_true(list->size == 0);
-
-    // add test nodes
-    NodeStore_addNode(store, oneHop1, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, oneHop2, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, oneHop3, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, twoHop, 1, Version_CURRENT_PROTOCOL);
-
-    // verify we only get nodes with 1 hop labels
-    list = NodeStore_getPeers(target, 10, alloc, store);
-    Assert_true(list->size == 3);
-    for (uint32_t i=0; i < list->size; i++) {
-        Assert_true(LabelSplicer_isOneHop(list->nodes[i]->address.path));
-    }
-
-    // verify max parameter works
-    list = NodeStore_getPeers(target, 1, alloc, store);
-    Assert_true(list->size == 1);
-}
-
-static void test_getBest()
-{
-    struct Address* myAddr = createAddress(0x99, (int[]){1}/*0x1*/);
-    struct NodeStore* store = setUp(myAddr, 8);
-    struct Address* target = createAddress(0x01, (int[]){2,1}/*0x15*/);
-    struct Address* a = createAddress(0x05, (int[]){3,1}/*0x17*/);  // 1 hop
-    struct Address* b = createAddress(0xff, (int[]){3,3,1}/*0x177*/); // 2 hops (behind 0x17)
-    struct Node* best = NULL;
-
-    // exact address match should be best
-    NodeStore_addNode(store, a, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, b, 1, Version_CURRENT_PROTOCOL);
-    best = NodeStore_getBest(b, store);
-    Assert_true(best != NULL);
-    Assert_true(Address_isSameIp(&best->address, b));
-
-    // shortest label should be used if no exact match
-    best = NodeStore_getBest(target, store);
-    Assert_true(best != NULL);
-    Assert_true(Address_isSameIp(&best->address, a));
-}
-
-static void test_getClosestNodes()
-{
-    // gets nodes that are "close" as in log2(path) aka # hops away
-    struct Address* myAddr = createAddress(0x99, (int[]){1} /*0x1*/);
-    struct NodeStore* store = setUp(myAddr, 8);
-    struct Address* target = createAddress(0x06, (int[]){0,1}/*0x13*/);
-    struct Address* oneHop = createAddress(0x05, (int[]){2,1}/*0x15*/);
-    struct Address* twoHop = createAddress(0x08, (int[]){2,2,1}/*0x155*/);
-    struct NodeList* closest = NULL;
-
-    NodeStore_addNode(store, oneHop, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, twoHop, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(
-        store, randomIp((int[]){3,3,3,3,1}/*0x17777*/), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(
-        store, randomIp((int[]){2,3,2,3,2,1}/*0x157575*/), 1, Version_CURRENT_PROTOCOL);
-
-    // check basic case returns in reverse order (of hops)
-    closest = NodeStore_getClosestNodes(store, target, NULL, 2,
-                                        Version_CURRENT_PROTOCOL, alloc);
-    Assert_true(closest != NULL);
-    Assert_true(closest->size == 2);
-    Assert_true(Address_isSameIp(&closest->nodes[0]->address, twoHop));
-    Assert_true(Address_isSameIp(&closest->nodes[1]->address, oneHop));
-}
-
-static void test_updateReach()
-{
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    struct Address* a = randomIp((int[]){3,1} /*0x17*/);  // 00010111      iface #3,#1
-    struct Address* b = randomIp((int[]){2,1} /*0x15*/);  // 00010101      iface #2,#1
-    struct Address* c = randomIp((int[]){2,2,1} /*0x155*/); // 000111011101  iface #2,#2,#1
-
-    // verify c routes through b
-    Assert_true(LabelSplicer_routesThrough(c->path, b->path));
-
-    NodeStore_addNode(store, a, 1, Version_CURRENT_PROTOCOL);
-    struct Node* node = NodeStore_addNode(store, b, 15, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, c, 20, Version_CURRENT_PROTOCOL);
-
-    // update reach of b, and verify reach of c is changed as well
-    node->reach = 10;
-    NodeStore_updateReach(node, store);
-    Assert_true(NodeStore_dumpTable(store, 2)->reach == 10);
-}
-
-static void test_nonZeroNodes()
-{
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    struct Node* node =
-       NodeStore_addNode(store, randomIp((int[]){0,1}), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, randomIp((int[]){2,1}), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, randomIp((int[]){3,1}), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, randomIp((int[]){4,1}), 1, Version_CURRENT_PROTOCOL);
-    Assert_true(store->size == 4);
-    Assert_true(NodeStore_nonZeroNodes(store)==4);
-
-    // zero a node and make sure we get one less.
-    node->reach = 0;
-    NodeStore_updateReach(node, store);
-    Assert_true(NodeStore_nonZeroNodes(store)==3);
-}
-
-static void test_size()
-{
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    Assert_true(NodeStore_size(store) == 0);
-    NodeStore_addNode(store, randomAddress(), 0, Version_CURRENT_PROTOCOL);
-    Assert_true(NodeStore_size(store) == 1);
-}
-
-static void test_getNodeByNetworkAddr()
-{
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    // empty case should be null
-    Assert_true(NodeStore_getNodeByNetworkAddr(getPath((int[]){2,1}),store)==NULL);
-
-    // happy case
-    NodeStore_addNode(store, randomIp((int[]){0,1}), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, randomIp((int[]){3,1}), 1, Version_CURRENT_PROTOCOL);
-    Assert_true(
-        NodeStore_getNodeByNetworkAddr(getPath((int[]){3,1}),store)->address.path ==
-            getPath((int[]){3,1})
-    );
-}
-
-static void test_brokenPath()
-{
-    struct Address* myAddr = randomIp((int[]){1});
-    struct NodeStore* store = setUp(myAddr, 8);
-    struct Address* a = randomIp((int[]){3,1});
-    struct Address* b = randomIp((int[]){2,1});
-    struct Address* c = randomIp((int[]){2,2,1});
-
-    // verify c routes through b
-    Assert_true(LabelSplicer_routesThrough(c->path, b->path));
-
-    // verify removing b should invalidate c
-    NodeStore_addNode(store, a, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, b, 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, c, 1, Version_CURRENT_PROTOCOL);
-
-    // calling brokenPath on B directly should remove it
-    Assert_true(NodeStore_brokenPath(b->path, store)==2);
-
-    // should only have 1 valid route now...
-    Assert_true(NodeStore_nonZeroNodes(store)==1);
-}
-
-static void test_dumpTable()
-{
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    NodeStore_addNode(store, randomIp((int[]){0,1}), 1, Version_CURRENT_PROTOCOL);
-    struct Node* orig =
-        NodeStore_addNode(store, randomIp((int[]){5,1}), 1, Version_CURRENT_PROTOCOL);
-    NodeStore_addNode(store, randomIp((int[]){3,1}), 1, Version_CURRENT_PROTOCOL);
-    // verify happy case
-    struct Node* test = NodeStore_dumpTable(store, 1);
-    Assert_true(Address_isSameIp(&orig->address, &test->address));
-    // verify out of bounds index gets NULL
-    Assert_true(NodeStore_dumpTable(store, -1) == NULL);
-    Assert_true(NodeStore_dumpTable(store, 3) == NULL);
-}
-
-static void test_pathfinderTwo_splitLink()
-{
-    #ifndef EXPERIMENTAL_PATHFINDER
-        return;
-    #endif
-    struct NodeStore* store = setUp(randomAddress(), 8);
-    struct EncodingScheme* scheme = NumberCompress_defineScheme(alloc);
-
-    // always linked to self
-    Assert_true(NodeStore_linkCount(store->selfNode) == 1);
-
-    // fcfe:15a1:15f1:ba25:ec32:4507:8d78:efef  0000.0000.0000.0031 --> 0000.0000.0000.0031
-    NodeStore_discoverNode(store, randomIp((int[]){8,1}), 0,
-                           Version_CURRENT_PROTOCOL, scheme, 0);
-
-    // should be just efef in the table.
-    Assert_true(NodeStore_linkCount(store->selfNode) == 2);
-
-    // fc98:0c83:e1be:0bdc:e177:49c6:2f96:39ee  0000.0000.0000.a629 --> 0000.0000.0014.c531
-    NodeStore_discoverNode(store, randomIp((int[]){8,4,8,4,1}), 0,
-                           Version_CURRENT_PROTOCOL, scheme, 0);
-
-    // Now should be efef->39ee
-    Assert_true(NodeStore_linkCount(store->selfNode) == 2);
-    struct Node_Link* linkSelfEfef = NodeStore_getLink(store->selfNode, 0);
-    Assert_true(NodeStore_linkCount(linkSelfEfef->child) == 1);
-    struct Node_Link* linkEfEf39ee = NodeStore_getLink(linkSelfEfef->child, 0);
-    struct Node_Two* node39ee = linkEfEf39ee->child;
-    Assert_true(NodeStore_linkCount(linkEfEf39ee->child) == 0);
-
-    // fc1e:7c83:c316:11e3:2b3b:0b25:e667:2765  0000.0000.0000.0029 --> 0000.0000.0000.0531
-    NodeStore_discoverNode(store, randomIp((int[]){8,4,1}), 0,
-                           Version_CURRENT_PROTOCOL, scheme, 0);
-
-    // This split efef->39ee resulting in:  efef->2765->39ee
-    Assert_true(NodeStore_linkCount(linkSelfEfef->child) == 1);
-    struct Node_Link* linkEfef2765 = NodeStore_getLink(linkSelfEfef->child, 0);
-    Assert_true(linkEfef2765->child != node39ee);
-    Assert_true(NodeStore_linkCount(linkEfef2765->child) == 1);
-    struct Node_Link* link276539ee = NodeStore_getLink(linkEfef2765->child, 0);
-    Assert_true(link276539ee->child == node39ee);
-    Assert_true(NodeStore_linkCount(node39ee) == 0);
-}
-
-int main(int argc, char** argv)
-{
-    if (argc > 1 && !CString_strcmp(argv[argc-1], "--genkeys")) {
-        genKeys = 1;
-    }
-
-    alloc = MallocAllocator_new(1<<20);
-    struct Writer* writer = FileWriter_new(stdout, alloc);
-    logger = WriterLog_new(writer, alloc);
-    rand = Random_new(alloc, NULL, NULL);
-
-    test_addNode();
-    test_getBest();
-    test_getNodesByAddr();
-    test_getPeers();
-    test_getClosestNodes();
-    test_updateReach();
-    test_nonZeroNodes();
-    test_size();
-    test_getNodeByNetworkAddr();
-    test_brokenPath();
-    test_dumpTable();
-    test_pathfinderTwo_splitLink();
-
-    Allocator_free(alloc);
-    return 0;
-}

+ 0 - 75
dht/dhtcore/test/TestFramework.h

@@ -1,75 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef TestFramework_H
-#define TestFramework_H
-
-#include "memory/Allocator.h"
-#include "dht/DHTModules.h"
-#include "dht/CJDHTConstants.h"
-
-static int catchOutgoing(struct DHTMessage* message, void* vcontext);
-static int bounceMessage(struct DHTMessage* message, void* vcontext);
-
-static void TestFramework_registerBouncerModule(struct DHTModuleRegistry* registry,
-                                                struct Allocator* allocator)
-__attribute__((unused));
-
-static void TestFramework_registerBouncerModule(struct DHTModuleRegistry* registry,
-                                                struct Allocator* allocator)
-{
-    struct DHTModule* module =
-        Allocator_clone(allocator, (&(struct DHTModule) {
-            .context = registry,
-            .handleIncoming = bounceMessage
-        });
-    DHTModules_register(module, registry);
-}
-
-static void TestFramework_registerOutputCatcher(struct DHTMessage** messagePointer,
-                                                struct DHTModuleRegistry* registry,
-                                                struct Allocator* allocator)
-{
-    struct DHTModule* module =
-        Allocator_clone(allocator, (&(struct DHTModule) {
-            .context = messagePointer,
-            .handleOutgoing = catchOutgoing
-        });
-    DHTModules_register(module, registry);
-}
-
-// A little module which just sends an empty reply to any incoming message.
-// Used to get a response from the store.
-static int bounceMessage(struct DHTMessage* message, void* vcontext)
-{
-    struct DHTModuleRegistry* registry = (struct DHTModuleRegistry*) vcontext;
-    struct DHTMessage* reply =
-        message->allocator->malloc(sizeof(struct DHTMessage), message->allocator);
-    reply->replyTo = message;
-    reply->allocator = message->allocator;
-    reply->asDict = Dict_new(reply->allocator);
-
-String* queryType = Dict_getString(message->asDict, CJDHTConstants_QUERY);
-printf("bouncing message %s", queryType->bytes);
-
-    DHTModules_handleOutgoing(reply, registry);
-    return 0;
-}
-
-// A module to catch responses and make a pointer to the message available.
-static int catchOutgoing(struct DHTMessage* message, void* vcontext)
-{
-    *((struct DHTMessage**)vcontext) = message;
-    return 0;
-}

+ 0 - 134
doc/FutureHeaders.h

@@ -1,134 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef DataHeader_H
-#define DataHeader_H
-
-#include "util/Assert.h"
-#include "util/Endian.h"
-
-/**
- *                     1               2               3
- *     0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
- *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- *  0 | ver |R| unused|    unused     |         Content Type          |
- *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- *
- * The DataHeader is protected from the switches by the l2 encryption layer and from the
- * routers by the l3 layer of encryption. It's primary uses are to tell the endpoint enough
- * information to route the packet to the correct cjdns subsystem and (maybe) reconstruct
- * the IPv6 header.
- */
-struct DataHeader
-{
-    /**
-     * If set, the receiving node should respond within 10 milliseconds, if in the next 10
-     * milliseconds it has something else to send back, this is acceptable, otherwise it should
-     * synthisize a control packet to respond with.
-     */
-    #define DataHeader_RESPOND_TO_ME (1<<7)
-
-    /**
-     * Version is set to the version of the data as per Version.h
-     * If the number is over 255, it wraps
-     */
-    uint8_t versionAndFlags;
-
-    uint8_t unused;
-
-    uint16_t contentType_be;
-};
-#define DataHeader_SIZE 4
-Assert_compileTime(sizeof(struct DataHeader) == DataHeader_SIZE);
-
-enum DataHeader_ContentType
-{
-    /**
-     * The lowest 255 message types are reserved for cjdns/IPv6 packets.
-     * AKA: packets where the IP address is within the FC00::/8 block.
-     * Any packet sent in this way will have the IPv6 header deconstructed and this
-     * field will come from the nextHeader field in the IPv6 header.
-     */
-    DataHeader_ContentType_IP6_IP =        0,
-    DataHeader_ContentType_IP6_ICMP =      1,
-    DataHeader_ContentType_IP6_IGMP =      2,
-    DataHeader_ContentType_IP6_IPIP =      4,
-    DataHeader_ContentType_IP6_TCP =       6,
-    DataHeader_ContentType_IP6_EGP =       8,
-    DataHeader_ContentType_IP6_PUP =       12,
-    DataHeader_ContentType_IP6_UDP =       17,
-    DataHeader_ContentType_IP6_IDP =       22,
-    DataHeader_ContentType_IP6_TP =        29,
-    DataHeader_ContentType_IP6_DCCP =      33,
-    DataHeader_ContentType_IP6_IPV6 =      41,
-    DataHeader_ContentType_IP6_RSVP =      46,
-    DataHeader_ContentType_IP6_GRE =       47,
-    DataHeader_ContentType_IP6_ESP =       50,
-    DataHeader_ContentType_IP6_AH =        51,
-    DataHeader_ContentType_IP6_MTP =       92,
-    DataHeader_ContentType_IP6_BEETPH =    94,
-    DataHeader_ContentType_IP6_ENCAP =     98,
-    DataHeader_ContentType_IP6_PIM =       103,
-    DataHeader_ContentType_IP6_COMP =      108,
-    DataHeader_ContentType_IP6_SCTP =      132,
-    DataHeader_ContentType_IP6_UDPLITE =   136,
-    DataHeader_ContentType_IP6_RAW =       255,
-
-    /** Bencoded inter-router CTRL messages. */
-    DataHeader_ContentType_CTRL =          256,
-
-    /**
-     * Content types in the AVAILABLE range are not defined and can be used
-     * like port numbers for subsystems of cjdns to communicate with subsystems within
-     * cjdns on other machines, providing they first agree on which numbers to use via
-     * CTRL messages.
-     */
-    DataHeader_ContentType_AVAILABLE =     257),
-    DataHeader_ContentType_AVAILABLE_MAX = 0xffff
-};
-
-static inline enum DataHeader_ContentType DataHeader_getContentType(struct DataHeader* hdr)
-{
-    return Endian_bigEndianToHost16(hdr->contentType_be);
-}
-
-static inline void DataHeader_setContentType(struct DataHeader* hdr,
-                                             enum DataHeader_ContentType type)
-{
-    Assert_true(type <= DataHeader_ContentType_AVAILABLE_MAX);
-    hdr->contentType_be = Endian_hostToBigEndian16(type);
-}
-
-static inline void DataHeader_setRespondToMe(struct DataHeader* hdr, bool rtm)
-{
-    type->versionAndFlags = (type->versionAndFlags & ~DataHeader_RESPOND_TO_ME) |
-        (rtm) ? DataHeader_RESPOND_TO_ME : 0;
-}
-
-static inline bool DataHeader_getRespondToMe(struct DataHeader* hdr)
-{
-    return type->versionAndFlags & DataHeader_RESPOND_TO_ME;
-}
-
-static inline void DataHeader_setVersion(struct DataHeader* hdr, uint8_t version)
-{
-    type->versionAndFlags = (type->versionAndFlags & 0x1f) | ((version % 8) << 5);
-}
-
-static inline uint8_t DataHeader_getVersion(struct DataHeader* hdr)
-{
-    return type->versionAndFlags >> 5;
-}
-
-#endif

+ 0 - 73
interface/Aligner.c

@@ -1,73 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "interface/Aligner.h"
-#include "interface/InterfaceWrapper.h"
-#include "util/Bits.h"
-#include "util/Identity.h"
-#include "wire/Message.h"
-
-struct Aligner_pvt
-{
-    struct Aligner pub;
-    struct Iface* wrapped;
-    uint32_t alignmentBytes;
-    Identity
-};
-
-static int isAligned(uint8_t* pointer, uint32_t alignmentBytes)
-{
-    return !( ((uintptr_t)(pointer)) % alignmentBytes );
-}
-
-static void alignMessage(struct Message* msg, uint32_t alignmentBytes)
-{
-    if (isAligned(msg->bytes, alignmentBytes)) { return; }
-    uint8_t* bytes = msg->bytes;
-    int length = msg->length;
-    do {
-        Message_push8(msg, 0, NULL);
-    } while (!isAligned(msg->bytes, alignmentBytes));
-    Bits_memmove(msg->bytes, bytes, length);
-    msg->length = length;
-}
-
-static uint8_t receiveMessage(struct Message* msg, struct Iface* iface)
-{
-    struct Aligner_pvt* al = Identity_check((struct Aligner_pvt*)iface->receiverContext);
-    alignMessage(msg, al->alignmentBytes);
-    Iface_send(&al->pub.generic, msg);
-    return 0;
-}
-
-static uint8_t sendMessage(struct Message* msg, struct Iface* iface)
-{
-    struct Aligner_pvt* al = Identity_check((struct Aligner_pvt*)iface);
-    alignMessage(msg, al->alignmentBytes);
-    return Interface_sendMessage(al->wrapped, msg);
-}
-
-struct Aligner* Aligner_new(struct Iface* external,
-                            struct Allocator* alloc,
-                            uint32_t alignmentBytes)
-{
-    Assert_true(Bits_popCountx32(alignmentBytes) == 1 && "alignmentBytes must be a power of 2");
-    struct Aligner_pvt* out = Allocator_clone(alloc, (&(struct Aligner_pvt) {
-        .wrapped = external,
-        .alignmentBytes = alignmentBytes
-    }));
-    Identity_set(out);
-    InterfaceWrapper_wrap(external, sendMessage, receiveMessage, &out->pub.generic);
-    return &out->pub;
-}

+ 0 - 30
interface/Aligner.h

@@ -1,30 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef Aligner_H
-#define Aligner_H
-#include "memory/Allocator.h"
-#include "util/Linker.h"
-Linker_require("interface/Aligner.c")
-
-struct Aligner
-{
-    struct Iface generic;
-};
-
-struct Aligner* Aligner_new(struct Iface* external,
-                            struct Allocator* alloc,
-                            uint32_t alignmentBytes);
-
-#endif

+ 0 - 1
interface/DNSServer.c

@@ -452,7 +452,6 @@ static void onRainflyReply(struct RainflyClient_Lookup* promise,
 
     struct Jmp jmp = { .message = NULL };
     Jmp_try(jmp) {
-// TODO should be an error (not using return)...
         onRainflyReplyB(lookup, ctx, value, code, &jmp.handler);
     } Jmp_catch {
         Log_debug(ctx->logger, "Failed to send DNS reply [%s]", jmp.message);

+ 1 - 1
interface/Iface.h

@@ -138,7 +138,7 @@ static inline Iface_DEFUN Iface_next(struct Iface* iface, struct Message* msg)
  * you are calling might use Iface_next(), you must call it with this macro instead of calling
  * it directly.
  * If you are calling from a Iface_Callback function, you must not use this function to call
- * the next function with the message passed to you. If  
+ * the next function with the message passed to you. In that case just call the function directly.
  */
 #ifdef PARANOIA
     #define Iface_CALL(func, msg, ...) \

+ 0 - 91
interface/Interface.h

@@ -1,91 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef Interface_H
-#define Interface_H
-
-#include <stdint.h>
-
-#include "wire/Message.h"
-
-/// OLD: use interface/Iface.h instead!
-#error poisoned
-
-#define Interface_ERROR_WRONG_STATE 256
-
-struct Iface;
-
-typedef uint8_t (* Interface_Callback)(struct Message*, struct Iface*);
-
-/**
- * An interface.
- * All interfaces are point-to-point, no addressing is done at this level.
- * If you have multiple direct connections (eg nodes in an ethernet),
- * you must register an interface for each.
- */
-struct Iface
-{
-    /** Arbitarary data which belongs to the wire side of this interface. */
-    void* senderContext;
-
-    /** The maximum allowable length for a message. */
-    uint16_t maxMessageLength;
-
-    /**
-     * The number of bytes of padding which must exist *before* the beginning of the message.
-     * when you call sendMessage, there must be requiredPadding number of bytes of free space before
-     * the location pointed to by message->bytes.
-     */
-    uint16_t requiredPadding;
-
-    /**
-     * Send a message through this interface.
-     *
-     * @return 0 If all goes well, non-zero in case of an error.
-     *           See Error.h for more information about interface error codes.
-     */
-    Interface_Callback sendMessage;
-
-    /** Used to allocate this interface, the interface will close when this allocator is freed. */
-    struct Allocator* allocator;
-
-    /** Arbitrary data which belongs to the receiver side of this interface. */
-    void* receiverContext;
-
-    /**
-     * Recieve a message from this interface.
-     *
-     * @param received the incoming message from the other node.
-     * @param senderContext arbitrary data which must be passed to the receiver.
-     * @return 0 If all goes well, non-zero in case of an error.
-     *           See Error.h for more information about interface error codes.
-     */
-    Interface_Callback receiveMessage;
-};
-
-static inline uint8_t Iface_send(struct Iface* iface, struct Message* msg)
-{
-    if (iface->receiveMessage) {
-        return iface->receiveMessage(msg, iface);
-    }
-    return 0;
-}
-
-static inline uint8_t Interface_sendMessage(struct Iface* iface, struct Message* msg)
-{
-    Assert_true(iface->sendMessage);
-    return iface->sendMessage(msg, iface);
-}
-
-#endif

+ 0 - 36
interface/InterfaceConnector.c

@@ -1,36 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "wire/Message.h"
-
-static uint8_t transferMessage(struct Message* msg, struct Iface* iface)
-{
-    struct Iface* other = (struct Iface*) iface->receiverContext;
-    return other->sendMessage(msg, other);
-}
-
-/**
- * Connect two interfaces together like a double female adapter.
- * Any traffic coming in on one will be forwarded to the other.
- *
- * @param a one interface.
- * @param b another interface.
- */
-void InterfaceConnector_connect(struct Iface* a, struct Iface* b)
-{
-    a->receiveMessage = transferMessage;
-    a->receiverContext = b;
-    b->receiveMessage = transferMessage;
-    b->receiverContext = a;
-}

+ 0 - 32
interface/InterfaceConnector.h

@@ -1,32 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef InterfaceConnector_H
-#define InterfaceConnector_H
-
-#error poison
-
-#include "util/Linker.h"
-Linker_require("interface/InterfaceConnector.c")
-
-/**
- * Connect two interfaces together like a double female adapter.
- * Any traffic coming in on one will be forwarded to the other.
- *
- * @param a one interface.
- * @param b another interface.
- */
-void InterfaceConnector_connect(struct Iface* a, struct Iface* b);
-
-#endif

+ 0 - 36
interface/InterfaceWrapper.h

@@ -1,36 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef InterfaceWrapper_H
-#define InterfaceWrapper_H
-
-#error poisoned
-
-#include "memory/Allocator.h"
-
-static void InterfaceWrapper_wrap(struct Iface* toWrap,
-                                  Interface_Callback sendMessage,
-                                  Interface_Callback receiveMessage,
-                                  struct Iface* output)
-{
-    toWrap->receiveMessage = receiveMessage;
-    toWrap->receiverContext = output;
-
-    Bits_memcpyConst(output, (&(struct Iface) {
-        .sendMessage = sendMessage,
-    }), sizeof(struct Iface));
-}
-
-
-#endif

+ 0 - 73
interface/addressable/AddrInterfaceAdapter.c

@@ -1,73 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "interface/addressable/AddrInterfaceAdapter.h"
-#include "memory/Allocator.h"
-#include "util/platform/Sockaddr.h"
-#include "util/Assert.h"
-#include "util/Identity.h"
-#include "wire/Message.h"
-
-/**
- * Convert a normal Interface to an AddrInterface, all incoming messages
- * will have the same address (Sockaddr_LOOPBACK).
- */
-struct AddrInterfaceAdapter_pvt
-{
-    struct AddrInterface pub;
-    struct Iface* wrapped;
-    Identity
-};
-
-static uint8_t sendMessage(struct Message* message, struct Iface* iface)
-{
-    struct AddrInterfaceAdapter_pvt* context =
-        Identity_check((struct AddrInterfaceAdapter_pvt*) iface);
-
-    Message_shift(message, -(context->pub.addr->addrLen), NULL);
-    return Interface_sendMessage(context->wrapped, message);
-}
-
-static uint8_t receiveMessage(struct Message* message, struct Iface* iface)
-{
-    struct AddrInterfaceAdapter_pvt* context =
-        Identity_check((struct AddrInterfaceAdapter_pvt*) iface->receiverContext);
-
-    Message_push(message, context->pub.addr, context->pub.addr->addrLen, NULL);
-    return Iface_send(&context->pub.generic, message);
-}
-
-struct AddrInterface* AddrInterfaceAdapter_new(struct Iface* toWrap, struct Allocator* alloc)
-{
-    struct AddrInterfaceAdapter_pvt* context =
-        Allocator_malloc(alloc, sizeof(struct AddrInterfaceAdapter_pvt));
-
-    Bits_memcpyConst(context, (&(struct AddrInterfaceAdapter_pvt) {
-        .pub = {
-            .generic = {
-                .sendMessage = sendMessage,
-                .senderContext = context,
-                .allocator = alloc
-            }
-        },
-        .wrapped = toWrap
-    }), sizeof(struct AddrInterfaceAdapter_pvt));
-    Identity_set(context);
-
-    context->pub.addr = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
-    toWrap->receiveMessage = receiveMessage;
-    toWrap->receiverContext = context;
-
-    return &context->pub;
-}

+ 0 - 24
interface/addressable/AddrInterfaceAdapter.h

@@ -1,24 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef AddrInterfaceAdapter_H
-#define AddrInterfaceAdapter_H
-
-#include "memory/Allocator.h"
-#include "util/Linker.h"
-Linker_require("interface/addressable/AddrInterfaceAdapter.c")
-
-struct AddrInterface* AddrInterfaceAdapter_new(struct Iface* toWrap, struct Allocator* alloc);
-
-#endif

+ 1 - 1
interface/tuntap/test/TUNTools.c

@@ -168,7 +168,7 @@ void TUNTools_echoTest(struct Sockaddr* udpBindTo,
     ctx->pub.log = logger;
 
     Timeout_setInterval(sendHello, ctx, 1000, base, alloc);
-    Timeout_setTimeout(fail, NULL, 5000, base, alloc);
+    Timeout_setTimeout(fail, NULL, 60000, base, alloc);
 
     EventBase_beginLoop(base);
 }

+ 0 - 1048
net/Ducttape.c

@@ -1,1048 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "crypto/AddressCalc.h"
-#include "crypto/CryptoAuth.h"
-#include "util/log/Log.h"
-#include "dht/Address.h"
-#include "dht/dhtcore/Node.h"
-#include "dht/dhtcore/Router.h"
-#include "dht/dhtcore/RumorMill.h"
-#include "interface/tuntap/TUNMessageType.h"
-#include "net/SessionTable.h"
-#include "util/log/Log.h"
-#include "memory/Allocator.h"
-#include "net/Ducttape_pvt.h"
-#include "switch/SwitchCore.h"
-#include "switch/LabelSplicer.h"
-#include "util/AddrTools.h"
-#include "util/Bits.h"
-#include "util/Checksum.h"
-#include "util/version/Version.h"
-#include "util/Assert.h"
-#include "util/events/Timeout.h"
-#include "tunnel/IpTunnel.h"
-#include "util/events/Time.h"
-#include "util/Defined.h"
-#include "wire/Control.h"
-#include "wire/Error.h"
-#include "wire/Headers.h"
-#include "wire/CryptoHeader.h"
-#include "wire/Ethernet.h"
-
-#include <stdint.h>
-
-/** Size of the per-message workspace. */
-#define PER_MESSAGE_BUF_SZ 8192
-
-#define FC_ONE "\xfc\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1"
-
-/** Header must not be encrypted and must be aligned on the beginning of the ipv6 header. */
-static inline uint8_t sendToRouter(struct Message* message,
-                                   struct Ducttape_MessageHeader* dtHeader,
-                                   struct SessionTable_Session* session,
-                                   struct Ducttape_pvt* context)
-{
-    int safeDistance = SwitchHeader_SIZE;
-
-    CryptoAuth_resetIfTimeout(session->internal);
-    if (CryptoAuth_getState(session->internal) < CryptoAuth_HANDSHAKE3) {
-        // Put the handle into the message so that it's authenticated.
-        // see: sendToSwitch()
-        //Log_debug(context->logger, "Sending receive handle under CryptoAuth");
-        Message_push(message, &session->receiveHandle_be, 4, NULL);
-
-        safeDistance += CryptoHeader_SIZE;
-    } else {
-        // 16 for the authenticator, 4 for the nonce and 4 for the handle
-        safeDistance += 24;
-    }
-
-    Message_shift(message, safeDistance, NULL);
-    if (dtHeader->switchHeader) {
-        if (message->bytes != (uint8_t*)dtHeader->switchHeader) {
-            Bits_memmoveConst(message->bytes, dtHeader->switchHeader, SwitchHeader_SIZE);
-            dtHeader->switchHeader = (struct SwitchHeader*) message->bytes;
-        }
-    } else {
-        dtHeader->switchHeader = (struct SwitchHeader*) message->bytes;
-        Bits_memset(dtHeader->switchHeader, 0, SwitchHeader_SIZE);
-    }
-    Message_shift(message, -safeDistance, NULL);
-
-    SwitchHeader_setVersion(dtHeader->switchHeader, SwitchHeader_CURRENT_VERSION);
-    SwitchHeader_setLabelShift(dtHeader->switchHeader, 0);
-    dtHeader->switchHeader->label_be = Endian_hostToBigEndian64(dtHeader->switchLabel);
-
-    // This comes out in outgoingFromCryptoAuth() then sendToSwitch()
-    dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
-    dtHeader->layer = Ducttape_SessionLayer_OUTER;
-    return Interface_sendMessage(session->internal, message);
-}
-
-static struct Ducttape_MessageHeader* getDtHeader(struct Message* message, bool init)
-{
-    int padding = message->padding;
-    Assert_true(padding > Ducttape_MessageHeader_SIZE);
-    Message_shift(message, padding, NULL);
-    struct Ducttape_MessageHeader* dtHeader = (struct Ducttape_MessageHeader*) message->bytes;
-    Message_shift(message, -padding, NULL);
-    if (init) {
-        Bits_memset(dtHeader, 0, Ducttape_MessageHeader_SIZE);
-        Identity_set(dtHeader);
-    } else {
-        Identity_check(dtHeader);
-    }
-    return dtHeader;
-}
-
-// [ struct Address ][ content (benc) ]
-// see ducttape.h -> dhtIf
-static Iface_DEFUN incomingFromDHTInterface(struct Message* msg, struct Iface* dhtIf)
-{
-    struct Ducttape_pvt* ctx = Identity_containerOf(dhtIf, struct Ducttape_pvt, pub.dhtIf);
-
-    struct Address addr;
-    Message_pop(msg, &addr, Address_SIZE, NULL);
-
-    // Sanity check (make sure the addr was actually calculated)
-    Assert_true(addr.ip6.bytes[0] == 0xfc && addr.padding == 0);
-
-    // Sending a message to yourself?
-    // Short circuit because setting up a CA session with yourself causes problems.
-    if (!Bits_memcmp(addr.key, ctx->myAddr.key, 32)) {
-        struct Allocator* alloc = Allocator_child(ctx->alloc);
-        Allocator_adopt(alloc, msg->alloc);
-        Message_push(msg, &addr, Address_SIZE, NULL);
-        Iface_send(dhtIf, msg);
-        Allocator_free(alloc);
-        return 0;
-    }
-
-    Message_push(msg, (&(struct Headers_UDPHeader) {
-        .srcPort_be = 0,
-        .destPort_be = 0,
-        .length_be = Endian_hostToBigEndian16(msg->length),
-        .checksum_be = 0,
-    }), Headers_UDPHeader_SIZE, NULL);
-
-    struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) msg->bytes;
-
-    {
-        struct Headers_IP6Header ip = {
-            .versionClassAndFlowLabel = 0,
-            .flowLabelLow_be = 0,
-            .nextHeader = 17,
-            .hopLimit = 0,
-            .payloadLength_be = Endian_hostToBigEndian16(msg->length),
-            .sourceAddr = {0}
-        };
-        Bits_memcpyConst(ip.sourceAddr,
-                         ctx->myAddr.ip6.bytes,
-                         Address_SEARCH_TARGET_SIZE);
-        Bits_memcpyConst(ip.destinationAddr,
-                         addr.ip6.bytes,
-                         Address_SEARCH_TARGET_SIZE);
-        Message_push(msg, &ip, Headers_IP6Header_SIZE, NULL);
-    }
-
-    struct Headers_IP6Header* ip = (struct Headers_IP6Header*) msg->bytes;
-
-    Assert_true(!((uintptr_t)msg->bytes % 4) || !"alignment fault");
-
-    uh->checksum_be = Checksum_udpIp6(ip->sourceAddr,
-                                      (uint8_t*) uh,
-                                      msg->length - Headers_IP6Header_SIZE);
-
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(msg, true);
-    dtHeader->ip6Header = ip;
-    dtHeader->switchLabel = addr.path;
-
-    struct SessionTable_Session* session =
-        SessionTable_getSession(addr.ip6.bytes, addr.key, ctx->sm);
-
-    // At the router level, we never send anything to anyone w/o knowing their protocol version.
-    session->version = addr.protocolVersion;
-    Assert_true(session->version);
-
-    sendToRouter(msg, dtHeader, session, ctx);
-
-    return 0;
-}
-
-// Aligned on the beginning of the content.
-static inline bool isRouterTraffic(struct Message* message, struct Headers_IP6Header* ip6)
-{
-    if (ip6->nextHeader != 17 || ip6->hopLimit != 0) {
-        return false;
-    }
-
-    struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) message->bytes;
-    return message->length >= Headers_UDPHeader_SIZE
-        && uh->srcPort_be == 0
-        && uh->destPort_be == 0
-        && (int) Endian_bigEndianToHost16(uh->length_be) ==
-            (message->length - Headers_UDPHeader_SIZE);
-}
-
-#define debugHandles(logger, session, message, ...) \
-    do {                                                                               \
-        uint8_t ip[40];                                                                \
-        AddrTools_printIp(ip, session->ip6);                                      \
-        Log_debug(logger, "ver[%u] send[%d] recv[%u] ip[%s] " message,                 \
-                  session->version,                                                    \
-                  Endian_hostToBigEndian32(session->sendHandle_be),                    \
-                  Endian_hostToBigEndian32(session->receiveHandle_be),                 \
-                  ip,                                                                  \
-                  __VA_ARGS__);                                                        \
-    } while (0)
-//CHECKFILES_IGNORE expecting a ;
-
-#define debugHandles0(logger, session, message) \
-    debugHandles(logger, session, message "%s", "")
-
-#define debugHandlesAndLabel(logger, session, label, message, ...) \
-    do {                                                                               \
-        uint8_t path[20];                                                              \
-        AddrTools_printPath(path, label);                                              \
-        debugHandles(logger, session, "path[%s] " message, path, __VA_ARGS__);         \
-    } while (0)
-//CHECKFILES_IGNORE expecting a ;
-
-#define debugHandlesAndLabel0(logger, session, label, message) \
-    debugHandlesAndLabel(logger, session, label, "%s", message)
-
-
-/**
- * Message which is for us, message is aligned on the beginning of the content.
- * this is called from core() which calls through an interfaceMap.
- */
-static inline uint8_t incomingForMe(struct Message* message,
-                                    struct Ducttape_MessageHeader* dtHeader,
-                                    struct SessionTable_Session* session,
-                                    struct Ducttape_pvt* context,
-                                    uint8_t herPublicKey[32])
-{
-    struct Address addr = { .protocolVersion = session->version };
-    addr.path = Endian_bigEndianToHost64(dtHeader->switchHeader->label_be);
-    Bits_memcpyConst(addr.key, herPublicKey, 32);
-    AddressCalc_addressForPublicKey(addr.ip6.bytes, herPublicKey);
-    Assert_true(!Bits_memcmp(session->ip6, addr.ip6.bytes, 16));
-
-    if (Bits_memcmp(addr.ip6.bytes, dtHeader->ip6Header->sourceAddr, 16)) {
-        #ifdef Log_DEBUG
-            uint8_t keyAddr[40];
-            Address_printShortIp(keyAddr, &addr);
-            Bits_memcpyConst(addr.ip6.bytes, dtHeader->ip6Header->sourceAddr, 16);
-            uint8_t srcAddr[40];
-            Address_printShortIp(srcAddr, &addr);
-            Log_debug(context->logger,
-                       "DROP packet because source address is not same as key.\n"
-                       "    %s source addr\n"
-                       "    %s hash of key\n",
-                       srcAddr,
-                       keyAddr);
-        #endif
-        return Error_INVALID;
-    }
-
-    if (isRouterTraffic(message, dtHeader->ip6Header)) {
-        // Check the checksum.
-        struct Headers_UDPHeader* uh = (struct Headers_UDPHeader*) message->bytes;
-
-        if (Checksum_udpIp6(dtHeader->ip6Header->sourceAddr, (uint8_t*)uh, message->length)) {
-            #ifdef Log_DEBUG
-                uint8_t keyAddr[40];
-                Address_printShortIp(keyAddr, &addr);
-                Log_debug(context->logger,
-                          "DROP Router packet with incorrect checksum, from [%s]", keyAddr);
-            #endif
-            return Error_INVALID;
-        }
-
-        // Shift off the UDP header.
-        Message_shift(message, -Headers_UDPHeader_SIZE, NULL);
-        Message_push(message, &addr, Address_SIZE, NULL);
-        return Iface_send(&context->pub.dhtIf, message);
-    }
-
-    if (!context->userIf) {
-        Log_warn(context->logger, "DROP packet because there is no TUN interface configured");
-        return Error_UNDELIVERABLE;
-    }
-
-    // Force set the hopLimit to a specific number, in preparation for the new protocol
-    // which will nolonger include hopLimit so it will need to be set at the end.
-    // This is here to test how applications behave with a weird hop limit.
-    dtHeader->ip6Header->hopLimit = 42;
-
-    // Now write a message to the TUN device.
-    // Need to move the ipv6 header forward up to the content because there's a crypto header
-    // between the ipv6 header and the content which just got eaten.
-    Message_shift(message, Headers_IP6Header_SIZE, NULL);
-    uint16_t sizeDiff = message->bytes - (uint8_t*)dtHeader->ip6Header;
-    if (sizeDiff) {
-        dtHeader->ip6Header->payloadLength_be =
-            Endian_hostToBigEndian16(
-                Endian_bigEndianToHost16(dtHeader->ip6Header->payloadLength_be) - sizeDiff);
-        Bits_memmoveConst(message->bytes, dtHeader->ip6Header, Headers_IP6Header_SIZE);
-    }
-
-    TUNMessageType_push(message, Ethernet_TYPE_IP6, NULL);
-
-    context->userIf->sendMessage(message, context->userIf);
-    return Error_NONE;
-}
-
-uint8_t Ducttape_injectIncomingForMe(struct Message* message,
-                                     struct Ducttape* dt,
-                                     uint8_t herPublicKey[32])
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)dt);
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
-    struct SwitchHeader sh;
-    Bits_memcpyConst(&sh, message->bytes, SwitchHeader_SIZE);
-    dtHeader->switchHeader = &sh;
-    Message_shift(message, -SwitchHeader_SIZE, NULL);
-
-    struct Headers_IP6Header ip6;
-    Bits_memcpyConst(&ip6, message->bytes, Headers_IP6Header_SIZE);
-    dtHeader->ip6Header = &ip6;
-    Message_shift(message, -Headers_IP6Header_SIZE, NULL);
-
-    struct SessionTable_Session s;
-    AddressCalc_addressForPublicKey(s.ip6, herPublicKey);
-    s.version = Version_CURRENT_PROTOCOL;
-
-    return incomingForMe(message, dtHeader, &s, context, herPublicKey);
-}
-
-/**
- * Send a message to another switch.
- * Switchheader will precede the message.
- */
-static inline uint8_t sendToSwitch(struct Message* message,
-                                   struct Ducttape_MessageHeader* dtHeader,
-                                   struct SessionTable_Session* session,
-                                   struct Ducttape_pvt* context)
-{
-    uint64_t label = dtHeader->switchLabel;
-
-    CryptoAuth_resetIfTimeout(session->internal);
-    if (CryptoAuth_getState(session->internal) >= CryptoAuth_HANDSHAKE3) {
-        //debugHandlesAndLabel0(context->logger, session, label, "layer2 sending run message");
-        uint32_t sendHandle_be = session->sendHandle_be;
-        Message_push(message, &sendHandle_be, 4, NULL);
-    } else {
-        debugHandlesAndLabel0(context->logger, session, label, "layer2 sending start message");
-    }
-
-    Message_shift(message, SwitchHeader_SIZE, NULL);
-
-    Assert_true(message->bytes == (uint8_t*)dtHeader->switchHeader);
-
-    Assert_true(!((uintptr_t)message->bytes % 4));
-
-    return Iface_send(&context->pub.switchIf, message);
-}
-
-static inline bool validEncryptedIP6(struct Message* message)
-{
-    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
-    // Empty ipv6 headers are tolerated at this stage but dropped later.
-    return message->length >= Headers_IP6Header_SIZE
-        && AddressCalc_validAddress(header->sourceAddr)
-        && AddressCalc_validAddress(header->destinationAddr);
-}
-
-static inline bool isForMe(struct Message* message, struct Ducttape_pvt* context)
-{
-    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
-    return (Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16) == 0);
-}
-
-static Iface_DEFUN incomingFromMagicInterface(struct Message* msg, struct Iface* magicIf)
-{
-    struct Ducttape_pvt* ctx = Identity_containerOf(magicIf, struct Ducttape_pvt, pub.magicIf);
-
-    Assert_ifParanoid(msg->length >= Headers_IP6Header_SIZE);
-    #ifdef PARANOIA
-        struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;
-        Assert_ifParanoid(!Bits_memcmp(header->destinationAddr, ctx->myAddr.ip6.bytes, 16));
-        Assert_ifParanoid(!Bits_memcmp(header->sourceAddr, FC_ONE, 16));
-    #endif
-
-    TUNMessageType_push(msg, Ethernet_TYPE_IP6, NULL);
-
-    if (ctx->userIf) {
-        return Interface_sendMessage(ctx->userIf, msg);
-    }
-    return Error_NONE;
-}
-
-// Called by the TUN device.
-static inline uint8_t incomingFromTun(struct Message* message,
-                                      struct Iface* iface)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->receiverContext);
-
-    uint16_t ethertype = TUNMessageType_pop(message, NULL);
-
-    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
-
-    int version = Headers_getIpVersion(message->bytes);
-    if ((ethertype == Ethernet_TYPE_IP4 && version != 4)
-        || (ethertype == Ethernet_TYPE_IP6 && version != 6))
-    {
-        Log_warn(context->logger, "DROP packet because ip version [%d] "
-                 "doesn't match ethertype [%u].", version, Endian_bigEndianToHost16(ethertype));
-        return Error_INVALID;
-    }
-
-    if (ethertype != Ethernet_TYPE_IP6 || !AddressCalc_validAddress(header->sourceAddr)) {
-        return context->ipTunnel->tunInterface.sendMessage(message,
-                                                           &context->ipTunnel->tunInterface);
-    } else if (!AddressCalc_validAddress(header->destinationAddr)) {
-        #ifdef Log_INFO
-            uint8_t dst[40];
-            AddrTools_printIp(dst, header->destinationAddr);
-            Log_warn(context->logger, "DROP packet to [%s] because it must begin with fc", dst);
-        #endif
-        return Error_INVALID;
-    }
-
-    if (Bits_memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16)) {
-        uint8_t expectedSource[40];
-        AddrTools_printIp(expectedSource, context->myAddr.ip6.bytes);
-        uint8_t packetSource[40];
-        AddrTools_printIp(packetSource, header->sourceAddr);
-        Log_warn(context->logger,
-                 "DROP packet from [%s] because all messages must have source address [%s]",
-                 (char*) packetSource, (char*) expectedSource);
-        return Error_INVALID;
-    }
-    if (!Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16)) {
-        // I'm Gonna Sit Right Down and Write Myself a Letter
-        TUNMessageType_push(message, ethertype, NULL);
-        iface->sendMessage(message, iface);
-        return Error_NONE;
-    }
-
-    if (!Bits_memcmp(header->destinationAddr, FC_ONE, 16)) {
-        return Iface_send(&context->pub.magicIf, message);
-    }
-
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
-    struct Node_Two* bestNext = Router_lookup(context->router, header->destinationAddr);
-    if (bestNext && !Bits_memcmp(header->destinationAddr, bestNext->address.ip6.bytes, 16)) {
-        struct SessionTable_Session* sess =
-            SessionTable_getSession(bestNext->address.ip6.bytes,
-                                      bestNext->address.key,
-                                      context->sm);
-
-        bestNext->address.protocolVersion = sess->version =
-            (bestNext->address.protocolVersion > sess->version)
-                ? bestNext->address.protocolVersion : sess->version;
-
-        dtHeader->switchLabel = bestNext->address.path;
-
-        // This only matters if we fall out of the if block and do 3 layer send...
-        dtHeader->nextHopReceiveHandle = Endian_bigEndianToHost32(sess->receiveHandle_be);
-
-        return sendToRouter(message, dtHeader, sess, context);
-    }
-
-    struct SessionTable_Session* session =
-        SessionTable_getSession(header->destinationAddr, NULL, context->sm);
-    if (session->knownSwitchLabel) {
-        // Do a direct send using a discovered label...
-        dtHeader->switchLabel = session->knownSwitchLabel;
-        return sendToRouter(message, dtHeader, session, context);
-    } else if (!bestNext) {
-        #ifdef Log_WARN
-            uint8_t thisAddr[40];
-            uint8_t destAddr[40];
-            AddrTools_printIp(thisAddr, context->myAddr.ip6.bytes);
-            AddrTools_printIp(destAddr, header->destinationAddr);
-            Log_warn(context->logger,
-                     "DROP message from TUN because this node [%s] is closest to dest [%s]",
-                     thisAddr, destAddr);
-        #endif
-        return Error_UNDELIVERABLE;
-    }
-
-    struct SessionTable_Session* nextHopSession =
-        SessionTable_getSession(bestNext->address.ip6.bytes,
-                                  bestNext->address.key,
-                                  context->sm);
-/*
-    #ifdef Log_DEBUG
-        uint8_t destAddr[40];
-        AddrTools_printIp(destAddr, header->destinationAddr);
-        uint8_t nhAddr[60];
-        Address_print(nhAddr, &bestNext->address);
-        Log_debug(context->logger, "Sending to [%s] via [%s]", destAddr, nhAddr);
-    #endif
-*/
-
-    // Copy the IP6 header back from where the CA header will be placed.
-    // this is a mess.
-    // We can't just copy the header to a safe place because the CryptoAuth
-    // might buffer the message and send a connect-to-me packet and when the
-    // hello packet comes in return, the CA will send the message and the header
-    // needs to be in the message buffer.
-    //
-    // The CryptoAuth may send a 120 byte CA header and it might only send a 4 byte
-    // nonce and 16 byte authenticator depending on its state.
-
-    CryptoAuth_resetIfTimeout(session->internal);
-    if (CryptoAuth_getState(session->internal) < CryptoAuth_HANDSHAKE3) {
-        // shift, copy, shift because shifting asserts that there is enough buffer space.
-        Message_shift(message, CryptoHeader_SIZE + 4, NULL);
-        Bits_memcpyConst(message->bytes, header, Headers_IP6Header_SIZE);
-        Message_shift(message, -(Headers_IP6Header_SIZE + CryptoHeader_SIZE + 4), NULL);
-        // now push the receive handle *under* the CA header.
-        Message_push(message, &session->receiveHandle_be, 4, NULL);
-        debugHandles0(context->logger, session, "layer3 sending start message");
-        debugHandles0(context->logger, nextHopSession, "handoff");
-    } else {
-        // shift, copy, shift because shifting asserts that there is enough buffer space.
-        Message_shift(message, 20, NULL);
-        Bits_memmoveConst(message->bytes, header, Headers_IP6Header_SIZE);
-        Message_shift(message, -(20 + Headers_IP6Header_SIZE), NULL);
-        // Per packet spam
-        //debugHandles0(context->logger, session, "layer3 sending run message");
-    }
-
-    // This comes out at outgoingFromCryptoAuth() then outgoingFromMe()
-    dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
-    dtHeader->layer = Ducttape_SessionLayer_INNER;
-    return Interface_sendMessage(session->internal, message);
-}
-
-/**
- * Send an arbitrary message to a node.
- *
- * @param message to be sent, must be prefixed with IpTunnel_PacketInfoHeader.
- * @param iface an interface for which receiverContext is the ducttape.
- */
-static uint8_t sendToNode(struct Message* message, struct Iface* iface)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
-    struct IpTunnel_PacketInfoHeader* header = (struct IpTunnel_PacketInfoHeader*) message->bytes;
-    Message_shift(message, -IpTunnel_PacketInfoHeader_SIZE, NULL);
-    struct Node_Two* n = Router_lookup(context->router, header->nodeIp6Addr);
-    if (n && !Bits_memcmp(header->nodeKey, n->address.key, 32)) {
-        // Found the node.
-        /* noisy
-        #ifdef Log_DEBUG
-            uint8_t nhAddr[60];
-            Address_print(nhAddr, &n->address);
-            Log_debug(context->logger, "Sending arbitrary data to [%s]", nhAddr);
-        #endif*/
-
-        struct SessionTable_Session* session =
-            SessionTable_getSession(n->address.ip6.bytes, n->address.key, context->sm);
-
-        n->address.protocolVersion = session->version =
-            (n->address.protocolVersion > session->version)
-                ? n->address.protocolVersion : session->version;
-
-        dtHeader->switchLabel = n->address.path;
-        return sendToRouter(message, dtHeader, session, context);
-    } else {
-        struct SessionTable_Session* session =
-            SessionTable_getSession(header->nodeIp6Addr, header->nodeKey, context->sm);
-        if (session->knownSwitchLabel) {
-            dtHeader->switchLabel = session->knownSwitchLabel;
-            return sendToRouter(message, dtHeader, session, context);
-        }
-    }
-
-    #ifdef Log_DEBUG
-        uint8_t printedIp6[40];
-        AddrTools_printIp(printedIp6, header->nodeIp6Addr);
-        Log_debug(context->logger, "DROP Couldn't find node [%s] for sending to.", printedIp6);
-    #endif
-
-    // Now lets trigger a search for this node.
-    uint64_t now = Time_currentTimeMilliseconds(context->eventBase);
-    if (context->timeOfLastSearch + context->timeBetweenSearches < now) {
-        context->timeOfLastSearch = now;
-        Router_searchForNode(context->router, header->nodeIp6Addr, context->alloc);
-    }
-    return 0;
-}
-
-/**
- * Send an arbitrary message to the tun device.
- *
- * @param message to be sent.
- * @param iface an interface for which receiverContext is the ducttape.
- */
-static uint8_t sendToTun(struct Message* message, struct Iface* iface)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*)iface->receiverContext);
-    uint16_t msgType = TUNMessageType_pop(message, NULL);
-    if (msgType == Ethernet_TYPE_IP6) {
-        Assert_true(message->length >= Headers_IP6Header_SIZE);
-        struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
-        if (header->sourceAddr[0] == 0xfc || header->destinationAddr[0] == 0xfc) {
-            Assert_failure("you can't do that");
-        }
-    }
-    TUNMessageType_push(message, msgType, NULL);
-    if (context->userIf) {
-        return context->userIf->sendMessage(message, context->userIf);
-    }
-    return 0;
-}
-
-/**
- * Messages with content encrypted and header decrypted are sent here to be forwarded.
- * they may come from us, or from another node and may be to us or to any other node.
- * Message is aligned on the beginning of the ipv6 header.
- */
-static inline int core(struct Message* message,
-                       struct Ducttape_MessageHeader* dtHeader,
-                       struct SessionTable_Session* session,
-                       struct Ducttape_pvt* context)
-{
-    struct Headers_IP6Header* ip6Header = (struct Headers_IP6Header*) message->bytes;
-    dtHeader->ip6Header = ip6Header;
-
-    if (isForMe(message, context)) {
-        Message_shift(message, -Headers_IP6Header_SIZE, NULL);
-
-        if (Bits_memcmp(session->ip6, ip6Header->sourceAddr, 16)) {
-            // triple encrypted
-            // This call goes to incomingForMe()
-            struct SessionTable_Session* session =
-                SessionTable_getSession(ip6Header->sourceAddr, NULL, context->sm);
-
-            /* Per packet logging...
-            #ifdef Log_DEBUG
-                uint8_t addr[40];
-                AddrTools_printIp(addr, ip6Header->sourceAddr);
-                Log_debug(context->logger, "Incoming layer3 message, ostensibly from [%s]", addr);
-            #endif */
-
-            dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
-            dtHeader->layer = Ducttape_SessionLayer_INNER;
-            int ret = Iface_send(&session->external, message);
-            if (ret == Error_AUTHENTICATION) {
-                uint8_t addr[40];
-                AddrTools_printIp(addr, ip6Header->sourceAddr);
-                Log_debug(context->logger, "error handling layer3 message from [%s]", addr);
-                ret = 0;
-            }
-            return ret;
-        } else {
-            // double encrypted, inner layer plaintext.
-            // The session is still set from the router-to-router traffic and that is the one we use
-            // to determine the node's id.
-            return incomingForMe(message, dtHeader, session, context,
-                                 CryptoAuth_getHerPublicKey(session->internal));
-        }
-    }
-
-    if (ip6Header->hopLimit == 0) {
-        Log_debug(context->logger, "DROP message because hop limit has been exceeded.\n");
-        // TODO(cjd): send back an error message in response.
-        return Error_UNDELIVERABLE;
-    }
-    ip6Header->hopLimit--;
-
-    struct SessionTable_Session* nextHopSession = NULL;
-    if (!dtHeader->nextHopReceiveHandle || !dtHeader->switchLabel) {
-        struct Node_Two* n = Router_lookup(context->router, ip6Header->destinationAddr);
-        if (n) {
-            nextHopSession =
-                SessionTable_getSession(n->address.ip6.bytes, n->address.key, context->sm);
-            dtHeader->switchLabel = n->address.path;
-        }
-    } else {
-        nextHopSession =
-            SessionTable_sessionForHandle(dtHeader->nextHopReceiveHandle, context->sm);
-    }
-
-    if (nextHopSession) {
-        #ifdef Log_DEBUG
-            struct Address addr;
-            Bits_memcpyConst(addr.ip6.bytes, nextHopSession->ip6, 16);
-            addr.path = dtHeader->switchLabel;
-            uint8_t nhAddr[60];
-            Address_print(nhAddr, &addr);
-            if (Bits_memcmp(ip6Header->destinationAddr, addr.ip6.bytes, 16)) {
-                // Potentially forwarding for ourselves.
-                /* per packet logging
-                #ifdef Log_DEBUG
-                    struct Address destination;
-                    Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
-                    uint8_t ipAddr[40];
-                    Address_printShortIp(ipAddr, &destination);
-                    Log_debug(context->logger, "Forwarding data to %s via %s\n", ipAddr, nhAddr);
-                #endif */
-            } else {
-                // Definitely forwarding on behalf of someone else.
-                //Log_debug(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
-            }
-        #endif
-        return sendToRouter(message, dtHeader, nextHopSession, context);
-    }
-
-    #ifdef Log_INFO
-        struct Address destination;
-        Bits_memcpyConst(destination.ip6.bytes, ip6Header->destinationAddr, 16);
-        uint8_t ipAddr[40];
-        Address_printShortIp(ipAddr, &destination);
-        Log_info(context->logger, "DROP message because this node is the closest known "
-                                   "node to the destination %s.", ipAddr);
-    #endif
-    return Error_UNDELIVERABLE;
-}
-
-/**
- * When we send a message it goes into the CryptoAuth.
- * for the content level crypto then it goes to outgoingFromCryptoAuth then comes here.
- * Message is aligned on the beginning of the CryptoAuth header.
- */
-static inline uint8_t outgoingFromMe(struct Message* message,
-                                     struct Ducttape_MessageHeader* dtHeader,
-                                     struct SessionTable_Session* session,
-                                     struct Ducttape_pvt* context)
-{
-    // Move back to the beginning of the ip6Header behind the crypto.
-    Message_shift(message, Headers_IP6Header_SIZE, NULL);
-    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;
-
-    if (!Bits_memcmp(header->destinationAddr, context->myAddr.ip6.bytes, 16)) {
-        // This happens when an empty connect-to-me packet is sent to us,
-        // CryptoAuth is called with a message and instead of returning a decrypted message
-        // to send to the TUN, it outputs a message to send back down the wire but the
-        // header is still the same.
-        // these messages are always empty so we just flip the source and destination around
-        // and send it back.
-        Bits_memcpyConst(header->destinationAddr, header->sourceAddr, 16);
-        Bits_memcpyConst(header->sourceAddr, context->myAddr.ip6.bytes, 16);
-
-    } else {
-        // sanity check.
-        Assert_ifParanoid(!Bits_memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16));
-    }
-
-    // Need to set the length field to take into account
-    // the crypto headers which are hidden under the ipv6 packet.
-    header->payloadLength_be =
-        Endian_hostToBigEndian16(message->length - Headers_IP6Header_SIZE);
-
-
-    // Forward this call to core() which will check its validity
-    // and since it's not to us, forward it to the correct node.
-    return core(message, dtHeader, session, context);
-}
-
-static inline int incomingFromRouter(struct Message* message,
-                                     struct Ducttape_MessageHeader* dtHeader,
-                                     struct SessionTable_Session* session,
-                                     struct Ducttape_pvt* context)
-{
-    uint8_t* pubKey = CryptoAuth_getHerPublicKey(session->internal);
-    if (!validEncryptedIP6(message)) {
-        // Not valid cjdns IPv6, we'll try it as an IPv4 or ICANN-IPv6 packet
-        // and check if we have an agreement with the node who sent it.
-        Message_shift(message, IpTunnel_PacketInfoHeader_SIZE, NULL);
-        struct IpTunnel_PacketInfoHeader* header =
-            (struct IpTunnel_PacketInfoHeader*) message->bytes;
-
-        uint8_t* addr = session->ip6;
-        Bits_memcpyConst(header->nodeIp6Addr, addr, 16);
-        Bits_memcpyConst(header->nodeKey, pubKey, 32);
-
-        struct Iface* ipTun = &context->ipTunnel->nodeInterface;
-        return ipTun->sendMessage(message, ipTun);
-    }
-
-    struct Address srcAddr = {
-        .path = Endian_bigEndianToHost64(dtHeader->switchHeader->label_be)
-    };
-    Bits_memcpyConst(srcAddr.key, pubKey, 32);
-
-    //Log_debug(context->logger, "Got message from router.\n");
-    return core(message, dtHeader, session, context);
-}
-
-
-static uint8_t incomingFromCryptoAuth(struct Message* message, struct Iface* iface)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->receiverContext);
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
-    enum Ducttape_SessionLayer layer = dtHeader->layer;
-    dtHeader->layer = Ducttape_SessionLayer_INVALID;
-    struct SessionTable_Session* session =
-        SessionTable_sessionForHandle(dtHeader->receiveHandle, context->sm);
-
-    if (!session) {
-        // This should never happen but there's no strong preventitive.
-        Log_info(context->logger, "SESSION DISAPPEARED!");
-        return 0;
-    }
-
-    // If the packet came from a new session, put the send handle in the session.
-    if (CryptoAuth_getState(session->internal) < CryptoAuth_ESTABLISHED) {
-        // If this is true then the incoming message is definitely a handshake.
-        if (message->length < 4) {
-            debugHandles0(context->logger, session, "runt");
-            return Error_INVALID;
-        }
-        if (layer == Ducttape_SessionLayer_OUTER) {
-            Message_pop(message, &session->sendHandle_be, 4, NULL);
-        } else {
-            // inner layer, always grab the handle
-            Message_pop(message, &session->sendHandle_be, 4, NULL);
-            debugHandles0(context->logger, session, "New session, incoming layer3");
-        }
-    }
-
-    switch (layer) {
-        case Ducttape_SessionLayer_OUTER:
-            return incomingFromRouter(message, dtHeader, session, context);
-        case Ducttape_SessionLayer_INNER:
-            return incomingForMe(message, dtHeader, session, context,
-                                 CryptoAuth_getHerPublicKey(session->internal));
-        default:
-            Assert_true(false);
-    }
-    // never reached.
-    return 0;
-}
-
-static uint8_t outgoingFromCryptoAuth(struct Message* message, struct Iface* iface)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) iface->senderContext);
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, false);
-    struct SessionTable_Session* session =
-        SessionTable_sessionForHandle(dtHeader->receiveHandle, context->sm);
-
-    enum Ducttape_SessionLayer layer = dtHeader->layer;
-    dtHeader->layer = Ducttape_SessionLayer_INVALID;
-
-    if (!session) {
-        // This should never happen but there's no strong preventitive.
-        Log_info(context->logger, "SESSION DISAPPEARED!");
-        return 0;
-    }
-
-    if (layer == Ducttape_SessionLayer_OUTER) {
-        return sendToSwitch(message, dtHeader, session, context);
-    } else if (layer == Ducttape_SessionLayer_INNER) {
-        //Log_debug(context->logger, "Sending layer3 message");
-        return outgoingFromMe(message, dtHeader, session, context);
-    } else {
-        Assert_true(0);
-    }
-}
-
-/**
- * This is called as sendMessage() by the switch.
- * There is only one switch interface which sends all traffic.
- * message is aligned on the beginning of the switch header.
- */
-static uint8_t incomingFromSwitch(struct Message* message, struct Iface* switchIf)
-{
-    struct Ducttape_pvt* ctx = Identity_containerOf(switchIf, struct Ducttape_pvt, pub.switchIf);
-
-    struct Ducttape_MessageHeader* dtHeader = getDtHeader(message, true);
-
-    struct SwitchHeader* switchHeader = (struct SwitchHeader*) message->bytes;
-    Message_shift(message, -SwitchHeader_SIZE, NULL);
-
-    // The label comes in reversed from the switch because the switch doesn't know that we aren't
-    // another switch ready to parse more bits, bit reversing the label yields the source address.
-    switchHeader->label_be = Bits_bitReverse64(switchHeader->label_be);
-
-    if (message->length < 8) {
-        Log_info(context->logger, "runt");
-        return Error_INVALID;
-    }
-
-    Assert_true(!((uintptr_t)message->bytes % 4));
-
-    // #1 try to get the session using the handle.
-
-    uint32_t nonceOrHandle = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
-
-    struct SessionTable_Session* session = NULL;
-
-    if (nonceOrHandle > 3) {
-        if (nonceOrHandle == 0xffffffff) {
-            Message_shift(message, SwitchHeader_SIZE, NULL);
-            return Iface_send(&context->pub.controlIf, message);
-        }
-        Message_shift(message, -4, NULL);
-
-        // Run message, it's a handle.
-        session = SessionTable_sessionForHandle(nonceOrHandle, context->sm);
-
-        if (session) {
-            /*
-            debugHandlesAndLabel(context->logger, session,
-                                 Endian_bigEndianToHost64(switchHeader->label_be),
-                                 "running session nonce[%u]",
-                                 nonce);
-            */
-            dtHeader->receiveHandle = nonceOrHandle;
-        } else {
-            Log_debug(context->logger, "Got message with unrecognized handle");
-        }
-    } else if (message->length >= CryptoHeader_SIZE) {
-        union CryptoHeader* caHeader = (union CryptoHeader*) message->bytes;
-        uint8_t ip6[16];
-        uint8_t* herKey = caHeader->handshake.publicKey;
-        AddressCalc_addressForPublicKey(ip6, herKey);
-        // a packet which claims to be "from us" causes problems
-        if (AddressCalc_validAddress(ip6) && Bits_memcmp(ip6, &context->myAddr, 16)) {
-            session = SessionTable_getSession(ip6, herKey, context->sm);
-            debugHandlesAndLabel(context->logger, session,
-                                 Endian_bigEndianToHost64(switchHeader->label_be),
-                                 "new session nonce[%d]", nonceOrHandle);
-            dtHeader->receiveHandle = Endian_bigEndianToHost32(session->receiveHandle_be);
-        } else {
-            Log_debug(context->logger, "Got message with invalid ip addr");
-        }
-    }
-
-    if (!session) {
-        #ifdef Log_INFO
-            uint8_t path[20];
-            AddrTools_printPath(path, Endian_bigEndianToHost64(switchHeader->label_be));
-            Log_info(context->logger, "DROP traffic packet from unknown node. [%s]", path);
-        #endif
-        return 0;
-    }
-
-    // This is needed so that the priority and other information
-    // from the switch header can be passed on properly.
-    dtHeader->switchHeader = switchHeader;
-
-    // Keep track of a known path to the node so we can always answer them.
-    session->knownSwitchLabel = Endian_bigEndianToHost64(switchHeader->label_be);
-
-    // This goes to incomingFromCryptoAuth()
-    // then incomingFromRouter() then core()
-    dtHeader->layer = Ducttape_SessionLayer_OUTER;
-
-    if (Iface_send(&session->external, message) == Error_AUTHENTICATION) {
-        debugHandlesAndLabel(context->logger, session,
-                             Endian_bigEndianToHost64(switchHeader->label_be),
-                             "DROP Failed decrypting message NoH[%d] state[%s]",
-                             nonceOrHandle,
-                             CryptoAuth_stateString(CryptoAuth_getState(session->internal)));
-        return Error_AUTHENTICATION;
-    }
-
-    return 0;
-}
-
-static Iface_DEFUN incomingFromControlHandler(struct Message* message, struct Iface* controlIf)
-{
-    struct Ducttape_pvt* ctx = Identity_containerOf(controlIf, struct Ducttape_pvt, pub.controlIf);
-    Assert_true(ctx->pub.switchIf.receiveMessage);
-    return Iface_send(&ctx->pub.switchIf, message);
-}
-
-static void checkStateOfSessions(void* vducttape)
-{
-    struct Ducttape_pvt* ctx = Identity_check((struct Ducttape_pvt*) vducttape);
-    if (!ctx->sessionMill) { return; }
-    struct Allocator* alloc = Allocator_child(ctx->alloc);
-    struct SessionTable_HandleList* handles = SessionTable_getHandleList(ctx->sm, alloc);
-    for (int i = 0; i < (int)handles->count; i++) {
-        struct SessionTable_Session* sess =
-            SessionTable_sessionForHandle(handles->handles[i], ctx->sm);
-        if (sess->cryptoAuthState == CryptoAuth_ESTABLISHED) { continue; }
-        if (!sess->knownSwitchLabel) { continue; }
-        if (!sess->version) { continue; }
-        uint8_t* hpk = CryptoAuth_getHerPublicKey(sess->internal);
-        if (Bits_isZero(hpk, 32)) { continue; }
-        struct Address addr = {
-            .path = sess->knownSwitchLabel,
-            .protocolVersion = sess->version
-        };
-        Bits_memcpyConst(addr.key, hpk, 32);
-        Address_getPrefix(&addr);
-        RumorMill_addNode(ctx->sessionMill, &addr);
-    }
-    Allocator_free(alloc);
-}
-
-struct Ducttape* Ducttape_new(uint8_t privateKey[32],
-                              struct Router* router,
-                              struct EventBase* eventBase,
-                              struct Allocator* allocator,
-                              struct Log* logger,
-                              struct IpTunnel* ipTun,
-                              struct Random* rand,
-                              struct RumorMill* sessionMill)
-{
-    struct Ducttape_pvt* context = Allocator_calloc(allocator, sizeof(struct Ducttape_pvt), 1);
-    context->router = router;
-    context->logger = logger;
-    context->eventBase = eventBase;
-    context->alloc = allocator;
-    context->sessionMill = sessionMill;
-    context->pub.magicIf.send = incomingFromMagicInterface;
-    context->pub.dhtIf.send = incomingFromDHTInterface;
-    Identity_set(context);
-
-    context->ipTunnel = ipTun;
-
-    ipTun->nodeInterface.receiveMessage = sendToNode;
-    ipTun->nodeInterface.receiverContext = context;
-    ipTun->tunInterface.receiveMessage = sendToTun;
-    ipTun->tunInterface.receiverContext = context;
-
-    struct CryptoAuth* cryptoAuth =
-        CryptoAuth_new(allocator, privateKey, eventBase, logger, rand);
-    Bits_memcpyConst(context->myAddr.key, cryptoAuth->publicKey, 32);
-    Address_getPrefix(&context->myAddr);
-
-    context->sm = SessionTable_new(incomingFromCryptoAuth,
-                                     outgoingFromCryptoAuth,
-                                     context,
-                                     eventBase,
-                                     cryptoAuth,
-                                     rand,
-                                     allocator);
-    context->pub.sessionTable = context->sm;
-
-    context->pub.switchIf.sendMessage = incomingFromSwitch;
-    context->pub.switchIf.allocator = allocator;
-
-    // setup the control frame interface.
-    context->pub.controlIf.send = incomingFromControlHandler;
-
-    Timeout_setInterval(checkStateOfSessions, context, 10000, eventBase, allocator);
-
-    return &context->pub;
-}
-
-void Ducttape_setUserInterface(struct Ducttape* dt, struct Iface* userIf)
-{
-    struct Ducttape_pvt* context = Identity_check((struct Ducttape_pvt*) dt);
-    context->userIf = userIf;
-    userIf->receiveMessage = incomingFromTun;
-    userIf->receiverContext = context;
-}

+ 0 - 95
net/Ducttape.h

@@ -1,95 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef Ducttape_H
-#define Ducttape_H
-
-#include "dht/dhtcore/Router.h"
-#include "dht/dhtcore/RumorMill.h"
-#include "switch/SwitchCore.h"
-#include "memory/Allocator.h"
-#include "tunnel/IpTunnel.h"
-#include "wire/Headers.h"
-#include "wire/SwitchHeader.h"
-#include "util/events/EventBase.h"
-#include "util/Linker.h"
-Linker_require("net/Ducttape.c")
-
-struct Ducttape
-{
-    /**
-     * Interface which sends and receives (switch level) CTRL frames.
-     * Content is: [ SwitchHeader ][ 0xffffffff ][ ctrl header ][ content... ]
-     */
-    struct Iface controlIf;
-
-    /**
-     * Interface which receives and sends messages to other routers.
-     * Content is: [ Address ][ content... ]
-     */
-    struct Iface dhtIf;
-
-    /**
-     * Interface which receives packets (from tun) that are addressed to "magic address" fc00::1
-     * Content is: [ IPv6 header ][ content... ]
-     */
-    struct Iface magicIf;
-
-    /**
-     * 
-     */
-    struct Iface tunIf;
-
-    struct Iface switchIf;
-
-    struct SessionTable* sessionTable;
-};
-
-struct Ducttape* Ducttape_new(uint8_t privateKey[32],
-                              struct Router* router,
-                              struct EventBase* eventBase,
-                              struct Allocator* allocator,
-                              struct Log* logger,
-                              struct IpTunnel* ipTun,
-                              struct Random* rand,
-                              struct RumorMill* sessionMill);
-
-/**
- * Set the interface which the user will use to communicate with the network.
- *
- * @param dt the ducttape struct.
- * @param userIf the (TUN) interface which will be used to send and receive packets.
- */
-void Ducttape_setUserInterface(struct Ducttape* dt, struct Iface* userIf);
-
-/**
- * The structure of data which should be the beginning
- * of the content in the message sent to injectIncomingForMe.
- */
-struct Ducttape_IncomingForMe
-{
-    struct SwitchHeader switchHeader;
-    struct Headers_IP6Header ip6Header;
-};
-
-/**
- * Inject a packet into the stream of packets destine for this node.
- * The message must contain switch header, ipv6 header, then content.
- * None of it should be encrypted and there should be no CryptoAuth headers.
- */
-uint8_t Ducttape_injectIncomingForMe(struct Message* message,
-                                     struct Ducttape* ducttape,
-                                     uint8_t herPublicKey[32]);
-
-#endif

+ 0 - 107
net/Ducttape_pvt.h

@@ -1,107 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef Ducttape_pvt_H
-#define Ducttape_pvt_H
-
-#include "dht/Address.h"
-#include "util/version/Version.h"
-#include "dht/dhtcore/Router.h"
-#include "util/log/Log.h"
-#include "net/Ducttape.h"
-#include "util/events/EventBase.h"
-#include "util/Identity.h"
-
-#include <stdint.h>
-
-enum Ducttape_SessionLayer {
-    Ducttape_SessionLayer_INVALID = 0,
-    Ducttape_SessionLayer_INNER,
-    Ducttape_SessionLayer_OUTER
-};
-
-/**
- * A network module which connects the DHT router to the SwitchCore.
- * This module's job is to grab messages off of the switch,
- * determine the peer's address,
- * map the message to the appropriate CryptoAuth obj and decrypt,
- * and send the message toward the DHT core.
- */
-
-struct Ducttape_pvt
-{
-    /** the public fields. */
-    struct Ducttape pub;
-
-    struct Router* router;
-
-    /** The interface which is used by the operator of the node to communicate in the network. */
-    struct Iface* userIf;
-
-    struct Address myAddr;
-
-    struct SessionTable* sm;
-
-    struct EventBase* eventBase;
-
-    struct RumorMill* sessionMill;
-
-    struct Log* logger;
-
-    /** For tunneling IPv4 and ICANN IPv6 packets. */
-    struct IpTunnel* ipTunnel;
-
-    struct Allocator* alloc;
-
-    /** Number of milliseconds to wait between searches for a node to send arbitrary data to. */
-    uint32_t timeBetweenSearches;
-
-    /** Absolute time of last search for node to send arbitrary data to. */
-    uint64_t timeOfLastSearch;
-
-    Identity
-};
-
-
-struct Ducttape_MessageHeader
-{
-    /**
-     * This is to tell the code whether it is in the outer later of encryption or the inner layer.
-     */
-    enum Ducttape_SessionLayer layer;
-
-    struct SwitchHeader* switchHeader;
-    struct Headers_IP6Header* ip6Header;
-
-    uint32_t nextHopReceiveHandle;
-
-    uint32_t receiveHandle;
-
-    uint64_t switchLabel;
-
-#ifdef Version_2_COMPAT
-    /**
-     * Cache the session handle and version so that if an incoming (stray) packet fails to
-     * authenticate it won't assasinate the session.
-     */
-    uint32_t currentSessionSendHandle_be;
-    uint32_t currentSessionVersion;
-#endif
-
-    Identity
-};
-
-#define Ducttape_MessageHeader_SIZE ((int)sizeof(struct Ducttape_MessageHeader))
-
-#endif

+ 1 - 1
net/SessionManager.c

@@ -115,7 +115,7 @@ static void sendSession(struct SessionManager_Session_pvt* sess,
     Iface_send(&sess->sessionManager->eventIf, msg);
     Allocator_free(alloc);
 }
-/* TODO: we're not trashing old sessions!
+/* XXX(cjd): we're not trashing old sessions!
 static int sessionCleanup(struct Allocator_OnFreeJob* job)
 {
     struct SessionManager_Session_pvt* sess =

+ 0 - 225
net/SessionTable.c

@@ -1,225 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "net/SessionTable.h"
-#include "crypto/CryptoAuth.h"
-#include "crypto/AddressCalc.h"
-#include "memory/Allocator.h"
-#include "util/Bits.h"
-#include "util/events/Time.h"
-#include "util/events/Timeout.h"
-#include "wire/Error.h"
-#include "wire/Headers.h"
-#include "wire/Message.h"
-
-#include <stdint.h>
-
-/** The number of seconds of inactivity before a session should expire. */
-#define SESSION_TIMEOUT_SECONDS 180
-
-/** The number of seconds between cleanup cycles. */
-#define CLEANUP_CYCLE_SECONDS 20
-
-/** Number of milliseconds between state change announcements. */
-#define STATE_UPDATE_TIME 8000
-
-/** Handle numbers 0-3 are reserved for CryptoAuth nonces. */
-#define MIN_FIRST_HANDLE 4
-
-#define MAX_FIRST_HANDLE 100000
-
-struct SessionTable_Session_pvt
-{
-    struct SessionTable_Session pub;
-    struct SessionTable* const sm;
-    Identity
-};
-
-struct Ip6
-{
-    uint8_t bytes[16];
-};
-#define Map_NAME OfSessionsByIp6
-#define Map_KEY_TYPE struct Ip6
-#define Map_VALUE_TYPE struct SessionTable_Session*
-#define Map_ENABLE_HANDLES
-#include "util/Map.h"
-
-
-/**
- * A SessionTable is a mechanism for getting a crypto session based on a given key.
- */
-struct SessionTable
-{
-    struct Map_OfSessionsByIp6 ifaceMap;
-
-    struct Allocator* allocator;
-
-    struct Timeout* cleanupInterval;
-
-    struct CryptoAuth* cryptoAuth;
-
-    /** The first handle number to start with, randomized at startup to reduce collisions. */
-    uint32_t first;
-
-    Identity
-};
-/*
-static void cleanup(void* vsm)
-{
-    struct SessionTable* sm = (struct SessionTable*) vsm;
-    uint64_t cutoffTime =
-        Time_currentTimeMilliseconds(sm->eventBase) - (SESSION_TIMEOUT_SECONDS * 1000);
-    for (uint32_t i = 0; i < sm->ifaceMap.count; i++) {
-        struct SessionTable_Session* sess = &sm->ifaceMap.values[i]->pub;
-
-        // Received a message since cutoff time.
-        if (sess->timeOfLastIn > cutoffTime) { continue; }
-
-        // Received a message (ever) or session is not older than cutoff time.
-        if (sess->timeOfLastIn || sess->timeOfCreation > cutoffTime) { continue; }
-
-        struct Allocator* ifAllocator = sess->external.allocator;
-        Map_OfSessionsByIp6_remove(i, &sm->ifaceMap);
-        Allocator_free(ifAllocator);
-        i--;
-    }
-}*/
-
-static int removeSession(struct Allocator_OnFreeJob* job)
-{
-    struct SessionTable_Session* s = (struct SessionTable_Session*) job->userData;
-    struct SessionTable* st = Identity_check((struct SessionTable*) s->sessionTable);
-    int index = Map_OfSessionsByIp6_indexForHandle(s->receiveHandle - st->first, &st->ifaceMap);
-    Assert_true(index >= 0);
-    Map_OfSessionsByIp6_remove(index, &st->ifaceMap);
-    return 0;
-}
-
-static void check(struct SessionTable* st, int mapIndex)
-{
-    Assert_true(st->ifaceMap.keys[mapIndex].bytes[0] == 0xfc);
-    uint8_t* herPubKey = st->ifaceMap.values[mapIndex].caSession->herPublicKey;
-    if (!Bits_isZero(herPubKey, 32)) {
-        uint8_t ip6[16];
-        AddressCalc_addressForPublicKey(ip6, herPubKey);
-        Assert_true(!Bits_memcmp(&st->ifaceMap.keys[mapIndex], ip6, 16));
-    }
-}
-/*
-static void stateChange(struct SessionTable_Session_pvt* ss,
-                        uint64_t prevTimeOfLastIn,
-                        uint64_t prevTimeOfLastOut,
-                        int prevCryptoAuthState)
-{
-}
-
-static uint8_t sendMessage(struct Message* msg, struct Iface* iface)
-{
-    struct SessionTable_Session_pvt* ss =
-        Identity_check((struct SessionTable_Session_pvt*)iface);
-
-    uint64_t timeOfLastOut = ss->pub.timeOfLastOut;
-    ss->pub.timeOfLastOut = Time_currentTimeMilliseconds(ss->sm->eventBase);
-    int prevState = ss->pub.cryptoAuthState;
-    ss->pub.cryptoAuthState = CryptoAuth_getState(ss->pub.internal);
-    if ((ss->pub.timeOfLastOut - timeOfLastOut) > STATE_UPDATE_TIME
-        || prevState != ss->pub.cryptoAuthState)
-    {
-        stateChange(ss, ss->pub.timeOfLastIn, timeOfLastOut, prevState);
-    }
-
-    return Interface_sendMessage(&ss->sm->iface, msg);
-}
-
-static uint8_t receiveMessage(struct Message* msg, struct Iface* iface)
-{
-    struct SessionTable_Session_pvt* ss =
-        Identity_check((struct SessionTable_Session_pvt*)iface->receiverContext);
-
-    uint64_t timeOfLastIn = ss->pub.timeOfLastIn;
-    ss->pub.timeOfLastIn = Time_currentTimeMilliseconds(ss->sm->eventBase);
-    int prevState = ss->pub.cryptoAuthState;
-    ss->pub.cryptoAuthState = CryptoAuth_getState(ss->pub.internal);
-    if ((ss->pub.timeOfLastIn - timeOfLastIn) > STATE_UPDATE_TIME
-        || prevState != ss->pub.cryptoAuthState)
-    {
-        stateChange(ss, timeOfLastIn, ss->pub.timeOfLastOut, prevState);
-    }
-
-    return Iface_send(&ss->sm->iface, msg);
-}*/
-
-struct SessionTable_Session* SessionTable_sessionForIp6(uint8_t* ip6, struct SessionTable* st)
-{
-    int ifaceIndex = Map_OfSessionsByIp6_indexForKey((struct Ip6*)ip6, &st->ifaceMap);
-    if (ifaceIndex == -1) { return NULL; }
-    check(st, ifaceIndex);
-    return st->ifaceMap.values[ifaceIndex];
-}
-
-void SessionTable_regSession(uint8_t* ip6,
-                             uint8_t cryptoKey[32],
-                             struct SessionTable_Session* session,
-                             struct Allocator* alloc,
-                             struct SessionTable* st)
-{
-    Assert_true(cryptoKey);
-    Assert_true(!SessionTable_sessionForIp6(ip6, st));
-    session->sessionTable = st;
-    session->caSession = CryptoAuth_newSession(cryptoKey, ip6, false, "inner", st->cryptoAuth);
-    int ifaceIndex = Map_OfSessionsByIp6_put((struct Ip6*)ip6, &ss, &st->ifaceMap);
-    session->receiveHandle = st->ifaceMap.handles[ifaceIndex] + st->first;
-    check(st, ifaceIndex);
-    Allocator_onFree(alloc, removeSession, session);
-    return &Identity_check(sm->ifaceMap.values[ifaceIndex])->pub;
-}
-
-struct SessionTable_Session* SessionTable_sessionForHandle(uint32_t handle, struct SessionTable* st)
-{
-    int index = Map_OfSessionsByIp6_indexForHandle(handle - st->first, &st->ifaceMap);
-    if (index < 0) { return NULL; }
-    check(st, index);
-    return st->ifaceMap.values[index];
-}
-
-struct SessionTable_HandleList* SessionTable_getHandleList(struct SessionTable* st,
-                                                           struct Allocator* alloc)
-{
-    struct SessionTable_HandleList* out =
-        Allocator_malloc(alloc, sizeof(struct SessionTable_HandleList));
-    uint32_t* buff = Allocator_malloc(alloc, 4 * st->ifaceMap.count);
-    Bits_memcpy(buff, st->ifaceMap.handles, 4 * st->ifaceMap.count);
-    out->handles = buff;
-    out->count = st->ifaceMap.count;
-    for (int i = 0; i < (int)out->count; i++) {
-        buff[i] += st->first;
-    }
-    return out;
-}
-
-struct SessionTable* SessionTable_new(struct CryptoAuth* cryptoAuth,
-                                      struct Random* rand,
-                                      struct Allocator* allocator)
-{
-    struct SessionTable* st = Allocator_calloc(allocator, sizeof(struct SessionTable), 1);
-    Identity_set(st);
-    st->ifaceMap.allocator = allocator;
-    st->cryptoAuth = cryptoAuth;
-    st->allocator = allocator;
-    st->first = (Random_uint32(rand) % (MAX_FIRST_HANDLE - MIN_FIRST_HANDLE)) + MIN_FIRST_HANDLE;
-  //  st->cleanupInterval =
-//        Timeout_setInterval(cleanup, sm, 1000 * CLEANUP_CYCLE_SECONDS, eventBase, allocator);
-    return st;
-}

+ 0 - 112
net/SessionTable.h

@@ -1,112 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef SessionManager_H
-#define SessionManager_H
-
-#error poisoned
-
-#include "crypto/CryptoAuth.h"
-#include "crypto/random/Random.h"
-#include "memory/Allocator.h"
-#include "util/events/EventBase.h"
-#include "util/Linker.h"
-Linker_require("net/SessionManager.c")
-
-#include <stdint.h>
-
-struct SessionManager;
-
-struct SessionManager_Session
-{
-    struct CryptoAuth_Session* caSession;
-
-    /** The handle which will be used to lookup this session on our side. */
-    uint32_t receiveHandle;
-
-    //struct Allocator* alloc;
-
-
-    /** When the last message was received on this session (milliseconds since epoch). */
-    //uint64_t timeOfLastIn;
-
-    /** When the last message was sent on this session (milliseconds since epoch). */
-    //uint64_t timeOfLastOut;
-
-    /** When this session was created. */
-    //uint64_t timeOfCreation;
-
-    /** The CryptoAuth state as of the last message. See: CryptoAuth_getState() */
-    //int cryptoAuthState;
-
-    /** The handle which we are expected to send to identify ourselves */
-    //uint32_t sendHandle;
-
-    /** The version of the other node. */
-    //uint32_t version;
-
-    /** The best known switch label for reaching this node. */
-    //uint64_t sendSwitchLabel;
-
-    /** The switch label which this node uses for reaching us. */
-    //uint64_t recvSwitchLabel;
-};
-
-struct SessionManager_HandleList
-{
-    int count;
-    uint32_t* handles;
-};
-
-/**
- * Create a new session manager for keeping track of and expiring crypto sessions.
- * The typical use case is discriminating between packets by ip address, keyOffset is the number
- * of bytes between the beginning of each message and the beginning of the ip address and keySize
- * is the number of bytes in the address.
- *
- * @param eventBase the libevent event base.
- * @param cryptoAuth the cryptoauthenticator for the sessions.
- * @param allocator means of getting memory.
- * @return a session manager.
- */
-struct SessionManager* SessionManager_new(struct CryptoAuth* cryptoAuth,
-                                      struct Random* rand,
-                                      struct Allocator* allocator);
-
-void SessionManager_regSession(uint8_t* ip6,
-                             uint8_t cryptoKey[32],
-                             struct SessionManager_Session* session,
-                             struct Allocator* alloc,
-                             struct SessionManager* st);
-
-/**
- * Get a session by its handle.
- *
- * @param handle an opaque handle associated with the session.
- * @param sm the session manager.
- * @return the sesssion if there is one by that handle or null.
- */
-struct SessionManager_Session* SessionManager_sessionForHandle(uint32_t handle,
-                                                               struct SessionManager* sm);
-
-struct SessionManager_Session* SessionManager_sessionForIp6(uint8_t* lookupKey,
-                                                            struct SessionManager* sm);
-
-/**
- * Get the list of all handles.
- */
-struct SessionManager_HandleList* SessionManager_getHandleList(struct SessionManager* sm,
-                                                           struct Allocator* alloc);
-
-#endif

+ 6 - 2
node_build/Codestyle.js

@@ -142,8 +142,12 @@ var parseFile = function (fileName, fileContent) {
             error("trailing whitespace.");
         }
 
-        if (/[^A-Z](TODO|FIXME|XXX)[^\(A-Z]/.test(line)) {
-            error("Please take responsibility for your TODO: eg: // TODO(cjd): make this work");
+        if (/[^A-Z](TODO|FIXME|XXX)[^A-Z]/.test(line)) {
+            if (/[^A-Z](TODO|FIXME|XXX)[^\(A-Z]/.test(line)) {
+                error("Please take responsibility for your TODO: eg: // TODO(cjd): make this work");
+            } else {
+                console.log(lineInfo + ' ' + line.replace(/[ \/]*/, ''));
+            }
         }
 
         if (/(if|for|while)\(/.test(line)) {

+ 9 - 4
test/RootTest.h

@@ -20,7 +20,11 @@
 
 #define RootTest_toStr(x) RootTest_toStr2(x)
 #define RootTest_toStr2(x) #x
-<?js file.RootTest_mainFunc = RootTest_toStr(main) ?>
+<?js
+    file.RootTest_mainFunc = RootTest_toStr(main);
+    file.RootTest_mainName = file.RootTest_mainFunc.replace(/_main$/, '');
+?>
+#define RootTest_mainName <?js return '"' + file.RootTest_mainName + '"' ?>
 
 #define RootTest_main <?js return 'RootTest_'+file.RootTest_mainFunc; ?>
 
@@ -40,9 +44,10 @@ int main(int argc, char** argv)
     if (runIt) {
         return RootTest_main(j,argv);
     } else {
-        fprintf(stderr, "\nRoot test %s disabled, use [%s +roottest] to include it\n",
-                RootTest_toStr(main),
-                (argc > 0) ? argv[0] : "");
+        fprintf(stderr, "\nRoot test %s disabled, use [%s %s +roottest] to include it\n",
+                RootTest_mainName,
+                (argc > 0) ? argv[0] : "",
+                RootTest_mainName);
     }
     return 0;
 }

+ 0 - 102
test/cjdroute_injection_test_disabled.c

@@ -1,102 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "crypto/AddressCalc.h"
-#include "memory/MallocAllocator.h"
-#include "memory/Allocator.h"
-#include "util/CString.h"
-#include "wire/SwitchHeader.h"
-#include "test/TestFramework.h"
-
-#include <stdio.h>
-
-#define PADDING 512
-
-int main()
-{
-    // This is valid benc but it takes over 75k of memory (on an amd64)
-    // to build a structure representing it.
-    char* evilBenc =
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "d1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:ad1:a"
-        "3:lol"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
-        "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
-
-    struct Allocator* alloc = MallocAllocator_new(1<<22);
-    struct Ducttape* dt =
-        TestFramework_setUp("0123456789abcdefghijklmnopqrstuv", alloc, NULL, NULL, NULL)->ducttape;
-
-    // This has to be limited because we are checking for an OOM issue.
-    struct Allocator* allocator = MallocAllocator_new(85000);
-    uint16_t buffLen = sizeof(struct Ducttape_IncomingForMe) + 8 + CString_strlen(evilBenc);
-    uint8_t* buff = Allocator_calloc(allocator, buffLen + PADDING, 1);
-
-    struct Headers_IP6Header* ip6 = (struct Headers_IP6Header*) (buff + SwitchHeader_SIZE);
-    uint8_t* herPublicKey = (uint8_t*) "0123456789abcdefghijklmnopqrstuv";
-    AddressCalc_addressForPublicKey(ip6->sourceAddr, herPublicKey);
-
-    struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) (ip6 + 1);
-    ip6->hopLimit = 0;
-    ip6->nextHeader = 17;
-    udp->srcPort_be = 0;
-    udp->destPort_be = 0;
-    udp->length_be = Endian_hostToBigEndian16(CString_strlen(evilBenc));
-
-    CString_strncpy((char*)(udp + 1), evilBenc, CString_strlen(evilBenc));
-
-    struct Message m = { .bytes = buff+PADDING, .length = buffLen, .padding = PADDING };
-
-    Ducttape_injectIncomingForMe(&m, dt, herPublicKey);
-
-    Allocator_free(alloc);
-    Allocator_free(allocator);
-    return 0;
-}

+ 0 - 107
test/cjdroute_routerPing_test_disabled.c

@@ -1,107 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "crypto/AddressCalc.h"
-#include "memory/MallocAllocator.h"
-#include "memory/Allocator.h"
-#include "util/Base32.h"
-#include "util/Checksum.h"
-#include "util/CString.h"
-#include "test/TestFramework.h"
-#include "wire/SwitchHeader.h"
-
-#include <stdio.h>
-
-#define PADDING 512
-
-static uint8_t catchResponse(struct Message* msg, struct Iface* iface)
-{
-    iface->receiverContext = msg;
-    return 0;
-}
-
-int main()
-{
-    return 0; // TODO(cjd): make this work again
-
-    char* pingBenc = "d1:q4:ping4:txid4:abcd1:pi2ee";
-    struct Allocator* alloc = MallocAllocator_new(1<<22);
-    struct TestFramework* tf =
-        TestFramework_setUp("0123456789abcdefghijklmnopqrstuv", alloc, NULL, NULL, NULL);
-    struct Ducttape_pvt* dt = (struct Ducttape_pvt*) tf->ducttape;
-
-    struct Allocator* allocator = MallocAllocator_new(85000);
-    uint16_t buffLen = sizeof(struct Ducttape_IncomingForMe) + 8 + CString_strlen(pingBenc);
-    uint8_t* buff = Allocator_calloc(allocator, buffLen+PADDING, 1);
-    struct SwitchHeader* sh = (struct SwitchHeader*) (buff + PADDING);
-    sh->label_be = Endian_hostToBigEndian64(4);
-    struct Headers_IP6Header* ip6 = (struct Headers_IP6Header*) &sh[1];
-
-    uint8_t herPublicKey[32];
-    Base32_decode(herPublicKey, 32,
-                  (uint8_t*) "0z5tscp8td1sc6cv4htp7jbls79ltqxw9pbg190x0kbm1lguqtx0", 52);
-    AddressCalc_addressForPublicKey(ip6->sourceAddr, herPublicKey);
-
-    struct Headers_UDPHeader* udp = (struct Headers_UDPHeader*) &ip6[1];
-    ip6->hopLimit = 0;
-    ip6->nextHeader = 17;
-    udp->srcPort_be = 0;
-    udp->destPort_be = 0;
-    udp->length_be = Endian_hostToBigEndian16(CString_strlen(pingBenc));
-
-    CString_strncpy((char*)(udp + 1), pingBenc, CString_strlen(pingBenc));
-
-    dt->pub.switchIf.receiveMessage = catchResponse;
-    dt->pub.switchIf.receiverContext = NULL;
-
-    // bad checksum
-    udp->checksum_be = 1;
-    struct Message m = {
-        .bytes = buff+PADDING,
-        .length = buffLen,
-        .padding = PADDING,
-        .alloc = alloc
-    };
-    Ducttape_injectIncomingForMe(&m, &dt->pub, herPublicKey);
-    Assert_true(!dt->pub.switchIf.receiverContext);
-
-    // zero checksum
-    udp->checksum_be = 0;
-    struct Message m2 = {
-        .bytes = buff+PADDING,
-        .length = buffLen,
-        .padding = PADDING,
-        .alloc = alloc
-    };
-    Ducttape_injectIncomingForMe(&m2, &dt->pub, herPublicKey);
-    Assert_true(!dt->pub.switchIf.receiverContext);
-
-    // good checksum
-    udp->checksum_be =
-        Checksum_udpIp6(ip6->sourceAddr,
-                        (uint8_t*)udp,
-                        CString_strlen(pingBenc) + Headers_UDPHeader_SIZE);
-    struct Message m3 = {
-        .bytes = buff+PADDING,
-        .length = buffLen,
-        .padding = PADDING,
-        .alloc = alloc
-    };
-    Ducttape_injectIncomingForMe(&m3, &dt->pub, herPublicKey);
-    Assert_true(dt->pub.switchIf.receiverContext);
-
-    Allocator_free(alloc);
-    Allocator_free(allocator);
-    return 0;
-}

+ 0 - 270
test/threeNodes_test_disabled.c

@@ -1,270 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "crypto/Key.h"
-#include "io/FileWriter.h"
-#include "memory/MallocAllocator.h"
-#include "memory/Allocator.h"
-#include "util/Base32.h"
-#include "util/Checksum.h"
-#include "util/log/WriterLog.h"
-#include "test/TestFramework.h"
-#include "wire/Headers.h"
-#include "wire/Ethernet.h"
-#include "interface/tuntap/TUNMessageType.h"
-#include "util/Hex.h"
-#include "util/events/Time.h"
-#include "util/events/Timeout.h"
-#include "dht/dhtcore/NodeStore.h"
-
-#include <stdio.h>
-
-#define TUNC 3
-#define TUNB 2
-#define TUNA 1
-static uint8_t incomingTunC(struct Message* msg, struct Iface* iface)
-{
-    Assert_true(TUNMessageType_pop(msg, NULL) == Ethernet_TYPE_IP6);
-    Message_shift(msg, -Headers_IP6Header_SIZE, NULL);
-    printf("Message from TUN in node C [%s] [%d]\n", msg->bytes, msg->length);
-    *((int*)iface->senderContext) = TUNC;
-    return 0;
-}
-
-static uint8_t incomingTunB(struct Message* msg, struct Iface* iface)
-{
-    Assert_true(TUNMessageType_pop(msg, NULL) == Ethernet_TYPE_IP6);
-    Message_shift(msg, -Headers_IP6Header_SIZE, NULL);
-    printf("Message from TUN in node B [%s]\n", msg->bytes);
-    *((int*)iface->senderContext) = TUNB;
-    return 0;
-}
-
-static uint8_t incomingTunA(struct Message* msg, struct Iface* iface)
-{
-    Assert_true(TUNMessageType_pop(msg, NULL) == Ethernet_TYPE_IP6);
-    Message_shift(msg, -Headers_IP6Header_SIZE, NULL);
-    uint8_t buff[1024];
-    Hex_encode(buff, 1024, msg->bytes, msg->length);
-    printf("Message from TUN in node A [%s] [%d] [%s]\n", msg->bytes, msg->length, buff);
-    *((int*)iface->senderContext) = TUNA;
-    return 0;
-}
-
-struct ThreeNodes;
-
-typedef void (RunTest)(struct ThreeNodes* ctx);
-
-struct ThreeNodes
-{
-    struct Iface tunIfC;
-    struct TestFramework* nodeC;
-
-    struct Iface tunIfB;
-    struct TestFramework* nodeB;
-
-    struct Iface tunIfA;
-    struct TestFramework* nodeA;
-    int messageFrom;
-
-    struct Timeout* checkLinkageTimeout;
-    struct Log* logger;
-    struct EventBase* base;
-
-#define ThreeNodes_state_AB_COMPLETE 1
-#define ThreeNodes_state_CB_COMPLETE 2
-    int state;
-
-    uint64_t startTime;
-
-    RunTest* runTest;
-
-    Identity
-};
-
-static void notLinkedYet(struct ThreeNodes* ctx)
-{
-    uint64_t now = Time_currentTimeMilliseconds(ctx->base);
-    if ((now - ctx->startTime) > 5000) {
-        Assert_failure("three nodes failed to link in 5 seconds");
-    }
-}
-
-static void checkLinkage(void* vThreeNodes)
-{
-    struct ThreeNodes* ctx = Identity_check((struct ThreeNodes*) vThreeNodes);
-
-    if (ctx->nodeA->nodeStore->nodeCount < 1) { notLinkedYet(ctx); return; }
-    if (ctx->state < ThreeNodes_state_AB_COMPLETE) {
-        ctx->state = ThreeNodes_state_AB_COMPLETE;
-        Log_debug(ctx->logger, "Link A and B complete");
-    }
-
-    if (ctx->nodeC->nodeStore->nodeCount < 1) { notLinkedYet(ctx); return; }
-    if (ctx->state < ThreeNodes_state_CB_COMPLETE) {
-        ctx->state = ThreeNodes_state_CB_COMPLETE;
-        Log_debug(ctx->logger, "Link C and B complete");
-    }
-
-    if (ctx->nodeB->nodeStore->nodeCount < 2) { notLinkedYet(ctx); return; }
-    Log_debug(ctx->logger, "Link C with B and A complete");
-    Log_debug(ctx->logger, "\n\nSetup Complete\n\n");
-
-    Timeout_clearTimeout(ctx->checkLinkageTimeout);
-
-    ctx->runTest(ctx);
-}
-
-static void start(struct Allocator* alloc,
-                  struct Log* logger,
-                  struct EventBase* base,
-                  struct Random* rand,
-                  RunTest* runTest)
-{
-    struct TestFramework* a =
-        TestFramework_setUp("\xad\x7e\xa3\x26\xaa\x01\x94\x0a\x25\xbc\x9e\x01\x26\x22\xdb\x69"
-                            "\x4f\xd9\xb4\x17\x7c\xf3\xf8\x91\x16\xf3\xcf\xe8\x5c\x80\xe1\x4a",
-                            alloc, base, rand, logger);
-    //"publicKey": "kmzm4w0kj9bswd5qmx74nu7kusv5pj40vcsmp781j6xxgpd59z00.k",
-    //"ipv6": "fc41:94b5:0925:7ba9:3959:11ab:a006:367a",
-
-    struct TestFramework* b =
-        TestFramework_setUp("\xea\x8d\x34\x04\xa9\x7c\xe4\xf9\xca\x7e\x24\xe6\xf1\x85\xb9\x3f"
-                            "\x01\x37\xb7\xa1\xf5\x2c\xce\xc0\x2c\xae\x03\xf1\x83\x38\x13\x24",
-                            alloc, base, rand, logger);
-    // This address was found by brute force for one which falls between A and C without being
-    // closer in either direction (XOR is bidirectional address space distance)
-    // ipv6: fc2e:3273:644e:426f:283d:e3c7:c87c:41c1
-
-    struct TestFramework* c =
-        TestFramework_setUp("\xd8\x54\x3e\x70\xb9\xae\x7c\x41\xbc\x18\xa4\x9a\x9c\xee\xca\x9c"
-                            "\xdc\x45\x01\x96\x6b\xbd\x7e\x76\xcf\x3a\x9f\xbc\x12\xed\x8b\xb4",
-                            alloc, base, rand, logger);
-    //"publicKey": "vz21tg07061s8v9mckrvgtfds7j2u5lst8cwl6nqhp81njrh5wg0.k",
-    //"ipv6": "fc1f:5b96:e1c5:625d:afde:2523:a7fa:383a",
-
-    Log_debug(a->logger, "Linking A and B");
-    TestFramework_linkNodes(b, a, false);
-
-    Log_debug(a->logger, "Linking B and C");
-    TestFramework_linkNodes(c, b, false);
-
-    struct ThreeNodes* out = Allocator_calloc(alloc, sizeof(struct ThreeNodes), 1);
-    Identity_set(out);
-    out->tunIfC.allocator = alloc;
-    out->tunIfB.allocator = alloc;
-    out->tunIfA.allocator = alloc;
-    out->tunIfC.sendMessage = incomingTunC;
-    out->tunIfB.sendMessage = incomingTunB;
-    out->tunIfA.sendMessage = incomingTunA;
-    out->tunIfC.senderContext = &out->messageFrom;
-    out->tunIfB.senderContext = &out->messageFrom;
-    out->tunIfA.senderContext = &out->messageFrom;
-    out->nodeC = c;
-    out->nodeB = b;
-    out->nodeA = a;
-    out->logger = logger;
-    out->checkLinkageTimeout = Timeout_setInterval(checkLinkage, out, 1, base, alloc);
-    out->base = base;
-    out->startTime = Time_currentTimeMilliseconds(base);
-    out->runTest = runTest;
-
-    Ducttape_setUserInterface(c->ducttape, &out->tunIfC);
-    Ducttape_setUserInterface(b->ducttape, &out->tunIfB);
-    Ducttape_setUserInterface(a->ducttape, &out->tunIfA);
-
-    Log_debug(a->logger, "Waiting for nodes to link asynchronously...");
-}
-
-static void sendMessage(struct ThreeNodes* tn,
-                        char* message,
-                        struct TestFramework* from,
-                        struct TestFramework* to)
-{
-    struct Message* msg;
-    Message_STACK(msg, 64, 512);
-
-    Bits_memcpy(msg->bytes, message, CString_strlen(message) + 1);
-    msg->length = CString_strlen(message) + 1;
-
-    TestFramework_craftIPHeader(msg, from->ip, to->ip);
-
-    msg = Message_clone(msg, from->alloc);
-
-    struct Iface* fromIf;
-
-    if (from == tn->nodeA) {
-        fromIf = &tn->tunIfA;
-    } else if (from == tn->nodeB) {
-        fromIf = &tn->tunIfB;
-    } else if (from == tn->nodeC) {
-        fromIf = &tn->tunIfC;
-    } else {
-        Assert_true(false);
-    }
-
-    TUNMessageType_push(msg, Ethernet_TYPE_IP6, NULL);
-    fromIf->receiveMessage(msg, fromIf);
-
-    if (to == tn->nodeA) {
-        Assert_true(tn->messageFrom == TUNA);
-    } else if (to == tn->nodeB) {
-        Assert_true(tn->messageFrom == TUNB);
-    } else if (to == tn->nodeC) {
-        Assert_true(tn->messageFrom == TUNC);
-    } else {
-        Assert_true(false);
-    }
-
-    TestFramework_assertLastMessageUnaltered(tn->nodeA);
-    TestFramework_assertLastMessageUnaltered(tn->nodeB);
-    TestFramework_assertLastMessageUnaltered(tn->nodeC);
-
-    tn->messageFrom = 0;
-}
-
-static void runTest(struct ThreeNodes* tn)
-{
-    sendMessage(tn, "Hello World!", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "Hello cjdns!", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "send", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "a", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "few", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "packets", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "to", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "make", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "sure", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "the", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "cryptoauth", tn->nodeA, tn->nodeC);
-    sendMessage(tn, "can", tn->nodeC, tn->nodeA);
-    sendMessage(tn, "establish", tn->nodeA, tn->nodeC);
-
-    Log_debug(tn->logger, "\n\nTest passed, shutting down\n\n");
-    EventBase_endLoop(tn->base);
-}
-
-/** Check if nodes A and C can communicate via B without A knowing that C exists. */
-int main()
-{
-    struct Allocator* alloc = MallocAllocator_new(1<<22);
-    struct Writer* logwriter = FileWriter_new(stdout, alloc);
-    struct Log* logger = WriterLog_new(logwriter, alloc);
-    struct Random* rand = Random_new(alloc, logger, NULL);
-    struct EventBase* base = EventBase_new(alloc);
-    start(alloc, logger, base, rand, runTest);
-
-    EventBase_beginLoop(base);
-    Allocator_free(alloc);
-    return 0;
-}

+ 0 - 108
util/events/libuv/FakeUDPAddrInterface.c

@@ -1,108 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "util/events/libuv/UvWrapper.h"
-#include "exception/Except.h"
-#include "memory/Allocator.h"
-#include "util/events/libuv/EventBase_pvt.h"
-#include "util/platform/Sockaddr.h"
-#include "util/Assert.h"
-#include "util/Identity.h"
-#include "wire/Message.h"
-#include "wire/Error.h"
-
-#define Map_NAME OfInterfacesByAddr
-#define Map_KEY_TYPE struct Sockaddr*
-#define Map_VALUE_TYPE struct Iface*
-#include "util/Map.h"
-
-struct FakeUDPAddrInterface {
-};
-
-struct AddrInterface* FakeUDPAddrInterface_new(struct EventBase* eventBase,
-                                               struct Sockaddr* addr,
-                                               struct Allocator* alloc,
-                                               struct Except* exHandler,
-                                               struct Log* logger)
-{
-    struct EventBase_pvt* base = EventBase_privatize(eventBase);
-    Assert_true(base->faker);
-
-    struct FakeUDPAddrInterface_pvt* context =
-        Allocator_clone(alloc, (&(struct FakeUDPAddrInterface_pvt) {
-            .pub = {
-                .generic = {
-                    .sendMessage = sendMessage,
-                    .allocator = alloc
-                },
-            },
-            .logger = logger
-        }));
-    Identity_set(context);
-
-    if (addr) {
-        Log_debug(logger, "Binding to address [%s]", Sockaddr_print(addr, alloc));
-    }
-
-    struct Sockaddr_storage ss;
-    if (!addr) {
-        Sockaddr_parse("0.0.0.0:0", &ss);
-        addr = &ss.addr;
-    }
-
-    if (Sockaddr_getPort(addr) && ) {
-//
-    }
-
-    uv_udp_init(base->loop, &context->uvHandle);
-    context->uvHandle.data = context;
-
-    int ret;
-    void* native = Sockaddr_asNative(addr);
-    if (Sockaddr_getFamily(addr) == Sockaddr_AF_INET6) {
-        ret = uv_udp_bind6(&context->uvHandle, *((struct sockaddr_in6*)native), 0);
-    } else {
-        ret = uv_udp_bind(&context->uvHandle, *((struct sockaddr_in*)native), 0);
-    }
-
-    if (ret) {
-        Except_throw(exHandler, "call to uv_udp_bind() failed [%s]",
-                     uv_strerror(ret);
-    }
-
-    ret = uv_udp_recv_start(&context->uvHandle, allocate, incoming)
-    if (ret) {
-        const char* err = uv_strerror(ret);
-        uv_close((uv_handle_t*) &context->uvHandle, NULL);
-        Except_throw(exHandler, "uv_udp_recv_start() failed [%s]", err);
-    }
-
-    int nameLen = sizeof(struct Sockaddr_storage);
-    Bits_memset(&ss, 0, sizeof(struct Sockaddr_storage));
-    ret = uv_udp_getsockname(&context->uvHandle, (void*)ss.nativeAddr, &nameLen)
-    if (ret) {
-        const char* err = uv_strerror(ret);
-        uv_close((uv_handle_t*) &context->uvHandle, NULL);
-        Except_throw(exHandler, "uv_udp_getsockname() failed [%s]", err);
-    }
-    ss.addr.addrLen = nameLen + 8;
-
-    context->pub.addr = Sockaddr_clone(&ss.addr, alloc);
-    Log_debug(logger, "Bound to address [%s]", Sockaddr_print(context->pub.addr, alloc));
-
-    Allocator_onFree(alloc, closeHandleOnFree, context);
-    Allocator_onFree(alloc, blockFreeInsideCallback, context);
-
-    return &context->pub;
-}

+ 0 - 297
util/events/libuv/UDPAddrInterface.c

@@ -1,297 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#include "util/events/libuv/UvWrapper.h"
-#include "exception/Except.h"
-#include "memory/Allocator.h"
-#include "util/events/libuv/EventBase_pvt.h"
-#include "util/platform/Sockaddr.h"
-#include "util/Assert.h"
-#include "util/Identity.h"
-#include "wire/Message.h"
-#include "wire/Error.h"
-#include "util/Hex.h"
-
-struct UDPAddrInterface_pvt
-{
-    struct AddrInterface pub;
-    struct Log* logger;
-
-    /** Job to close the handle when the allocator is freed */
-    struct Allocator_OnFreeJob* closeHandleOnFree;
-
-    /** Job which blocks the freeing until the callback completes */
-    struct Allocator_OnFreeJob* blockFreeInsideCallback;
-
-    uv_udp_t uvHandle;
-    int queueLen;
-
-    /** true if we are inside of the callback, used by blockFreeInsideCallback */
-    int inCallback;
-
-    Identity
-};
-
-struct UDPAddrInterface_WriteRequest_pvt {
-    uv_udp_send_t uvReq;
-    int32_t length;
-    struct UDPAddrInterface_pvt* udp;
-    struct Message* msg;
-    struct Allocator* alloc;
-    Identity
-};
-
-struct UDPAddrInterface_pvt* ifaceForHandle(uv_udp_t* handle)
-{
-    char* hp = ((char*)handle) - offsetof(struct UDPAddrInterface_pvt, uvHandle);
-    return Identity_check((struct UDPAddrInterface_pvt*) hp);
-}
-
-static void sendComplete(uv_udp_send_t* uvReq, int error)
-{
-    struct UDPAddrInterface_WriteRequest_pvt* req =
-        Identity_check((struct UDPAddrInterface_WriteRequest_pvt*) uvReq);
-    if (error) {
-        Log_info(req->udp->logger, "DROP Failed to write to UDPAddrInterface [%s]",
-                 uv_strerror(error) );
-    }
-    Assert_true(req->msg->length == req->length);
-    req->udp->queueLen -= req->msg->length;
-    Assert_true(req->udp->queueLen >= 0);
-    Allocator_free(req->alloc);
-}
-
-
-static uint8_t sendMessage(struct Message* m, struct Iface* iface)
-{
-    struct UDPAddrInterface_pvt* context = Identity_check((struct UDPAddrInterface_pvt*) iface);
-
-    Assert_true(m->length >= Sockaddr_OVERHEAD);
-    if (((struct Sockaddr*)m->bytes)->flags & Sockaddr_flags_BCAST) {
-        // bcast not supported.
-        return Error_UNDELIVERABLE;
-    }
-
-    if (context->queueLen > UDPAddrInterface_MAX_QUEUE) {
-        Log_warn(context->logger, "DROP Maximum queue length reached");
-        return Error_UNDELIVERABLE;
-    }
-
-    // This allocator will hold the message allocator in existance after it is freed.
-    struct Allocator* reqAlloc = Allocator_child(context->pub.generic.allocator);
-    if (m->alloc) {
-        Allocator_adopt(reqAlloc, m->alloc);
-    } else {
-        m = Message_clone(m, reqAlloc);
-    }
-
-    struct UDPAddrInterface_WriteRequest_pvt* req =
-        Allocator_clone(reqAlloc, (&(struct UDPAddrInterface_WriteRequest_pvt) {
-            .udp = context,
-            .msg = m,
-            .alloc = reqAlloc
-        }));
-    Identity_set(req);
-
-    struct Sockaddr_storage ss;
-    Message_pop(m, &ss, context->pub.addr->addrLen, NULL);
-    Assert_true(ss.addr.addrLen == context->pub.addr->addrLen);
-
-    req->length = m->length;
-
-    uv_buf_t buffers[] = {
-        { .base = (char*)m->bytes, .len = m->length }
-    };
-
-    int ret = 0;
-    uv_udp_send(&req->uvReq, &context->uvHandle, buffers, 1,
-                (const struct sockaddr*)ss.nativeAddr, (uv_udp_send_cb)&sendComplete);
-
-    if (ret) {
-        Log_info(context->logger, "DROP Failed writing to UDPAddrInterface [%s]",
-                 uv_strerror(ret));
-        Allocator_free(req->alloc);
-        return Error_UNDELIVERABLE;
-    }
-    context->queueLen += m->length;
-
-    return Error_NONE;
-}
-
-#if UDPAddrInterface_PADDING_AMOUNT < 8
-    #error
-#endif
-#define ALLOC(buff) (((struct Allocator**) &(buff[-(8 + (((uintptr_t)buff) % 8))]))[0])
-
-static void incoming(uv_udp_t* handle,
-                     ssize_t nread,
-                     const uv_buf_t* buf,
-                     const struct sockaddr* addr,
-                     unsigned flags)
-{
-    struct UDPAddrInterface_pvt* context = ifaceForHandle(handle);
-
-    context->inCallback = 1;
-
-    // Grab out the allocator which was placed there by allocate()
-    struct Allocator* alloc = buf->base ? ALLOC(buf->base) : NULL;
-
-    // if nread < 0, we used to log uv_last_error, which doesn't exist anymore.
-    if (nread == 0) {
-        // Happens constantly
-        //Log_debug(context->logger, "0 length read");
-
-    } else if (context->pub.generic.receiveMessage) {
-        struct Message* m = Allocator_malloc(alloc, sizeof(struct Message));
-        m->length = nread;
-        m->padding = UDPAddrInterface_PADDING_AMOUNT + context->pub.addr->addrLen;
-        m->capacity = buf->len;
-        m->bytes = (uint8_t*)buf->base;
-        m->alloc = alloc;
-        Message_push(m, addr, context->pub.addr->addrLen - Sockaddr_OVERHEAD, NULL);
-
-        // make sure the sockaddr doesn't have crap in it which will
-        // prevent it from being used as a lookup key
-        Sockaddr_normalizeNative((struct sockaddr*) m->bytes);
-
-        Message_push(m, context->pub.addr, Sockaddr_OVERHEAD, NULL);
-
-        /*uint8_t buff[256] = {0};
-        Assert_true(Hex_encode(buff, 255, m->bytes, context->pub.addr->addrLen));
-        Log_debug(context->logger, "Message from [%s]", buff);*/
-
-        Iface_send(&context->pub.generic, m);
-    }
-
-    if (alloc) {
-        Allocator_free(alloc);
-    }
-
-    context->inCallback = 0;
-    if (context->blockFreeInsideCallback) {
-        Allocator_onFreeComplete((struct Allocator_OnFreeJob*) context->blockFreeInsideCallback);
-    }
-}
-
-static void allocate(uv_handle_t* handle, size_t size, uv_buf_t* buf)
-{
-    struct UDPAddrInterface_pvt* context = ifaceForHandle((uv_udp_t*)handle);
-
-    size = UDPAddrInterface_BUFFER_CAP;
-    size_t fullSize = size + UDPAddrInterface_PADDING_AMOUNT + context->pub.addr->addrLen;
-
-    struct Allocator* child = Allocator_child(context->pub.generic.allocator);
-    char* buff = Allocator_malloc(child, fullSize);
-    buff += UDPAddrInterface_PADDING_AMOUNT + context->pub.addr->addrLen;
-
-    ALLOC(buff) = child;
-
-    buf->base = buff;
-    buf->len = size;
-}
-
-static void onClosed(uv_handle_t* wasClosed)
-{
-    struct UDPAddrInterface_pvt* context =
-        Identity_check((struct UDPAddrInterface_pvt*) wasClosed->data);
-    Allocator_onFreeComplete((struct Allocator_OnFreeJob*) context->closeHandleOnFree);
-}
-
-static int closeHandleOnFree(struct Allocator_OnFreeJob* job)
-{
-    struct UDPAddrInterface_pvt* context =
-        Identity_check((struct UDPAddrInterface_pvt*) job->userData);
-    context->closeHandleOnFree = job;
-    uv_close((uv_handle_t*)&context->uvHandle, onClosed);
-    return Allocator_ONFREE_ASYNC;
-}
-
-static int blockFreeInsideCallback(struct Allocator_OnFreeJob* job)
-{
-    struct UDPAddrInterface_pvt* context =
-        Identity_check((struct UDPAddrInterface_pvt*) job->userData);
-    if (!context->inCallback) {
-        return 0;
-    }
-    context->blockFreeInsideCallback = job;
-    return Allocator_ONFREE_ASYNC;
-}
-
-struct AddrInterface* UDPAddrInterface_new(struct EventBase* eventBase,
-                                           struct Sockaddr* addr,
-                                           struct Allocator* alloc,
-                                           struct Except* exHandler,
-                                           struct Log* logger)
-{
-    struct EventBase_pvt* base = EventBase_privatize(eventBase);
-
-    struct UDPAddrInterface_pvt* context =
-        Allocator_clone(alloc, (&(struct UDPAddrInterface_pvt) {
-            .pub = {
-                .generic = {
-                    .sendMessage = sendMessage,
-                    .allocator = alloc
-                },
-            },
-            .logger = logger
-        }));
-    Identity_set(context);
-
-    if (addr) {
-        Log_debug(logger, "Binding to address [%s]", Sockaddr_print(addr, alloc));
-    }
-
-    struct Sockaddr_storage ss;
-    if (!addr) {
-        Sockaddr_parse("0.0.0.0:0", &ss);
-        addr = &ss.addr;
-    }
-
-    uv_udp_init(base->loop, &context->uvHandle);
-    context->uvHandle.data = context;
-
-    int ret;
-    void* native = Sockaddr_asNative(addr);
-    ret = uv_udp_bind(&context->uvHandle, (const struct sockaddr*)native, 0);
-
-    if (ret) {
-        Except_throw(exHandler, "call to uv_udp_bind() failed [%s]",
-                     uv_strerror(ret));
-    }
-
-    ret = uv_udp_recv_start(&context->uvHandle, allocate, incoming);
-    if (ret) {
-        const char* err = uv_strerror(ret);
-        uv_close((uv_handle_t*) &context->uvHandle, NULL);
-        Except_throw(exHandler, "uv_udp_recv_start() failed [%s]", err);
-    }
-
-    int nameLen = sizeof(struct Sockaddr_storage);
-    Bits_memset(&ss, 0, sizeof(struct Sockaddr_storage));
-    ret = uv_udp_getsockname(&context->uvHandle, (void*)ss.nativeAddr, &nameLen);
-    if (ret) {
-        const char* err = uv_strerror(ret);
-        uv_close((uv_handle_t*) &context->uvHandle, NULL);
-        Except_throw(exHandler, "uv_udp_getsockname() failed [%s]", err);
-    }
-    ss.addr.addrLen = nameLen + 8;
-
-    context->pub.addr = Sockaddr_clone(&ss.addr, alloc);
-    Log_debug(logger, "Bound to address [%s]", Sockaddr_print(context->pub.addr, alloc));
-
-    Allocator_onFree(alloc, closeHandleOnFree, context);
-    Allocator_onFree(alloc, blockFreeInsideCallback, context);
-
-    return &context->pub;
-}

+ 0 - 33
util/platform/clock_gettime.h

@@ -1,33 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef clock_gettime_H
-#define clock_gettime_H
-<?js
-    if (typeof(state.clock_gettime) !== 'undefined') { return; }
-    console.log("Searching for clock_gettime()");
-    var done = this.async();
-
-    var HasFunction = require("./HasFunction");
-
-    HasFunction.check(builder, "clock_gettime", function (err, has) {
-        if (err) { throw err; }
-        if (has) {
-            console.log("Successfully found clock_gettime()");
-        } else {
-            console.log("Could not find clock_gettime()");
-        }
-    });
-?>
-#endif

+ 1 - 1
util/version/Version.h

@@ -309,7 +309,7 @@ Version_COMPAT(15, ([12,13,14]))
  * February 13, 2014
  *
  * Verschlumbesserung
- * 
+ * XXX(cjd): Explain this version
  */
 Version_COMPAT(16, ([12,13,14,15]))
 

+ 0 - 47
wire/BridgeHeader.h

@@ -1,47 +0,0 @@
-/* vim: set expandtab ts=4 sw=4: */
-/*
- * You may redistribute this program and/or modify it under the terms of
- * the GNU General Public License as published by the Free Software Foundation,
- * either version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-#ifndef BridgeHeader_H
-#define BridgeHeader_H
-
-#include "wire/ContentType.h"
-
-/**
- *                     1               2               3
- *     0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
- *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- *  0 |    version    |    unused     |             length            |
- *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- *    |                         ContentType                           |
- *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
- *
- * The BridgeHeader is a data header which is used internally for sending messages
- * around the inside of cjdns. Length and ContentType fields are both in host
- * endian encoding.
- */
-struct BridgeHeader
-{
-    /** If this is a mismatch, fail. */
-    uint8_t version;
-
-    uint8_t unused;
-    uint16_t length;
-    enum ContentType type;
-};
-#define BridgeHeader_SIZE 8
-Assert_compileTime(sizeof(struct BridgeHeader) == BridgeHeader_SIZE);
-
-#define BridgeHeader_CURRENT_VERSION 0
-
-#endif