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