• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// -*- mode:doc; -*-
2// vim: set syntax=asciidoc tw=0
3
4coap_pdu_setup(3)
5=================
6:doctype: manpage
7:man source:   coap_pdu_setup
8:man version:  @PACKAGE_VERSION@
9:man manual:   libcoap Manual
10
11NAME
12----
13coap_pdu_setup,
14coap_new_pdu,
15coap_pdu_init,
16coap_new_message_id,
17coap_session_init_token,
18coap_session_new_token,
19coap_add_token,
20coap_new_optlist,
21coap_insert_optlist,
22coap_delete_optlist,
23coap_encode_var_safe,
24coap_encode_var_safe8,
25coap_add_optlist_pdu,
26coap_add_option,
27coap_add_data,
28coap_add_data_blocked_response,
29coap_send,
30coap_split_path,
31coap_split_query,
32coap_pdu_set_mid,
33coap_pdu_set_code,
34coap_pdu_set_type
35- Setting up CoAP PDUs
36
37SYNOPSIS
38--------
39*#include <coap@LIBCOAP_API_VERSION@/coap.h>*
40
41*coap_pdu_t *coap_new_pdu(coap_pdu_type_t _type_, coap_pdu_code_t _code_,
42coap_session_t *_session_);*
43
44*coap_pdu_t *coap_pdu_init(coap_pdu_type_t _type_, coap_pdu_code_t _code_,
45coap_mid_t _message_id_, size_t _max_size_);*
46
47*uint16_t coap_new_message_id(coap_session_t *_session_);*
48
49*void coap_session_init_token(coap_session_t *_session_, size_t _length_,
50const uint8_t *_token_);*
51
52*void coap_session_new_token(coap_session_t *_session_, size_t *_length_,
53uint8_t *_token_);*
54
55*int coap_add_token(coap_pdu_t *_pdu_, size_t _length_,
56const uint8_t *_data_);*
57
58*coap_optlist_t *coap_new_optlist(uint16_t _number_, size_t _length_,
59const uint8_t *_data_);*
60
61*int coap_insert_optlist(coap_optlist_t **_optlist_chain_,
62coap_optlist_t *_optlist_);*
63
64*void coap_delete_optlist(coap_optlist_t *_optlist_chain_);*
65
66*unsigned int coap_encode_var_safe(uint8_t *_buffer_, size_t _size_,
67unsigned int _value_);*
68
69*unsigned int coap_encode_var_safe8(uint8_t *_buffer_, size_t _size_,
70uint64_t _value_);*
71
72*int coap_add_optlist_pdu(coap_pdu_t *_pdu_, coap_optlist_t **_optlist_chain_);*
73
74*size_t coap_add_option(coap_pdu_t *_pdu_, uint16_t _number_, size_t _length_,
75const uint8_t *_data_);*
76
77*int coap_add_data(coap_pdu_t *_pdu_, size_t _length_, const uint8_t *_data_);*
78
79*void coap_add_data_blocked_response(const coap_pdu_t *_request_,
80coap_pdu_t *_response_, uint16_t _media_type_, int _maxage_, size_t _length_,
81const uint8_t *_data_);*
82
83*coap_mid_t coap_send(coap_session_t *_session_, coap_pdu_t *_pdu_);*
84
85*int coap_split_path(const uint8_t *_path_, size_t _length_, uint8_t *_buffer_,
86size_t *_buflen_);*
87
88*int coap_split_query(const uint8_t *_query_, size_t _length_,
89uint8_t *_buffer_, size_t *_buflen_);*
90
91*void coap_pdu_set_mid(coap_pdu_t *_pdu_, coap_mid_t _mid_);*
92
93*void coap_pdu_set_code(coap_pdu_t *_pdu_, coap_pdu_code_t _code_);*
94
95*void coap_pdu_set_type(coap_pdu_t *_pdu_, coap_pdu_type_t _type_);*
96
97For specific (D)TLS library support, link with
98*-lcoap-@LIBCOAP_API_VERSION@-notls*, *-lcoap-@LIBCOAP_API_VERSION@-gnutls*,
99*-lcoap-@LIBCOAP_API_VERSION@-openssl*, *-lcoap-@LIBCOAP_API_VERSION@-mbedtls*
100or *-lcoap-@LIBCOAP_API_VERSION@-tinydtls*.   Otherwise, link with
101*-lcoap-@LIBCOAP_API_VERSION@* to get the default (D)TLS library support.
102
103DESCRIPTION
104-----------
105The CoAP PDU is of the form
106
107--header--|--optional token--|--optional options--|--optional payload--
108
109The terminology used is taken mainly from
110"https://rfc-editor.org/rfc/rfc7252#section-1.2[RFC7252 1.2. Terminology]".
111
112The PDU must be built in the correct order, from left to right.  In particular,
113the options need to be added in the correct numerical option order as they are
114stored in the PDU using relative numeric offsets from the previous option
115number.
116
117There are option list functions available where options can be added to a
118chained list of options and then the chain list is sorted and then be added to
119the PDU.
120
121Typically for clients, when creating a request, the PDU needs to be created
122before filling it with the appropriate information.
123
124Typically with a server, the response PDU, with the optional token already added
125in, will already be created before the response handler is called, and the
126response PDU will need to be updated as appropriate starting with the optional
127options.  Note that updating the response pdu's code variable will cause the
128response pdu to get transmitted.  If code does not get updated, and the PDU is
129of type CONFIRMABLE, then the response PDU is transmitted as an empty ACK
130packet. The response pdu is always freed off by the underlying library.
131
132For handling situations where the data to be transmitted does not fit into a
133single packet, see *coap_block*(3).
134
135PDU CREATE AND HEADER FUNCTIONS
136-------------------------------
137
138*Function: coap_new_pdu()*
139
140The *coap_new_pdu*() function returns a newly created PDU of type
141_coap_pdu_t_.
142
143The _type_ is one of the following
144
145[source, c]
146----
147COAP_MESSAGE_CON Set the _PDU_ to be of type confirmable.
148COAP_MESSAGE_NON Set the _PDU_ to be of type non-confirmable.
149COAP_MESSAGE_ACK Set the _PDU_ to be of type acknowledge (for internal use).
150COAP_MESSAGE_RST Set the _PDU_ to be of type reset.
151----
152
153The _code_ is one of the following
154
155[source, c]
156----
157COAP_EMPTY_CODE                               0.00
158COAP_REQUEST_CODE_GET                         0.01
159COAP_REQUEST_CODE_POST                        0.02
160COAP_REQUEST_CODE_PUT                         0.03
161COAP_REQUEST_CODE_DELETE                      0.04
162COAP_REQUEST_CODE_FETCH                       0.05
163COAP_REQUEST_CODE_PATCH                       0.06
164COAP_REQUEST_CODE_IPATCH                      0.07
165COAP_RESPONSE_CODE_OK                         2.00
166COAP_RESPONSE_CODE_CREATED                    2.01
167COAP_RESPONSE_CODE_DELETED                    2.02
168COAP_RESPONSE_CODE_VALID                      2.03
169COAP_RESPONSE_CODE_CHANGED                    2.04
170COAP_RESPONSE_CODE_CONTENT                    2.05
171COAP_RESPONSE_CODE_CONTINUE                   2.31
172COAP_RESPONSE_CODE_BAD_REQUEST                4.00
173COAP_RESPONSE_CODE_UNAUTHORIZED               4.01
174COAP_RESPONSE_CODE_BAD_OPTION                 4.02
175COAP_RESPONSE_CODE_FORBIDDEN                  4.03
176COAP_RESPONSE_CODE_NOT_FOUND                  4.04
177COAP_RESPONSE_CODE_NOT_ALLOWED                4.05
178COAP_RESPONSE_CODE_NOT_ACCEPTABLE             4.06
179COAP_RESPONSE_CODE_INCOMPLETE                 4.08
180COAP_RESPONSE_CODE_CONFLICT                   4.09
181COAP_RESPONSE_CODE_PRECONDITION_FAILED        4.12
182COAP_RESPONSE_CODE_REQUEST_TOO_LARGE          4.13
183COAP_RESPONSE_CODE_UNSUPPORTED_CONTENT_FORMAT 4.15
184COAP_RESPONSE_CODE_UNPROCESSABLE              4.22
185COAP_RESPONSE_CODE_TOO_MANY_REQUESTS          4.29
186COAP_RESPONSE_CODE_INTERNAL_ERROR             5.00
187COAP_RESPONSE_CODE_NOT_IMPLEMENTED            5.01
188COAP_RESPONSE_CODE_BAD_GATEWAY                5.02
189COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE        5.03
190COAP_RESPONSE_CODE_GATEWAY_TIMEOUT            5.04
191COAP_RESPONSE_CODE_PROXYING_NOT_SUPPORTED     5.05
192COAP_RESPONSE_CODE_HOP_LIMIT_REACHED          5.08
193COAP_SIGNALING_CODE_CSM                       7.01
194COAP_SIGNALING_CODE_PING                      7.02
195COAP_SIGNALING_CODE_PONG                      7.03
196COAP_SIGNALING_CODE_RELEASE                   7.04
197COAP_SIGNALING_CODE_ABORT                     7.05
198----
199
200and _session_ is used to set up other default values.
201
202*Function: coap_pdu_init()*
203
204The *coap_pdu_init*() function does the same work as *coap_new_pdu*() but gives
205the additional ability to define the default values for _message_id_ and
206_max_size_ that *coap_new_pdu*() creates.
207
208The _message_id_ must be unique per request (which is not the same as the
209token), and must not be reused within EXCHANGE_LIFETIME (usually 247 seconds).
210To automate this, the function *coap_new_message_id*(_session_) should be
211called.
212
213At the CoAP protocol level, requests and responses are matched by _message_id_
214which is why it needs to be unique.  At the application level, for "separate"
215responses, the initial empty ACK response matches the _message_id_ of the
216request (handled by libcoap) but the actual response has the same token as the
217request and this must be used for the match.  For "piggybacked" responses the
218token must still be used as the valid match for request and response. and the
219_message_id_ just happens to match (but unsafe in case the server is sending
220back a "separate" response).
221
222The _max_size_ parameter defines the maximum size of a _PDU_ and is usually
223determined by calling *coap_session_max_pdu_size*(session);
224
225*Function: coap_new_message_id()*
226
227The *coap_new_message_id*() function returns the next message id to use for
228sending a new request message.
229
230*NOTE:* For reliable messages https://rfc-editor.org/rfc/rfc8323[RFC8323],
231this will always return 0.
232
233*Function: coap_pdu_set_mid()*
234
235The *coap_pdu_set_mid*() function is used to set the message id _mid_ in the
236PDU _pdu_.
237
238*Function: coap_pdu_set_code()*
239
240The *coap_pdu_set_code*() function is used to set the code _code_ in the PDU
241_pdu_.
242
243*Function: coap_pdu_set_type()*
244
245The *coap_pdu_set_type*() function is used to set the _type_ of the PDU _pdu_.
246
247*NOTE:* A PDU does not need to be created by the server application to send
248back a response.  The libcoap server logic creates the initial PDU with
249COAP_EMPTY_CODE, appropriate message_id, matching token and potentially some
250other options before calling the appropriate request handler (See
251*coap_register_request_handler*(3)).
252
253PDU TOKEN FUNCTIONS
254-------------------
255
256*Function: coap_session_init_token()*
257
258The *coap_session_init_token*() function is used to initialize the starting
259_token_ of _length_ for the _session_.
260
261*NOTE:* this only takes the first 8 bytes of the token if extended tokens
262are being used (https://rfc-editor.org/rfc/rfc8974[RFC8974]).
263
264*Function: coap_session_new_token()*
265
266The *coap_session_new_token*() function is used to obtain the next available
267_token_ of _length_ for the _session_.  Note that the same token must be used
268for doing an observe cancellation that was used for doing the observe
269registration.  Otherwise tokens should be unique for each request/response so
270that they can be correctly matched.
271
272*NOTE:* Only a token of up to 8 bytes is returned.
273
274*Function: coap_add_token()*
275
276The *coap_add_token*() function adds in the specified token's _data_ of length
277_length_ to the PDU _pdu_.  The maximum (but impractical due to PDU sizes)
278length of the token is 65804 bytes.  If anything more than 8, the remote peer
279needs to support extended tokens for this to work.
280Adding the token must be done before any options or data are added.
281This function must only be called once per _pdu_, and must not be called
282in the appropriate request handler as the token has already been added into
283the skeletal response PDU.
284
285If a token is not added, then the token in the PDU is zero length, but still a
286valid token which is used for matching.  The exception is an empty ACK packet.
287
288*NOTE:* The token provided by the client application may not be the same as
289used internally by libcoap - for example when doing data transmission where
290the body of data is spread over multiple payloads (see *coap_block*(3)).
291However, when the data transfers complete, the application will receive the
292corrected token in the response PDU.
293
294PDU OPTIONS FUNCTIONS
295---------------------
296
297The following is the current list of options with their numeric value
298----
299/*
300 * The C, U, and N flags indicate the properties
301 * Critical, Unsafe, and NoCacheKey, respectively.
302 * If U is set, then N has no meaning as per
303 * https://rfc-editor.org/rfc/rfc7252#section-5.10
304 * and is set to a -.
305 * Separately, R is for the options that can be repeated
306 *
307 * The least significant byte of the option is set as followed
308 * as per https://rfc-editor.org/rfc/rfc7252#section-5.4.6
309 *
310 *   0   1   2   3   4   5   6   7
311 * --+---+---+---+---+---+---+---+
312 *           | NoCacheKey| U | C |
313 * --+---+---+---+---+---+---+---+
314 *
315 * https://rfc-editor.org/rfc/rfc8613#section-4 goes on to define E, I and U
316 * properties Encrypted and Integrity Protected, Integrity Protected Only and
317 * Unprotected respectively.  Integrity Protected Only is not currently used.
318 *
319 * An Option is tagged with CUNREIU with any of the letters replaced with _ if
320 * not set, or - for N if U is set (see above) for aiding understanding of the
321 * Option.
322 */
323
324COAP_OPTION_IF_MATCH        1 /* C__RE__, opaque,    0-8 B, RFC7252 */
325COAP_OPTION_URI_HOST        3 /* CU-___U, String,  1-255 B, RFC7252 */
326COAP_OPTION_ETAG            4 /* ___RE__, opaque,    1-8 B, RFC7252 */
327COAP_OPTION_IF_NONE_MATCH   5 /* C___E__, empty,       0 B, RFC7252 */
328COAP_OPTION_OBSERVE         6 /* _U-_E_U, empty/uint,  0 B/0-3 B, RFC7641 */
329COAP_OPTION_URI_PORT        7 /* CU-___U, uint,      0-2 B, RFC7252 */
330COAP_OPTION_LOCATION_PATH   8 /* ___RE__, String,  0-255 B, RFC7252 */
331COAP_OPTION_OSCORE          9 /* C_____U, *,       0-255 B, RFC8613 */
332COAP_OPTION_URI_PATH       11 /* CU-RE__, String,  0-255 B, RFC7252 */
333COAP_OPTION_CONTENT_FORMAT 12 /* ____E__, uint,      0-2 B, RFC7252 */
334/* COAP_OPTION_MAXAGE default 60 seconds if not set */
335COAP_OPTION_MAXAGE         14 /* _U-_E_U, uint,      0-4 B, RFC7252 */
336COAP_OPTION_URI_QUERY      15 /* CU-RE__, String,  1-255 B, RFC7252 */
337COAP_OPTION_HOP_LIMIT      16 /* ______U, uint,        1 B, RFC8768 */
338COAP_OPTION_ACCEPT         17 /* C___E__, uint,      0-2 B, RFC7252 */
339COAP_OPTION_Q_BLOCK1       19 /* CU__E_U, uint,      0-3 B, RFC8177 */
340COAP_OPTION_LOCATION_QUERY 20 /* ___RE__, String,  0-255 B, RFC7252 */
341COAP_OPTION_BLOCK2         23 /* CU-_E_U, uint,      0-3 B, RFC7959 */
342COAP_OPTION_BLOCK1         27 /* CU-_E_U, uint,      0-3 B, RFC7959 */
343COAP_OPTION_SIZE2          28 /* __N_E_U, uint,      0-4 B, RFC7959 */
344COAP_OPTION_Q_BLOCK2       31 /* CU_RE_U, uint,      0-3 B, RFC9177 */
345COAP_OPTION_PROXY_URI      35 /* CU-___U, String, 1-1034 B, RFC7252 */
346COAP_OPTION_PROXY_SCHEME   39 /* CU-___U, String,  1-255 B, RFC7252 */
347COAP_OPTION_SIZE1          60 /* __N_E_U, uint,      0-4 B, RFC7252 */
348COAP_OPTION_ECHO          252 /* _N__E_U, opaque,   0-40 B, RFC9175 */
349COAP_OPTION_NORESPONSE    258 /* _U-_E_U, uint,      0-1 B, RFC7967 */
350COAP_OPTION_RTAG          292 /* ___RE_U, opaque,    0-8 B, RFC9175 */
351----
352See FURTHER INFORMATION as to how to get the latest list.
353
354*Function: coap_new_optlist()*
355
356The *coap_new_optlist*() function returns a newly created _optlist_ entry of
357type _coap_optlist_t_*.  The _number_ specifies which CoAP option is to be
358used, and is one of the COAP_OPTION_* definitions.  The _length_ is the length
359of the data of the option, and _data_ points to the content of the option.
360
361*NOTE:* Where possible, the option data needs to be stripped of leading zeros
362(big endian) to reduce the amount of data needed in the PDU, as well as in
363some cases the maximum data size of an option can be exceeded if not stripped
364and hence be illegal.  This is done by using *coap_encode_var_safe*() or
365*coap_encode_var_safe8*().
366
367*Function: coap_insert_optlist()*
368
369The *coap_insert_optlist*() function adds the _optlist_ entry onto the
370end of the _optlist_chain_.
371The initial _optlist_chain_ entry needs to be set to NULL before this function
372is first called.  The *coap_delete_optlist*() function has to be called to free
373off all the _optlist_chain_ entries.
374
375*Function: coap_delete_optlist()*
376
377The *coap_delete_optlist*() function deletes and frees off all the optlist
378entries in the _optlist_chain_.
379
380*Function: coap_add_optlist_pdu()*
381
382The *coap_add_optlist_pdu*() function sorts all of the entries in
383_optlist_chain_ into ascending option numeric order and adds all the entries
384to the _pdu_.  This function does not free off the entries in _optlist_chain_.
385This function must be called after adding any token and before adding in the
386payload data.
387
388*Function: coap_add_option()*
389
390The *coap_add_option*() function adds in the specified option of type _number_
391with _data_ of length _length_ to the PDU _pdu_.
392It is important that options are added to the _pdu_ with _number_ either
393being the same or greater than the previous option _number_ that was added.
394
395*NOTE:* Where possible, the option data needs to be stripped of leading zeros
396(big endian) to reduce the amount of data needed in the PDU, as well as in
397some cases the maximum data size of an option can be exceeded if not stripped
398and hence be illegal.  This is done by using *coap_encode_var_safe*() or
399*coap_encode_var_safe8*().
400
401*Function: coap_encode_var_safe()*
402
403The *coap_encode_var_safe*() function encodes _value_ into _buffer_ which has
404a size of _size_ in bytes.  Normally, the _buffer_ size should be at least
405the sizeof(int) bytes unless you definitely know less space is required.
406
407*Function: coap_encode_var_safe8()*
408
409The *coap_encode_var_safe8*() function encodes 8 byte _value_ into _buffer_
410which has a size of _size_ in bytes.  Normally, the _buffer_ size should be at
411least 8 bytes unless you definitely know less space is required.
412
413*Function: coap_split_path()*
414
415The *coap_split_path*() function splits up _path_ of length _length_ and
416places the result in _buffer_ which has a size of _buflen_ with the nul
417character separating each path component.  _buflen_ needs
418to be preset with the size of _buffer_ before the function call, and then
419_buflen_ is updated with the actual size of _buffer_ used. The return
420value indicates the number of components that individual COAP_OPTION_URI_PATH
421options need to be created for.
422
423*Function: coap_split_query()*
424
425The *coap_split_query*() function splits up _query_ of length _length_ and
426places the result in _buffer_ which has a size of _buflen_ with the nul
427character separating each path component.  _buflen_ needs
428to be preset with the size of _buffer_ before the function call, and then
429_buflen_ is updated with the actual size of _buffer_ used. The return
430value indicates the number of components that individual COAP_OPTION_URI_QUERY
431options need to be created for.
432
433PDU OPTIONS - LIBCOAP HANDLING
434------------------------------
435Most of the options are under the control of the applications, but the
436following are primarily used internally by libcoap.
437
438*COAP_OPTION_BLOCK1* and *COAP_OPTION_BLOCK2*
439
440These Block options are used when a large body needs to be split up into
441multiple payloads.  Following the introduction of
442*coap_context_set_block_mode*(3), libcoap can internally handle the setting
443of these options (see *coap_block*(3)). Applications can continue to include
444these options to set hint block size values.
445
446It is recommended that
447*coap_context_set_block_mode(context, COAP_BLOCK_USE_LIBCOAP|COAP_BLOCK_SINGLE_BODY)*
448is used to reduce the programming requirements for block handling within
449the applications.
450
451*COAP_OPTION_ECHO*
452
453This option can be set by the server application to indicate that the state of
454the client's freshness is confirmed. The libcoap client logic will detect the
455use of the Echo option by the server and reflect back the Echo value in the
456next request without involving the client application.  The opaque
457option Echo may be seen by the client application.
458
459*COAP_OPTION_ETAG*
460
461This option is normally set by the server libcoap logic when sending back
462multiple payloads so that the (libcoap logic) client can re-assemble the
463correct body.
464
465*COAP_OPTION_HOP_LIMIT*
466
467When using proxy logic, the value of the Hop-Limit option is decremented by
468one for each proxy hop. If the count decrements to zero, then a 5.08 (Hop
469Limit Reached) error code is returned to the sender.  The initial count is
47016, unless the client application sets its own limit using the Hop-Limit option.
471
472*COAP_OPTION_RTAG*
473
474This option is set by the libcoap client logic when transmitting multiple
475bodies with multiple payloads so that the (libcoap logic) server can
476differentiate and re-assemble the correct body.
477
478*COAP_OPTION_SIZE1* and *COAP_OPTION_SIZE2*
479
480These options are added by the libcoap logic to provide a size (Size1 by
481libcoap client logic, Size2 by libcoap server logic) indication to the
482recipient of the size of the large body that is to be transferred. See
483*coap_block*(3).
484
485*COAP_OPTION_OSCORE*
486
487This option is used during OSCORE enabled communications.  It should not be
488set by any application, but is used internally.  See *coap_oscore*(3) for
489further information on how to set up OSCORE.
490
491PDU PAYLOAD FUNCTIONS
492---------------------
493
494*Function: coap_add_data()*
495
496The *coap_add_data*() function adds in the specified payload _data_ of length
497_length_ to the PDU _pdu_. Adding the payload data must be done after any
498token or options are added.  This function must only be called once per _pdu_.
499
500*Function: coap_add_data_blocked_response()*
501
502The *coap_add_data_blocked_response*() function adds in the appropriate part
503of the payload _data_ of length _length_ to the PDU _pdu_. It should be used
504as a direct replacement for *coap_add_data*() if it is possible that the data
505will not fit into a single pdu. It also adds in the appropriate
506CoAP options to handle Block-Wise transfer. This function is usually used for
507a server's GET / FETCH response.  The _request_ and _response_ are the same
508parameters for the registered GET / FETCH resource handler.
509The _media_type_ is for the format of the _data_ and _maxage_ defines the
510lifetime of the response.  If set to -1,  then the Max-Age option does not get
511included.  This function must only be called once per _pdu_.
512It is the responsibility of the client to recognize that it has only
513received a part of the data and request the next block (with the appropriate
514Block options) from the server.  Returning the next requested block is handled
515by this function.
516
517*NOTE:* This function has been superseded by *coap_add_data_large_response*().
518See *coap_block*(3).
519
520PDU TRANSMIT FUNCTIONS
521----------------------
522
523*Function: coap_send()*
524
525The *coap_send*() function is used to initiate the transmission of the _pdu_
526associated with the _session_. The caller must not access or delete _pdu_
527after calling *coap_send*() - even if there is a return error.
528
529*NOTE:* For request handlers, returning from the request handler will cause
530the response PDU to be transmitted as appropriate and there is no need to call
531*coap_send*() to do this.
532
533RETURN VALUES
534-------------
535*coap_new_pdu*() and *coap_pdu_init*() return a newly created
536_PDU_ or NULL if there is a malloc or parameter failure.
537
538*coap_new_optlist*() returns a newly created _optlist_ or NULL
539if there is a malloc failure.
540
541*coap_add_token*(), *coap_insert_optlist*(), *coap_add_optlist_pdu*()
542and *coap_add_data*() return 0 on failure, 1 on success.
543
544*coap_encode_var_safe*() returns either the length of bytes
545encoded (which can be 0 when encoding 0) or 0 on failure.
546
547*coap_encode_var_safe8*() returns either the length of bytes
548encoded (which can be 0 when encoding 0) or 0 on failure.
549
550*coap_add_option*() returns the size of option added, or 0 on
551failure.
552
553*coap_send*() returns the CoAP message ID on success or
554COAP_INVALID_MID on failure.
555
556*coap_split_path*() and *coap_split_query*() return the number
557of components found.
558
559*coap_new_message_id*() returns the next CoAP message ID to use.
560
561EXAMPLES
562--------
563*Setup PDU and Transmit*
564
565[source, c]
566----
567#include <coap@LIBCOAP_API_VERSION@/coap.h>
568
569static int
570build_send_pdu(coap_context_t *context, coap_session_t *session,
571uint8_t msgtype, uint8_t request_code, const char *uri, const char *query,
572unsigned char *data, size_t length, int observe) {
573
574  coap_pdu_t *pdu;
575  uint8_t buf[1024];
576  size_t buflen;
577  uint8_t *sbuf = buf;
578  int res;
579  coap_optlist_t *optlist_chain = NULL;
580  /* Remove (void) definition if variable is used */
581  (void)context;
582
583  /* Create the pdu with the appropriate options */
584  pdu = coap_pdu_init(msgtype, request_code, coap_new_message_id(session),
585                      coap_session_max_pdu_size(session));
586  if (!pdu)
587    return 0;
588
589  /*
590   * Create unique token for this request for handling unsolicited /
591   * delayed responses
592   */
593  coap_session_new_token(session, &buflen, buf);
594  if (!coap_add_token(pdu, buflen, buf)) {
595    coap_log_debug("cannot add token to request\n");
596    goto error;
597  }
598
599  if (uri) {
600    /* Add in the URI options */
601    buflen = sizeof(buf);
602    res = coap_split_path((const uint8_t*)uri, strlen(uri), sbuf, &buflen);
603    while (res--) {
604      if (!coap_insert_optlist(&optlist_chain,
605                               coap_new_optlist(COAP_OPTION_URI_PATH,
606                        coap_opt_length(sbuf), coap_opt_value(sbuf))))
607        goto error;
608      sbuf += coap_opt_size(sbuf);
609    }
610  }
611
612  if (query) {
613    /* Add in the QUERY options */
614    buflen = sizeof(buf);
615    res = coap_split_query((const uint8_t*)query, strlen(query), sbuf, &buflen);
616    while (res--) {
617      if (!coap_insert_optlist(&optlist_chain,
618                               coap_new_optlist(COAP_OPTION_URI_QUERY,
619                        coap_opt_length(sbuf), coap_opt_value(sbuf))))
620        goto error;
621      sbuf += coap_opt_size(sbuf);
622    }
623  }
624
625  if (request_code == COAP_REQUEST_GET && observe) {
626    /* Indicate that we want to observe this resource */
627    if (!coap_insert_optlist(&optlist_chain,
628                             coap_new_optlist(COAP_OPTION_OBSERVE,
629                               coap_encode_var_safe(buf, sizeof(buf),
630                               COAP_OBSERVE_ESTABLISH), buf)
631                             ))
632      goto error;
633  }
634
635  /* ... Other code / options etc. ... */
636
637  /* Add in all the options (after internal sorting) to the pdu */
638  if (!coap_add_optlist_pdu(pdu, &optlist_chain))
639    goto error;
640
641  if (data && length) {
642    /* Add in the specified data */
643    if (!coap_add_data(pdu, length, data))
644      goto error;
645  }
646
647  if (coap_send(session, pdu) == COAP_INVALID_MID)
648    goto error;
649  return 1;
650
651error:
652
653  if (pdu)
654    coap_delete_pdu(pdu);
655  return 0;
656
657}
658----
659
660*Resource Request Handler Response PDU Update*
661
662[source, c]
663----
664#include <coap@LIBCOAP_API_VERSION@/coap.h>
665
666#include <stdio.h>
667
668static void
669hnd_get_time(coap_resource_t *resource, coap_session_t *session,
670const coap_pdu_t *request, const coap_string_t *query, coap_pdu_t *response) {
671
672  unsigned char buf[40];
673  size_t len;
674  time_t now;
675
676  /* ... Additional analysis code for resource, request pdu etc.  ... */
677
678  /* After analysis, generate a suitable response */
679
680  now = time(NULL);
681
682  if (query != NULL && coap_string_equal(query, coap_make_str_const("secs"))) {
683    /* Output secs since Jan 1 1970 */
684    len = snprintf((char *)buf, sizeof(buf), "%lu", now);
685  }
686  else {
687    /* Output human-readable time */
688    struct tm *tmp;
689    tmp = gmtime(&now);
690    if (!tmp) {
691      /* If 'now' is not valid */
692      coap_pdu_set_code(response, COAP_RESPONSE_CODE_NOT_FOUND);
693      return;
694    }
695    len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp);
696  }
697  coap_pdu_set_code(response, COAP_RESPONSE_CODE_CONTENT);
698  /*
699   * Invoke coap_add_data_large_response() to do all the hard work.
700   *
701   * Define the format - COAP_MEDIATYPE_TEXT_PLAIN - to add in
702   * Define how long this response is valid for (secs) - 1 - to add in.
703   * Etag Option added internally with unique value as param set to 0
704   *
705   * Observe Option added internally if needed within the function
706   * Block2 Option added internally if output too large
707   * Size2 Option added internally
708   */
709  coap_add_data_large_response(resource, session, request, response,
710                               query, COAP_MEDIATYPE_TEXT_PLAIN, 1, 0,
711                               len,
712                               buf, NULL, NULL);
713
714  /*
715   * Returning from the request handler will cause the response to be
716   * sent off (assuming coap_pdu_set_code() has been called), unless
717   * the response is confirmable and the code is COAP_EMPTY_CODE which
718   * will cause an empty ACK packet to be returned).
719   */
720
721}
722----
723
724SEE ALSO
725--------
726*coap_block*(3), *coap_observe*(3), *coap_oscore*(3), *coap_pdu_access*(3)
727and *coap_resource*(3)
728
729FURTHER INFORMATION
730-------------------
731See
732
733"https://rfc-editor.org/rfc/rfc7252[RFC7252: The Constrained Application Protocol (CoAP)]"
734
735"https://rfc-editor.org/rfc/rfc7959[RFC7959: Block-Wise Transfers in the Constrained Application Protocol (CoAP)]"
736
737"https://rfc-editor.org/rfc/rfc8613[RFC8613: Object Security for Constrained RESTful Environments (OSCORE)]"
738
739"https://rfc-editor.org/rfc/rfc8974[RFC8974: Extended Tokens and Stateless Clients in the Constrained Application Protocol (CoAP)]"
740
741for further information.
742
743See https://www.iana.org/assignments/core-parameters/core-parameters.xhtml#option-numbers
744for the current set of defined CoAP Options.
745
746BUGS
747----
748Please report bugs on the mailing list for libcoap:
749libcoap-developers@lists.sourceforge.net or raise an issue on GitHub at
750https://github.com/obgm/libcoap/issues
751
752AUTHORS
753-------
754The libcoap project <libcoap-developers@lists.sourceforge.net>
755