libcoap  4.3.0rc1
coap_pdu_setup(3)
coap_pdu_setup

NAME

coap_pdu_setup, coap_pdu_init, coap_session_init_token, coap_session_new_token, coap_add_token, coap_new_optlist, coap_insert_optlist, coap_delete_optlist, coap_encode_var_safe — Work with CoAP PDUs

SYNOPSIS

#include <coap2/coap.h>

coap_pdu_t *coap_pdu_init(uint8_t type, uint8_t code, uint16_t message_id, size_t max_size);

void coap_session_init_token(coap_session_t *session, size_t length, const uint8_t *token);

void coap_session_new_token(coap_session_t *session, size_t *length, uint8_t *token);

int coap_add_token(coap_pdu_t *pdu, size_t length, const uint8_t *data);

coap_optlist_t *coap_new_optlist(uint16_t number, size_t length, const uint8_t *data);

int coap_insert_optlist(coap_optlist_t **optlist_chain, coap_optlist_t *optlist);

void coap_delete_optlist(coap_optlist_t *optlist_chain);

unsigned int coap_encode_var_safe(uint8_t *buffer, size_t size, unsigned int value);

unsigned int coap_encode_var_safe8(uint8_t *buffer, size_t size, uint64_t value);

int coap_add_optlist_pdu(coap_pdu_t *pdu, coap_optlist_t **optlist_chain);

size_t coap_add_option(coap_pdu_t *pdu, uint16_t number, size_t length, const uint8_t *data);

int coap_add_data(coap_pdu_t *pdu, size_t length, const uint8_t *data);

void coap_add_data_blocked_response(coap_resource_t *resource, coap_session_t *session, coap_pdu_t *request, coap_pdu_t *response, const coap_binary_t *token, uint16_t media_type, int maxage, size_t length, const uint8_t *data);

coap_mid_t coap_send(coap_session_t *session, coap_pdu_t *pdu);

int coap_split_path(const uint8_t *path, size_t length, uint8_t *buffer, size_t *buflen);

int coap_split_query(const uint8_t *query, size_t length, uint8_t *buffer, size_t *buflen);

Link with -lcoap-2, -lcoap-2-gnutls, -lcoap-2-openssl, -lcoap-2-mbedtls or -lcoap-2-tinydtls depending on your (D)TLS library type.

DESCRIPTION

The CoAP PDU is of the form

--header--|--optional token--|--optional options--|--optional payload--

The PDU must be built in the correct order, from left to right. In particular, the options need to be added in the correct numerical option order as they are stored in the PDU using relative numeric offsets from the previous option number.

There are option list functions available where options can be added to a chained list of options and then the chain list is sorted and then be added to the PDU.

Typically for clients, when creating a request, the PDU needs to be created before filling it with the appropriate information.

Typically with a server, the response PDU, with the optional token already added in, will already be created before the response handler is called, and the response PDU will need to be updated as appropriate starting with the optional options. Note that updating the response pdu’s code variable will cause the response pdu to get transmitted. If code does not get updated, then the response pdu is freed off by the underlying library.

For handling situations where the data to be transmitted does not fit into a single packet, see coap_block(3).

The coap_pdu_init() function returns a newly created PDU of type coap_pdu_t*. type is one of the following

COAP_MESSAGE_CON

Set the PDU to be of type confirmable.

COAP_MESSAGE_NON

Set the PDU to be of type non-confirmable.

COAP_MESSAGE_ACK

Set the PDU to be of type acknowledge (for internal use).

COAP_MESSAGE_RST

Set the PDU to be of type reset.

The code is one of the following

COAP_REQUEST_GET

Set the PDU request to be of type GET.

COAP_REQUEST_POST

Set the PDU request to be of type POST.

COAP_REQUEST_PUT

Set the PDU request to be of type PUT.

COAP_REQUEST_DELETE

Set the PDU request to be of type DELETE.

COAP_REQUEST_FETCH

Set the PDU request to be of type FETCH.

COAP_REQUEST_PATCH

Set the PDU request to be of type PATCH.

COAP_REQUEST_IPATCH

Set the PDU request to be of type IPATCH.

The message_id must be unique per request (which is not the same as the token), and must not be reused within EXCHANGE_LIFETIME (usually 247 seconds). To automate this, the function coap_new_message_id(session) should be called.

The max_size parameter defines the maximum size of a PDU and is usually determined by calling coap_session_max_pdu_size(session);

The coap_session_init_token() function is used to initialize the starting token of length for the session.

The coap_session_new_token() function is used to obtain the next available token of length for the session. Note that the same token must be used for doing an observe cancellation that was used for doing the observe registration. Otherwise tokens should be unique for each request/response so that they can be correctly matched.

The coap_add_token() function adds in the specified token’s data of length length to the PDU pdu. The maximum length of the token is 8 bytes. Adding the token must be done before any options or data are added. This function must only be called once per pdu, and must not be called in the appropriate response handler.

The coap_new_optlist() function returns a newly created optlist entry of type coap_optlist_t*. The number specifies which CoAP option is to be used, and is one of the COAP_OPTION_* definitions. The length is the length of the data of the option, and data points to the content of the option.

The following is the current list of options with their numeric value

/*
 * The C, U, and N flags indicate the properties
 * Critical, Unsafe, and NoCacheKey, respectively.
 * If U is set, then N has no meaning as per
 * https://tools.ietf.org/html/rfc7252#section-5.10
 * and is set to a -.
 * Separately, R is for the options that can be repeated
 *
 * The least significant byte of the option is set as followed
 * as per https://tools.ietf.org/html/rfc7252#section-5.4.6
 *
 *   0   1   2   3   4   5   6   7
 * --+---+---+---+---+---+---+---+
 *           | NoCacheKey| U | C |
 * --+---+---+---+---+---+---+---+
 *
 * https://tools.ietf.org/html/rfc8613#section-4 goes on to define E, I and U
 * properties Encrypted and Integrity Protected, Integrity Protected Only and
 * Unprotected respectively.  Integretity Protected Only is not currently used.
 *
 * An Option is tagged with CUNREIU with any of the letters replaced with _ if
 * not set, or - for N if U is set (see above) for aiding understanding of the
 * Option.
 */

#define COAP_OPTION_IF_MATCH        1 /* C__RE__, opaque,    0-8 B, RFC7252 */
#define COAP_OPTION_URI_HOST        3 /* CU-___U, String,  1-255 B, RFC7252 */
#define COAP_OPTION_ETAG            4 /* ___RE__, opaque,    1-8 B, RFC7252 */
#define COAP_OPTION_IF_NONE_MATCH   5 /* C___E__, empty,       0 B, RFC7252 */
#define COAP_OPTION_OBSERVE         6 /* _U-_E_U, empty/uint,  0 B/0-3 B, RFC7641 */
#define COAP_OPTION_URI_PORT        7 /* CU-___U, uint,      0-2 B, RFC7252 */
#define COAP_OPTION_LOCATION_PATH   8 /* ___RE__, String,  0-255 B, RFC7252 */
#define COAP_OPTION_OSCORE          9 /* C_____U, *,       0-255 B, RFC8613 */
#define COAP_OPTION_URI_PATH       11 /* CU-RE__, String,  0-255 B, RFC7252 */
#define COAP_OPTION_CONTENT_FORMAT 12 /* ____E__, uint,      0-2 B, RFC7252 */
/* COAP_OPTION_MAXAGE default 60 seconds if not set */
#define COAP_OPTION_MAXAGE         14 /* _U-_E_U, uint,      0-4 B, RFC7252 */
#define COAP_OPTION_URI_QUERY      15 /* CU-RE__, String,  1-255 B, RFC7252 */
#define COAP_OPTION_HOP_LIMIT      16 /* ______U, uint,        1 B, RFC8768 */
#define COAP_OPTION_ACCEPT         17 /* C___E__, uint,      0-2 B, RFC7252 */
#define COAP_OPTION_LOCATION_QUERY 20 /* ___RE__, String,  0-255 B, RFC7252 */
#define COAP_OPTION_BLOCK2         23 /* CU-_E_U, uint,      0-3 B, RFC7959 */
#define COAP_OPTION_BLOCK1         27 /* CU-_E_U, uint,      0-3 B, RFC7959 */
#define COAP_OPTION_SIZE2          28 /* __N_E_U, uint,      0-4 B, RFC7959 */
#define COAP_OPTION_PROXY_URI      35 /* CU-___U, String, 1-1034 B, RFC7252 */
#define COAP_OPTION_PROXY_SCHEME   39 /* CU-___U, String,  1-255 B, RFC7252 */
#define COAP_OPTION_SIZE1          60 /* __N_E_U, uint,      0-4 B, RFC7252 */
#define COAP_OPTION_NORESPONSE    258 /* _U-_E_U, uint,      0-1 B, RFC7967 */

See FURTHER INFORMATION as to how to get the latest list.

The coap_insert_optlist() function adds the optlist entry onto the optlist_chain and then sorts the optlist_chain before returning. The initial optlist_chain entry needs to be set to NULL before this function is first called. The coap_delete_optlist() function has to be called to free off all the optlist_chain entries.

The coap_delete_optlist() function deletes and frees off all the optlist entries in the optlist_chain.

The coap_add_optlist_pdu() function sorts all of the entries in optlist_chain into ascending option numeric order and adds all the entries to the pdu. This function does not free off the entries in optlist_chain. This function must be called after adding any token and before adding in the payload data.

The coap_add_option() function adds in the specified option of type number with data of length length to the PDU pdu. It is important that options are added to the pdu with number either being the same or greater than the previous option number that was added.

The coap_add_data() function adds in the specified payload data of length length to the PDU pdu. Adding the payload data must be done after any token or options are added. This function must only be called once per pdu.

The coap_add_data_blocked_response() function adds in the appropriate part of the payload data of length length to the PDU pdu. It should be used as a direct replacement for coap_add_data() if it is possible that the data will not fit into a single pdu. It also adds in the appropriate CoAP options to handle Block-Wise transfer. This function is usually used for a server’s GET / FETCH response. The resource, session, request, response and token are the same parameters for the registered GET / FETCH resource handler. The media_type is for the format of the data and maxage defines the lifetime of the response. If set to -1, then the MAXAGE option does not get included. This function must only be called once per pdu. It is the responsibility of the client to recognize that it has only received a part of the data and request the next block (with the appropriate Block options) from the server. Returning the next requested block is handled by this function.

NOTE: This function has been superseded by coap_add_data_response_large(). See coap_block(3).

The coap_encode_var_safe() function encodes value into buffer which has a size of size in bytes. Normally, the buffer size should be at least the sizeof(int) bytes unless you definitely know less space is required.

The coap_encode_var_safe8() function encodes 8 byte value into buffer which has a size of size in bytes. Normally, the buffer size should be at least 8 bytes unless you definitely know less space is required.

The coap_send() function is used to initiate the transmission of the pdu associated with the session.

The coap_split_path() function splits up path of length length and places the result in buffer which has a size of buflen. buflen needs to be preset with the size of buffer before the function call, and then buflen is updated with the actual size of buffer used.

The coap_split_query() function splits up query of length length and places the result in buffer which has a size of buflen. buflen needs to be preset with the size of buffer before the function call, and then buflen is updated with the actual size of buffer used.

RETURN VALUES

The coap_pdu_init() function returns a newly created PDU or NULL if there is a malloc or parameter failure.

The coap_new_optlist() function returns a newly created optlist or NULL if there is a malloc failure.

The coap_add_token(), coap_insert_optlist(), coap_delete_optlist(), coap_add_optlist_pdu() and coap_add_data() functions return 0 on failure, 1 on success.

The coap_add_optlist() function returns either the length of the option or 0 on failure.

The coap_encode_var_safe() function returns either the length of bytes encoded or 0 on failure.

The coap_encode_var_safe8() function returns either the length of bytes encoded or 0 on failure.

The coap_send() function returns the CoAP message ID on success or COAP_INVALID_MID on failure.

EXAMPLES

Setup PDU and Transmit

#include <coap2/coap.h>

static int
build_send_pdu(coap_context_t *context, coap_session_t *session,
uint8_t msgtype, uint8_t request_code, const char *uri, const char *query,
unsigned char *data, size_t length, int observe) {

  coap_pdu_t *pdu;
  uint8_t buf[1024];
  size_t buflen;
  uint8_t *sbuf = buf;
  int res;
  coap_optlist_t *optlist_chain = NULL;
  /* Remove (void) definition if variable is used */
  (void)context;

  /* Create the pdu with the appropriate options */
  pdu = coap_pdu_init(msgtype, request_code, coap_new_message_id(session),
                      coap_session_max_pdu_size(session));
  if (!pdu)
    return 0;

  /*
   * Create unique token for this request for handling unsolicited /
   * delayed responses
   */
  coap_session_new_token(session, &buflen, buf);
  if (!coap_add_token(pdu, buflen, buf)) {
    coap_log(LOG_DEBUG, "cannot add token to request\n");
    goto error;
  }

  if (uri) {
    /* Add in the URI options */
    buflen = sizeof(buf);
    res = coap_split_path((const uint8_t*)uri, strlen(uri), sbuf, &buflen);
    while (res--) {
      if (!coap_insert_optlist(&optlist_chain,
                               coap_new_optlist(COAP_OPTION_URI_PATH,
                        coap_opt_length(sbuf), coap_opt_value(sbuf))))
        goto error;
      sbuf += coap_opt_size(sbuf);
    }
  }

  if (query) {
    /* Add in the QUERY options */
    buflen = sizeof(buf);
    res = coap_split_query((const uint8_t*)query, strlen(query), sbuf, &buflen);
    while (res--) {
      if (!coap_insert_optlist(&optlist_chain,
                               coap_new_optlist(COAP_OPTION_URI_QUERY,
                        coap_opt_length(sbuf), coap_opt_value(sbuf))))
        goto error;
      sbuf += coap_opt_size(sbuf);
    }
  }

  if (request_code == COAP_REQUEST_GET && observe) {
    /* Indicate that we want to observe this resource */
    if (!coap_insert_optlist(&optlist_chain,
                             coap_new_optlist(COAP_OPTION_OBSERVE,
                               coap_encode_var_safe(buf, sizeof(buf),
                               COAP_OBSERVE_ESTABLISH), buf)
                             ))
      goto error;
  }

  /* ... Other code / options etc. ... */

  /* Add in all the options (after internal sorting) to the pdu */
  if (!coap_add_optlist_pdu(pdu, &optlist_chain))
    goto error;

  if (data && length) {
    /* Add in the specified data */
    if (!coap_add_data(pdu, length, data))
      goto error;
  }

  if (coap_send(session, pdu) == COAP_INVALID_MID)
    goto error;
  return 1;

error:

  if (pdu)
    coap_delete_pdu(pdu);
  return 0;

}

Resource Handler Response PDU Update

#include <coap2/coap.h>

#include <stdio.h>

static void
hnd_get_time(coap_context_t *context, coap_resource_t *resource,
coap_session_t *session, coap_pdu_t *request, coap_binary_t *token,
coap_string_t *query, coap_pdu_t *response) {

  unsigned char buf[40];
  size_t len;
  time_t now;
  /* Remove (void) definition if variable is used */
  (void)context;

  /* ... Additional analysis code for resource, request pdu etc.  ... */

  /* After analysis, generate a suitable response */

  /* Note that token is already in the response pdu */

  now = time(NULL);

  if (query != NULL && coap_string_equal(query, coap_make_str_const("secs"))) {
    /* Output secs since Jan 1 1970 */
    len = snprintf((char *)buf, sizeof(buf), "%lu", now);
  }
  else {
    /* Output human-readable time */
    struct tm *tmp;
    tmp = gmtime(&now);
    if (!tmp) {
      /* If 'now' is not valid */
      response->code = COAP_RESPONSE_CODE_NOT_FOUND;
      return;
    }
    len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp);
  }
  response->code = COAP_RESPONSE_CODE_CONTENT;
  /*
   * Invoke coap_add_data_blocked_response() to do all the hard work.
   *
   * Define the format - COAP_MEDIATYPE_TEXT_PLAIN - to add in
   * Define how long this response is valid for (secs) - 1 - to add in.
   *
   * OBSERVE Option added internally if needed within the function
   * BLOCK2 Option added internally if output too large
   * SIZE2 Option added internally
   * ETAG Option added internally
   */
  coap_add_data_blocked_response(resource, session, request, response, token,
                                 COAP_MEDIATYPE_TEXT_PLAIN, 1,
                                 len,
                                 buf);

}

FURTHER INFORMATION

See

"RFC7252: The Constrained Application Protocol (CoAP)"

"RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)"

for further information.

See https://www.iana.org/assignments/core-parameters/core-parameters.xhtml#option-numbers for the current set of defined CoAP Options.

BUGS

Please report bugs on the mailing list for libcoap: libcoap-developers@lists.sourceforge.net or raise an issue on GitHub at https://github.com/obgm/libcoap/issues

AUTHORS

The libcoap project <libcoap-developers@lists.sourceforge.net>

coap_pdu_setup(3)