Search in sources :

Example 1 with BlockOption

use of org.eclipse.californium.core.coap.BlockOption in project californium by eclipse.

the class LibCoapClientOpensslInteroperabilityTest method testLibCoapClientPsk4k4kSmallBlocks.

@Test
public void testLibCoapClientPsk4k4kSmallBlocks() throws Exception {
    processUtil.setVerboseLevel(null);
    CipherSuite cipherSuite = CipherSuite.TLS_PSK_WITH_AES_128_CCM_8;
    californiumUtil.start(BIND, null, cipherSuite);
    String message = "Hello, CoAP! " + californiumUtil.createTextPayload(4096);
    processUtil.setClientBlocksize(128);
    int szx = BlockOption.size2Szx(128);
    processUtil.setClientOption(new BlockOption(szx, false, 0).toOption(OptionNumberRegistry.BLOCK2));
    processUtil.startupClient(DESTINATION_URL + "large?size=4096", PSK, message, cipherSuite);
    ProcessResult result = connect(message, "3f#############################################################");
    assertThat(result, is(notNullValue()));
    assertThat(result.console, is(notNullValue()));
    assertThat(result.console.length(), is(greaterThan(4096)));
    californiumUtil.assertPrincipalType(PreSharedKeyIdentity.class);
}
Also used : CipherSuite(org.eclipse.californium.scandium.dtls.cipher.CipherSuite) ProcessResult(org.eclipse.californium.interoperability.test.ProcessUtil.ProcessResult) BlockOption(org.eclipse.californium.core.coap.BlockOption) Test(org.junit.Test)

Example 2 with BlockOption

use of org.eclipse.californium.core.coap.BlockOption in project californium by eclipse.

the class ResponseEncryptor method encrypt.

/**
 * @param db the context DB
 * @param response the response
 * @param ctx the OSCore context
 * @param newPartialIV boolean to indicate whether to use a new partial IV
 *            or not
 * @param outerBlockwise boolean to indicate whether the block-wise options
 *            should be encrypted or not
 * @param requestSequenceNr sequence number (Partial IV) from the request
 *            (if encrypting a response)
 *
 * @return the response with the encrypted OSCore option
 *
 * @throws OSException when encryption fails
 */
public static Response encrypt(OSCoreCtxDB db, Response response, OSCoreCtx ctx, final boolean newPartialIV, boolean outerBlockwise, int requestSequenceNr) throws OSException {
    if (ctx == null) {
        LOGGER.error(ErrorDescriptions.CTX_NULL);
        throw new OSException(ErrorDescriptions.CTX_NULL);
    }
    // Perform context re-derivation procedure if ongoing
    try {
        ctx = ContextRederivation.outgoingResponse(db, ctx);
    } catch (OSException e) {
        LOGGER.error(ErrorDescriptions.CONTEXT_REGENERATION_FAILED);
        throw new OSException(ErrorDescriptions.CONTEXT_REGENERATION_FAILED);
    }
    int realCode = response.getCode().value;
    response = OptionJuggle.setFakeCodeResponse(response);
    OptionSet options = response.getOptions();
    // Save block1 option in the case of outer block-wise to re-add later
    BlockOption block1Option = null;
    if (outerBlockwise) {
        block1Option = options.getBlock1();
        options.removeBlock1();
    }
    byte[] confidential = OSSerializer.serializeConfidentialData(options, response.getPayload(), realCode);
    Encrypt0Message enc = prepareCOSEStructure(confidential);
    byte[] cipherText = encryptAndEncode(enc, ctx, response, newPartialIV, requestSequenceNr);
    compression(ctx, cipherText, response, newPartialIV);
    options = response.getOptions();
    response.setOptions(OptionJuggle.prepareUoptions(options));
    if (outerBlockwise) {
        response.setOptions(response.getOptions().setBlock1(block1Option));
    }
    // If new partial IV was generated for response increment sender seq nr.
    if (newPartialIV) {
        ctx.increaseSenderSeq();
    }
    return response;
}
Also used : Encrypt0Message(org.eclipse.californium.cose.Encrypt0Message) OptionSet(org.eclipse.californium.core.coap.OptionSet) BlockOption(org.eclipse.californium.core.coap.BlockOption)

Example 3 with BlockOption

use of org.eclipse.californium.core.coap.BlockOption in project californium by eclipse.

the class BlockwiseClientSideTest method testRandomAccessGET.

@Test
public void testRandomAccessGET() throws Exception {
    respPayload = generateRandomPayload(300);
    String path = "test";
    Request request = createRequest(GET, path, server);
    request.getOptions().setBlock2(new BlockOption(BlockOption.size2Szx(128), false, 2));
    client.sendRequest(request);
    server.expectRequest(CON, GET, path).storeBoth("A").block2(2, false, 128).go();
    server.sendResponse(ACK, CONTENT).loadBoth("A").block2(2, false, 128).payload(respPayload.substring(256)).go();
    Response response = request.waitForResponse(RESPONSE_TIMEOUT_IN_MS);
    printServerLog(clientInterceptor);
    assertResponseContainsExpectedPayload(response, CONTENT, respPayload.substring(256));
}
Also used : Response(org.eclipse.californium.core.coap.Response) Request(org.eclipse.californium.core.coap.Request) IntegrationTestTools.createRequest(org.eclipse.californium.core.test.lockstep.IntegrationTestTools.createRequest) BlockOption(org.eclipse.californium.core.coap.BlockOption) Test(org.junit.Test)

Example 4 with BlockOption

use of org.eclipse.californium.core.coap.BlockOption in project californium by eclipse.

the class RandomAccessBlockTest method testServerReturnsIndividualBlocks.

@Test
public void testServerReturnsIndividualBlocks() throws Exception {
    // We do not test for block 0 because the client is currently unable to
    // know if the user attempts to just retrieve block 0 or if he wants to
    // do early block negotiation with a specific size but actually wants to
    // retrieve all blocks.
    int[] blockOrder = { 2, 1, 5, 3 };
    String[] expectations = { RESP_PAYLOAD.substring(32, 48), RESP_PAYLOAD.substring(16, 32), RESP_PAYLOAD.substring(80), RESP_PAYLOAD.substring(48, 64) };
    String uri = getUri(serverEndpoint, TARGET);
    CoapClient client = new CoapClient();
    client.setEndpoint(clientEndpoint);
    client.setTimeout(1000L);
    for (int i = 0; i < blockOrder.length; i++) {
        int num = blockOrder[i];
        int szx = BlockOption.size2Szx(16);
        Request request = Request.newGet();
        request.setURI(uri);
        request.getOptions().setBlock2(szx, false, num);
        CoapResponse response = client.advanced(request);
        assertNotNull(i + ": Client received no response", response);
        assertThat(REQUEST_COUNTER.get(), is(i + 1));
        assertThat(i + ": ", response.getCode(), is(ResponseCode.CONTENT));
        assertThat(i + ": ", response.getResponseText(), is(expectations[i]));
        assertTrue(i + ": ", response.getOptions().hasBlock2());
        BlockOption block2 = response.getOptions().getBlock2();
        assertThat(i + ": " + block2.toString(), block2.getOffset(), is(num * 16));
        assertThat(i + ": " + block2.toString(), block2.getSzx(), is(szx));
        assertThat(i + ": " + block2.toString(), block2.isM(), is(block2.getOffset() + response.getPayloadSize() < RESP_PAYLOAD.length()));
    }
    assertThat(REQUEST_COUNTER.get(), is(blockOrder.length));
    client.shutdown();
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) Request(org.eclipse.californium.core.coap.Request) CoapClient(org.eclipse.californium.core.CoapClient) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) Endpoint(org.eclipse.californium.core.network.Endpoint) BlockOption(org.eclipse.californium.core.coap.BlockOption) Test(org.junit.Test)

Example 5 with BlockOption

use of org.eclipse.californium.core.coap.BlockOption in project californium by eclipse.

the class BlockwiseLayer method handleEntityTooLarge.

/**
 * Handle 4.13 Entity Too Large error.
 *
 * @param exchange current exchange
 * @param response the Entity Too Larger response.
 * @return {@code true} if the response is handled by auto failover
 */
private boolean handleEntityTooLarge(Exchange exchange, Response response) {
    if (enableAutoFailoverOn413) {
        final KeyUri key = KeyUri.getKey(exchange);
        try {
            Request initialRequest = exchange.getRequest();
            if (response.getOptions().hasBlock1()) {
                BlockOption block1 = response.getOptions().getBlock1();
                Request blockRequest = null;
                boolean start = !initialRequest.isCanceled() && block1.getNum() == 0 && block1.getSize() < initialRequest.getPayloadSize();
                Block1BlockwiseStatus status;
                synchronized (block1Transfers) {
                    status = getBlock1Status(key);
                    if (status == null && start) {
                        // We sent a request without using block1 and
                        // server give us hint it want it with block1
                        // Start block1 transfer
                        blockRequest = startBlockwiseUpload(key, exchange, initialRequest, Math.min(block1.getSzx(), preferredBlockSzx));
                    }
                }
                if (status == null) {
                    if (blockRequest != null) {
                        exchange.setCurrentRequest(blockRequest);
                        lower().sendRequest(exchange, blockRequest);
                        return true;
                    }
                } else if (!status.hasMatchingToken(response)) {
                    // a concurrent block1 transfer has been started in
                    // the meantime which has "overwritten" the status
                    // object with the new (concurrent) request to we simply
                    // discard the response
                    LOGGER.debug("{}discarding obsolete block1 response: {}", tag, response);
                    return true;
                } else if (initialRequest.isCanceled()) {
                    clearBlock1Status(status);
                    return true;
                } else {
                    // if blocksize requested is smaller
                    if (status.isStarting() && block1.getSzx() < preferredBlockSzx) {
                        // re-send first block with smaller szx
                        status.restart();
                        sendNextBlock(exchange, response, status);
                        return true;
                    }
                }
            } else if (!exchange.getRequest().isCanceled()) {
                Request requestToSend = null;
                // We sent a request without using block1 and
                // server give us hint it want it with block1
                // Try to guess the a block size to use
                Integer maxSize = response.getOptions().getSize1();
                if (maxSize != null) {
                    if (maxSize < MINIMAL_BLOCK_SIZE || maxSize >= initialRequest.getPayloadSize()) {
                        maxSize = null;
                    }
                }
                if (maxSize == null && initialRequest.getPayloadSize() > MINIMAL_BLOCK_SIZE) {
                    maxSize = initialRequest.getPayloadSize() - 1;
                }
                if (maxSize != null) {
                    synchronized (block1Transfers) {
                        if (getBlock1Status(key) == null) {
                            // Start blockwise if we guess a correct size
                            int blockszx = BlockOption.size2Szx(maxSize);
                            requestToSend = startBlockwiseUpload(key, exchange, initialRequest, Math.min(blockszx, preferredBlockSzx));
                        }
                    }
                }
                if (requestToSend != null) {
                    exchange.setCurrentRequest(requestToSend);
                    lower().sendRequest(exchange, requestToSend);
                    return true;
                }
            }
        } catch (BlockwiseTransferException ex) {
            LOGGER.debug("{}{} {}", tag, key, ex.getMessage());
        // send original error response.
        }
    }
    return false;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Request(org.eclipse.californium.core.coap.Request) BlockOption(org.eclipse.californium.core.coap.BlockOption)

Aggregations

BlockOption (org.eclipse.californium.core.coap.BlockOption)18 Request (org.eclipse.californium.core.coap.Request)7 Response (org.eclipse.californium.core.coap.Response)7 Test (org.junit.Test)5 CoapEndpoint (org.eclipse.californium.core.network.CoapEndpoint)2 Endpoint (org.eclipse.californium.core.network.Endpoint)2 ProcessResult (org.eclipse.californium.interoperability.test.ProcessUtil.ProcessResult)2 CipherSuite (org.eclipse.californium.scandium.dtls.cipher.CipherSuite)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 CoapClient (org.eclipse.californium.core.CoapClient)1 CoapResponse (org.eclipse.californium.core.CoapResponse)1 ResponseCode (org.eclipse.californium.core.coap.CoAP.ResponseCode)1 OptionSet (org.eclipse.californium.core.coap.OptionSet)1 Token (org.eclipse.californium.core.coap.Token)1 Scope (org.eclipse.californium.core.network.TokenGenerator.Scope)1 DataSerializer (org.eclipse.californium.core.network.serialization.DataSerializer)1 UdpDataSerializer (org.eclipse.californium.core.network.serialization.UdpDataSerializer)1 IntegrationTestTools.createRequest (org.eclipse.californium.core.test.lockstep.IntegrationTestTools.createRequest)1 Encrypt0Message (org.eclipse.californium.cose.Encrypt0Message)1 EndpointContext (org.eclipse.californium.elements.EndpointContext)1