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