Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / resource / csdk / connectivity / lib / libcoap-4.1.1 / net.c
1 /* net.c -- CoAP network interface
2  *
3  * Copyright (C) 2010--2014 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 #include "config.h"
10
11 #include <ctype.h>
12 #include <stdio.h>
13 #ifdef HAVE_LIMITS_H
14 #include <limits.h>
15 #endif
16 #ifdef HAVE_UNISTD_H
17 #include <unistd.h>
18 #elif HAVE_SYS_UNISTD_H
19 #include <sys/unistd.h>
20 #endif
21 #ifdef HAVE_SYS_TYPES_H
22 #include <sys/types.h>
23 #endif
24 #ifdef HAVE_SYS_SOCKET_H
25 #include <sys/socket.h>
26 #endif
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
29 #endif
30 #ifdef HAVE_ARPA_INET_H
31 #include <arpa/inet.h>
32 #endif
33
34 #ifdef WITH_LWIP
35 #include <lwip/pbuf.h>
36 #include <lwip/udp.h>
37 #include <lwip/timers.h>
38 #endif
39
40 #include "debug.h"
41 #include "mem.h"
42 #include "str.h"
43 #include "async.h"
44 #include "resource.h"
45 #include "option.h"
46 #include "encode.h"
47 #include "block.h"
48 #include "net.h"
49
50 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
51
52 time_t clock_offset=0;
53
54 static inline coap_queue_t *
55 coap_malloc_node()
56 {
57     return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
58 }
59
60 static inline void
61 coap_free_node(coap_queue_t *node)
62 {
63     coap_free(node);
64 }
65 #endif /* WITH_POSIX || WITH_ARDUINO */
66 #ifdef WITH_LWIP
67
68 #include <lwip/memp.h>
69
70 static void coap_retransmittimer_execute(void *arg);
71 static void coap_retransmittimer_restart(coap_context_t *ctx);
72
73 static inline coap_queue_t *
74 coap_malloc_node()
75 {
76     return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
77 }
78
79 static inline void
80 coap_free_node(coap_queue_t *node)
81 {
82     memp_free(MEMP_COAP_NODE, node);
83 }
84
85 #endif /* WITH_LWIP */
86 #ifdef WITH_CONTIKI
87 # ifndef DEBUG
88 #  define DEBUG DEBUG_PRINT
89 # endif /* DEBUG */
90
91 #include "memb.h"
92 #include "net/uip-debug.h"
93
94 clock_time_t clock_offset;
95
96 #define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
97 #define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
98
99 void coap_resources_init();
100 void coap_pdu_resources_init();
101
102 unsigned char initialized = 0;
103 coap_context_t the_coap_context;
104
105 MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
106
107 PROCESS(coap_retransmit_process, "message retransmit process");
108
109 static inline coap_queue_t *
110 coap_malloc_node()
111 {
112     return (coap_queue_t *)memb_alloc(&node_storage);
113 }
114
115 static inline void
116 coap_free_node(coap_queue_t *node)
117 {
118     memb_free(&node_storage, node);
119 }
120 #endif /* WITH_CONTIKI */
121 #ifdef WITH_LWIP
122
123 /** Callback to udp_recv when using lwIP. Gets called by lwIP on arriving
124  * packages, places a reference in context->pending_package, and calls
125  * coap_read to process the package. Thus, coap_read needs not be called in
126  * lwIP main loops. (When modifying this for thread-like operation, ie. if you
127  * remove the coap_read call from this, make sure that coap_read gets a chance
128  * to run before this callback is entered the next time.)
129  */
130 static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
131 {
132     struct coap_context_t *context = (coap_context_t *)arg;
133
134     LWIP_ASSERT("pending_package was not cleared.", context->pending_package == NULL);
135
136     context->pending_package = p; /* we don't free it, coap_read has to do that */
137     context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */
138     context->pending_port = port;
139
140     coap_read(context);
141 }
142
143 #endif /* WITH_LWIP */
144
145 int print_wellknown(coap_context_t *, unsigned char *, size_t *, size_t, coap_opt_t *);
146
147 void coap_handle_failed_notify(coap_context_t *, const coap_address_t *, const str *);
148
149 unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now)
150 {
151     unsigned int result = 0;
152     coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
153
154     if (ctx->sendqueue)
155     {
156         /* delta < 0 means that the new time stamp is before the old. */
157         if (delta <= 0)
158         {
159             ctx->sendqueue->t -= delta;
160         }
161         else
162         {
163             /* This case is more complex: The time must be advanced forward,
164              * thus possibly leading to timed out elements at the queue's
165              * start. For every element that has timed out, its relative
166              * time is set to zero and the result counter is increased. */
167
168             coap_queue_t *q = ctx->sendqueue;
169             coap_tick_t t = 0;
170             while (q && (t + q->t < (coap_tick_t) delta))
171             {
172                 t += q->t;
173                 q->t = 0;
174                 result++;
175                 q = q->next;
176             }
177
178             /* finally adjust the first element that has not expired */
179             if (q)
180             {
181                 q->t = (coap_tick_t) delta - t;
182             }
183         }
184     }
185
186     /* adjust basetime */
187     ctx->sendqueue_basetime += delta;
188
189     return result;
190 }
191
192 int coap_insert_node(coap_queue_t **queue, coap_queue_t *node)
193 {
194     coap_queue_t *p, *q;
195     if (!queue || !node)
196         return 0;
197
198     /* set queue head if empty */
199     if (!*queue)
200     {
201         *queue = node;
202         return 1;
203     }
204
205     /* replace queue head if PDU's time is less than head's time */
206     q = *queue;
207     if (node->t < q->t)
208     {
209         node->next = q;
210         *queue = node;
211         q->t -= node->t; /* make q->t relative to node->t */
212         return 1;
213     }
214
215     /* search for right place to insert */
216     do
217     {
218         node->t -= q->t; /* make node-> relative to q->t */
219         p = q;
220         q = q->next;
221     } while (q && q->t <= node->t);
222
223     /* insert new item */
224     if (q)
225     {
226         q->t -= node->t; /* make q->t relative to node->t */
227     }
228     node->next = q;
229     p->next = node;
230     return 1;
231 }
232
233 int coap_delete_node(coap_queue_t *node)
234 {
235     if (!node)
236         return 0;
237
238     coap_delete_pdu(node->pdu);
239     coap_free_node(node);
240
241     return 1;
242 }
243
244 void coap_delete_all(coap_queue_t *queue)
245 {
246     if (!queue)
247         return;
248
249     coap_delete_all(queue->next);
250     coap_delete_node(queue);
251 }
252
253 coap_queue_t *
254 coap_new_node()
255 {
256     coap_queue_t *node;
257     node = coap_malloc_node();
258
259     if (!node)
260     {
261 #ifndef NDEBUG
262         coap_log(LOG_WARNING, "coap_new_node: malloc\n");
263 #endif
264         return NULL;
265     }
266
267     memset(node, 0, sizeof *node);
268     return node;
269 }
270
271 coap_queue_t *
272 coap_peek_next(coap_context_t *context)
273 {
274     if (!context || !context->sendqueue)
275         return NULL;
276
277     return context->sendqueue;
278 }
279
280 coap_queue_t *
281 coap_pop_next(coap_context_t *context)
282 {
283     coap_queue_t *next;
284
285     if (!context || !context->sendqueue)
286         return NULL;
287
288     next = context->sendqueue;
289     context->sendqueue = context->sendqueue->next;
290     if (context->sendqueue)
291     {
292         context->sendqueue->t += next->t;
293     }
294     next->next = NULL;
295     return next;
296 }
297
298 #ifdef COAP_DEFAULT_WKC_HASHKEY
299 /** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
300 #define is_wkc(Key)                         \
301   (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
302 #else
303 /* Implements a singleton to store a hash key for the .wellknown/core
304  * resources. */
305 int
306 is_wkc(coap_key_t k)
307 {
308     static coap_key_t wkc;
309     static unsigned char _initialized = 0;
310     if (!_initialized)
311     {
312         _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN,
313                 sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc);
314     }
315     return memcmp(k, wkc, sizeof(coap_key_t)) == 0;
316 }
317 #endif
318
319
320 #ifndef WITH_ARDUINO
321 coap_context_t *
322 coap_new_context(const coap_address_t *listen_addr)
323 {
324 #if defined(WITH_POSIX)
325     coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
326     int reuse = 1;
327 #endif /* WITH_POSIX */
328 #ifdef WITH_LWIP
329     coap_context_t *c = memp_malloc(MEMP_COAP_CONTEXT);
330 #endif /* WITH_LWIP */
331 #ifdef WITH_CONTIKI
332     coap_context_t *c;
333
334     if (initialized)
335     return NULL;
336 #endif /* WITH_CONTIKI */
337
338     if (!listen_addr)
339     {
340         coap_log(LOG_EMERG, "no listen address specified\n");
341         return NULL;
342     }
343
344     coap_clock_init();
345 #ifdef WITH_LWIP
346     prng_init(LWIP_RAND());
347 #else /* WITH_LWIP */
348     prng_init((unsigned long)listen_addr ^ clock_offset);
349 #endif /* WITH_LWIP */
350
351 #ifndef WITH_CONTIKI
352     if (!c)
353     {
354 #ifndef NDEBUG
355         coap_log(LOG_EMERG, "coap_init: malloc:\n");
356 #endif
357         return NULL;
358     }
359 #endif /* not WITH_CONTIKI */
360 #ifdef WITH_CONTIKI
361     coap_resources_init();
362     coap_pdu_resources_init();
363
364     c = &the_coap_context;
365     initialized = 1;
366 #endif /* WITH_CONTIKI */
367
368     memset(c, 0, sizeof(coap_context_t));
369
370     /* initialize message id */
371     prng((unsigned char *)&c->message_id, sizeof(unsigned short));
372
373     /* register the critical options that we know */
374     coap_register_option(c, COAP_OPTION_IF_MATCH);
375     coap_register_option(c, COAP_OPTION_URI_HOST);
376     coap_register_option(c, COAP_OPTION_IF_NONE_MATCH);
377     coap_register_option(c, COAP_OPTION_URI_PORT);
378     coap_register_option(c, COAP_OPTION_URI_PATH);
379     coap_register_option(c, COAP_OPTION_URI_QUERY);
380     coap_register_option(c, COAP_OPTION_ACCEPT);
381     coap_register_option(c, COAP_OPTION_PROXY_URI);
382     coap_register_option(c, COAP_OPTION_PROXY_SCHEME);
383     coap_register_option(c, COAP_OPTION_BLOCK2);
384     coap_register_option(c, COAP_OPTION_BLOCK1);
385
386 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
387     c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
388     if ( c->sockfd < 0 )
389     {
390 #ifndef NDEBUG
391         coap_log(LOG_EMERG, "coap_new_context: socket\n");
392 #endif /* WITH_POSIX */
393         goto onerror;
394     }
395
396     if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 )
397     {
398 #ifndef NDEBUG
399         coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n");
400 #endif
401     }
402
403     if (bind(c->sockfd, &listen_addr->addr.sa, listen_addr->size) < 0)
404     {
405 #ifndef NDEBUG
406         coap_log(LOG_EMERG, "coap_new_context: bind\n");
407 #endif
408         goto onerror;
409     }
410
411     return c;
412
413     onerror:
414     if ( c->sockfd >= 0 )
415     close ( c->sockfd );
416     coap_free( c );
417     return NULL;
418
419 #endif /* WITH_POSIX || WITH_ARDUINO */
420 #ifdef WITH_CONTIKI
421     c->conn = udp_new(NULL, 0, NULL);
422     udp_bind(c->conn, listen_addr->port);
423
424     process_start(&coap_retransmit_process, (char *)c);
425
426     PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
427 #ifndef WITHOUT_OBSERVE
428     etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
429 #endif /* WITHOUT_OBSERVE */
430     /* the retransmit timer must be initialized to some large value */
431     etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
432     PROCESS_CONTEXT_END(&coap_retransmit_process);
433     return c;
434 #endif /* WITH_CONTIKI */
435 #ifdef WITH_LWIP
436     c->pcb = udp_new();
437     /* hard assert: this is not expected to fail dynamically */
438     LWIP_ASSERT("Failed to allocate PCB for CoAP", c->pcb != NULL);
439
440     udp_recv(c->pcb, received_package, (void*)c);
441     udp_bind(c->pcb, &listen_addr->addr, listen_addr->port);
442
443     c->timer_configured = 0;
444
445     return c;
446 #endif
447 }
448
449 void coap_free_context(coap_context_t *context)
450 {
451 #if defined(WITH_POSIX) || defined(WITH_LWIP)
452     coap_resource_t *res;
453 #ifndef COAP_RESOURCES_NOHASH
454     coap_resource_t *rtmp;
455 #endif
456 #endif /* WITH_POSIX || WITH_LWIP */
457     if (!context)
458         return;
459
460     coap_delete_all(context->recvqueue);
461     coap_delete_all(context->sendqueue);
462
463 #ifdef WITH_LWIP
464     context->sendqueue = NULL;
465     coap_retransmittimer_restart(context);
466 #endif
467
468 #if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
469 #ifdef COAP_RESOURCES_NOHASH
470     LL_FOREACH(context->resources, res)
471     {
472 #else
473         HASH_ITER(hh, context->resources, res, rtmp)
474         {
475 #endif
476             coap_delete_resource(context, res->key);
477         }
478 #endif /* WITH_POSIX || WITH_LWIP */
479
480 #ifdef WITH_POSIX
481     /* coap_delete_list(context->subscriptions); */
482     close( context->sockfd );
483     coap_free( context );
484 #endif
485 #ifdef WITH_LWIP
486     udp_remove(context->pcb);
487     memp_free(MEMP_COAP_CONTEXT, context);
488 #endif
489 #ifdef WITH_CONTIKI
490     memset(&the_coap_context, 0, sizeof(coap_context_t));
491     initialized = 0;
492 #endif /* WITH_CONTIKI */
493 }
494 #endif //ifndef WITH_ARDUINO
495 int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown)
496 {
497
498     coap_opt_iterator_t opt_iter;
499     int ok = 1;
500
501     coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL, coap_udp);
502
503     while (coap_option_next(&opt_iter))
504     {
505
506         /* The following condition makes use of the fact that
507          * coap_option_getb() returns -1 if type exceeds the bit-vector
508          * filter. As the vector is supposed to be large enough to hold
509          * the largest known option, we know that everything beyond is
510          * bad.
511          */
512         if (opt_iter.type & 0x01 && coap_option_getb(ctx->known_options, opt_iter.type) < 1)
513         {
514             debug("unknown critical option %d\n", opt_iter.type);
515
516             ok = 0;
517
518             /* When opt_iter.type is beyond our known option range,
519              * coap_option_setb() will return -1 and we are safe to leave
520              * this loop. */
521             if (coap_option_setb(unknown, opt_iter.type) == -1)
522                 break;
523         }
524     }
525
526     return ok;
527 }
528
529 void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap_tid_t *id)
530 {
531     coap_key_t h;
532
533     memset(h, 0, sizeof(coap_key_t));
534
535     /* Compare the complete address structure in case of IPv4. For IPv6,
536      * we need to look at the transport address only. */
537
538 #ifdef WITH_POSIX
539     switch (peer->addr.sa.sa_family)
540     {
541         case AF_INET:
542         coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h);
543         break;
544         case AF_INET6:
545         coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port,
546                 sizeof(peer->addr.sin6.sin6_port), h);
547         coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr,
548                 sizeof(peer->addr.sin6.sin6_addr), h);
549         break;
550         default:
551         return;
552     }
553 #endif
554
555 #ifdef WITH_ARDUINO
556     coap_hash((const unsigned char *)peer->addr, peer->size, h);
557 #endif /* WITH_ARDUINO */
558
559 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
560     /* FIXME: with lwip, we can do better */
561     coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
562     coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
563 #endif /* WITH_LWIP || WITH_CONTIKI */
564
565     coap_hash((const unsigned char *)&pdu->hdr->coap_hdr_udp_t.id, sizeof(unsigned short), h);
566
567     *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
568 }
569
570 coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *request)
571 {
572     coap_pdu_t *response;
573     coap_tid_t result = COAP_INVALID_TID;
574
575     if (request && request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON)
576     {
577         response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->coap_hdr_udp_t.id,
578                                  sizeof(coap_pdu_t), coap_udp);
579         if (response)
580         {
581             result = coap_send(context, dst, response);
582             coap_delete_pdu(response);
583         }
584     }
585     return result;
586 }
587
588 #if defined(WITH_ARDUINO)
589 coap_tid_t
590 coap_send_impl(coap_context_t *context,
591                const coap_address_t *dst,
592                coap_pdu_t *pdu)
593 {
594     return 0;
595 }
596 #endif
597
598 #if defined(WITH_POSIX)
599 /* releases space allocated by PDU if free_pdu is set */
600 coap_tid_t
601 coap_send_impl(coap_context_t *context,
602         const coap_address_t *dst,
603         coap_pdu_t *pdu)
604 {
605     ssize_t bytes_written;
606     coap_tid_t id = COAP_INVALID_TID;
607
608     if ( !context || !dst || !pdu )
609     return id;
610
611     bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0,
612             &dst->addr.sa, dst->size);
613
614     if (bytes_written >= 0)
615     {
616         coap_transaction_id(dst, pdu, &id);
617     }
618     else
619     {
620         coap_log(LOG_CRIT, "coap_send: sendto\n");
621     }
622
623     return id;
624 }
625 #endif /* WITH_POSIX || WITH_ARDUINO */
626 #ifdef WITH_CONTIKI
627 /* releases space allocated by PDU if free_pdu is set */
628 coap_tid_t
629 coap_send_impl(coap_context_t *context,
630         const coap_address_t *dst,
631         coap_pdu_t *pdu)
632 {
633     coap_tid_t id = COAP_INVALID_TID;
634
635     if ( !context || !dst || !pdu )
636     return id;
637
638     /* FIXME: is there a way to check if send was successful? */
639     uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length,
640             &dst->addr, dst->port);
641
642     coap_transaction_id(dst, pdu, &id);
643
644     return id;
645 }
646 #endif /* WITH_CONTIKI */
647 #ifdef WITH_LWIP
648 coap_tid_t
649 coap_send_impl(coap_context_t *context,
650         const coap_address_t *dst,
651         coap_pdu_t *pdu)
652 {
653     coap_tid_t id = COAP_INVALID_TID;
654     struct pbuf *p;
655     uint8_t err;
656     char *data_backup;
657
658     if ( !context || !dst || !pdu )
659     {
660         return id;
661     }
662
663     data_backup = pdu->data;
664
665     /* FIXME: we can't check this here with the existing infrastructure, but we
666      * should actually check that the pdu is not held by anyone but us. the
667      * respective pbuf is already exclusively owned by the pdu. */
668
669     p = pdu->pbuf;
670     LWIP_ASSERT("The PDU header is not where it is expected", pdu->hdr == p->payload + sizeof(coap_pdu_t));
671
672     err = pbuf_header(p, -sizeof(coap_pdu_t));
673     if (err)
674     {
675         debug("coap_send_impl: pbuf_header failed\n");
676         pbuf_free(p);
677         return id;
678     }
679
680     coap_transaction_id(dst, pdu, &id);
681
682     pbuf_realloc(p, pdu->length);
683
684     udp_sendto(context->pcb, p,
685             &dst->addr, dst->port);
686
687     pbuf_header(p, -(ptrdiff_t)((uint8_t*)pdu - (uint8_t*)p->payload) - sizeof(coap_pdu_t)); /* FIXME hack around udp_sendto not restoring; see http://lists.gnu.org/archive/html/lwip-users/2013-06/msg00008.html. for udp over ip over ethernet, this was -42; as we're doing ppp too, this has to be calculated generically */
688
689     err = pbuf_header(p, sizeof(coap_pdu_t));
690     LWIP_ASSERT("Cannot undo pbuf_header", err == 0);
691
692     /* restore destroyed pdu data */
693     LWIP_ASSERT("PDU not restored", p->payload == pdu);
694     pdu->max_size = p->tot_len - sizeof(coap_pdu_t); /* reduced after pbuf_realloc */
695     pdu->hdr = p->payload + sizeof(coap_pdu_t);
696     pdu->max_delta = 0; /* won't be used any more */
697     pdu->length = pdu->max_size;
698     pdu->data = data_backup;
699     pdu->pbuf = p;
700
701     return id;
702 }
703 #endif /* WITH_LWIP */
704
705 coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu)
706 {
707 #ifndef WITH_ARDUINO
708     return coap_send_impl(context, dst, pdu);
709 #endif
710 }
711
712 coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, const coap_address_t *dst,
713         unsigned char code, coap_opt_filter_t opts)
714 {
715     coap_pdu_t *response;
716     coap_tid_t result = COAP_INVALID_TID;
717
718     assert(request);
719     assert(dst);
720
721     response = coap_new_error_response(request, code, opts);
722     if (response)
723     {
724         result = coap_send(context, dst, response);
725         coap_delete_pdu(response);
726     }
727
728     return result;
729 }
730
731 coap_tid_t coap_send_message_type(coap_context_t *context, const coap_address_t *dst,
732         coap_pdu_t *request, unsigned char type)
733 {
734     coap_pdu_t *response;
735     coap_tid_t result = COAP_INVALID_TID;
736
737     if (request)
738     {
739         response = coap_pdu_init(type, 0, request->hdr->coap_hdr_udp_t.id,
740                                  sizeof(coap_pdu_t), coap_udp);
741         if (response)
742         {
743             result = coap_send(context, dst, response);
744             coap_delete_pdu(response);
745         }
746     }
747     return result;
748 }
749
750 coap_tid_t coap_send_confirmed(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu)
751 {
752     coap_queue_t *node;
753     coap_tick_t now;
754     int r;
755
756     node = coap_new_node();
757     if (!node)
758     {
759         debug("coap_send_confirmed: insufficient memory\n");
760         return COAP_INVALID_TID;
761     }
762
763     node->id = coap_send_impl(context, dst, pdu);
764     if (COAP_INVALID_TID == node->id)
765     {
766         debug("coap_send_confirmed: error sending pdu\n");
767         coap_free_node(node);
768         return COAP_INVALID_TID;
769     }
770
771     prng((unsigned char *)&r, sizeof(r));
772
773     /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
774     node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND
775             + (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
776
777     memcpy(&node->remote, dst, sizeof(coap_address_t));
778     node->pdu = pdu;
779
780     /* Set timer for pdu retransmission. If this is the first element in
781      * the retransmission queue, the base time is set to the current
782      * time and the retransmission time is node->timeout. If there is
783      * already an entry in the sendqueue, we must check if this node is
784      * to be retransmitted earlier. Therefore, node->timeout is first
785      * normalized to the base time and then inserted into the queue with
786      * an adjusted relative time.
787      */coap_ticks(&now);
788     if (context->sendqueue == NULL)
789     {
790         node->t = node->timeout;
791         context->sendqueue_basetime = now;
792     }
793     else
794     {
795         /* make node->t relative to context->sendqueue_basetime */
796         node->t = (now - context->sendqueue_basetime) + node->timeout;
797     }
798
799     coap_insert_node(&context->sendqueue, node);
800
801 #ifdef WITH_LWIP
802     if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
803     coap_retransmittimer_restart(context);
804 #endif
805
806 #ifdef WITH_CONTIKI
807     { /* (re-)initialize retransmission timer */
808         coap_queue_t *nextpdu;
809
810         nextpdu = coap_peek_next(context);
811         assert(nextpdu); /* we have just inserted a node */
812
813         /* must set timer within the context of the retransmit process */
814         PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
815         etimer_set(&context->retransmit_timer, nextpdu->t);
816         PROCESS_CONTEXT_END(&coap_retransmit_process);
817     }
818 #endif /* WITH_CONTIKI */
819
820     return node->id;
821 }
822
823 coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
824 {
825     if (!context || !node)
826         return COAP_INVALID_TID;
827
828     /* re-initialize timeout when maximum number of retransmissions are not reached yet */
829     if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT)
830     {
831         node->retransmit_cnt++;
832         node->t = node->timeout << node->retransmit_cnt;
833         coap_insert_node(&context->sendqueue, node);
834 #ifdef WITH_LWIP
835         /* don't bother with timer stuff if there are earlier retransmits */
836         if (node == context->sendqueue)
837         coap_retransmittimer_restart(context);
838 #endif
839
840         debug(
841                 "** retransmission #%d of transaction %d\n", node->retransmit_cnt,
842                 ntohs(node->pdu->hdr->coap_hdr_udp_t.id));
843
844         node->id = coap_send_impl(context, &node->remote, node->pdu);
845         return node->id;
846     }
847
848     /* no more retransmissions, remove node from system */
849
850 #if !defined(WITH_CONTIKI) && !defined(WITH_ARDUINO)
851     debug("** removed transaction %d\n", ntohs(node->id));
852 #endif
853
854 #ifndef WITHOUT_OBSERVE
855     /* Check if subscriptions exist that should be canceled after
856      COAP_MAX_NOTIFY_FAILURES */
857     if (node->pdu->hdr->coap_hdr_udp_t.code >= 64)
858     {
859         str token =
860         { 0, NULL };
861
862         token.length = node->pdu->hdr->coap_hdr_udp_t.token_length;
863         token.s = node->pdu->hdr->coap_hdr_udp_t.token;
864
865         coap_handle_failed_notify(context, &node->remote, &token);
866     }
867 #endif /* WITHOUT_OBSERVE */
868
869     /* And finally delete the node */
870     coap_delete_node(node);
871     return COAP_INVALID_TID;
872 }
873
874 /**
875  * Checks if @p opt fits into the message that ends with @p maxpos.
876  * This function returns @c 1 on success, or @c 0 if the option @p opt
877  * would exceed @p maxpos.
878  */
879 static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
880 {
881     if (opt && opt < maxpos)
882     {
883         if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos))
884             return opt + COAP_OPT_SIZE(opt) < maxpos;
885     }
886     return 0;
887 }
888
889 #ifndef WITH_ARDUINO
890 int coap_read(coap_context_t *ctx)
891 {
892 #if defined(WITH_POSIX)
893     static char buf[COAP_MAX_PDU_SIZE];
894 #endif
895 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
896     char *buf;
897 #endif
898     coap_hdr_t *pdu;
899     ssize_t bytes_read = -1;
900     coap_address_t src, dst;
901     coap_queue_t *node;
902
903 #ifdef WITH_CONTIKI
904     buf = uip_appdata;
905 #endif /* WITH_CONTIKI */
906 #ifdef WITH_LWIP
907     LWIP_ASSERT("No package pending", ctx->pending_package != NULL);
908     LWIP_ASSERT("Can only deal with contiguous PBUFs to read the initial details", ctx->pending_package->tot_len == ctx->pending_package->len);
909     buf = ctx->pending_package->payload;
910 #endif /* WITH_LWIP */
911
912     pdu = (coap_hdr_t *) buf;
913
914     coap_address_init(&src);
915
916 #if defined(WITH_POSIX)
917     bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
918
919 #endif /* WITH_POSIX || WITH_ARDUINO */
920 #ifdef WITH_CONTIKI
921     if(uip_newdata())
922     {
923         uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr);
924         src.port = UIP_UDP_BUF->srcport;
925         uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr);
926         dst.port = UIP_UDP_BUF->destport;
927
928         bytes_read = uip_datalen();
929         ((char *)uip_appdata)[bytes_read] = 0;
930         PRINTF("Server received %d bytes from [", (int)bytes_read);
931         PRINT6ADDR(&src.addr);
932         PRINTF("]:%d\n", uip_ntohs(src.port));
933     }
934 #endif /* WITH_CONTIKI */
935 #ifdef WITH_LWIP
936     /* FIXME: use lwip address operation functions */
937     src.addr.addr = ctx->pending_address.addr;
938     src.port = ctx->pending_port;
939     bytes_read = ctx->pending_package->tot_len;
940 #endif /* WITH_LWIP */
941
942     if (bytes_read < 0)
943     {
944         warn("coap_read: recvfrom");
945         goto error_early;
946     }
947
948     if ((size_t) bytes_read < sizeof(coap_hdr_t))
949     {
950         debug("coap_read: discarded invalid frame\n");
951         goto error_early;
952     }
953
954     if (pdu->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
955     {
956         debug("coap_read: unknown protocol version\n");
957         goto error_early;
958     }
959
960     node = coap_new_node();
961     if (!node)
962         goto error_early;
963
964 #ifdef WITH_LWIP
965     node->pdu = coap_pdu_from_pbuf(ctx->pending_package);
966     ctx->pending_package = NULL;
967 #else
968     node->pdu = coap_pdu_init(0, 0, 0, bytes_read, coap_udp);
969 #endif
970     if (!node->pdu)
971         goto error;
972
973     coap_ticks(&node->t);
974     memcpy(&node->local, &dst, sizeof(coap_address_t));
975     memcpy(&node->remote, &src, sizeof(coap_address_t));
976
977     if (!coap_pdu_parse((unsigned char *) buf, bytes_read, node->pdu, coap_udp))
978     {
979         warn("discard malformed PDU");
980         goto error;
981     }
982
983     /* and add new node to receive queue */
984     coap_transaction_id(&node->remote, node->pdu, &node->id);
985     coap_insert_node(&ctx->recvqueue, node);
986
987 #ifndef NDEBUG
988     if (LOG_DEBUG <= coap_get_log_level())
989     {
990 #ifndef INET6_ADDRSTRLEN
991 #define INET6_ADDRSTRLEN 40
992 #endif
993         unsigned char addr[INET6_ADDRSTRLEN + 8];
994
995         if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN + 8))
996             debug("** received %d bytes from %s:\n", (int)bytes_read, addr);
997
998         coap_show_pdu(node->pdu);
999     }
1000 #endif
1001
1002     return 0;
1003
1004     error:
1005     /* FIXME: send back RST? */
1006     coap_delete_node(node);
1007     return -1;
1008     error_early:
1009 #ifdef WITH_LWIP
1010     /* even if there was an error, clean up */
1011     pbuf_free(ctx->pending_package);
1012     ctx->pending_package = NULL;
1013 #endif
1014     return -1;
1015 }
1016 #endif //#ifndef WITH_ARDUINO
1017
1018 int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node)
1019 {
1020     coap_queue_t *p, *q;
1021
1022     if (!queue || !*queue)
1023         return 0;
1024
1025     /* replace queue head if PDU's time is less than head's time */
1026
1027     if (id == (*queue)->id)
1028     { /* found transaction */
1029         *node = *queue;
1030         *queue = (*queue)->next;
1031         if (*queue)
1032         { /* adjust relative time of new queue head */
1033             (*queue)->t += (*node)->t;
1034         }
1035         (*node)->next = NULL;
1036         /* coap_delete_node( q ); */
1037         debug("*** removed transaction %u\n", id);
1038         return 1;
1039     }
1040
1041     /* search transaction to remove (only first occurence will be removed) */
1042     q = *queue;
1043     do
1044     {
1045         p = q;
1046         q = q->next;
1047     } while (q && id != q->id);
1048
1049     if (q)
1050     { /* found transaction */
1051         p->next = q->next;
1052         if (p->next)
1053         { /* must update relative time of p->next */
1054             p->next->t += q->t;
1055         }
1056         q->next = NULL;
1057         *node = q;
1058         /* coap_delete_node( q ); */
1059         debug("*** removed transaction %u\n", id);
1060         return 1;
1061     }
1062
1063     return 0;
1064
1065 }
1066
1067 static inline int token_match(const unsigned char *a, size_t alen, const unsigned char *b,
1068         size_t blen)
1069 {
1070     return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
1071 }
1072
1073 void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst,
1074         const unsigned char *token, size_t token_length)
1075 {
1076     /* cancel all messages in sendqueue that are for dst
1077      * and use the specified token */
1078     coap_queue_t *p, *q;
1079
1080     debug("cancel_all_messages\n");
1081     while (context->sendqueue && coap_address_equals(dst, &context->sendqueue->remote)
1082             && token_match(token, token_length, context->sendqueue->pdu->hdr->coap_hdr_udp_t.token,
1083                     context->sendqueue->pdu->hdr->coap_hdr_udp_t.token_length))
1084     {
1085         q = context->sendqueue;
1086         context->sendqueue = q->next;
1087         debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->coap_hdr_udp_t.id));
1088         coap_delete_node(q);
1089     }
1090
1091     if (!context->sendqueue)
1092         return;
1093
1094     p = context->sendqueue;
1095     q = p->next;
1096
1097     /* when q is not NULL, it does not match (dst, token), so we can skip it */
1098     while (q)
1099     {
1100         if (coap_address_equals(dst, &q->remote)
1101                 && token_match(token, token_length, q->pdu->hdr->coap_hdr_udp_t.token,
1102                                q->pdu->hdr->coap_hdr_udp_t.token_length))
1103         {
1104             p->next = q->next;
1105             debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->coap_hdr_udp_t.id));
1106             coap_delete_node(q);
1107             q = p->next;
1108         }
1109         else
1110         {
1111             p = q;
1112             q = q->next;
1113         }
1114     }
1115 }
1116
1117 coap_queue_t *
1118 coap_find_transaction(coap_queue_t *queue, coap_tid_t id)
1119 {
1120     while (queue && queue->id != id)
1121         queue = queue->next;
1122
1123     return queue;
1124 }
1125
1126 coap_pdu_t *
1127 coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter_t opts)
1128 {
1129     coap_opt_iterator_t opt_iter;
1130     coap_pdu_t *response;
1131     size_t size = sizeof(coap_hdr_t) + request->hdr->coap_hdr_udp_t.token_length;
1132     int type;
1133     coap_opt_t *option;
1134     unsigned short opt_type = 0; /* used for calculating delta-storage */
1135
1136 #if COAP_ERROR_PHRASE_LENGTH > 0
1137     char *phrase = coap_response_phrase(code);
1138
1139     /* Need some more space for the error phrase and payload start marker */
1140     if (phrase)
1141         size += strlen(phrase) + 1;
1142 #endif
1143
1144     assert(request);
1145
1146     /* cannot send ACK if original request was not confirmable */
1147     type = request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
1148
1149     /* Estimate how much space we need for options to copy from
1150      * request. We always need the Token, for 4.02 the unknown critical
1151      * options must be included as well. */
1152     coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
1153
1154     coap_option_iterator_init(request, &opt_iter, opts, coap_udp);
1155
1156     /* Add size of each unknown critical option. As known critical
1157      options as well as elective options are not copied, the delta
1158      value might grow.
1159      */
1160     while ((option = coap_option_next(&opt_iter)))
1161     {
1162         unsigned short delta = opt_iter.type - opt_type;
1163         /* calculate space required to encode (opt_iter.type - opt_type) */
1164         if (delta < 13)
1165         {
1166             size++;
1167         }
1168         else if (delta < 269)
1169         {
1170             size += 2;
1171         }
1172         else
1173         {
1174             size += 3;
1175         }
1176
1177         /* add coap_opt_length(option) and the number of additional bytes
1178          * required to encode the option length */
1179
1180         size += coap_opt_length(option);
1181         switch (*option & 0x0f)
1182         {
1183             case 0x0e:
1184                 size++;
1185                 /* fall through */
1186             case 0x0d:
1187                 size++;
1188                 break;
1189             default:
1190                 ;
1191         }
1192
1193         opt_type = opt_iter.type;
1194     }
1195
1196     /* Now create the response and fill with options and payload data. */
1197     response = coap_pdu_init(type, code, request->hdr->coap_hdr_udp_t.id, size, coap_udp);
1198     if (response)
1199     {
1200         /* copy token */
1201         if (!coap_add_token(response, request->hdr->coap_hdr_udp_t.token_length,
1202                             request->hdr->coap_hdr_udp_t.token, coap_udp))
1203         {
1204             debug("cannot add token to error response\n");
1205             coap_delete_pdu(response);
1206             return NULL;
1207         }
1208
1209         /* copy all options */
1210         coap_option_iterator_init(request, &opt_iter, opts, coap_udp);
1211         while ((option = coap_option_next(&opt_iter)))
1212             coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option),
1213                     COAP_OPT_VALUE(option), coap_udp);
1214
1215 #if COAP_ERROR_PHRASE_LENGTH > 0
1216         /* note that diagnostic messages do not need a Content-Format option. */
1217         if (phrase)
1218             coap_add_data(response, strlen(phrase), (unsigned char *) phrase);
1219 #endif
1220     }
1221
1222     return response;
1223 }
1224
1225 /**
1226  * Quick hack to determine the size of the resource description for
1227  * .well-known/core.
1228  */
1229 static inline size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
1230 {
1231     unsigned char buf[1];
1232     size_t len = 0;
1233
1234     if (print_wellknown(context, buf, &len, UINT_MAX, query_filter) & COAP_PRINT_STATUS_ERROR)
1235     {
1236         warn("cannot determine length of /.well-known/core\n");
1237         return 0;
1238     }
1239
1240     debug("get_wkc_len: print_wellknown() returned %zu\n", len);
1241
1242     return len;
1243 }
1244
1245 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
1246
1247 coap_pdu_t *
1248 wellknown_response(coap_context_t *context, coap_pdu_t *request)
1249 {
1250     coap_pdu_t *resp;
1251     coap_opt_iterator_t opt_iter;
1252     size_t len, wkc_len;
1253     unsigned char buf[2];
1254     int result = 0;
1255     int need_block2 = 0; /* set to 1 if Block2 option is required */
1256     coap_block_t block;
1257     coap_opt_t *query_filter;
1258     size_t offset = 0;
1259
1260     resp = coap_pdu_init(
1261             request->hdr->coap_hdr_udp_t.type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
1262             COAP_RESPONSE_CODE(205),
1263             request->hdr->coap_hdr_udp_t.id, COAP_MAX_PDU_SIZE, coap_udp);
1264     if (!resp)
1265     {
1266         debug("wellknown_response: cannot create PDU\n");
1267         return NULL;
1268     }
1269
1270     if (!coap_add_token(resp, request->hdr->coap_hdr_udp_t.token_length,
1271                         request->hdr->coap_hdr_udp_t.token, coap_udp))
1272     {
1273         debug("wellknown_response: cannot add token\n");
1274         goto error;
1275     }
1276
1277     query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
1278     wkc_len = get_wkc_len(context, query_filter);
1279
1280     /* check whether the request contains the Block2 option */
1281     if (coap_get_block(request, COAP_OPTION_BLOCK2, &block))
1282     {
1283         offset = block.num << (block.szx + 4);
1284         if (block.szx > 6)
1285         { /* invalid, MUST lead to 4.00 Bad Request */
1286             resp->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(400);
1287             return resp;
1288         }
1289         else if (block.szx > COAP_MAX_BLOCK_SZX)
1290         {
1291             block.szx = COAP_MAX_BLOCK_SZX;
1292             block.num = offset >> (block.szx + 4);
1293         }
1294
1295         need_block2 = 1;
1296     }
1297
1298     /* Check if there is sufficient space to add Content-Format option
1299      * and data. We do this before adding the Content-Format option to
1300      * avoid sending error responses with that option but no actual
1301      * content. */
1302     if (resp->max_size <= (size_t) resp->length + 3)
1303     {
1304         debug("wellknown_response: insufficient storage space\n");
1305         goto error;
1306     }
1307
1308     /* Add Content-Format. As we have checked for available storage,
1309      * nothing should go wrong here. */
1310     assert(coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
1311     coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
1312             coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf, coap_udp);
1313
1314     /* check if Block2 option is required even if not requested */
1315     if (!need_block2 && (resp->max_size - (size_t) resp->length < wkc_len))
1316     {
1317         assert(resp->length <= resp->max_size);
1318         const size_t payloadlen = resp->max_size - resp->length;
1319         /* yes, need block-wise transfer */
1320         block.num = 0;
1321         block.m = 0; /* the M bit is set by coap_write_block_opt() */
1322         block.szx = COAP_MAX_BLOCK_SZX;
1323         while (payloadlen < SZX_TO_BYTES(block.szx))
1324         {
1325             if (block.szx == 0)
1326             {
1327                 debug("wellknown_response: message to small even for szx == 0\n");
1328                 goto error;
1329             }
1330             else
1331             {
1332                 block.szx--;
1333             }
1334         }
1335
1336         need_block2 = 1;
1337     }
1338
1339     /* write Block2 option if necessary */
1340     if (need_block2)
1341     {
1342         if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0)
1343         {
1344             debug("wellknown_response: cannot add Block2 option\n");
1345             goto error;
1346         }
1347     }
1348
1349     /* Manually set payload of response to let print_wellknown() write,
1350      * into our buffer without copying data. */
1351
1352     resp->data = (unsigned char *) resp->hdr + resp->length;
1353     *resp->data = COAP_PAYLOAD_START;
1354     resp->data++;
1355     resp->length++;
1356     len = need_block2 ? SZX_TO_BYTES(block.szx) : resp->max_size - resp->length;
1357
1358     result = print_wellknown(context, resp->data, &len, offset, query_filter);
1359     if ((result & COAP_PRINT_STATUS_ERROR) != 0)
1360     {
1361         debug("print_wellknown failed\n");
1362         goto error;
1363     }
1364
1365     resp->length += COAP_PRINT_OUTPUT_LENGTH(result);
1366     return resp;
1367
1368     error:
1369     /* set error code 5.03 and remove all options and data from response */
1370     resp->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(503);
1371     resp->length = sizeof(coap_hdr_t) + resp->hdr->coap_hdr_udp_t.token_length;
1372     return resp;
1373 }
1374
1375 #define WANT_WKC(Pdu,Key)                   \
1376   (((Pdu)->hdr->coap_hdr_udp_t.code == COAP_REQUEST_GET) && is_wkc(Key))
1377
1378 void handle_request(coap_context_t *context, coap_queue_t *node, const char* responseData)
1379 {
1380
1381     coap_method_handler_t h = NULL;
1382     coap_pdu_t *response = NULL;
1383     coap_opt_filter_t opt_filter;
1384     coap_resource_t *resource;
1385     coap_key_t key;
1386
1387     coap_option_filter_clear(opt_filter);
1388
1389     /* try to find the resource from the request URI */
1390     coap_hash_request_uri(node->pdu, key);
1391     resource = coap_get_resource_from_key(context, key);
1392
1393     if (!resource)
1394     {
1395         /* The resource was not found. Check if the request URI happens to
1396          * be the well-known URI. In that case, we generate a default
1397          * response, otherwise, we return 4.04 */
1398
1399         switch (node->pdu->hdr->coap_hdr_udp_t.code)
1400         {
1401
1402             case COAP_REQUEST_GET:
1403                 if (is_wkc(key))
1404                 { /* GET request for .well-known/core */
1405                     info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1406
1407                     response = wellknown_response(context, node->pdu);
1408
1409                 }
1410                 else
1411                 { /* GET request for any another resource, return 4.04 */
1412
1413                     debug(
1414                             "GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n", key[0], key[1], key[2], key[3]);
1415                     response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404),
1416                             opt_filter);
1417                 }
1418                 break;
1419
1420             default: /* any other request type */
1421
1422                 debug(
1423                         "unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n", key[0], key[1], key[2], key[3]);
1424                 if (!coap_is_mcast(&node->local))
1425                     response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
1426                             opt_filter);
1427         }
1428
1429         if (response && coap_send(context, &node->remote, response) == COAP_INVALID_TID)
1430         {
1431             warn("cannot send response for transaction %u\n", node->id);
1432         }
1433         coap_delete_pdu(response);
1434
1435         return;
1436     }
1437
1438     /* the resource was found, check if there is a registered handler */
1439     if ((size_t) node->pdu->hdr->coap_hdr_udp_t.code - 1
1440             < sizeof(resource->handler) / sizeof(coap_method_handler_t))
1441         h = resource->handler[node->pdu->hdr->coap_hdr_udp_t.code - 1];
1442
1443     if (h)
1444     {
1445         debug(
1446                 "call custom handler for resource 0x%02x%02x%02x%02x\n", key[0], key[1], key[2], key[3]);
1447         response = coap_pdu_init(
1448                 node->pdu->hdr->coap_hdr_udp_t.type ==
1449                         COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
1450                 0, node->pdu->hdr->coap_hdr_udp_t.id, COAP_MAX_PDU_SIZE, coap_udp);
1451
1452         /* Implementation detail: coap_add_token() immediately returns 0
1453          if response == NULL */
1454         if (coap_add_token(response, node->pdu->hdr->coap_hdr_udp_t.token_length,
1455                            node->pdu->hdr->coap_hdr_udp_t.token, coap_udp))
1456         {
1457             str token =
1458             { node->pdu->hdr->coap_hdr_udp_t.token_length, node->pdu->hdr->coap_hdr_udp_t.token };
1459
1460             h(context, resource, &node->remote, node->pdu, &token, response);
1461
1462             unsigned char buf[3];
1463             response->hdr->coap_hdr_udp_t.code = COAP_RESPONSE_CODE(205);
1464             coap_add_option(response, COAP_OPTION_CONTENT_TYPE,
1465                     coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf, coap_udp);
1466             coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf, coap_udp);
1467             coap_add_data(response, strlen(responseData), (unsigned char *) responseData);
1468
1469             if (response->hdr->coap_hdr_udp_t.type != COAP_MESSAGE_NON
1470                     || (response->hdr->coap_hdr_udp_t.code >= 64 && !coap_is_mcast(&node->local)))
1471             {
1472
1473                 if (coap_send(context, &node->remote, response) == COAP_INVALID_TID)
1474                 {
1475                     debug("cannot send response for message %d\n", node->pdu->hdr->coap_hdr_udp_t.id);
1476                 }
1477             }
1478
1479             coap_delete_pdu(response);
1480         }
1481         else
1482         {
1483             warn("cannot generate response\r\n");
1484         }
1485     }
1486     else
1487     {
1488         if (WANT_WKC(node->pdu, key))
1489         {
1490             debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1491             response = wellknown_response(context, node->pdu);
1492         }
1493         else
1494             response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), opt_filter);
1495
1496         if (!response || (coap_send(context, &node->remote, response) == COAP_INVALID_TID))
1497         {
1498             debug("cannot send response for transaction %u\n", node->id);
1499         }
1500         coap_delete_pdu(response);
1501     }
1502 }
1503
1504 static inline void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd)
1505 {
1506
1507     /* Call application-specific reponse handler when available.  If
1508      * not, we must acknowledge confirmable messages. */
1509     if (context->response_handler)
1510     {
1511
1512         context->response_handler(context, &rcvd->remote, sent ? sent->pdu : NULL, rcvd->pdu,
1513                 rcvd->id);
1514     }
1515     else
1516     {
1517         /* send ACK if rcvd is confirmable (i.e. a separate response) */
1518         coap_send_ack(context, &rcvd->remote, rcvd->pdu);
1519     }
1520 }
1521
1522 static inline int
1523 #ifdef __GNUC__
1524 handle_locally(coap_context_t *context __attribute__ ((unused)),
1525         coap_queue_t *node __attribute__ ((unused)))
1526 {
1527 #else /* not a GCC */
1528     handle_locally(coap_context_t *context, coap_queue_t *node)
1529     {
1530 #endif /* GCC */
1531         /* this function can be used to check if node->pdu is really for us */
1532         return 1;
1533     }
1534
1535     /**
1536      * This function handles RST messages received for the message passed
1537      * in @p sent.
1538      */
1539     static void coap_handle_rst(coap_context_t *context, const coap_queue_t *sent)
1540     {
1541 #ifndef WITHOUT_OBSERVE
1542         coap_resource_t *r;
1543 #ifndef COAP_RESOURCES_NOHASH
1544         coap_resource_t *tmp;
1545 #endif
1546         str token =
1547         { 0, NULL };
1548
1549         /* remove observer for this resource, if any
1550          * get token from sent and try to find a matching resource. Uh!
1551          */
1552
1553         COAP_SET_STR(&token, sent->pdu->hdr->coap_hdr_udp_t.token_length,
1554                      sent->pdu->hdr->coap_hdr_udp_t.token);
1555
1556 #ifndef WITH_CONTIKI
1557 #ifdef COAP_RESOURCES_NOHASH
1558         LL_FOREACH(context->resources, r)
1559         {
1560 #else
1561         HASH_ITER(hh, context->resources, r, tmp)
1562         {
1563 #endif
1564             coap_delete_observer(r, &sent->remote, &token);
1565             coap_cancel_all_messages(context, &sent->remote, token.s, token.length);
1566         }
1567 #else /* WITH_CONTIKI */
1568         r = (coap_resource_t *)resource_storage.mem;
1569         for (i = 0; i < resource_storage.num; ++i, ++r)
1570         {
1571             if (resource_storage.count[i])
1572             {
1573                 coap_delete_observer(r, &sent->remote, &token);
1574                 coap_cancel_all_messages(context, &sent->remote, token.s, token.length);
1575             }
1576         }
1577 #endif /* WITH_CONTIKI */
1578 #endif /* WITOUT_OBSERVE */
1579     }
1580
1581     void coap_dispatch(coap_context_t *context, const char* responseData)
1582     {
1583         coap_queue_t *rcvd = NULL, *sent = NULL;
1584         coap_pdu_t *response;
1585         coap_opt_filter_t opt_filter;
1586
1587         if (!context)
1588             return;
1589
1590         memset(opt_filter, 0, sizeof(coap_opt_filter_t));
1591
1592         while (context->recvqueue)
1593         {
1594             rcvd = context->recvqueue;
1595
1596             /* remove node from recvqueue */
1597             context->recvqueue = context->recvqueue->next;
1598             rcvd->next = NULL;
1599
1600             if (rcvd->pdu->hdr->coap_hdr_udp_t.version != COAP_DEFAULT_VERSION)
1601             {
1602                 debug("dropped packet with unknown version %u\n", rcvd->pdu->hdr->coap_hdr_udp_t.version);
1603                 goto cleanup;
1604             }
1605
1606             switch (rcvd->pdu->hdr->coap_hdr_udp_t.type)
1607             {
1608                 case COAP_MESSAGE_ACK:
1609                     /* find transaction in sendqueue to stop retransmission */
1610                     coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1611
1612                     if (rcvd->pdu->hdr->coap_hdr_udp_t.code == 0)
1613                         goto cleanup;
1614
1615                     /* FIXME: if sent code was >= 64 the message might have been a
1616                      * notification. Then, we must flag the observer to be alive
1617                      * by setting obs->fail_cnt = 0. */
1618                     if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->coap_hdr_udp_t.code) == 2)
1619                     {
1620                         const str token =
1621                         { sent->pdu->hdr->coap_hdr_udp_t.token_length,
1622                           sent->pdu->hdr->coap_hdr_udp_t.token };
1623
1624                         coap_touch_observer(context, &sent->remote, &token);
1625                     }
1626                     break;
1627
1628                 case COAP_MESSAGE_RST:
1629                     /* We have sent something the receiver disliked, so we remove
1630                      * not only the transaction but also the subscriptions we might
1631                      * have. */
1632
1633                     coap_log(LOG_ALERT, "got RST for message %u\n",
1634                              ntohs(rcvd->pdu->hdr->coap_hdr_udp_t.id));
1635
1636                     /* find transaction in sendqueue to stop retransmission */
1637                     coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1638
1639                     if (sent)
1640                         coap_handle_rst(context, sent);
1641                     goto cleanup;
1642
1643                 case COAP_MESSAGE_NON: /* check for unknown critical options */
1644                     if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0)
1645                         goto cleanup;
1646                     break;
1647
1648                 case COAP_MESSAGE_CON: /* check for unknown critical options */
1649                     if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0)
1650                     {
1651
1652                         /* FIXME: send response only if we have received a request. Otherwise,
1653                          * send RST. */
1654                         response = coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402),
1655                                 opt_filter);
1656
1657                         if (!response)
1658                             warn("coap_dispatch: cannot create error reponse\n");
1659                         else
1660                         {
1661                             if (coap_send(context, &rcvd->remote, response) == COAP_INVALID_TID)
1662                             {
1663                                 warn("coap_dispatch: error sending reponse\n");
1664                             }
1665                             coap_delete_pdu(response);
1666                         }
1667
1668                         goto cleanup;
1669                     }
1670                     break;
1671             }
1672
1673             /* Pass message to upper layer if a specific handler was
1674              * registered for a request that should be handled locally. */
1675             if (handle_locally(context, rcvd))
1676             {
1677                 if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr->coap_hdr_udp_t))
1678                     handle_request(context, rcvd, responseData);
1679                 else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr->coap_hdr_udp_t))
1680                     handle_response(context, sent, rcvd);
1681                 else
1682                 {
1683                     debug("dropped message with invalid code\n");
1684                     coap_send_message_type(context, &rcvd->remote, rcvd->pdu, COAP_MESSAGE_RST);
1685                 }
1686             }
1687
1688             cleanup: coap_delete_node(sent);
1689             coap_delete_node(rcvd);
1690         }
1691     }
1692
1693     int coap_can_exit(coap_context_t *context)
1694     {
1695         return !context || (context->recvqueue == NULL && context->sendqueue == NULL);
1696     }
1697
1698 #ifdef WITH_CONTIKI
1699
1700     /*---------------------------------------------------------------------------*/
1701     /* CoAP message retransmission */
1702     /*---------------------------------------------------------------------------*/
1703     PROCESS_THREAD(coap_retransmit_process, ev, data)
1704     {
1705         coap_tick_t now;
1706         coap_queue_t *nextpdu;
1707
1708         PROCESS_BEGIN();
1709
1710         debug("Started retransmit process\r\n");
1711
1712         while(1)
1713         {
1714             PROCESS_YIELD();
1715             if (ev == PROCESS_EVENT_TIMER)
1716             {
1717                 if (etimer_expired(&the_coap_context.retransmit_timer))
1718                 {
1719
1720                     nextpdu = coap_peek_next(&the_coap_context);
1721
1722                     coap_ticks(&now);
1723                     while (nextpdu && nextpdu->t <= now)
1724                     {
1725                         coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
1726                         nextpdu = coap_peek_next(&the_coap_context);
1727                     }
1728
1729                     /* need to set timer to some value even if no nextpdu is available */
1730                     etimer_set(&the_coap_context.retransmit_timer,
1731                             nextpdu ? nextpdu->t - now : 0xFFFF);
1732                 }
1733 #ifndef WITHOUT_OBSERVE
1734                 if (etimer_expired(&the_coap_context.notify_timer))
1735                 {
1736                     coap_check_notify(&the_coap_context);
1737                     etimer_reset(&the_coap_context.notify_timer);
1738                 }
1739 #endif /* WITHOUT_OBSERVE */
1740             }
1741         }
1742
1743         PROCESS_END();
1744     }
1745     /*---------------------------------------------------------------------------*/
1746
1747 #endif /* WITH_CONTIKI */
1748
1749 #ifdef WITH_LWIP
1750     /* FIXME: retransmits that are not required any more due to incoming packages
1751      * do *not* get cleared at the moment, the wakeup when the transmission is due
1752      * is silently accepted. this is mainly due to the fact that the required
1753      * checks are similar in two places in the code (when receiving ACK and RST)
1754      * and that they cause more than one patch chunk, as it must be first checked
1755      * whether the sendqueue item to be dropped is the next one pending, and later
1756      * the restart function has to be called. nothing insurmountable, but it can
1757      * also be implemented when things have stabilized, and the performance
1758      * penality is minimal
1759      *
1760      * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
1761      * */
1762
1763     static void coap_retransmittimer_execute(void *arg)
1764     {
1765         coap_context_t *ctx = (coap_context_t*)arg;
1766         coap_tick_t now;
1767         coap_tick_t elapsed;
1768         coap_queue_t *nextinqueue;
1769
1770         ctx->timer_configured = 0;
1771
1772         coap_ticks(&now);
1773
1774         elapsed = now - ctx->sendqueue_basetime; /* that's positive for sure, and unless we haven't been called for a complete wrapping cycle, did not wrap */
1775
1776         nextinqueue = coap_peek_next(ctx);
1777         while (nextinqueue != NULL)
1778         {
1779             if (nextinqueue->t > elapsed)
1780             {
1781                 nextinqueue->t -= elapsed;
1782                 break;
1783             }
1784             else
1785             {
1786                 elapsed -= nextinqueue->t;
1787                 coap_retransmit(ctx, coap_pop_next(ctx));
1788                 nextinqueue = coap_peek_next(ctx);
1789             }
1790         }
1791
1792         ctx->sendqueue_basetime = now;
1793
1794         coap_retransmittimer_restart(ctx);
1795     }
1796
1797     static void coap_retransmittimer_restart(coap_context_t *ctx)
1798     {
1799         coap_tick_t now, elapsed, delay;
1800
1801         if (ctx->timer_configured)
1802         {
1803             printf("clearing\n");
1804             sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
1805             ctx->timer_configured = 0;
1806         }
1807         if (ctx->sendqueue != NULL)
1808         {
1809             coap_ticks(&now);
1810             elapsed = now - ctx->sendqueue_basetime;
1811             if (ctx->sendqueue->t >= elapsed)
1812             {
1813                 delay = ctx->sendqueue->t - elapsed;
1814             }
1815             else
1816             {
1817                 /* a strange situation, but not completely impossible.
1818                  *
1819                  * this happens, for example, right after
1820                  * coap_retransmittimer_execute, when a retransmission
1821                  * was *just not yet* due, and the clock ticked before
1822                  * our coap_ticks was called.
1823                  *
1824                  * not trying to retransmit anything now, as it might
1825                  * cause uncontrollable recursion; let's just try again
1826                  * with the next main loop run.
1827                  * */
1828                 delay = 0;
1829             }
1830
1831             printf("scheduling for %d ticks\n", delay);
1832             sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
1833             ctx->timer_configured = 1;
1834         }
1835     }
1836 #endif