• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * net.h -- CoAP network interface
3  *
4  * Copyright (C) 2010-2015 Olaf Bergmann <bergmann@tzi.org>
5  *
6  * This file is part of the CoAP library libcoap. Please see README for terms
7  * of use.
8  */
9 
10 #ifndef COAP_NET_H_
11 #define COAP_NET_H_
12 
13 #include <stdlib.h>
14 #include <string.h>
15 #ifndef _WIN32
16 #include <sys/time.h>
17 #endif
18 #include <time.h>
19 
20 #ifdef WITH_LWIP
21 #include <lwip/ip_addr.h>
22 #endif
23 
24 #include "coap_io.h"
25 #if defined(HAVE_LIBTINYDTLS) || defined(HAVE_OPENSSL) || defined(HAVE_LIBGNUTLS)
26 #include "coap_dtls.h"
27 #endif /* HAVE_LIBTINYDTLS || HAVE_OPENSSL || HAVE_LIBGNUTLS */
28 #include "coap_event.h"
29 #include "coap_time.h"
30 #include "option.h"
31 #include "pdu.h"
32 #include "prng.h"
33 #include "coap_session.h"
34 
35 struct coap_queue_t;
36 
37 /**
38  * Queue entry
39  */
40 typedef struct coap_queue_t {
41   struct coap_queue_t *next;
42   coap_tick_t t;                /**< when to send PDU for the next time */
43   unsigned char retransmit_cnt; /**< retransmission counter, will be removed
44                                  *    when zero */
45   unsigned int timeout;         /**< the randomized timeout value */
46   coap_session_t *session;      /**< the CoAP session */
47   coap_tid_t id;                /**< CoAP transaction id */
48   coap_pdu_t *pdu;              /**< the CoAP PDU to send */
49 } coap_queue_t;
50 
51 /**
52  * Adds @p node to given @p queue, ordered by variable t in @p node.
53  *
54  * @param queue Queue to add to.
55  * @param node Node entry to add to Queue.
56  *
57  * @return @c 1 added to queue, @c 0 failure.
58  */
59 int coap_insert_node(coap_queue_t **queue, coap_queue_t *node);
60 
61 /**
62  * Destroys specified @p node.
63  *
64  * @param node Node entry to remove.
65  *
66  * @return @c 1 node deleted from queue, @c 0 failure.
67  */
68 int coap_delete_node(coap_queue_t *node);
69 
70 /**
71  * Removes all items from given @p queue and frees the allocated storage.
72  *
73  * @param queue The queue to delete.
74  */
75 void coap_delete_all(coap_queue_t *queue);
76 
77 /**
78  * Creates a new node suitable for adding to the CoAP sendqueue.
79  *
80  * @return New node entry, or @c NULL if failure.
81  */
82 coap_queue_t *coap_new_node(void);
83 
84 struct coap_resource_t;
85 struct coap_context_t;
86 #ifndef WITHOUT_ASYNC
87 struct coap_async_state_t;
88 #endif
89 
90 /**
91  * Response handler that is used as call-back in coap_context_t.
92  *
93  * @param context CoAP session.
94  * @param session CoAP session.
95  * @param sent The PDU that was transmitted.
96  * @param received The PDU that was received.
97  * @param id CoAP transaction ID.
98  */
99 typedef void (*coap_response_handler_t)(struct coap_context_t *context,
100                                         coap_session_t *session,
101                                         coap_pdu_t *sent,
102                                         coap_pdu_t *received,
103                                         const coap_tid_t id);
104 
105 /**
106  * Negative Acknowedge handler that is used as call-back in coap_context_t.
107  *
108  * @param context CoAP session.
109  * @param session CoAP session.
110  * @param sent The PDU that was transmitted.
111  * @param reason The reason for the NACK.
112  * @param id CoAP transaction ID.
113  */
114 typedef void (*coap_nack_handler_t)(struct coap_context_t *context,
115                                     coap_session_t *session,
116                                     coap_pdu_t *sent,
117                                     coap_nack_reason_t reason,
118                                     const coap_tid_t id);
119 
120 /**
121  * Recieved Ping handler that is used as call-back in coap_context_t.
122  *
123  * @param context CoAP session.
124  * @param session CoAP session.
125  * @param received The PDU that was received.
126  * @param id CoAP transaction ID.
127  */
128 typedef void (*coap_ping_handler_t)(struct coap_context_t *context,
129                                     coap_session_t *session,
130                                     coap_pdu_t *received,
131                                     const coap_tid_t id);
132 
133 /**
134  * Recieved Pong handler that is used as call-back in coap_context_t.
135  *
136  * @param context CoAP session.
137  * @param session CoAP session.
138  * @param received The PDU that was received.
139  * @param id CoAP transaction ID.
140  */
141 typedef void (*coap_pong_handler_t)(struct coap_context_t *context,
142                                     coap_session_t *session,
143                                     coap_pdu_t *received,
144                                     const coap_tid_t id);
145 
146 /**
147  * The CoAP stack's global state is stored in a coap_context_t object.
148  */
149 typedef struct coap_context_t {
150   coap_opt_filter_t known_options;
151   struct coap_resource_t *resources; /**< hash table or list of known
152                                           resources */
153   struct coap_resource_t *unknown_resource; /**< can be used for handling
154                                                  unknown resources */
155 
156 #ifndef WITHOUT_ASYNC
157   /**
158    * list of asynchronous transactions */
159   struct coap_async_state_t *async_state;
160 #endif /* WITHOUT_ASYNC */
161 
162   /**
163    * The time stamp in the first element of the sendqeue is relative
164    * to sendqueue_basetime. */
165   coap_tick_t sendqueue_basetime;
166   coap_queue_t *sendqueue;
167   coap_endpoint_t *endpoint;      /**< the endpoints used for listening  */
168   coap_session_t *sessions;       /**< client sessions */
169 
170 #ifdef WITH_CONTIKI
171   struct uip_udp_conn *conn;      /**< uIP connection object */
172   struct etimer retransmit_timer; /**< fires when the next packet must be sent */
173   struct etimer notify_timer;     /**< used to check resources periodically */
174 #endif /* WITH_CONTIKI */
175 
176 #ifdef WITH_LWIP
177   uint8_t timer_configured;       /**< Set to 1 when a retransmission is
178                                    *   scheduled using lwIP timers for this
179                                    *   context, otherwise 0. */
180 #endif /* WITH_LWIP */
181 
182   coap_response_handler_t response_handler;
183   coap_nack_handler_t nack_handler;
184   coap_ping_handler_t ping_handler;
185   coap_pong_handler_t pong_handler;
186 
187   /**
188    * Callback function that is used to signal events to the
189    * application.  This field is set by coap_set_event_handler().
190    */
191   coap_event_handler_t handle_event;
192 
193   ssize_t (*network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen);
194 
195   ssize_t (*network_read)(coap_socket_t *sock, struct coap_packet_t *packet);
196 
197 #if defined(HAVE_LIBTINYDTLS) || defined(HAVE_OPENSSL) || defined(HAVE_LIBGNUTLS)
198   size_t(*get_client_psk)(const coap_session_t *session, const uint8_t *hint, size_t hint_len, uint8_t *identity, size_t *identity_len, size_t max_identity_len, uint8_t *psk, size_t max_psk_len);
199   size_t(*get_server_psk)(const coap_session_t *session, const uint8_t *identity, size_t identity_len, uint8_t *psk, size_t max_psk_len);
200   size_t(*get_server_hint)(const coap_session_t *session, uint8_t *hint, size_t max_hint_len);
201 
202   void *dtls_context;
203   uint8_t *psk_hint;
204   size_t psk_hint_len;
205   uint8_t *psk_key;
206   size_t psk_key_len;
207 #endif /* HAVE_LIBTINYDTLS || HAVE_OPENSSL || HAVE_LIBGNUTLS */
208 
209   unsigned int session_timeout;    /**< Number of seconds of inactivity after which an unused session will be closed. 0 means use default. */
210   unsigned int max_idle_sessions;  /**< Maximum number of simultaneous unused sessions per endpoint. 0 means no maximum. */
211   unsigned int max_handshake_sessions; /**< Maximum number of simultaneous negotating sessions per endpoint. 0 means use default. */
212   unsigned int ping_timeout;           /**< Minimum inactivity time before sending a ping message. 0 means disabled. */
213   unsigned int csm_timeout;           /**< Timeout for waiting for a CSM from the remote side. 0 means disabled. */
214 
215   void *app;                       /**< application-specific data */
216 #ifdef COAP_EPOLL_SUPPORT
217   int epfd;                        /**< External FD for epoll */
218   int eptimerfd;                   /**< Internal FD for timeout */
219   coap_tick_t next_timeout;        /**< When the next timeout is to occur */
220 #endif /* COAP_EPOLL_SUPPORT */
221 } coap_context_t;
222 
223 /**
224  * Registers a new message handler that is called whenever a response was
225  * received that matches an ongoing transaction.
226  *
227  * @param context The context to register the handler for.
228  * @param handler The response handler to register.
229  */
230 COAP_STATIC_INLINE void
coap_register_response_handler(coap_context_t * context,coap_response_handler_t handler)231 coap_register_response_handler(coap_context_t *context,
232                                coap_response_handler_t handler) {
233   context->response_handler = handler;
234 }
235 
236 /**
237  * Registers a new message handler that is called whenever a confirmable
238  * message (request or response) is dropped after all retries have been
239  * exhausted, or a rst message was received, or a network or TLS level
240  * event was received that indicates delivering the message is not possible.
241  *
242  * @param context The context to register the handler for.
243  * @param handler The nack handler to register.
244  */
245 COAP_STATIC_INLINE void
coap_register_nack_handler(coap_context_t * context,coap_nack_handler_t handler)246 coap_register_nack_handler(coap_context_t *context,
247                            coap_nack_handler_t handler) {
248   context->nack_handler = handler;
249 }
250 
251 /**
252  * Registers a new message handler that is called whenever a CoAP Ping
253  * message is received.
254  *
255  * @param context The context to register the handler for.
256  * @param handler The ping handler to register.
257  */
258 COAP_STATIC_INLINE void
coap_register_ping_handler(coap_context_t * context,coap_ping_handler_t handler)259 coap_register_ping_handler(coap_context_t *context,
260                            coap_ping_handler_t handler) {
261   context->ping_handler = handler;
262 }
263 
264 /**
265  * Registers a new message handler that is called whenever a CoAP Pong
266  * message is received.
267  *
268  * @param context The context to register the handler for.
269  * @param handler The pong handler to register.
270  */
271 COAP_STATIC_INLINE void
coap_register_pong_handler(coap_context_t * context,coap_pong_handler_t handler)272 coap_register_pong_handler(coap_context_t *context,
273                            coap_pong_handler_t handler) {
274   context->pong_handler = handler;
275 }
276 
277 /**
278  * Registers the option type @p type with the given context object @p ctx.
279  *
280  * @param ctx  The context to use.
281  * @param type The option type to register.
282  */
283 COAP_STATIC_INLINE void
coap_register_option(coap_context_t * ctx,uint16_t type)284 coap_register_option(coap_context_t *ctx, uint16_t type) {
285   coap_option_setb(ctx->known_options, type);
286 }
287 
288 /**
289  * Set sendqueue_basetime in the given context object @p ctx to @p now. This
290  * function returns the number of elements in the queue head that have timed
291  * out.
292  */
293 unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now);
294 
295 /**
296  * Returns the next pdu to send without removing from sendqeue.
297  */
298 coap_queue_t *coap_peek_next( coap_context_t *context );
299 
300 /**
301  * Returns the next pdu to send and removes it from the sendqeue.
302  */
303 coap_queue_t *coap_pop_next( coap_context_t *context );
304 
305 /**
306  * Creates a new coap_context_t object that will hold the CoAP stack status.
307  */
308 coap_context_t *coap_new_context(const coap_address_t *listen_addr);
309 
310 #ifdef WITH_LWIP
311 /**
312  * This API is called when the caller is not in the same thread with tcpip thread.
313  * Creates a new coap_context_t object that will hold the CoAP stack status.
314  */
315 coap_context_t *coap_new_context_lwip(const coap_address_t *listen_addr);
316 #endif /* WITH_LWIP */
317 
318 #if defined(HAVE_LIBTINYDTLS) || defined(HAVE_OPENSSL) || defined(HAVE_LIBGNUTLS)
319 /**
320  * Set the context's default PSK hint and/or key for a server.
321  *
322  * @param context The current coap_context_t object.
323  * @param hint    The default PSK server hint sent to a client. If @p NULL, PSK
324  *                authentication is disabled. Empty string is a valid hint.
325  * @param key     The default PSK key. If @p NULL, PSK authentication will fail.
326  * @param key_len The default PSK key's length. If @p 0, PSK authentication will
327  *                fail.
328  *
329  * @return @c 1 if successful, else @c 0.
330  */
331 int coap_context_set_psk( coap_context_t *context, const char *hint,
332                            const uint8_t *key, size_t key_len );
333 
334 /**
335  * Set the context's default PKI information for a server.
336  *
337  * @param context        The current coap_context_t object.
338  * @param setup_data     If @p NULL, PKI authentication will fail. Certificate
339  *                       information required.
340  *
341  * @return @c 1 if successful, else @c 0.
342  */
343 int
344 coap_context_set_pki(coap_context_t *context,
345                      coap_dtls_pki_t *setup_data);
346 
347 /**
348  * Set the context's default Root CA information for a client or server.
349  *
350  * @param context        The current coap_context_t object.
351  * @param ca_file        If not @p NULL, is the full path name of a PEM encoded
352  *                       file containing all the Root CAs to be used.
353  * @param ca_dir         If not @p NULL, points to a directory containing PEM
354  *                       encoded files containing all the Root CAs to be used.
355  *
356  * @return @c 1 if successful, else @c 0.
357  */
358 int
359 coap_context_set_pki_root_cas(coap_context_t *context,
360                               const char *ca_file,
361                               const char *ca_dir);
362 #endif /* HAVE_LIBTINYDTLS || HAVE_OPENSSL || HAVE_LIBGNUTLS */
363 
364 /**
365  * Set the context keepalive timer for sessions.
366  * A keepalive message will be sent after if a session has been inactive,
367  * i.e. no packet sent or received, for the given number of seconds.
368  * For unreliable protocols, a CoAP Empty message will be sent. If a
369  * CoAP RST is not received, the CoAP Empty messages will get resent based
370  * on the Confirmable retry parameters until there is a failure timeout,
371  * at which point the session will be considered as disconnected.
372  * For reliable protocols, a CoAP PING message will be sent. If a CoAP PONG
373  * has not been received before the next PING is due to be sent, the session
374  * will be considered as disconnected.
375  *
376  * @param context        The coap_context_t object.
377  * @param seconds        Number of seconds for the inactivity timer, or zero
378  *                       to disable CoAP-level keepalive messages.
379  *
380  * @return 1 if successful, else 0
381  */
382 void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds);
383 
384 /**
385  * Get the libcoap internal file descriptor for using in an application's
386  * select() or returned as an event in an application's epoll_wait() call.
387  *
388  * @param context        The coap_context_t object.
389  *
390  * @return The libcoap file descriptor or @c -1 if epoll is not available.
391  */
392 int coap_context_get_coap_fd(coap_context_t *context);
393 
394 /**
395  * Returns a new message id and updates @p session->tx_mid accordingly. The
396  * message id is returned in network byte order to make it easier to read in
397  * tracing tools.
398  *
399  * @param session The current coap_session_t object.
400  *
401  * @return        Incremented message id in network byte order.
402  */
403 COAP_STATIC_INLINE uint16_t
coap_new_message_id(coap_session_t * session)404 coap_new_message_id(coap_session_t *session) {
405   return ++session->tx_mid;
406 }
407 
408 /**
409  * CoAP stack context must be released with coap_free_context(). This function
410  * clears all entries from the receive queue and send queue and deletes the
411  * resources that have been registered with @p context, and frees the attached
412  * endpoints.
413  *
414  * @param context The current coap_context_t object to free off.
415  */
416 void coap_free_context(coap_context_t *context);
417 
418 #ifdef WITH_LWIP
419 /**
420  * This API is called when the caller is not in the same thread with tcpip thread.
421  * CoAP stack context must be released with coap_free_context(). This function
422  * clears all entries from the receive queue and send queue and deletes the
423  * resources that have been registered with @p context, and frees the attached
424  * endpoints.
425  *
426  * @param context The current coap_context_t object to free off.
427  */
428 void coap_free_context_lwip(coap_context_t *context);
429 #endif /* WITH_LWIP */
430 
431 /**
432  * Stores @p data with the given CoAP context. This function
433  * overwrites any value that has previously been stored with @p
434  * context.
435  *
436  * @param context The CoAP context.
437  * @param data The data to store with wih the context. Note that this data
438  *             must be valid during the lifetime of @p context.
439  */
440 void coap_set_app_data(coap_context_t *context, void *data);
441 
442 /**
443  * Returns any application-specific data that has been stored with @p
444  * context using the function coap_set_app_data(). This function will
445  * return @c NULL if no data has been stored.
446  *
447  * @param context The CoAP context.
448  *
449  * @return The data previously stored or @c NULL if not data stored.
450  */
451 void *coap_get_app_data(const coap_context_t *context);
452 
453 /**
454  * Creates a new ACK PDU with specified error @p code. The options specified by
455  * the filter expression @p opts will be copied from the original request
456  * contained in @p request. Unless @c SHORT_ERROR_RESPONSE was defined at build
457  * time, the textual reason phrase for @p code will be added as payload, with
458  * Content-Type @c 0.
459  * This function returns a pointer to the new response message, or @c NULL on
460  * error. The storage allocated for the new message must be relased with
461  * coap_free().
462  *
463  * @param request Specification of the received (confirmable) request.
464  * @param code    The error code to set.
465  * @param opts    An option filter that specifies which options to copy from
466  *                the original request in @p node.
467  *
468  * @return        A pointer to the new message or @c NULL on error.
469  */
470 coap_pdu_t *coap_new_error_response(coap_pdu_t *request,
471                                     unsigned char code,
472                                     coap_opt_filter_t opts);
473 
474 /**
475  * Sends an error response with code @p code for request @p request to @p dst.
476  * @p opts will be passed to coap_new_error_response() to copy marked options
477  * from the request. This function returns the transaction id if the message was
478  * sent, or @c COAP_INVALID_TID otherwise.
479  *
480  * @param session         The CoAP session.
481  * @param request         The original request to respond to.
482  * @param code            The response code.
483  * @param opts            A filter that specifies the options to copy from the
484  *                        @p request.
485  *
486  * @return                The transaction id if the message was sent, or @c
487  *                        COAP_INVALID_TID otherwise.
488  */
489 coap_tid_t coap_send_error(coap_session_t *session,
490                            coap_pdu_t *request,
491                            unsigned char code,
492                            coap_opt_filter_t opts);
493 
494 /**
495  * Helper funktion to create and send a message with @p type (usually ACK or
496  * RST). This function returns @c COAP_INVALID_TID when the message was not
497  * sent, a valid transaction id otherwise.
498  *
499  * @param session         The CoAP session.
500  * @param request         The request that should be responded to.
501  * @param type            Which type to set.
502  * @return                transaction id on success or @c COAP_INVALID_TID
503  *                        otherwise.
504  */
505 coap_tid_t
506 coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type);
507 
508 /**
509  * Sends an ACK message with code @c 0 for the specified @p request to @p dst.
510  * This function returns the corresponding transaction id if the message was
511  * sent or @c COAP_INVALID_TID on error.
512  *
513  * @param session         The CoAP session.
514  * @param request         The request to be acknowledged.
515  *
516  * @return                The transaction id if ACK was sent or @c
517  *                        COAP_INVALID_TID on error.
518  */
519 coap_tid_t coap_send_ack(coap_session_t *session, coap_pdu_t *request);
520 
521 /**
522  * Sends an RST message with code @c 0 for the specified @p request to @p dst.
523  * This function returns the corresponding transaction id if the message was
524  * sent or @c COAP_INVALID_TID on error.
525  *
526  * @param session         The CoAP session.
527  * @param request         The request to be reset.
528  *
529  * @return                The transaction id if RST was sent or @c
530  *                        COAP_INVALID_TID on error.
531  */
532 COAP_STATIC_INLINE coap_tid_t
coap_send_rst(coap_session_t * session,coap_pdu_t * request)533 coap_send_rst(coap_session_t *session, coap_pdu_t *request) {
534   return coap_send_message_type(session, request, COAP_MESSAGE_RST);
535 }
536 
537 #ifdef WITH_LWIP
538 /**
539  * This API is called when the caller is not in the same thread
540  * with tcpip thread.
541  * Sends an error response with code @p code for request @p request to @p dst.
542  * @p opts will be passed to coap_new_error_response() to copy marked options
543  * from the request. This function returns the transaction id if the message was
544  * sent, or @c COAP_INVALID_TID otherwise.
545  *
546  * @param session         The CoAP session.
547  * @param request         The original request to respond to.
548  * @param code            The response code.
549  * @param opts            A filter that specifies the options to copy from the
550  *                        @p request.
551  *
552  * @return                The transaction id if the message was sent, or @c
553  *                        COAP_INVALID_TID otherwise.
554  */
555 coap_tid_t coap_send_error_lwip(coap_session_t *session,
556                            coap_pdu_t *request,
557                            unsigned char code,
558                            coap_opt_filter_t opts);
559 
560 /**
561  * This API is called when the caller is not in the same thread
562  * with tcpip thread.
563  * Helper funktion to create and send a message with @p type (usually ACK or
564  * RST). This function returns @c COAP_INVALID_TID when the message was not
565  * sent, a valid transaction id otherwise.
566  *
567  * @param session         The CoAP session.
568  * @param request         The request that should be responded to.
569  * @param type            Which type to set.
570  * @return                transaction id on success or @c COAP_INVALID_TID
571  *                        otherwise.
572  */
573 coap_tid_t
574 coap_send_message_type_lwip(coap_session_t *session, coap_pdu_t *request, unsigned char type);
575 
576 /**
577  * This API is called when the caller is not in the same thread
578  * with tcpip thread.
579  * Sends an ACK message with code @c 0 for the specified @p request to @p dst.
580  * This function returns the corresponding transaction id if the message was
581  * sent or @c COAP_INVALID_TID on error.
582  *
583  * @param session         The CoAP session.
584  * @param request         The request to be acknowledged.
585  *
586  * @return                The transaction id if ACK was sent or @c
587  *                        COAP_INVALID_TID on error.
588  */
589 coap_tid_t coap_send_ack_lwip(coap_session_t *session, coap_pdu_t *request);
590 
591 /**
592  * This API is called when the caller is not in the same thread
593  * with tcpip thread.
594  * Sends an RST message with code @c 0 for the specified @p request to @p dst.
595  * This function returns the corresponding transaction id if the message was
596  * sent or @c COAP_INVALID_TID on error.
597  *
598  * @param session         The CoAP session.
599  * @param request         The request to be reset.
600  *
601  * @return                The transaction id if RST was sent or @c
602  *                        COAP_INVALID_TID on error.
603  */
604 COAP_STATIC_INLINE coap_tid_t
coap_send_rst_lwip(coap_session_t * session,coap_pdu_t * request)605 coap_send_rst_lwip(coap_session_t *session, coap_pdu_t *request) {
606   return coap_send_message_type_lwip(session, request, COAP_MESSAGE_RST);
607 }
608 #endif
609 
610 /**
611 * Sends a CoAP message to given peer. The memory that is
612 * allocated by pdu will be released by coap_send().
613 * The caller must not use the pdu after calling coap_send().
614 *
615 * @param session         The CoAP session.
616 * @param pdu             The CoAP PDU to send.
617 *
618 * @return                The message id of the sent message or @c
619 *                        COAP_INVALID_TID on error.
620 */
621 coap_tid_t coap_send( coap_session_t *session, coap_pdu_t *pdu );
622 
623 #ifdef WITH_LWIP
624 /**
625 * This API is called when the caller is not in the same thread
626 * with tcpip thread.
627 * Sends a CoAP message to given peer. The memory that is
628 * allocated by pdu will be released by coap_send_lwip().
629 * The caller must not use the pdu after calling coap_send_lwip().
630 *
631 * @param session         The CoAP session.
632 * @param pdu             The CoAP PDU to send.
633 *
634 * @return                The message id of the sent message or @c
635 *                        COAP_INVALID_TID on error.
636 */
637 coap_tid_t coap_send_lwip(coap_session_t *session, coap_pdu_t *pdu);
638 #endif /* WITH_LWIP */
639 
640 /**
641  * Handles retransmissions of confirmable messages
642  *
643  * @param context      The CoAP context.
644  * @param node         The node to retransmit.
645  *
646  * @return             The message id of the sent message or @c
647  *                     COAP_INVALID_TID on error.
648  */
649 coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node);
650 
651 /**
652 * For applications with their own message loop, send all pending retransmits and
653 * return the list of sockets with events to wait for and the next timeout
654 * The application should call coap_read, then coap_write again when any condition below is true:
655 * - data is available on any of the sockets with the COAP_SOCKET_WANT_READ
656 * - an incoming connection is pending in the listen queue and the COAP_SOCKET_WANT_ACCEPT flag is set
657 * - at least some data can be written without blocking on any of the sockets with the COAP_SOCKET_WANT_WRITE flag set
658 * - a connection event occured (success or failure) and the COAP_SOCKET_WANT_CONNECT flag is set
659 * - the timeout has expired
660 * Before calling coap_read or coap_write again, the application should position COAP_SOCKET_CAN_READ and COAP_SOCKET_CAN_WRITE flags as applicable.
661 *
662 * @param ctx The CoAP context
663 * @param sockets array of socket descriptors, filled on output
664 * @param max_sockets size of socket array.
665 * @param num_sockets pointer to the number of valid entries in the socket arrays on output
666 * @param now Current time.
667 *
668 * @return timeout as maxmimum number of milliseconds that the application should wait for network events or 0 if the application should wait forever.
669 */
670 
671 unsigned int
672 coap_write(coap_context_t *ctx,
673   coap_socket_t *sockets[],
674   unsigned int max_sockets,
675   unsigned int *num_sockets,
676   coap_tick_t now
677 );
678 
679 /**
680  * For applications with their own message loop, reads all data from the network.
681  *
682  * @param ctx The CoAP context
683  * @param now Current time
684  */
685 void coap_read(coap_context_t *ctx, coap_tick_t now);
686 
687 #define COAP_RUN_BLOCK    0
688 #define COAP_RUN_NONBLOCK 1
689 
690 /**
691  * The main message processing loop.
692  *
693  * @param ctx The CoAP context
694  * @param timeout_ms Minimum number of milliseconds to wait for new packets
695  *                   before returning. If COAP_RUN_BLOCK, the call will block
696  *                   until at least one new packet is received. If
697  *                   COAP_RUN_NONBLOCK, the function will return immediately
698  *                   following without waiting for any new input not already
699  *                   available.
700  *
701  * @return Number of milliseconds spent in coap_run_once, or @c -1 if there
702  *         was an error
703  */
704 
705 int coap_run_once( coap_context_t *ctx, unsigned int timeout_ms );
706 
707 /**
708  * Any now timed out delayed packet is transmitted, along with any packets
709  * associated with requested observable response.
710  *
711  * In addition, it returns when the next expected I/O is expected to take place
712  * (e.g. a packet retransmit).
713  *
714  * Note: If epoll support is compiled into libcoap, coap_io_prepare_epoll() must
715  * be used instead of coap_write().
716  *
717  * Internal function.
718  *
719  * @param ctx The CoAP context
720  * @param now Current time.
721  *
722  * @return timeout Maxmimum number of milliseconds that can be used by a
723  *                 epoll_wait() to wait for network events or 0 if wait should be
724  *                 forever.
725  */
726 unsigned int
727 coap_io_prepare_epoll(coap_context_t *ctx, coap_tick_t now);
728 
729 struct epoll_event;
730 /**
731  * Process all the epoll events
732  *
733  * Internal function
734  *
735  * @param ctx    The current CoAP context.
736  * @param events The list of events returned from an epoll_wait() call.
737  * @param nevents The number of events.
738  *
739  */
740 void coap_io_do_events(coap_context_t *ctx, struct epoll_event* events,
741                       size_t nevents);
742 
743 /**
744  * Parses and interprets a CoAP datagram with context @p ctx. This function
745  * returns @c 0 if the datagram was handled, or a value less than zero on
746  * error.
747  *
748  * @param ctx    The current CoAP context.
749  * @param session The current CoAP session.
750  * @param data The received packet'd data.
751  * @param data_len The received packet'd data length.
752  *
753  * @return       @c 0 if message was handled successfully, or less than zero on
754  *               error.
755  */
756 int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *data, size_t data_len);
757 
758 /**
759  * Invokes the event handler of @p context for the given @p event and
760  * @p data.
761  *
762  * @param context The CoAP context whose event handler is to be called.
763  * @param event   The event to deliver.
764  * @param session The session related to @p event.
765  * @return The result from the associated event handler or 0 if none was
766  * registered.
767  */
768 int coap_handle_event(coap_context_t *context,
769                       coap_event_t event,
770                       coap_session_t *session);
771 /**
772  * This function removes the element with given @p id from the list given list.
773  * If @p id was found, @p node is updated to point to the removed element. Note
774  * that the storage allocated by @p node is @b not released. The caller must do
775  * this manually using coap_delete_node(). This function returns @c 1 if the
776  * element with id @p id was found, @c 0 otherwise. For a return value of @c 0,
777  * the contents of @p node is undefined.
778  *
779  * @param queue The queue to search for @p id.
780  * @param session The session to look for.
781  * @param id    The transaction id to look for.
782  * @param node  If found, @p node is updated to point to the removed node. You
783  *              must release the storage pointed to by @p node manually.
784  *
785  * @return      @c 1 if @p id was found, @c 0 otherwise.
786  */
787 int coap_remove_from_queue(coap_queue_t **queue,
788                            coap_session_t *session,
789                            coap_tid_t id,
790                            coap_queue_t **node);
791 
792 coap_tid_t
793 coap_wait_ack( coap_context_t *context, coap_session_t *session,
794                coap_queue_t *node);
795 
796 /**
797  * Retrieves transaction from the queue.
798  *
799  * @param queue The transaction queue to be searched.
800  * @param session The session to find.
801  * @param id    The transaction id to find.
802  *
803  * @return      A pointer to the transaction object or @c NULL if not found.
804  */
805 coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_session_t *session, coap_tid_t id);
806 
807 /**
808  * Cancels all outstanding messages for session @p session that have the specified
809  * token.
810  *
811  * @param context      The context in use.
812  * @param session      Session of the messages to remove.
813  * @param token        Message token.
814  * @param token_length Actual length of @p token.
815  */
816 void coap_cancel_all_messages(coap_context_t *context,
817                               coap_session_t *session,
818                               const uint8_t *token,
819                               size_t token_length);
820 
821 /**
822 * Cancels all outstanding messages for session @p session.
823 *
824 * @param context      The context in use.
825 * @param session      Session of the messages to remove.
826 * @param reason       The reasion for the session cancellation
827 */
828 void
829 coap_cancel_session_messages(coap_context_t *context,
830                              coap_session_t *session,
831                              coap_nack_reason_t reason);
832 
833 /**
834  * Dispatches the PDUs from the receive queue in given context.
835  */
836 void coap_dispatch(coap_context_t *context, coap_session_t *session,
837                    coap_pdu_t *pdu);
838 
839 /**
840  * Returns 1 if there are no messages to send or to dispatch in the context's
841  * queues. */
842 int coap_can_exit(coap_context_t *context);
843 
844 /**
845  * Returns the current value of an internal tick counter. The counter counts \c
846  * COAP_TICKS_PER_SECOND ticks every second.
847  */
848 void coap_ticks(coap_tick_t *);
849 
850 /**
851  * Verifies that @p pdu contains no unknown critical options. Options must be
852  * registered at @p ctx, using the function coap_register_option(). A basic set
853  * of options is registered automatically by coap_new_context(). This function
854  * returns @c 1 if @p pdu is ok, @c 0 otherwise. The given filter object @p
855  * unknown will be updated with the unknown options. As only @c COAP_MAX_OPT
856  * options can be signalled this way, remaining options must be examined
857  * manually.
858  *
859  * @code
860   coap_opt_filter_t f = COAP_OPT_NONE;
861   coap_opt_iterator_t opt_iter;
862 
863   if (coap_option_check_critical(ctx, pdu, f) == 0) {
864     coap_option_iterator_init(pdu, &opt_iter, f);
865 
866     while (coap_option_next(&opt_iter)) {
867       if (opt_iter.type & 0x01) {
868         ... handle unknown critical option in opt_iter ...
869       }
870     }
871   }
872    @endcode
873  *
874  * @param ctx      The context where all known options are registered.
875  * @param pdu      The PDU to check.
876  * @param unknown  The output filter that will be updated to indicate the
877  *                 unknown critical options found in @p pdu.
878  *
879  * @return         @c 1 if everything was ok, @c 0 otherwise.
880  */
881 int coap_option_check_critical(coap_context_t *ctx,
882                                coap_pdu_t *pdu,
883                                coap_opt_filter_t unknown);
884 
885 /**
886  * Creates a new response for given @p request with the contents of @c
887  * .well-known/core. The result is NULL on error or a newly allocated PDU that
888  * must be either sent with coap_sent() or released by coap_delete_pdu().
889  *
890  * @param context The current coap context to use.
891  * @param session The CoAP session.
892  * @param request The request for @c .well-known/core .
893  *
894  * @return        A new 2.05 response for @c .well-known/core or NULL on error.
895  */
896 coap_pdu_t *coap_wellknown_response(coap_context_t *context,
897                                     coap_session_t *session,
898                                     coap_pdu_t *request);
899 
900 /**
901  * Calculates the initial timeout based on the session CoAP transmission
902  * parameters 'ack_timeout', 'ack_random_factor', and COAP_TICKS_PER_SECOND.
903  * The calculation requires 'ack_timeout' and 'ack_random_factor' to be in
904  * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r
905  * is interpreted as the fractional part of a Q0.MAX_BITS random value.
906  *
907  * @param session session timeout is associated with
908  * @param r  random value as fractional part of a Q0.MAX_BITS fixed point
909  *           value
910  * @return   COAP_TICKS_PER_SECOND * 'ack_timeout' *
911  *           (1 + ('ack_random_factor' - 1) * r)
912  */
913 unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r);
914 
915 /**
916  * Function interface for joining a multicast group for listening
917  *
918  * @param ctx   The current context
919  * @param groupname The name of the group that is to be joined for listening
920  *
921  * @return       0 on success, -1 on error
922  */
923 int
924 coap_join_mcast_group(coap_context_t *ctx, const char *groupname);
925 
926 #ifdef WITH_LWIP
927 /**
928  * Check if there any sessions which created by server has been idle without send/receive any
929  * packets. The duration time of idle can be setted through ctx->session_timeout (unit is second).
930  * if ctx->session_timeout is 0, the default duration time is defined by COAP_DEFAULT_SESSION_TIMEOUT.
931  */
932 void coap_server_sessions_check_idle(coap_context_t *ctx);
933 
934 /**
935  * This API is called when the caller is not in the same thread
936  * with tcpip thread.
937  * Check if there any sessions which created by server has been idle without send/receive any
938  * packets. The duration time of idle can be setted through ctx->session_timeout (unit is second).
939  * if ctx->session_timeout is 0, the default duration time is defined by COAP_DEFAULT_SESSION_TIMEOUT.
940  */
941 void coap_server_sessions_check_idle_lwip(coap_context_t *ctx);
942 #endif
943 
944 #endif /* COAP_NET_H_ */
945