Implemented libcoap's tinyDTLS interface
[contrib/iotivity.git] / resource / csdk / libcoap-4.1.1 / net.h
1 /* net.h -- CoAP network interface
2  *
3  * Copyright (C) 2010--2013 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8
9 #ifndef _COAP_NET_H_
10 #define _COAP_NET_H_
11
12 #ifdef WITH_ARDUINO
13 #include "Time.h"
14 #endif /* WITH_ARDUINO */
15
16 #ifdef __cplusplus
17 extern "C" {
18 #endif
19
20 #include "config.h"
21
22 #ifdef HAVE_ASSERT_H
23 #include <assert.h>
24 #else
25 #ifndef assert
26 #warning "assertions are disabled"
27 #  define assert(x)
28 #endif
29 #endif
30
31 #include <stdlib.h>
32 #include <string.h>
33 #ifdef HAVE_NETINET_IN_H
34 #include <netinet/in.h>
35 #endif
36 #ifdef HAVE_TIME_H
37 #include <time.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 #include <sys/time.h>
41 #endif
42
43 #ifdef WITH_LWIP
44 #include <lwip/ip_addr.h>
45 #endif
46
47 #include "option.h"
48 #include "address.h"
49 #include "prng.h"
50 #include "pdu.h"
51 #include "coap_time.h"
52
53 typedef enum {
54     SEND_NOW            = (1 << 0), /*Flag used when sending non-confirmable, ACK and RESET coap pdus*/
55     SEND_NOW_CON        = (1 << 1), /*Flag used when sending confirmable coap pdu*/
56     SEND_DELAYED        = (1 << 2), /*Flag used to delay the transmission of coap pdu*/
57     SEND_RETX           = (1 << 3), /*Flag used to retransmit a confirmable pdu*/
58     SEND_SECURE_PORT    = (1 << 4)  /*Flag used to indicate that PDU needs to
59                                       be transmitted on secure port */
60 } coap_send_flags_t;
61
62 struct coap_queue_t;
63
64 typedef struct coap_queue_t {
65   struct coap_queue_t *next;
66
67   coap_tick_t t;            /**< when to send PDU for the next time */
68   unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */
69   unsigned int timeout;     /**< the randomized timeout value */
70
71   coap_address_t local;     /**< local address */
72   coap_address_t remote;    /**< remote address */
73   coap_tid_t id;        /**< unique transaction id */
74
75   coap_pdu_t *pdu;      /**< the CoAP PDU to send */
76
77   unsigned char delayedResponse;  /**< delayed response flag */
78   unsigned char secure;      /**< rx/tx will use secure channel (DTLS) */
79 } coap_queue_t;
80
81 /** Adds node to given queue, ordered by node->t. */
82 int coap_insert_node(coap_queue_t **queue, coap_queue_t *node);
83
84 /** Destroys specified node. */
85 int coap_delete_node(coap_queue_t *node);
86
87 /** Removes all items from given queue and frees the allocated storage. */
88 void coap_delete_all(coap_queue_t *queue);
89
90 /** Creates a new node suitable for adding to the CoAP sendqueue. */
91 coap_queue_t *coap_new_node();
92
93 struct coap_resource_t;
94 struct coap_context_t;
95 #ifndef WITHOUT_ASYNC
96 struct coap_async_state_t;
97 #endif
98
99 struct coap_dtls_context_t;
100
101 /** Message handler for requests that is used as call-back in coap_context_t */
102 typedef void (*coap_request_handler_t)(struct coap_context_t  *,
103         const coap_queue_t * rcvd);
104
105 /** Message handler for responses that is used as call-back in coap_context_t */
106 typedef void (*coap_response_handler_t)(struct coap_context_t  *,
107         const coap_queue_t * rcvd);
108
109 /** Message handler for ack and rst that is used as call-back in coap_context_t */
110 typedef void (*coap_ack_rst_handler_t)(struct coap_context_t  *, uint8_t msgType,
111         const coap_queue_t * sent);
112
113 #define COAP_MID_CACHE_SIZE 3
114 typedef struct {
115   unsigned char flags[COAP_MID_CACHE_SIZE];
116   coap_key_t item[COAP_MID_CACHE_SIZE];
117 } coap_mid_cache_t;
118
119 /** The CoAP stack's global state is stored in a coap_context_t object */
120 typedef struct coap_context_t {
121   coap_opt_filter_t known_options;
122 #ifndef WITH_CONTIKI
123   struct coap_resource_t *resources; /**< hash table or list of known resources */
124 #endif /* WITH_CONTIKI */
125 #ifndef WITHOUT_ASYNC
126   /** list of asynchronous transactions */
127   struct coap_async_state_t *async_state;
128 #endif /* WITHOUT_ASYNC */
129   /**
130    * The time stamp in the first element of the sendqeue is relative
131    * to sendqueue_basetime. */
132   coap_tick_t sendqueue_basetime;
133   coap_queue_t *sendqueue, *recvqueue;
134 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
135   int sockfd;           /**< send/receive socket */
136   int sockfd_wellknown; /**< well-known discovery socket */
137   int sockfd_dtls;      /**< secure communication happens on this socket */
138   /** dtls interface */
139   struct coap_dtls_context_t *coap_dtls_ctx;
140 #endif /* WITH_POSIX || WITH_ARDUINO */
141 #ifdef WITH_CONTIKI
142   struct uip_udp_conn *conn;    /**< uIP connection object */
143
144   struct etimer retransmit_timer; /**< fires when the next packet must be sent */
145   struct etimer notify_timer;     /**< used to check resources periodically */
146 #endif /* WITH_CONTIKI */
147 #ifdef WITH_LWIP
148   struct udp_pcb *pcb; /**< the underlying lwIP UDP PCB */
149   struct pbuf *pending_package; /**< pbuf containing the last received package if not handled yet. This is only used to pass the package from the udp_recv callback into the coap_read function, which frees the pbuf and clears this field. */
150   ip_addr_t pending_address; /**< the address associated with pending_package */
151   u16_t pending_port; /**< the port associated with pending_package */
152
153   uint8_t timer_configured; /**< Set to 1 when a retransmission is scheduled using lwIP timers for this context, otherwise 0. */
154 #endif /* WITH_LWIP */
155
156   /**
157    * The last message id that was used is stored in this field.  The
158    * initial value is set by coap_new_context() and is usually a
159    * random value. A new message id can be created with
160    * coap_new_message_id().
161    */
162   unsigned short message_id;
163
164   /**
165    * The next value to be used for Observe. This field is global for
166    * all resources and will be updated when notifications are created.
167    */
168   unsigned int observe;
169
170   coap_request_handler_t request_handler;
171   coap_response_handler_t response_handler;
172   coap_ack_rst_handler_t ack_rst_handler;
173 } coap_context_t;
174
175 /**
176  * Registers a new message handler that is called whenever a request
177  * was received that matches an ongoing transaction.
178  *
179  * @param context The context to register the handler for.
180  * @param handler The response handler to register.
181  */
182 static inline void
183 coap_register_request_handler(coap_context_t *context,
184                    coap_request_handler_t handler) {
185   context->request_handler = handler;
186 }
187
188 /**
189  * Registers a new message handler that is called whenever a response
190  * was received that matches an ongoing transaction.
191  *
192  * @param context The context to register the handler for.
193  * @param handler The response handler to register.
194  */
195 static inline void
196 coap_register_response_handler(coap_context_t *context,
197                    coap_response_handler_t handler) {
198   context->response_handler = handler;
199 }
200
201 /**
202  * Registers a new message handler that is called whenever ack or rst
203  * was received that matches an ongoing transaction.
204  *
205  * @param context The context to register the handler for.
206  * @param handler The handler to register.
207  */
208 static inline void
209 coap_register_ack_rst_handler(coap_context_t *context,
210                    coap_ack_rst_handler_t handler) {
211   context->ack_rst_handler = handler;
212 }
213
214 /**
215  * Registers the option type @p type with the given context object @p
216  * ctx.
217  *
218  * @param ctx  The context to use.
219  * @param type The option type to register.
220  */
221 inline static void
222 coap_register_option(coap_context_t *ctx, unsigned char type) {
223   coap_option_setb(ctx->known_options, type);
224 }
225
226
227 /**
228  * Set sendqueue_basetime in the given context object @p ctx to @p
229  * now. This function returns the number of elements in the queue
230  * head that have timed out.
231  */
232 unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now);
233
234 /** Returns the next pdu to send without removing from sendqeue. */
235 coap_queue_t *coap_peek_next( coap_context_t *context );
236
237 /** Returns the next pdu to send and removes it from the sendqeue. */
238 coap_queue_t *coap_pop_next( coap_context_t *context );
239
240 /** Creates a new coap_context_t object that will hold the CoAP stack status.  */
241 coap_context_t *coap_new_context(const coap_address_t *listen_addr);
242
243 /** Joins the CoAP stack to well-known multicast address.  */
244 int coap_join_wellknown_group(coap_context_t *context,
245                 const coap_address_t *multicast_addr);
246
247 /**
248  * Returns a new message id and updates @p context->message_id
249  * accordingly. The message id is returned in network byte order
250  * to make it easier to read in tracing tools.
251  *
252  * @param context the current coap_context_t object
253  * @return incremented message id in network byte order
254  */
255 static inline unsigned short
256 coap_new_message_id(coap_context_t *context) {
257     ++(context->message_id);
258 #ifdef WITH_ARDUINO
259   return ((context->message_id << 8) | ((context->message_id >> 8) & (0xFF)));
260 #elif WITH_CONTIKI
261   return uip_htons(context->message_id);
262 #else
263   return htons(context->message_id);
264 #endif
265 }
266
267 /* CoAP stack context must be released with coap_free_context() */
268 void coap_free_context( coap_context_t *context );
269
270 /**
271  * Sends a confirmed CoAP message to given destination. The memory
272  * that is allocated by pdu will not be released by
273  * coap_send_confirmed(). The caller must release the memory.
274  *
275  * @param context The CoAP context to use.
276  * @param dst     The address to send to.
277  * @param pdu     The CoAP PDU to send.
278  * @return The message id of the sent message or @c COAP_INVALID_TID on error.
279  */
280 coap_tid_t coap_send_confirmed(coap_context_t *context,
281                    const coap_address_t *dst,
282                    coap_pdu_t *pdu);
283
284 /**
285  * Creates a new ACK PDU with specified error @p code. The options
286  * specified by the filter expression @p opts will be copied from the
287  * original request contained in @p request.  Unless @c
288  * SHORT_ERROR_RESPONSE was defined at build time, the textual reason
289  * phrase for @p code will be added as payload, with Content-Type @c
290  * 0.  This function returns a pointer to the new response message, or
291  * @c NULL on error. The storage allocated for the new message must be
292  * relased with coap_free().
293  *
294  * @param request Specification of the received (confirmable) request.
295  * @param code The error code to set.
296  * @param opts An option filter that specifies which options to copy
297  *             from the original request in @p node.
298  *
299  * @return A pointer to the new message or @c NULL on error.
300  */
301 coap_pdu_t *coap_new_error_response(coap_pdu_t *request,
302                     unsigned char code,
303                     coap_opt_filter_t opts);
304 /**
305  * Sends a CoAP message to given destination. The memory
306  * that is allocated by pdu will be released by coap_send().
307  *
308  * @param context       The CoAP context to use.
309  * @param dst           The address to send to.
310  * @param pdu           The CoAP PDU to send.
311  * @param flag          The flag indicating how the message will be send
312  * @param cache_flag    When DTLS library determines that a secure session does
313  *                      not exist with the peer yet, it caches the 'pdu pointer'
314  *                      so that it can be sent later and 'coap_send' sets this
315  *                      variable to TRUE to instruct the caller of this method
316  *                      to not delete the 'pdu'.
317  * @return The message id of the sent message or @c COAP_INVALID_TID on error.
318  */
319 coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst,
320                  coap_pdu_t *pdu,
321                  coap_send_flags_t flags,
322                  uint8_t *cache_flag);
323
324 /**
325  * Sends an error response with code @p code for request @p request to
326  * @p dst.  @p opts will be passed to coap_new_error_response() to
327  * copy marked options from the request. This function returns the
328  * transaction id if the message was sent, or @c COAP_INVALID_TID
329  * otherwise.
330  *
331  * @param context The context to use.
332  * @param request The original request to respond to.
333  * @param dst     The remote peer that sent the request.
334  * @param code    The reponse code.
335  * @param opts    A filter that specifies the options to copy from the
336  *                @p request.
337  *
338  * @return The transaction id if the message was sent, or @c
339  * COAP_INVALID_TID otherwise.
340  */
341 coap_tid_t coap_send_error(coap_context_t *context,
342                coap_pdu_t *request,
343                const coap_address_t *dst,
344                unsigned char code,
345                coap_opt_filter_t opts,
346                coap_send_flags_t flag);
347
348 /**
349  * Helper funktion to create and send a message with @p type (usually
350  * ACK or RST).  This function returns @c COAP_INVALID_TID when the
351  * message was not sent, a valid transaction id otherwise.
352  *
353  * @param context The CoAP context.
354  * @param dst Where to send the context.
355  * @param request The request that should be responded to.
356  * @param type Which type to set
357  * @param flag options for sending the message
358  * @return transaction id on success or @c COAP_INVALID_TID otherwise.
359  */
360 coap_tid_t
361 coap_send_message_type(coap_context_t *context,
362                const coap_address_t *dst,
363                coap_pdu_t *request,
364                coap_send_flags_t flag,
365                unsigned char type);
366 /**
367  * Sends an ACK message with code @c 0 for the specified @p request to
368  * @p dst. This function returns the corresponding transaction id if
369  * the message was sent or @c COAP_INVALID_TID on error.
370  *
371  * @param context The context to use.
372  * @param dst     The destination address.
373  * @param request The request to be acknowledged.
374  * @param flag    Options for sending the acknowledgement.
375  *
376  * @return The transaction id if ACK was sent or @c COAP_INVALID_TID
377  * on error.
378  */
379 coap_tid_t coap_send_ack(coap_context_t *context,
380              const coap_address_t *dst,
381              coap_pdu_t *request,
382              coap_send_flags_t flag);
383
384 /**
385  * Sends an RST message with code @c 0 for the specified @p request to
386  * @p dst. This function returns the corresponding transaction id if
387  * the message was sent or @c COAP_INVALID_TID on error.
388  *
389  * @param context The context to use.
390  * @param dst     The destination address.
391  * @param request The request to be reset.
392  * @param flag    Options for sending the reset message.
393  *
394  * @return The transaction id if RST was sent or @c COAP_INVALID_TID
395  * on error.
396  */
397 static inline coap_tid_t
398 coap_send_rst(coap_context_t *context,
399           const coap_address_t *dst,
400           coap_pdu_t *request,
401           coap_send_flags_t flag) {
402   return coap_send_message_type(context, dst, request, flag, COAP_MESSAGE_RST);
403 }
404
405 /** Handles retransmissions of confirmable messages */
406 coap_tid_t coap_retransmit( coap_context_t *context, coap_queue_t *node);
407
408 /**
409  * Reads data from the network and tries to parse as CoAP PDU. On success, 0 is returned
410  * and a new node with the parsed PDU is added to the receive queue in the specified context
411  * object.
412  */
413 int coap_read( coap_context_t *context, int sockfd );
414
415 /**
416  * Calculates a unique transaction id from given arguments @p peer and
417  * @p pdu. The id is returned in @p id.
418  *
419  * @param peer The remote party who sent @p pdu.
420  * @param pdu  The message that initiated the transaction.
421  * @param id   Set to the new id.
422  */
423 void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
424              coap_tid_t *id);
425
426 /**
427  * This function removes the element with given @p id from the list
428  * given list. If @p id was found, @p node is updated to point to the
429  * removed element. Note that the storage allocated by @p node is
430  * @b not released. The caller must do this manually using
431  * coap_delete_node(). This function returns @c 1 if the element with
432  * id @p id was found, @c 0 otherwise. For a return value of @c 0,
433  * the contents of @p node is undefined.
434  *
435  * @param queue The queue to search for @p id.
436  * @param id    The node id to look for.
437  * @param node  If found, @p node is updated to point to the
438  *   removed node. You must release the storage pointed to by
439  *   @p node manually.
440  *
441  * @return @c 1 if @p id was found, @c 0 otherwise.
442  */
443 int coap_remove_from_queue(coap_queue_t **queue,
444                coap_tid_t id,
445                coap_queue_t **node);
446
447 /**
448  * Removes the transaction identified by @p id from given @p queue.
449  * This is a convenience function for coap_remove_from_queue() with
450  * automatic deletion of the removed node.
451  *
452  * @param queue The queue to search for @p id.
453  * @param id    The transaction id.
454  *
455  * @return @c 1 if node was found, removed and destroyed, @c 0 otherwise.
456  */
457 inline static int
458 coap_remove_transaction(coap_queue_t **queue, coap_tid_t id) {
459   coap_queue_t *node;
460   if (!coap_remove_from_queue(queue, id, &node))
461     return 0;
462
463   coap_delete_node(node);
464   return 1;
465 }
466
467 /**
468  * Retrieves transaction from queue.
469  * @queue The transaction queue to be searched
470  * @id Unique key of the transaction to find.
471  * @return A pointer to the transaction object or NULL if not found
472  */
473 coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id);
474
475 /**
476  * Cancels all outstanding messages for peer @p dst that have the
477  * specified token.
478  *
479  * @param context The context in use
480  * @param dst     Destination address of the messages to remove.
481  * @param token   Message token
482  * @param token_length Actual length of @p token
483  */
484 void coap_cancel_all_messages(coap_context_t *context,
485                   const coap_address_t *dst,
486                   const unsigned char *token,
487                   size_t token_length);
488
489 /** Dispatches the PDUs from the receive queue in given context. */
490 void coap_dispatch( coap_context_t *context );
491
492 /** Returns 1 if there are no messages to send or to dispatch in the context's queues. */
493 int coap_can_exit( coap_context_t *context );
494
495 /**
496  * Returns the current value of an internal tick counter. The counter
497  * counts \c COAP_TICKS_PER_SECOND ticks every second.
498  */
499 void coap_ticks(coap_tick_t *);
500
501 /**
502  * Verifies that @p pdu contains no unknown critical options. Options
503  * must be registered at @p ctx, using the function
504  * coap_register_option(). A basic set of options is registered
505  * automatically by coap_new_context(). This function returns @c 1 if
506  * @p pdu is ok, @c 0 otherwise. The given filter object @p unknown
507  * will be updated with the unknown options. As only @c COAP_MAX_OPT
508  * options can be signalled this way, remaining options must be
509  * examined manually.
510  *
511  * @code
512   coap_opt_filter_t f = COAP_OPT_NONE;
513   coap_opt_iterator_t opt_iter;
514
515   if (coap_option_check_critical(ctx, pdu, f) == 0) {
516     coap_option_iterator_init(pdu, &opt_iter, f);
517
518     while (coap_option_next(&opt_iter)) {
519       if (opt_iter.type & 0x01) {
520     ... handle unknown critical option in opt_iter ...
521       }
522     }
523   }
524  * @endcode
525  *
526  * @param ctx      The context where all known options are registered.
527  * @param pdu      The PDU to check.
528  * @param unknown  The output filter that will be updated to indicate the
529  *                 unknown critical options found in @p pdu.
530  *
531  * @return @c 1 if everything was ok, @c 0 otherwise.
532  */
533 int coap_option_check_critical(coap_context_t *ctx,
534                    coap_pdu_t *pdu,
535                    coap_opt_filter_t unknown);
536
537 #ifdef __cplusplus
538 }
539 #endif
540
541 #endif /* _COAP_NET_H_ */