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);
}
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;
}
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));
}
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();
}
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;
}
Aggregations