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