Ejemplo n.º 1
0
static uint8_t receiveMessageTUN(struct Message* msg, struct Interface* iface)
{
    receivedMessageTUNCount++;
    uint16_t ethertype = TUNMessageType_pop(msg, NULL);
    if (ethertype != Ethernet_TYPE_IP6) {
        printf("Spurious packet with ethertype [%04x]\n", Endian_bigEndianToHost16(ethertype));
        return 0;
    }

    struct Headers_IP6Header* header = (struct Headers_IP6Header*) msg->bytes;

    if (msg->length != Headers_IP6Header_SIZE + Headers_UDPHeader_SIZE + 12) {
        int type = (msg->length >= Headers_IP6Header_SIZE) ? header->nextHeader : -1;
        printf("Message of unexpected length [%u] ip6->nextHeader: [%d]\n", msg->length, type);
        return 0;
    }

    Assert_always(!Bits_memcmp(header->destinationAddr, testAddrB, 16));
    Assert_always(!Bits_memcmp(header->sourceAddr, testAddrA, 16));

    Bits_memcpyConst(header->destinationAddr, testAddrA, 16);
    Bits_memcpyConst(header->sourceAddr, testAddrB, 16);

    TUNMessageType_push(msg, ethertype, NULL);

    return iface->sendMessage(msg, iface);
}
Ejemplo n.º 2
0
static void showConn(struct IpTunnel_Connection* conn,
                     String* txid,
                     struct Admin* admin,
                     struct Allocator* alloc)
{
    Dict* d = Dict_new(alloc);

    if (!Bits_isZero(conn->connectionIp6, 16)) {
        struct Sockaddr* addr = Sockaddr_clone(Sockaddr_LOOPBACK6, alloc);
        uint8_t* address;
        Assert_always(16 == Sockaddr_getAddress(addr, &address));
        Bits_memcpyConst(address, conn->connectionIp6, 16);
        char* printedAddr = Sockaddr_print(addr, alloc);
        Dict_putString(d, String_CONST("ip6Address"), String_CONST(printedAddr), alloc);
    }

    if (!Bits_isZero(conn->connectionIp4, 4)) {
        struct Sockaddr* addr = Sockaddr_clone(Sockaddr_LOOPBACK, alloc);
        uint8_t* address;
        Assert_always(4 == Sockaddr_getAddress(addr, &address));
        Bits_memcpyConst(address, conn->connectionIp4, 4);
        char* printedAddr = Sockaddr_print(addr, alloc);
        Dict_putString(d, String_CONST("ip4Address"), String_CONST(printedAddr), alloc);
    }

    Dict_putString(d, String_CONST("key"), Key_stringify(conn->header.nodeKey, alloc), alloc);
    Dict_putInt(d, String_CONST("outgoing"), (conn->isOutgoing) ? 1 : 0, alloc);
    Dict_putString(d, String_CONST("error"), String_CONST("none"), alloc);

    Admin_sendMessage(d, txid, admin);
}
Ejemplo n.º 3
0
void testSerialize(struct Writer* writer, struct Reader* reader)
{
    Assert_always(!StandardBencSerializer_get()->serializeString(writer, String_CONST("hello")));
    Assert_always(!expect("5:hello", writer, reader));

    Assert_always(!StandardBencSerializer_get()->serializeString(writer, String_CONST("")));
    Assert_always(!expect("0:", writer, reader));
}
Ejemplo n.º 4
0
struct AdminTestFramework* AdminTestFramework_setUp(int argc, char** argv, char* testName)
{
    if (argc > 2 && !strcmp(testName, argv[1]) && !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_always(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 Interface* 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 AddrInterface* udpAdmin =
        UDPAddrInterface_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_always(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
    }));
Ejemplo n.º 5
0
Archivo: dt.c Proyecto: pkuwwt/Detri
void dt_save (const char path_name[], int type, Trist *s, const Trist_num *q)
{
  Dt dt;
  int h1, h2;
  int saved_max = s->max_triangle;
  Assert_always (s->magic == MAGIC);
  ;
  { /* using binary format */
    FILE *f = basic_fopen (path_name, "w");
    print ("Saving binary file \"%s\" ...\n", path_name);
    ;
    h2 = trist_pack ();
    h1 = EdFacet (1, 0);  /* trist_pack*() moves hull facets to: [1..h2] */
    if (NOT trist_hull_facet (h1))
      h1 = Sym (h1);
#ifdef __DEBUG__
    trist_io_check (s, *q);
#endif
    ;
    dt.bpt = (short) sizeof (Trist_record);
    dt.type = (short) type;
    dt.hull_ef = h1;
    dt.last_hull = h2;
    dt.num = *q;
    dt.n = s->max_org;
    dt.redundant  = s->max_org - dt.num.v;
    dt.trist = NULL;
    s->max_triangle = s->last_triangle;
    Assert_always (dt.n == dt.num.v + dt.redundant);
    ;
    /* binfwrite (&dt, 1, f); */
    Write1f (dt.type);
    Write1f (dt.bpt);
    Write1f (dt.n);
    Write1f (dt.redundant);
    Write1f (dt.hull_ef);
    Write1f (dt.last_hull);
    Write1f (dt.num);
    Write1f (dummy_word);
    ;
    /* binfwrite (s, 1, f); */
    Write1f (s->magic);
    Write1f (dummy_word);
    Write1f (s->last_triangle);
    Write1f (s->max_triangle);
    Write1f (s->max_org);
    Write1f (dummy_word);
    Write1f (s->used_triangles);
    Write1f (s->next_reusable_triangle);
    ;
    binfwrite (s->triangle, s->max_triangle + 1, f);
    ;
    basic_fclose (f);
  }
  s->max_triangle = saved_max;  /* such that s leaves unchanged! */
}
Ejemplo n.º 6
0
static void standardClientCallback(struct AdminClient_Promise* p, struct AdminClient_Result* res)
{
    struct Context* ctx = p->userData;
    //printf("%d\n", res->err);
    Assert_always(!res->err);
    Assert_always(Dict_getInt(res->responseDict, String_CONST("called!")));
    Assert_always(ctx->called);

    EventBase_endLoop(ctx->framework->eventBase);
}
Ejemplo n.º 7
0
static void expectConvert(char* address, char* expectedOutput)
{
    struct Sockaddr_storage ss;
    Assert_always(!Sockaddr_parse(address, &ss));
    struct Allocator* alloc = MallocAllocator_new(20000);
    char* outAddr = Sockaddr_print(&ss.addr, alloc);
    Assert_always(outAddr);
    Assert_always(strlen(outAddr) == strlen(expectedOutput));
    Assert_always(!strcmp(outAddr, expectedOutput));
    Allocator_free(alloc);
}
Ejemplo n.º 8
0
static uint8_t messageToTun(struct Message* message, struct Interface* iface)
{
    Assert_always(TUNMessageType_pop(message, NULL) == Ethernet_TYPE_IP6);
    struct Headers_IP6Header* ip = (struct Headers_IP6Header*) message->bytes;
    Assert_always(Headers_getIpVersion(ip) == 6);
    uint16_t length = Endian_bigEndianToHost16(ip->payloadLength_be);
    Assert_always(length + Headers_IP6Header_SIZE == message->length);
    Assert_always(ip->nextHeader == 17);
    Assert_always(!Bits_memcmp(ip->sourceAddr, fakeIp6ToGive, 16));
    called = 1;
    return 0;
}
Ejemplo n.º 9
0
int main(int argc, char** argv)
{
    struct Allocator* alloc = MallocAllocator_new(1<<20);
    struct EventBase* base = EventBase_new(alloc);
    struct Writer* logWriter = FileWriter_new(stdout, alloc);
    struct Log* logger = WriterLog_new(logWriter, alloc);

    struct Sockaddr* addrA = Sockaddr_fromBytes(testAddrA, Sockaddr_AF_INET6, alloc);

    char assignedIfName[TUNInterface_IFNAMSIZ];
    struct Interface* tun = TUNInterface_new(NULL, assignedIfName, base, logger, NULL, alloc);
    NetDev_addAddress(assignedIfName, addrA, 126, logger, NULL);

    struct Sockaddr_storage addr;
    Assert_always(!Sockaddr_parse("[fd00::1]", &addr));

    #ifdef freebsd
        // tun is not setup synchronously in bsd but it lets you bind to the tun's
        // address anyway.
        sleep(1);
    #endif

    // Mac OSX and BSD do not set up their TUN devices synchronously.
    // We'll just keep on trying until this works.
    struct AddrInterface* udp = NULL;
    for (int i = 0; i < 20; i++) {
        if ((udp = setupUDP(base, &addr.addr, alloc, logger))) {
            break;
        }
    }
    Assert_always(udp);

    struct Sockaddr* dest = Sockaddr_clone(udp->addr, alloc);
    uint8_t* addrBytes;
    Assert_always(16 == Sockaddr_getAddress(dest, &addrBytes));
    Bits_memcpy(addrBytes, testAddrB, 16);

    struct Message* msg;
    Message_STACK(msg, 0, 64);
    Message_push(msg, "Hello World", 12, NULL);
    Message_push(msg, dest, dest->addrLen, NULL);

    udp->generic.receiveMessage = receiveMessageUDP;
    udp->generic.receiverContext = alloc;
    tun->receiveMessage = receiveMessageTUN;

    udp->generic.sendMessage(msg, &udp->generic);

    Timeout_setTimeout(fail, NULL, 10000, base, alloc);

    EventBase_beginLoop(base);
    return 0;
}
Ejemplo n.º 10
0
int main()
{
    char* pingBenc = "d1:q4:ping4:txid4:abcde";
    struct Allocator* alloc = MallocAllocator_new(1<<22);
    struct TestFramework* tf = TestFramework_setUp("0123456789abcdefghijklmnopqrstuv", alloc, NULL);
    struct Ducttape_pvt* dt = Identity_cast((struct Ducttape_pvt*) tf->ducttape);

    struct Allocator* allocator = MallocAllocator_new(85000);
    uint16_t buffLen = sizeof(struct Ducttape_IncomingForMe) + 8 + strlen(pingBenc);
    uint8_t* buff = allocator->calloc(buffLen, 1, allocator);
    struct Headers_SwitchHeader* sh = (struct Headers_SwitchHeader*) buff;
    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->sourceAndDestPorts = 0;
    udp->length_be = Endian_hostToBigEndian16(strlen(pingBenc));

    strncpy((char*)(udp + 1), pingBenc, strlen(pingBenc));

    dt->switchInterface.receiveMessage = catchResponse;
    dt->switchInterface.receiverContext = NULL;

    // bad checksum
    udp->checksum_be = 1;
    struct Message m = { .bytes = buff, .length = buffLen, .padding = 0 };
    Ducttape_injectIncomingForMe(&m, &dt->public, herPublicKey);
    Assert_always(!dt->switchInterface.receiverContext);

    // zero checksum
    udp->checksum_be = 0;
    struct Message m2 = { .bytes = buff, .length = buffLen, .padding = 0 };
    Ducttape_injectIncomingForMe(&m2, &dt->public, herPublicKey);
    Assert_always(dt->switchInterface.receiverContext);

    // good checksum
    udp->checksum_be =
        Checksum_udpIp6(ip6->sourceAddr, (uint8_t*) udp, strlen(pingBenc) + Headers_UDPHeader_SIZE);
    struct Message m3 = { .bytes = buff, .length = buffLen, .padding = 0 };
    Ducttape_injectIncomingForMe(&m3, &dt->public, herPublicKey);
    Assert_always(dt->switchInterface.receiverContext);
}
Ejemplo n.º 11
0
static void testDuplicates(struct Random* rand)
{
    uint16_t randomShorts[8192];
    uint16_t out[8192];
    struct ReplayProtector rp = {.bitfield = 0};

    Random_bytes(rand, (uint8_t*)randomShorts, sizeof(randomShorts));

    uint32_t outIdx = 0;
    for (uint32_t i = 0; i < 1024; i++) {
        if (ReplayProtector_checkNonce((randomShorts[i] % (i + 20)), &rp)) {
            out[outIdx] = (randomShorts[i] % (i + 20));
            outIdx++;
        }
    }

    for (uint32_t i = 0; i < outIdx; i++) {
        for (uint32_t j = i + 1; j < outIdx; j++) {
            Assert_always(out[i] != out[j]);
        }
    }
}

int main()
{
    struct Allocator* alloc = MallocAllocator_new(4096);
    struct Random* rand = Random_new(alloc, NULL, NULL);
    for (int i = 0; i < CYCLES; i++) {
        testDuplicates(rand);
    }
    return 0;
}
Ejemplo n.º 12
0
static void parse()
{
    struct Sockaddr_storage test;
    Assert_always(Sockaddr_asNative(&test.addr) == ((uint8_t*)&test) + Sockaddr_OVERHEAD);


    expectSuccess("0.0.0.0");
    expectSuccess("111.111.111.111");
    expectSuccess("111.111.111.111:12345");

    expectFailure("111.111.111.111:99999");
    expectFailure("[111.111.111.111]");
    expectFailure("[fc00::");

    expectConvert("[fc00::]", "fc00::");
    expectSuccess("fc00::");
    expectSuccess("::");
    expectSuccess("1::1");
    expectSuccess("1::1");
    expectSuccess("[1::1]:12345");
    expectFailure("[1::1]:99999");
    expectSuccess("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:12345");
    expectFailure("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:12345");
    expectFailure("[:]:12345");
    expectFailure("[0]:12345");
    expectFailure("0");
    expectFailure("1.0.0.");
}
Ejemplo n.º 13
0
static uint8_t sendTo(struct Message* msg, struct Interface* iface)
{
    struct TestFramework_Link* link =
        Identity_cast((struct TestFramework_Link*)iface->senderContext);

    struct Interface* dest;
    struct TestFramework* srcTf;
    if (&link->destIf == iface) {
        dest = &link->srcIf;
        srcTf = link->dest;
    } else if (&link->srcIf == iface) {
        dest = &link->destIf;
        srcTf = link->src;
    } else {
        Assert_always(false);
    }

    printf("Transferring message to [%p] - message length [%d]\n", (void*)dest, msg->length);

    // Store the original message and a copy of the original so they can be compared later.
    srcTf->lastMsgBackup = Message_clone(msg, srcTf->alloc);
    srcTf->lastMsg = msg;
    if (msg->alloc) {
        // If it's a message which was buffered inside of CryptoAuth then it will be freed
        // so by adopting the allocator we can hold it in memory.
        Allocator_adopt(srcTf->alloc, msg->alloc);
    }

    // Copy the original and send that to the other end.
    struct Message* sendMsg = Message_clone(msg, dest->allocator);
    return dest->receiveMessage(sendMsg, dest);
}
Ejemplo n.º 14
0
void NetPlatform_addAddress(const char* interfaceName,
                            char* addrBytes,
                            int prefixLen,
                            int addrFam,
                            struct Log* logger,
                            struct Except* eh)
{
    unsigned long ifIndex;
    WinFail_check(eh, GetAdapterIndex(interfaceName, &ifIndex));

    MIB_UNICASTIPADDRESS_ROW ipRow;
    InitializeUnicastIpAddressEntry(&ipRow);
    ipRow.InterfaceIndex = ifIndex;

    ipRow.Address.si_family = addrFamily;
    if (addrFam == Socket_AF_INET6) {
        Bits_memcpy(&ipRow.Address.Ipv6.sin6_addr, addr, 16);
    } else if (addrFam == Socket_AF_INET) {
        Bits_memcpy(&ipRow.Address.Ipv4.sin_addr, addr, 4);
    } else {
        Assert_always(0);
    }

    ipRow.OnLinkPrefixLength = prefixLen;

    WinFail_check(eh, CreateUnicastIpAddressEntry(&ipRow));
}
Ejemplo n.º 15
0
int main()
{
    uint16_t randomShorts[8192];
    uint16_t out[8192];
    struct ReplayProtector rp = {0,0};

    struct Allocator* alloc;
    BufferAllocator_STACK(alloc, 1024);

    struct Random* rand = Random_new(alloc, NULL, NULL);

    Random_bytes(rand, (uint8_t*)randomShorts, sizeof(randomShorts));

    uint32_t outIdx = 0;
    for (uint32_t i = 0; i < 1024; i++) {
        if (ReplayProtector_checkNonce((randomShorts[i] % (i + 20)), &rp)) {
            out[outIdx] = (randomShorts[i] % (i + 20));
            outIdx++;
        }
    }

    for (uint32_t i = 0; i < outIdx; i++) {
        for (uint32_t j = i + 1; j < outIdx; j++) {
            Assert_always(out[i] != out[j]);
        }
    }

    return 0;
}
Ejemplo n.º 16
0
int main(int argc, char** argv)
{
printf("init test");
    struct Allocator* alloc = MallocAllocator_new(1<<20);
    struct Log* logger = FileWriterLog_new(stdout, alloc);
    struct EventBase* base = EventBase_new(alloc);

    char* ifName;
    struct Interface* iface = TAPInterface_new(NULL, &ifName, NULL, logger, base, alloc);
    struct NDPServer* ndp = NDPServer_new(iface, alloc);
    ndp->generic.receiveMessage = receiveMessage;
    ndp->generic.receiverContext = alloc;
    ndp->advertisePrefix[0] = 0xfd;
    ndp->prefixLen = 8;

    struct Sockaddr_storage ss;
    Assert_always(!Sockaddr_parse("fd00::1", &ss));
    NetDev_addAddress(ifName, &ss.addr, 8, logger, NULL);

    Timeout_setTimeout(fail, alloc, 10000, base, alloc);

    EventBase_beginLoop(base);
printf("Test ended\n");
    return 0;
}
Ejemplo n.º 17
0
Archivo: pool.c Proyecto: Phidll/Endrov
static Pool* cast (const Lia_pool_adt pid)
{
  Pool *p = (Pool *) pid;
  Assert_always (p and (minp <= p) and (p <= maxp));
  Assert ((p->magic == Magic_number)
          and (p->block_digits >= MIN_BLOCK_SIZE * lia_common.max));
  return (p);
}
Ejemplo n.º 18
0
static void routesThrough()
{
    // 0000000000000000100100000000101011101010100101011100101001010101
    uint64_t dest = 0x0000900aea95ca55llu;
    // 0000000000000000000000010110010100100110001110011100011001010101
    uint64_t mid =  0x000001652639c655llu;
    Assert_always(!LabelSplicer_routesThrough(dest, mid));
}
Ejemplo n.º 19
0
struct AdminTestFramework* AdminTestFramework_setUp()
{
    struct Allocator* alloc = MallocAllocator_new(1<<20);

    struct Writer* logwriter = FileWriter_new(stdout, alloc);
    Assert_always(logwriter);
    struct Log* logger =
        alloc->clone(sizeof(struct Log), alloc, &(struct Log) { .writer = logwriter });
Ejemplo n.º 20
0
static uint8_t sendMessageToIf1(struct Message* message, struct Interface* iface)
{
    uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
    printf("sent message <--  nonce=%d\n", nonce);
    Assert_always(message->length + message->padding <= BUFFER_SIZE);
    if1->receiveMessage(message, if1);
    return Error_NONE;
}
Ejemplo n.º 21
0
int sos_smaller_dist_abcd (int i, int k,
                           const Lia_ptr a, const Lia_ptr b, const Lia_ptr c)
{
  int result, s;
#ifdef __DEBUG__
  if (sos_proto_flag)
    print ("sos_smaller_abcd (%d,%d,...)\n", i, k); 
#endif
  if (i < k)
    s = 0;
  else
    { /* swap i <--> k */
      s = i;
      i = k;
      k = s;
      s = 1;
    }
  do
    {
      lia_push (a);
      lia_push (sos_lia (i, 1));
      lia_push (sos_lia (k, 1));
      lia_minus ();
      lia_times ();
      lia_push (b);
      lia_push (sos_lia (i, 2));
      lia_push (sos_lia (k, 2));
      lia_minus ();
      lia_times ();
      lia_push (c);
      lia_push (sos_lia (i, 2));
      lia_push (sos_lia (k, 2));
      lia_minus ();
      lia_times ();
      lia_plus ();
      lia_plus ();
      result = lia_sign (lia_popf ());
      if (result)
        break;
      result = lia_sign (c);
      if (result)
        break;
      result = lia_sign (b);
      if (result)
        break;
      result = lia_sign (a);
      if (result)
        break;
      Assert_always (FALSE);
    } once;
  if (Odd (s))
    result = -result;
#ifdef __DEBUG__
  if (sos_proto_flag)
    print  ("sos_smaller_dist_abcd result: %d\n", result);
#endif
  return (result);
}
Ejemplo n.º 22
0
void testParse(struct Writer* w, struct Reader* r, struct Allocator* alloc)
{
    char* badBenc = "d2:aq21:RouterModule_pingNode4:argsd4:path39:fcd9:6a75:6c9c7:timeouti4000ee"
                    "6:cookie0:4:hash64:09c6bcd1482df339757c99bbc5e796192968a28562f701fb53a57ed6"
                    "e26b15511:q4:auth4:txid19:43866780dc455e15619e";
    Writer_write(w, badBenc, strlen(badBenc)+1);
    Dict dict;
    Assert_always(StandardBencSerializer_get()->parseDictionary(r, alloc, &dict));
}
Ejemplo n.º 23
0
static uint8_t sendMessageToIf2(struct Message* message, struct Interface* iface)
{
    uint32_t nonce = Endian_bigEndianToHost32(((uint32_t*)message->bytes)[0]);
    printf("sent message -->  nonce=%d%s\n", nonce, suppressMessages ? " SUPPRESSED" : "");
    if (!suppressMessages) {
        Assert_always(message->length + message->padding <= BUFFER_SIZE);
        if2->receiveMessage(message, if2);
    }
    return Error_NONE;
}
Ejemplo n.º 24
0
int main()
{
    struct Allocator* alloc = MallocAllocator_new(1<<20);
    struct Random* rand = Random_new(alloc, NULL, NULL);

    // mock interface controller.
    struct Context ctx = {
        .ic = {
            .registerPeer = registerPeer,
            .getPeerState = getPeerState
        }
    };

    struct Interface externalIf = {
        .sendMessage = sendMessage,
        .allocator = alloc,
        .senderContext = &ctx
    };

    /*struct MultiInterface* mif = */MultiInterface_new(KEY_SIZE, &externalIf, &ctx.ic);

    struct Entry* entries = Allocator_malloc(alloc, sizeof(struct Entry) * ENTRY_COUNT);
    Random_bytes(rand, (uint8_t*)entries, ENTRY_COUNT * sizeof(struct Entry));

    struct Interface** ifaces = Allocator_calloc(alloc, sizeof(char*), ENTRY_COUNT);

    // seed the list with some near collisions.
    for (int i = 0; i < 10; i++) {
        int rnd = (((uint32_t*)entries)[i] >> 1) % ENTRY_COUNT;
        ((uint32_t*) (&entries[rnd]))[0] = ((uint32_t*) (&entries[i]))[0];
    }

    for (int i = 0; i < CYCLES; i++) {
        int rnd = ((uint32_t*)entries)[i] % ENTRY_COUNT;
        struct Entry* entry = &entries[rnd];
        struct Interface* iface = ifaces[rnd];

        struct Message* msg;
        Message_STACK(msg, 0, 128);

        Message_push(msg, "hello world", 12);
        Message_push(msg, entry, 16);

        externalIf.receiveMessage(msg, &externalIf);

        //printf("Received message for iface [%u] from [%p]\n", rnd, (void*)ctx.receivedOn);
        if (iface) {
            Assert_always(ctx.receivedOn == iface);
        } else {
            ifaces[rnd] = ctx.receivedOn;
        }
    }

    Allocator_free(alloc);
}
Ejemplo n.º 25
0
int main()
{
    struct Allocator* alloc;
    BufferAllocator_STACK(alloc, 512);
    struct Random* rand = Random_new(alloc, NULL);

    uint8_t bytes[32];
    Random_bytes(rand, bytes, 32);

    uint8_t base32[64];
    Bits_memset(base32, 0, 64);

    Assert_always(Base32_encode(base32, 64, bytes, 32) == 52);

    //printf("base32 encoded: %s\n", base32);

    uint8_t bytes2[32];
    Assert_always(Base32_decode(bytes2, 32, base32, 52) == 32);

    Assert_always(Bits_memcmp(bytes, bytes2, 32) == 0);
}
Ejemplo n.º 26
0
/**
 * Doesn't read more than maxRead bytes into buf[*have..bufSize]
 * Increments *have by amount of read bytes
 *
 * Buffer mustn't be full, and maxRead > 0
 *
 * return values:
 * n>0: read n new bytes
 *  -1: eof/network or read error - closed
 *  -2: EAGAIN
 */
static int inFromChildFillBuffer(struct Admin* admin,
                                 void *buf,
                                 uint32_t bufSize,
                                 uint32_t* have,
                                 uint32_t maxRead)
{
    char *charBuf = (char*) buf;
    Assert_true(*have < bufSize);
    Assert_true(maxRead > 0);

    if (maxRead > bufSize - *have) {
        maxRead = bufSize - *have;
    }

    Assert_always(maxRead > 0);
    Assert_always(maxRead <= INT_MAX);

    errno = 0;
    ssize_t amount = read(admin->inFd, charBuf + *have, maxRead);

    if (amount < 0 && (EAGAIN == errno || EWOULDBLOCK == errno)) {
        return -2;
    } else if (0 == amount) {
        Log_error(admin->logger, "Connection to admin process closed unexpectedly");
        adminClosePipes(admin);
        return -1;
    } else if (amount < 0) {
        Log_error(admin->logger, "Broken pipe to admin process, [%s]", strerror(errno));
        adminClosePipes(admin);
        return -1;
    }

    Assert_always(amount > 0);
    Assert_true(amount <= (ssize_t) maxRead);

    *have += amount;
    Assert_true(*have <= bufSize);

    return amount;
}
Ejemplo n.º 27
0
static inline uint8_t* hashPassword(struct CryptoAuth_Auth* auth,
                                    const String* password,
                                    const uint8_t authType)
{
    switch (authType) {
        case 1:
            hashPassword_sha256(auth, password);
            break;
        default:
            Assert_always(!"Unsupported auth type.");
    };
    return auth->secret;
}
Ejemplo n.º 28
0
int main()
{
    /* verify public key */
    struct Address address;
    crypto_scalarmult_curve25519_base(address.key, privateKey);

    AddressCalc_addressForPublicKey(address.ip6.bytes, address.key);

    uint8_t privateKeyHexOut[65];
    uint8_t publicKeyHexOut[65];
    uint8_t publicKeyBase32Out[53];

    Hex_encode(privateKeyHexOut, 65, privateKey, 32);

    Hex_encode(publicKeyHexOut, 65, publicKey, 32);

    printf("Private key %s (hex)\n\nExpect:\nPublic Key: %s (hex)\n"
           "Public Key: %s (base32)\nAddress: %s\n",
           privateKeyHexOut,
           publicKeyHexOut,
           publicKeyBase32,
           ipv6);

    uint8_t addressOut[40];

    Hex_encode(publicKeyHexOut, 65, address.key, 32);
    Base32_encode(publicKeyBase32Out, 53, address.key, 32);
    Address_printIp(addressOut, &address);

    printf("\nGot:\nPublic Key: %s (hex)\n"
           "Public Key: %s (base32)\nAddress: %s\n",
           publicKeyHexOut,
           publicKeyBase32Out,
           addressOut);

    Assert_always(0 == memcmp(address.key, publicKey, 32));
    Assert_always(0 == strcmp(publicKeyBase32, (char*) publicKeyBase32Out));
    Assert_always(0 == strcmp(ipv6, (char*) addressOut));
}
Ejemplo n.º 29
0
static void showConn(struct IpTunnel_Connection* conn, String* txid, struct Admin* admin)
{
    struct Allocator* alloc;
    BufferAllocator_STACK(alloc, 1024);
    Dict* d = Dict_new(alloc);

    char ip6[40];
    if (!Bits_isZero(conn->connectionIp6, 16)) {
        Assert_always(evutil_inet_ntop(AF_INET6, conn->connectionIp6, ip6, 40));
        Dict_putString(d, String_CONST("ip6Address"), String_CONST(ip6), alloc);
    }

    char ip4[16];
    if (!Bits_isZero(conn->connectionIp4, 4)) {
        Assert_always(evutil_inet_ntop(AF_INET, conn->connectionIp4, ip4, 16));
        Dict_putString(d, String_CONST("ip4Address"), String_CONST(ip4), alloc);
    }

    Dict_putString(d, String_CONST("key"), Key_stringify(conn->header.nodeKey, alloc), alloc);
    Dict_putInt(d, String_CONST("outgoing"), conn->isOutgoing, alloc);

    Admin_sendMessage(d, txid, admin);
}
Ejemplo n.º 30
0
/** @see Allocator->realloc() */
static void* allocatorRealloc(const void* original,
                              size_t size,
                              const struct Allocator* allocator)
{
    struct CanaryAllocator_pvt* ctx = Identity_cast((struct CanaryAllocator_pvt*) allocator);
    if (((uint8_t*) original) == NULL) {
        return allocatorMalloc(size, allocator);
    }
    uint32_t* beginCanary = ((uint32_t*) original) - 1;
    Assert_always(*beginCanary == ctx->canaryValue);
    for (int i = 0; i < ctx->canaryCount; i++) {
        if (ctx->canaries[i] == beginCanary) {
            Assert_always(ctx->canaryCount > i + 1 && *ctx->canaries[i + 1] == ctx->canaryValue);
            for (int j = i + 2; j < ctx->canaryCount; j++) {
                ctx->canaries[j - 2] = ctx->canaries[j];
            }
            ctx->canaryCount -= 2;
            break;
        }
    }
    uint32_t* out = ctx->alloc->realloc(((uint32_t*)original) - 1, SIZE_BYTES(size), ctx->alloc);
    return newAllocation(ctx, out, SIZE_INTS(size));
}