LONGBOW_TEST_CASE(Object, parcRandomAccessFile_Write)
{
    char *fname = "tmpfile";

    PARCFile *file = parcFile_Create(fname);

    parcFile_CreateNewFile(file);

    uint8_t data[128];
    for (int i = 0; i < 128; i++) {
        data[i] = i;
    }

    PARCRandomAccessFile *instance = parcRandomAccessFile_Open(file);
    PARCBuffer *buffer = parcBuffer_Allocate(128);
    parcBuffer_PutArray(buffer, 128, data);
    parcBuffer_Flip(buffer);
    size_t numBytes = parcRandomAccessFile_Write(instance, buffer);
    assertTrue(numBytes == 128, "Expected 128 bytes to be read, but got %zu", numBytes);
    parcBuffer_Release(&buffer);

    parcRandomAccessFile_Close(instance);
    parcRandomAccessFile_Release(&instance);

    uint8_t bytes[128];
    FILE *fp = fopen(fname, "r");
    numBytes = fread(bytes, 1, 128, fp);
    assertTrue(numBytes == 128, "Expected 128 bytes to be read, but got %zu", numBytes);

    fclose(fp);

    assertTrue(memcmp(data, bytes, 128) == 0, "Expected buffers to be equal");

    parcFile_Release(&file);
}
CCNxInterestPayloadId *
ccnxInterestPayloadId_CreateAsSHA256Hash(const PARCBuffer *data)
{
    CCNxInterestPayloadId *result = parcObject_CreateInstance(CCNxInterestPayloadId);

    PARCCryptoHasher *hasher = parcCryptoHasher_Create(PARCCryptoHashType_SHA256);
    parcCryptoHasher_Init(hasher);
    parcCryptoHasher_UpdateBuffer(hasher, data);
    PARCCryptoHash *hash = parcCryptoHasher_Finalize(hasher);
    parcCryptoHasher_Release(&hasher);

    PARCBuffer *hashData = parcCryptoHash_GetDigest(hash);
    PARCBuffer *codedHash = parcBuffer_Allocate(parcBuffer_Capacity(hashData) + 1);
    parcBuffer_PutUint8(codedHash, CCNxInterestPayloadId_TypeCode_RFC6920_SHA256);
    parcBuffer_PutBuffer(codedHash, hashData);
    parcBuffer_Flip(codedHash);

    result->nameSegment =
        ccnxNameSegment_CreateTypeValue(CCNxNameLabelType_PAYLOADID, codedHash);

    parcBuffer_Release(&codedHash);
    parcCryptoHash_Release(&hash);

    return result;
}
LONGBOW_TEST_CASE(Global, cpiAddress_CreateFromLink)
{
    uint8_t mac[] = { 0x01, 0x02, 0x03, 0x04, 0xFF, 0x8F };
    PARCBuffer *macbuffer = parcBuffer_Flip(parcBuffer_CreateFromArray(mac, sizeof(mac)));

    CPIAddress *address = cpiAddress_CreateFromLink(mac, sizeof(mac));

    // Do not release test, it is the same reference as address->blob
    PARCBuffer *test = cpiAddress_GetLinkAddress(address);
    assertNotNull(test, "Got null link address buffer");
    assertTrue(parcBuffer_Equals(test, address->blob), "Returned buffer from cpiAddress_GetLinkAddress not equal to address");

    assertTrue(cpiAddress_GetType(address) == cpiAddressType_LINK,
               "Got wrong address type, expected %d, got %d", cpiAddressType_LINK, cpiAddress_GetType(address));

    PARCJSON *json = cpiAddress_ToJson(address);
    CPIAddress *fromjson = cpiAddress_CreateFromJson(json);

    assertTrue(cpiAddress_GetType(address) == cpiAddress_GetType(fromjson),
               "fromjson type does not equal known");
    assertTrue(parcBuffer_Equals(address->blob, fromjson->blob),
               "fromjson blob does not equal known address");
    assertTrue(cpiAddress_Equals(address, fromjson),
               "cpiAddress_Equals broken for LINK type");

    CPIAddress *copy = cpiAddress_Copy(address);
    assertTrue(cpiAddress_Equals(copy, address),
               "Copy and address not equal for LINK");

    parcJSON_Release(&json);
    cpiAddress_Destroy(&address);
    cpiAddress_Destroy(&copy);
    cpiAddress_Destroy(&fromjson);
    parcBuffer_Release(&macbuffer);
}
LONGBOW_TEST_CASE(Global, parc_Chunker_ReverseIterator_BufferSmall)
{
    PARCBuffer *buffer = parcBuffer_Allocate(16);

    // Special 0xFF to mark the start
    for (int i = 0; i < 16; i++) {
        parcBuffer_PutUint8(buffer, 0xFF);
    }
    parcBuffer_Flip(buffer);

    PARCBufferChunker *chunker = parcBufferChunker_Create(buffer, 32); // each chunk is 32 bytes
    assertNotNull(chunker, "Expected non-NULL Chunker");

    PARCIterator *itr = parcBufferChunker_ReverseIterator(chunker);
    size_t count = 0;
    while (parcIterator_HasNext(itr)) {
        PARCBuffer *payload = (PARCBuffer *) parcIterator_Next(itr);

        uint8_t *contents = parcBuffer_Overlay(payload, 0);
        for (size_t i = 0; i < 16; i++) {
            assertTrue(contents[i] == 0xFF, "Expected %zu at index %zu, got %d", (size_t) 0xFF, i, contents[i]);
        }
        count++;

        parcBuffer_Release(&payload);
    }
    assertTrue(count == 1, "Expected to iterate over 1 content objects from the chunker, but for %zu", count);
    parcIterator_Release(&itr);

    parcBufferChunker_Release(&chunker);
    parcBuffer_Release(&buffer);
}
LONGBOW_TEST_CASE(Object, parcRandomAccessFile_Read)
{
    char *fname = "tmpfile";

    PARCFile *file = parcFile_Create(fname);

    parcFile_CreateNewFile(file);
    FILE *fp = fopen(fname, "w");
    fseek(fp, 0, SEEK_SET);

    uint8_t data[128];
    for (int i = 0; i < 128; i++) {
        data[i] = i;
    }
    fwrite(data, 1, 128, fp);
    fclose(fp);

    PARCRandomAccessFile *instance = parcRandomAccessFile_Open(file);
    parcFile_Release(&file);

    PARCBuffer *buffer = parcBuffer_Allocate(128);
    size_t numBytes = parcRandomAccessFile_Read(instance, buffer);
    assertTrue(numBytes == 128, "Expected 128 bytes to be read, but got %zu", numBytes);

    parcBuffer_Flip(buffer);
    uint8_t *bytes = parcBuffer_Overlay(buffer, parcBuffer_Remaining(buffer));
    assertTrue(memcmp(data, bytes, 128) == 0, "Expected buffers to be equal");

    parcBuffer_Release(&buffer);
    parcRandomAccessFile_Close(instance);
    parcRandomAccessFile_Release(&instance);
}
LONGBOW_TEST_CASE(Global, parc_Chunker_ReverseIterator_Buffer)
{
    PARCBuffer *buffer = parcBuffer_Allocate(1024);

    for (size_t i = 0; i < 32; i++) {
        for (size_t j = 0; j < 32; j++) {
            parcBuffer_PutUint8(buffer, i);
        }
    }
    parcBuffer_Flip(buffer);

    PARCBufferChunker *chunker = parcBufferChunker_Create(buffer, 32); // each chunk is 32 bytes
    assertNotNull(chunker, "Expected non-NULL Chunker");

    PARCIterator *itr = parcBufferChunker_ReverseIterator(chunker);
    size_t count = 0;
    while (parcIterator_HasNext(itr)) {
        PARCBuffer *payload = (PARCBuffer *) parcIterator_Next(itr);

        uint8_t *contents = parcBuffer_Overlay(payload, 0);
        for (size_t i = 0; i < 32; i++) {
            assertTrue(contents[i] == (31 - count), "Expected %zu at index %zu, got %d", (31 - count), i, contents[i]);
        }
        count++;

        parcBuffer_Release(&payload);
    }
    assertTrue(count == 32, "Expected to iterate over 32 content objects from the chunker, but for %zu", count);
    parcIterator_Release(&itr);

    parcBufferChunker_Release(&chunker);
    parcBuffer_Release(&buffer);
}
Beispiel #7
0
static PARCBuffer *
_encodeControlPlaneInformation(const CCNxControl *cpiControlMessage)
{
    PARCJSON *json = ccnxControl_GetJson(cpiControlMessage);
    char *str = parcJSON_ToCompactString(json);

    // include +1 because we need the NULL byte
    size_t len = strlen(str) + 1;

    size_t packetLength = sizeof(_MetisTlvFixedHeaderV0) + sizeof(MetisTlvType) + len;
    PARCBuffer *packet = parcBuffer_Allocate(packetLength);

    _MetisTlvFixedHeaderV0 hdr;
    memset(&hdr, 0, sizeof(hdr));
    hdr.version = 0;
    hdr.packetType = METIS_PACKET_TYPE_CONTROL;
    hdr.payloadLength = htons(len + sizeof(MetisTlvType));

    parcBuffer_PutArray(packet, sizeof(hdr), (uint8_t *) &hdr);

    MetisTlvType tlv = { .type = htons(T_CPI), .length = htons(len) };
    parcBuffer_PutArray(packet, sizeof(tlv), (uint8_t *) &tlv);

    parcBuffer_PutArray(packet, len, (uint8_t *) str);

    parcMemory_Deallocate((void **) &str);
    return parcBuffer_Flip(packet);
}
Beispiel #8
0
/**
 * If the user specified a device name, set the MAC address in ether->macAddress
 *
 * <#Paragraphs Of Explanation#>
 *
 * @param [in] ether An allocated MetisGenericEther
 * @param [in] devstr A C-String of the device name
 *
 * Example:
 * @code
 * <#example#>
 * @endcode
 */
static void
_darwinEthernet_SetInterfaceAddress(MetisGenericEther *ether, const char *devstr)
{
    if (devstr) {
        struct ifaddrs *ifaddr;
        int failure = getifaddrs(&ifaddr);
        assertFalse(failure, "Error getifaddrs: (%d) %s", errno, strerror(errno));

        struct ifaddrs *next;
        for (next = ifaddr; next != NULL; next = next->ifa_next) {
            if (strcmp(next->ifa_name, devstr) == 0) {
                if (next->ifa_addr->sa_family == AF_LINK) {
                    struct sockaddr_dl *addr_dl = (struct sockaddr_dl *) next->ifa_addr;

                    // addr_dl->sdl_data[12] contains the interface name followed by the MAC address, so
                    // need to offset in to the array past the interface name.
                    PARCBuffer *addr = parcBuffer_Allocate(addr_dl->sdl_alen);
                    parcBuffer_PutArray(addr, addr_dl->sdl_alen, (uint8_t *) &addr_dl->sdl_data[ addr_dl->sdl_nlen]);
                    parcBuffer_Flip(addr);
                    ether->macAddress = addr;

                    // break out of loop and freeifaddrs
                    break;
                }
            }
        }
        freeifaddrs(ifaddr);
    }
}
Beispiel #9
0
PARCBuffer *
parcLogFormatText_FormatEntry(const PARCLogEntry *entry)
{
    PARCBuffer *payload = parcLogEntry_GetPayload(entry);

    char theTime[64];
    parcTime_TimevalAsRFC3339(parcLogEntry_GetTimeStamp(entry), theTime);

    PARCBufferComposer *composer = parcBufferComposer_Allocate(128);

    parcBufferComposer_PutStrings(composer,
                                  theTime, " ",
                                  parcLogLevel_ToString(parcLogEntry_GetLevel(entry)), " ",
                                  parcLogEntry_GetHostName(entry), " ",
                                  parcLogEntry_GetApplicationName(entry), " ",
                                  parcLogEntry_GetProcessName(entry), " ", NULL);

    parcBufferComposer_Format(composer, "%" PRId64 " [ ", parcLogEntry_GetMessageId(entry));
    parcBufferComposer_PutBuffer(composer, payload);
    parcBufferComposer_PutStrings(composer, " ]\n", NULL);
    PARCBuffer *result = parcBuffer_Flip(parcBuffer_Acquire(parcBufferComposer_GetBuffer(composer)));

    parcBufferComposer_Release(&composer);

    return result;
}
LONGBOW_TEST_CASE(Global, ccnxCodecSchemaV1ManifestDecoder_DecodeType)
{
    uint8_t rawManifest[40] = { 0x00, 0x07, 0x00, 0x24,
                                0x00, 0x02, 0x00, 0x20,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46,
                                0x46, 0x46, 0x46, 0x46 };
    PARCBuffer *wireFormat = parcBuffer_Flip(parcBuffer_CreateFromArray(rawManifest, 40));

    CCNxCodecTlvDecoder *decoder = ccnxCodecTlvDecoder_Create(wireFormat);
    CCNxTlvDictionary *dict = ccnxCodecSchemaV1TlvDictionary_CreateManifest();

    uint16_t type = ccnxCodecTlvDecoder_GetType(decoder);
    uint16_t length = ccnxCodecTlvDecoder_GetLength(decoder);

    bool result = _decodeType(decoder, dict, type, length);
    assertTrue(result, "Expected the manifest type to be correctly decoded at the top level");

    ccnxManifest_Release(&dict);
    ccnxCodecTlvDecoder_Destroy(&decoder);
    parcBuffer_Release(&wireFormat);
}
Beispiel #11
0
static PARCSignature *
_SignDigest(PARCPublicKeySigner *signer, const PARCCryptoHash *digestToSign)
{
    parcSecurity_AssertIsInitialized();

    assertNotNull(signer, "Parameter must be non-null CCNxFileKeystore");
    assertNotNull(digestToSign, "Buffer to sign must not be null");

    // TODO: what is the best way to expose this?
    PARCKeyStore *keyStore = signer->keyStore;
    PARCBuffer *privateKeyBuffer = parcKeyStore_GetDEREncodedPrivateKey(keyStore);
    EVP_PKEY *privateKey = NULL;
    size_t keySize = parcBuffer_Remaining(privateKeyBuffer);
    uint8_t *bytes = parcBuffer_Overlay(privateKeyBuffer, keySize);
    privateKey = d2i_PrivateKey(EVP_PKEY_RSA, &privateKey, (const unsigned char **) &bytes, keySize);
    parcBuffer_Release(&privateKeyBuffer);

    RSA *rsa = EVP_PKEY_get1_RSA(privateKey);

    int opensslDigestType;

    switch (parcCryptoHash_GetDigestType(digestToSign)) {
        case PARCCryptoHashType_SHA256:
            opensslDigestType = NID_sha256;
            break;
        case PARCCryptoHashType_SHA512:
            opensslDigestType = NID_sha512;
            break;
        default:
            trapUnexpectedState("Unknown digest type: %s",
                                parcCryptoHashType_ToString(parcCryptoHash_GetDigestType(digestToSign)));
    }

    uint8_t *sig = parcMemory_Allocate(RSA_size(rsa));
    assertNotNull(sig, "parcMemory_Allocate(%u) returned NULL", RSA_size(rsa));

    unsigned sigLength = 0;
    PARCBuffer *bb_digest = parcCryptoHash_GetDigest(digestToSign);
    int result = RSA_sign(opensslDigestType,
                          (unsigned char *) parcByteArray_Array(parcBuffer_Array(bb_digest)),
                          (int) parcBuffer_Remaining(bb_digest),
                          sig,
                          &sigLength,
                          rsa);
    assertTrue(result == 1, "Got error from RSA_sign: %d", result);
    RSA_free(rsa);

    PARCBuffer *bbSign = parcBuffer_Allocate(sigLength);
    parcBuffer_Flip(parcBuffer_PutArray(bbSign, sigLength, sig));
    parcMemory_Deallocate((void **) &sig);

    PARCSignature *signature =
    parcSignature_Create(_GetSigningAlgorithm(signer),
                         parcCryptoHash_GetDigestType(digestToSign),
                         bbSign
                         );
    parcBuffer_Release(&bbSign);
    return signature;
}
int
reader_writer(CCNxPortalFactory *factory, const char *uri)
{

    CCNxPortal *portal = ccnxPortalFactory_GetInstance(factory, ccnxPortalTypeDatagram, ccnxPortalProtocol_TLV, &ccnxPortalAttributes_Blocking);

    CCNxName *prefix = ccnxName_CreateFromURI(uri);
    CCNxName *bye = ccnxName_CreateFromURI("lci:/Hello/Goodbye%21");
    CCNxName *contentname = ccnxName_CreateFromURI("lci:/Hello/World");

    if (ccnxPortal_Listen(portal, prefix, 365 * 86400, CCNxStackTimeout_Never)) {
        CCNxMetaMessage *msg;

        while ((msg = ccnxPortal_Receive(portal, CCNxStackTimeout_Never)) != NULL) {

            if (ccnxMetaMessage_IsInterest(msg)) {
                CCNxInterest *interest = ccnxMetaMessage_GetInterest(msg);

                CCNxName *interestName = ccnxInterest_GetName(interest);

                if (ccnxName_Equals(interestName, contentname)) {
                    const PARCKeyId *publisherKeyId = ccnxPortal_GetKeyId(portal);

                    char buffer[128];
                    time_t theTime = time(0);
                    sprintf(buffer, "Hello World. The time is %s", ctime(&theTime));

                    PARCBuffer *payload = parcBuffer_CreateFromArray(buffer, 128);
                    parcBuffer_Flip(payload);

                    PARCBuffer *b = parcBuffer_Acquire(payload);
                    CCNxContentObject *uob = ccnxContentObject_CreateWithDataPayload(contentname, b);

                    // missing NULL check, case 1024

                    CCNxMetaMessage *message = ccnxMetaMessage_CreateFromContentObject(uob);
                    if (ccnxPortal_Send(portal, message, CCNxTransportStackTimeCCNxStackTimeout_Neverout_Never) == false) {
                        fprintf(stderr, "ccnx_write failed\n");
                    }
                    // ccnxMessage_Release(message);
                } else if (ccnxName_Equals(interestName, bye)) {
                    break;
                }
            } else {
                ccnxMetaMessage_Display(msg, 0);
            }
            ccnxMetaMessage_Release(&msg);
        }
    }

    ccnxName_Release(&prefix);
    ccnxName_Release(&bye);
    ccnxName_Release(&contentname);

    ccnxPortal_Release(&portal);

    return 0;
}
Beispiel #13
0
static PARCCryptoHash *
_GetPublickKeyDigest(PARCPkcs12KeyStore *keystore)
{
    parcSecurity_AssertIsInitialized();

    assertNotNull(keystore, "Parameter must be non-null PARCPkcs12KeyStore");

    if (keystore->public_key_digest == NULL) {
        AUTHORITY_KEYID  *akid = X509_get_ext_d2i(keystore->x509_cert, NID_authority_key_identifier, NULL, NULL);
        if (akid != NULL) {
            ASN1_OCTET_STRING *skid = X509_get_ext_d2i(keystore->x509_cert, NID_subject_key_identifier, NULL, NULL);
            if (skid != NULL) {
                keystore->public_key_digest =
                    parcBuffer_PutArray(parcBuffer_Allocate(skid->length), skid->length, skid->data);
                parcBuffer_Flip(keystore->public_key_digest);
                ASN1_OCTET_STRING_free(skid);
            }
            AUTHORITY_KEYID_free(akid);
        }
    }

    // If we could not load the digest from the certificate, then calculate it from the public key.
    if (keystore->public_key_digest == NULL) {
        uint8_t digestBuffer[SHA256_DIGEST_LENGTH];

        int result = ASN1_item_digest(ASN1_ITEM_rptr(X509_PUBKEY),
                                      EVP_sha256(),
                                      X509_get_X509_PUBKEY(keystore->x509_cert),
                                      digestBuffer,
                                      NULL);
        if (result != 1) {
            assertTrue(0, "Could not compute digest over certificate public key");
        } else {
            keystore->public_key_digest =
                parcBuffer_PutArray(parcBuffer_Allocate(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH, digestBuffer);
            parcBuffer_Flip(keystore->public_key_digest);
        }
    }

    // This stores a reference, so keystore->public_key_digest will remain valid
    // even if the cryptoHasher is destroyed
    return parcCryptoHash_Create(PARC_HASH_SHA256, keystore->public_key_digest);
}
/**
 * Create a symmetric (secret) key of the given bit length (e.g. 256)
 *
 * Example:
 * @code
 * <#example#>
 * @endcode
 */
PARCBuffer *
parcSymmetricSignerFileStore_CreateKey(unsigned bits)
{
    assertTrue((bits & 0x07) == 0, "bits must be a multiple of 8");

    unsigned keylength = bits / 8;
    uint8_t buffer[keylength];
    RAND_bytes(buffer, keylength);
    return parcBuffer_Flip(parcBuffer_PutArray(parcBuffer_Allocate(keylength), keylength, buffer));
}
Beispiel #15
0
CCNxNameSegment *
ccnxNameSegment_CreateTypeValueArray(CCNxNameLabelType type, size_t length, const char array[length])
{
    PARCBuffer *value = parcBuffer_PutArray(parcBuffer_Allocate(length), length, (const uint8_t *) array);
    parcBuffer_Flip(value);

    CCNxNameSegment *result = ccnxNameSegment_CreateTypeValue(type, value);
    parcBuffer_Release(&value);

    return result;
}
Beispiel #16
0
PARCBuffer *
parcBuffer_AllocateCString(const char *string)
{
    size_t length = strlen(string);
    PARCBuffer *buffer = parcBuffer_Allocate(length + 1);
    parcBuffer_PutArray(buffer, length, (const uint8_t *) string);
    parcBuffer_PutUint8(buffer, 0);
    parcBuffer_SetPosition(buffer, buffer->position - 1);
    parcBuffer_Flip(buffer);

    return buffer;
}
Beispiel #17
0
static void *
_ccnxChunker_NextFromBuffer(PARCBufferChunker *chunker, _ChunkerState *state)
{
    size_t chunkSize = state->nextChunkSize;

    parcBuffer_SetPosition(chunker->data, state->position);
    PARCBuffer *slice = parcBuffer_CreateFromArray(parcBuffer_Overlay(chunker->data, chunkSize), chunkSize);
    slice = parcBuffer_Flip(slice);

    _advanceState(chunker, state);

    return slice;
}
LONGBOW_TEST_CASE(Object, parcRandomAccessFile_Seek)
{
    char *fname = "tmpfile";

    PARCFile *file = parcFile_Create(fname);

    parcFile_CreateNewFile(file);
    FILE *fp = fopen(fname, "w");
    fseek(fp, 0, SEEK_SET);

    uint8_t data[128];
    for (int i = 0; i < 128; i++) {
        data[i] = i;
    }
    fwrite(data, 1, 128, fp);
    fclose(fp);

    PARCRandomAccessFile *instance = parcRandomAccessFile_Open(file);
    PARCBuffer *buffer = parcBuffer_Allocate(128);
    parcRandomAccessFile_Seek(instance, 64, PARCRandomAccessFilePosition_Start);
    size_t numBytes = parcRandomAccessFile_Read(instance, buffer);
    assertTrue(numBytes == 64, "Expected 64 bytes to be read, but got %zu", numBytes);

    parcRandomAccessFile_Seek(instance, 0, PARCRandomAccessFilePosition_End);
    parcBuffer_Flip(buffer);
    numBytes = parcRandomAccessFile_Read(instance, buffer);
    assertTrue(numBytes == 0, "Expected 0 bytes to be read, but got %zu", numBytes);

    parcRandomAccessFile_Seek(instance, 0, PARCRandomAccessFilePosition_Start);
    parcBuffer_Flip(buffer);
    numBytes = parcRandomAccessFile_Read(instance, buffer);
    assertTrue(numBytes == 128, "Expected 128 bytes to be read, but got %zu", numBytes);

    parcBuffer_Release(&buffer);
    parcRandomAccessFile_Close(instance);
    parcRandomAccessFile_Release(&instance);

    parcFile_Release(&file);
}
static CCNxTlvDictionary *
createSignedContentObject(void)
{
    CCNxName *name = ccnxName_CreateFromURI("lci:/some/name");
    PARCBuffer *payload = parcBuffer_Flip(parcBuffer_PutArray(parcBuffer_Allocate(20), 11, (uint8_t *) "the payload"));
    CCNxTlvDictionary *contentObject = ccnxContentObject_CreateWithDataPayload(name, payload);
    parcBuffer_Release(&payload);
    ccnxName_Release(&name);

    PARCBuffer *keyid = parcBuffer_Flip(parcBuffer_PutArray(parcBuffer_Allocate(20), 5, (uint8_t *) "keyid"));
    ccnxValidationRsaSha256_Set(contentObject, keyid, NULL);
    parcBuffer_Release(&keyid);

    PARCBuffer *sigbits = parcBuffer_WrapCString("the signature");
    PARCSignature *signature = parcSignature_Create(PARCSigningAlgorithm_RSA, PARC_HASH_SHA256, parcBuffer_Flip(sigbits));
    ccnxContentObject_SetSignature(contentObject, keyid, signature, NULL);

    parcSignature_Release(&signature);
    parcBuffer_Release(&sigbits);

    return contentObject;
}
Beispiel #20
0
PARCURISegment *
parcURISegment_Create(size_t length, const unsigned char segment[length])
{
    PARCURISegment *result = NULL;

    PARCBuffer *buffer = parcBuffer_Allocate(length);
    if (buffer != NULL) {
        parcBuffer_PutArray(buffer, length, segment);
        parcBuffer_Flip(buffer);
        result = parcURISegment_CreateFromBuffer(buffer);
        parcBuffer_Release(&buffer);
    }
    return result;
}
Beispiel #21
0
static void *
_parcChunker_NextFromBuffer(PARCFileChunker *chunker, _ChunkerState *state)
{
    size_t chunkSize = state->nextChunkSize;

    parcRandomAccessFile_Seek(chunker->fhandle, state->position, PARCRandomAccessFilePosition_Start);

    PARCBuffer *slice = parcBuffer_Allocate(chunkSize);
    parcRandomAccessFile_Read(chunker->fhandle, slice);
    slice = parcBuffer_Flip(slice);

    _advanceState(chunker, state);

    return slice;
}
LONGBOW_TEST_CASE(Global, parc_Chunker_ForwardIterator_BufferPartial)
{
    // Allocate something that's not divisible by the chunk size
    PARCBuffer *buffer = parcBuffer_Allocate(1030);

    for (size_t i = 0; i < 32; i++) {
        for (size_t j = 0; j < 32; j++) {
            parcBuffer_PutUint8(buffer, i);
        }
    }

    // Special 0xFF to mark the end...
    for (int i = 0; i < 6; i++) {
        parcBuffer_PutUint8(buffer, 0xFF);
    }

    parcBuffer_Flip(buffer);

    PARCBufferChunker *chunker = parcBufferChunker_Create(buffer, 32); // each chunk is 32 bytes
    assertNotNull(chunker, "Expected non-NULL Chunker");

    PARCIterator *itr = parcBufferChunker_ForwardIterator(chunker);
    size_t count = 0;
    while (parcIterator_HasNext(itr)) {
        PARCBuffer *payload = (PARCBuffer *) parcIterator_Next(itr);

        uint8_t *contents = parcBuffer_Overlay(payload, 0);
        if (count < 32) {
            for (size_t i = 0; i < 32; i++) {
                assertTrue(contents[i] == count, "Expected %zu at index %zu, got %d", count, i, contents[i]);
            }
        } else {
            for (size_t i = 0; i < 6; i++) {
                assertTrue(contents[i] == 0xFF, "Expected %zu at index %zu, got %d", (size_t) 0xFF, i, contents[i]);
            }
        }
        count++;

        parcBuffer_Release(&payload);
    }
    assertTrue(count == 33, "Expected to iterate over 33 content objects from the chunker, but for %zu", count);
    parcIterator_Release(&itr);

    parcBufferChunker_Release(&chunker);
    parcBuffer_Release(&buffer);
}
CCNxInterestPayloadId *
ccnxInterestPayloadId_Create(const PARCBuffer *data, uint8_t type)
{
    CCNxInterestPayloadId *result = parcObject_CreateInstance(CCNxInterestPayloadId);
    parcBuffer_AssertValid(data);

    PARCBuffer *buffer = parcBuffer_Allocate(parcBuffer_Capacity(data) + 1);
    assertTrue(type > CCNxInterestPayloadId_TypeCode_App, "App type must be greater than 0x80");

    parcBuffer_PutUint8(buffer, type);
    parcBuffer_PutBuffer(buffer, data);
    parcBuffer_Flip(buffer);
    result->nameSegment = ccnxNameSegment_CreateTypeValue(CCNxNameLabelType_PAYLOADID, buffer);
    parcBuffer_Release(&buffer);

    return result;
}
Beispiel #24
0
static PARCCryptoHash *
_GetCertificateDigest(PARCPkcs12KeyStore *keystore)
{
    parcSecurity_AssertIsInitialized();

    assertNotNull(keystore, "Parameter must be non-null PARCPkcs12KeyStore");

    if (keystore->certificate_digest == NULL) {
        uint8_t digestBuffer[SHA256_DIGEST_LENGTH];
        int result = X509_digest(keystore->x509_cert, EVP_sha256(), digestBuffer, NULL);
        if (result) {
            keystore->certificate_digest =
                parcBuffer_Flip(parcBuffer_PutArray(parcBuffer_Allocate(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH, digestBuffer));
        }
    }

    PARCCryptoHash *hash = parcCryptoHash_Create(PARC_HASH_SHA256, keystore->certificate_digest);
    return hash;
}
Beispiel #25
0
LONGBOW_TEST_CASE(Global, parcNetwork_LinkAddress_Parse_dashes)
{
    char *expected = "link://01-23-45-67-89-ab";
    PARCBuffer *address = parcNetwork_ParseLinkAddress(expected);
    parcBuffer_Flip(address);

    PARCBuffer *e = parcBuffer_Wrap((uint8_t []) { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab }, 6, 0, 6);

    parcBuffer_SetPosition(address, 0);
    parcBuffer_SetLimit(address, 6);

    parcBuffer_SetPosition(e, 0);
    parcBuffer_SetLimit(e, 6);

    assertTrue(parcBuffer_Equals(address, e),
               "Expected result failed.");

    parcBuffer_Release(&e);
    parcBuffer_Release(&address);
}
Beispiel #26
0
/**
 * Create a PARCBuffer payload containing a JSON string with information about this ContentStore's
 * size.
 */
static PARCBuffer *
_createStatSizeResponsePayload(const AthenaLRUContentStore *impl, const CCNxName *name, uint64_t chunkNumber)
{
    PARCJSON *json = parcJSON_Create();

    parcJSON_AddString(json, "moduleName", AthenaContentStore_LRUImplementation.description);
    parcJSON_AddInteger(json, "time", parcClock_GetTime(impl->wallClock));
    parcJSON_AddInteger(json, "numEntries", impl->numEntries);
    parcJSON_AddInteger(json, "sizeInBytes", impl->currentSizeInBytes);

    char *jsonString = parcJSON_ToString(json);

    parcJSON_Release(&json);

    PARCBuffer *result = parcBuffer_CreateFromArray(jsonString, strlen(jsonString));

    parcMemory_Deallocate(&jsonString);

    return parcBuffer_Flip(result);
}
Beispiel #27
0
static PARCBuffer *
_GetDEREncodedPrivateKey(PARCPkcs12KeyStore *keystore)
{
    parcSecurity_AssertIsInitialized();

    assertNotNull(keystore, "Parameter must be non-null PARCPkcs12KeyStore");

    if (keystore->private_key_der == NULL) {
        uint8_t *der = NULL;

        // this allocates memory for der
        int derLength = i2d_PrivateKey(keystore->private_key, &der);
        if (derLength > 0) {
            keystore->private_key_der =
            parcBuffer_Flip(parcBuffer_PutArray(parcBuffer_Allocate(derLength), derLength, der));
        }
        OPENSSL_free(der);
    }

    return parcBuffer_Copy(keystore->private_key_der);
}
Beispiel #28
0
static CCNxMetaMessage *
_create_stats_response(Athena *athena, CCNxName *ccnxName)
{
    PARCJSON *json = parcJSON_Create();

    struct timeval tv;
    gettimeofday(&tv, NULL);

    uint64_t nowInMillis = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

    parcJSON_AddString(json, "moduleName", athenaAbout_Name());
    parcJSON_AddInteger(json, "time", nowInMillis);
    parcJSON_AddInteger(json, "numProcessedInterests",
                        athena->stats.numProcessedInterests);
    parcJSON_AddInteger(json, "numProcessedContentObjects",
                        athena->stats.numProcessedContentObjects);
    parcJSON_AddInteger(json, "numProcessedControlMessages",
                        athena->stats.numProcessedControlMessages);
    parcJSON_AddInteger(json, "numProcessedInterestReturns",
                        athena->stats.numProcessedInterestReturns);

    char *jsonString = parcJSON_ToString(json);

    parcJSON_Release(&json);

    PARCBuffer *payload = parcBuffer_CreateFromArray(jsonString, strlen(jsonString));

    parcMemory_Deallocate(&jsonString);

    CCNxContentObject *contentObject =
        ccnxContentObject_CreateWithNameAndPayload(ccnxName, parcBuffer_Flip(payload));
    ccnxContentObject_SetExpiryTime(contentObject, nowInMillis + 100); // this response is good for 100 millis

    CCNxMetaMessage *result = ccnxMetaMessage_CreateFromContentObject(contentObject);

    ccnxContentObject_Release(&contentObject);
    parcBuffer_Release(&payload);

    return result;
}
Beispiel #29
0
static void
_stressTestNext(PARCSecureRandom *rng)
{
    PARCLinkedList *seen = parcLinkedList_Create();
    size_t duplicates = 0;
    for (size_t i = 0; i < NUM_TESTS; i++) {
        uint32_t next = parcSecureRandom_Next(rng);
        PARCBuffer *buffer = parcBuffer_Allocate(sizeof(next));
        parcBuffer_Flip(parcBuffer_PutUint32(buffer, next));

        if (parcLinkedList_Contains(seen, buffer)) {
            duplicates++;
        } else {
            parcLinkedList_Append(seen, buffer);
        }

        parcBuffer_Release(&buffer);
    }

    assertFalse(duplicates > (NUM_TESTS * EPSILON), "The RNG failed to generate random values: saw %zu duplicates", duplicates);
    parcLinkedList_Release(&seen);
}
static PARCBuffer *
_iovecToParcBuffer(const CCNxCodecNetworkBufferIoVec *iovec)
{
    PARCBuffer *result = NULL;

    size_t iovcnt = ccnxCodecNetworkBufferIoVec_GetCount((CCNxCodecNetworkBufferIoVec *) iovec);
    const struct iovec *array = ccnxCodecNetworkBufferIoVec_GetArray((CCNxCodecNetworkBufferIoVec *) iovec);

    size_t totalbytes = 0;
    for (int i = 0; i < iovcnt; i++) {
        totalbytes += array[i].iov_len;
    }

    result = parcBuffer_Allocate(totalbytes);
    for (int i = 0; i < iovcnt; i++) {
        parcBuffer_PutArray(result, array[i].iov_len, array[i].iov_base);
    }

    parcBuffer_Flip(result);


    return result;
}