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