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