From e32a0f3497285e5b8552c065a45ceabf919c093c Mon Sep 17 00:00:00 2001 From: chrysn Date: Fri, 19 Apr 2013 17:51:24 +0200 Subject: [PATCH] add coap_add_option_later function the coap_add_option_later works like coap_add_option, but does not take data. instead, it allocates the option empty, and returns an address the application has to fill with data later. this is especially useful for the etag and block options; the application can write out its variable data, generate a checksum while writing, and fill the etag when the data is already written to the pdu. with the block options, the more flag can be set at the last moment. --- pdu.c | 33 +++++++++++++++++++++++++++++++++ pdu.h | 10 ++++++++++ 2 files changed, 43 insertions(+) diff --git a/pdu.c b/pdu.c index ce324731..ea8ab87a 100644 --- a/pdu.c +++ b/pdu.c @@ -120,6 +120,7 @@ coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) { return 1; } +/** @FIXME de-duplicate code with coap_add_option_later */ size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data) { size_t optsize; @@ -151,6 +152,38 @@ coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const un return optsize; } +/** @FIXME de-duplicate code with coap_add_option */ +unsigned char* +coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) { + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) { + warn("coap_add_option: options are not in correct order\n"); + return NULL; + } + + opt = (unsigned char *)pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, + type - pdu->max_delta, NULL, len); + + if (!optsize) { + warn("coap_add_option: cannot add option\n"); + /* error */ + return NULL; + } else { + pdu->max_delta = type; + pdu->length += optsize; + } + + return ((unsigned char*)opt) + optsize - len; +} + int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) { assert(pdu); diff --git a/pdu.h b/pdu.h index 6f27487d..2cf04f88 100644 --- a/pdu.h +++ b/pdu.h @@ -287,6 +287,16 @@ int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data); size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data); +/** + * Adds option of given type to pdu that is passed as first + * parameter, but does not write a value. It works like coap_add_option with + * respect to calling sequence (i.e. after token and before data). + * This function returns a memory address to which the option data has to be + * written before the PDU can be sent, or @c NULL on error. + */ +unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type, + unsigned int len); + /** * Adds given data to the pdu that is passed as first parameter. Note * that the PDU's data is destroyed by coap_add_option(). coap_add_data()