]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/core/ipv6/nd6.c
2694194af18257ac3b957ae685f7c35f30275194
[pes-rpp/rpp-lwip.git] / src / core / ipv6 / nd6.c
1 /**
2  * @file
3  *
4  * Neighbor discovery and stateless address autoconfiguration for IPv6.
5  * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862
6  * (Address autoconfiguration).
7  */
8
9 /*
10  * Copyright (c) 2010 Inico Technologies Ltd.
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without modification,
14  * are permitted provided that the following conditions are met:
15  *
16  * 1. Redistributions of source code must retain the above copyright notice,
17  *    this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright notice,
19  *    this list of conditions and the following disclaimer in the documentation
20  *    and/or other materials provided with the distribution.
21  * 3. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
25  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
27  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
28  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
29  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
33  * OF SUCH DAMAGE.
34  *
35  * This file is part of the lwIP TCP/IP stack.
36  *
37  * Author: Ivan Delamer <delamer@inicotech.com>
38  *
39  *
40  * Please coordinate changes and requests with Ivan Delamer
41  * <delamer@inicotech.com>
42  */
43
44 #include "lwip/opt.h"
45
46 #if LWIP_IPV6  /* don't build if not configured for use in lwipopts.h */
47
48 #include "lwip/nd6.h"
49 #include "lwip/pbuf.h"
50 #include "lwip/mem.h"
51 #include "lwip/memp.h"
52 #include "lwip/ip6.h"
53 #include "lwip/ip6_addr.h"
54 #include "lwip/inet_chksum.h"
55 #include "lwip/netif.h"
56 #include "lwip/icmp6.h"
57 #include "lwip/mld6.h"
58 #include "lwip/stats.h"
59
60 #include <string.h>
61
62
63 /* Router tables. */
64 struct nd6_neighbor_cache_entry neighbor_cache[LWIP_ND6_NUM_NEIGHBORS];
65 struct nd6_destination_cache_entry destination_cache[LWIP_ND6_NUM_DESTINATIONS];
66 struct nd6_prefix_list_entry prefix_list[LWIP_ND6_NUM_PREFIXES];
67 struct nd6_router_list_entry default_router_list[LWIP_ND6_NUM_ROUTERS];
68
69 /* Default values, can be updated by a RA message. */
70 u32_t reachable_time = LWIP_ND6_REACHABLE_TIME;
71 u32_t retrans_timer = LWIP_ND6_RETRANS_TIMER; /* TODO implement this value in timer */
72
73 /* Index for cache entries. */
74 static u8_t nd6_cached_neighbor_index;
75 static u8_t nd6_cached_destination_index;
76
77 /* Multicast address holder. */
78 static ip6_addr_t multicast_address;
79
80 /* Static buffer to parse RA packet options (size of a prefix option, biggest option) */
81 static u8_t nd6_ra_buffer[sizeof(struct prefix_option)];
82
83 /* Forward declarations. */
84 static s8_t nd6_find_neighbor_cache_entry(ip6_addr_t * ip6addr);
85 static s8_t nd6_new_neighbor_cache_entry(void);
86 static void nd6_free_neighbor_cache_entry(s8_t i);
87 static s8_t nd6_find_destination_cache_entry(ip6_addr_t * ip6addr);
88 static s8_t nd6_new_destination_cache_entry(void);
89 static s8_t nd6_is_prefix_in_netif(ip6_addr_t * ip6addr, struct netif * netif);
90 static s8_t nd6_get_router(ip6_addr_t * router_addr, struct netif * netif);
91 static s8_t nd6_new_router(ip6_addr_t * router_addr, struct netif * netif);
92 static s8_t nd6_get_onlink_prefix(ip6_addr_t * prefix, struct netif * netif);
93 static s8_t nd6_new_onlink_prefix(ip6_addr_t * prefix, struct netif * netif);
94
95 #define ND6_SEND_FLAG_MULTICAST_DEST 0x01
96 #define ND6_SEND_FLAG_ALLNODES_DEST 0x02
97 static void nd6_send_ns(struct netif * netif, ip6_addr_t * target_addr, u8_t flags);
98 static void nd6_send_na(struct netif * netif, ip6_addr_t * target_addr, u8_t flags);
99 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
100 static void nd6_send_rs(struct netif * netif);
101 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
102
103 #if LWIP_ND6_QUEUEING
104 static void nd6_free_q(struct nd6_q_entry *q);
105 static void nd6_send_q(s8_t i);
106 #endif /* LWIP_ND6_QUEUEING */
107
108
109 /**
110  * Process an incoming neighbor discovery message
111  *
112  * @param p the nd packet, p->payload pointing to the icmpv6 header
113  * @param inp the netif on which this packet was received
114  */
115 void
116 nd6_input(struct pbuf *p, struct netif *inp)
117 {
118   u8_t msg_type;
119   s8_t i;
120
121   ND6_STATS_INC(nd6.recv);
122
123   msg_type = *((u8_t *)p->payload);
124   switch (msg_type) {
125   case ICMP6_TYPE_NA: /* Neighbor Advertisement. */
126   {
127     struct na_header * na_hdr;
128     struct lladdr_option * lladdr_opt;
129
130     /* Check that na header fits in packet. */
131     if (p->len < (sizeof(struct na_header))) {
132       /* TODO debug message */
133       pbuf_free(p);
134       ND6_STATS_INC(nd6.lenerr);
135       ND6_STATS_INC(nd6.drop);
136       return;
137     }
138
139     na_hdr = (struct na_header *)p->payload;
140
141     /* Unsolicited NA?*/
142     if (ip6_addr_ismulticast(ip6_current_dest_addr())) {
143       /* This is an unsolicited NA.
144        * link-layer changed?
145        * part of DAD mechanism? */
146
147       /* Check that link-layer address option also fits in packet. */
148       if (p->len < (sizeof(struct na_header) + sizeof(struct lladdr_option))) {
149         /* TODO debug message */
150         pbuf_free(p);
151         ND6_STATS_INC(nd6.lenerr);
152         ND6_STATS_INC(nd6.drop);
153         return;
154       }
155
156       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
157
158       /* Override ip6_current_dest_addr() so that we have an aligned copy. */
159       ip6_addr_set(ip6_current_dest_addr(), &(na_hdr->target_address));
160
161 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS
162       /* If the target address matches this netif, it is a DAD response. */
163       for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
164         if (ip6_addr_cmp(ip6_current_dest_addr(), netif_ip6_addr(inp, i))) {
165           /* We are using a duplicate address. */
166           netif_ip6_addr_set_state(inp, i, IP6_ADDR_INVALID);
167
168 #if LWIP_IPV6_MLD
169           /* Leave solicited node multicast group. */
170           ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(inp, i)->addr[3]);
171           mld6_leavegroup(netif_ip6_addr(inp, i), &multicast_address);
172 #endif /* LWIP_IPV6_MLD */
173
174
175
176
177 #if LWIP_IPV6_AUTOCONFIG
178           /* Check to see if this address was autoconfigured. */
179           if (!ip6_addr_islinklocal(ip6_current_dest_addr())) {
180             i = nd6_get_onlink_prefix(ip6_current_dest_addr(), inp);
181             if (i >= 0) {
182               /* Mark this prefix as duplicate, so that we don't use it
183                * to generate this address again. */
184               prefix_list[i].flags |= ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE;
185             }
186           }
187 #endif /* LWIP_IPV6_AUTOCONFIG */
188
189           pbuf_free(p);
190           return;
191         }
192       }
193 #endif /* LWIP_IPV6_DUP_DETECT_ATTEMPTS */
194
195       /* This is an unsolicited NA, most likely there was a LLADDR change. */
196       i = nd6_find_neighbor_cache_entry(ip6_current_dest_addr());
197       if (i >= 0) {
198         if (na_hdr->flags & ND6_FLAG_OVERRIDE) {
199           MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
200         }
201       }
202     }
203     else {
204       /* This is a solicited NA.
205        * neighbor address resolution response?
206        * neighbor unreachability detection response? */
207
208       /* Override ip6_current_dest_addr() so that we have an aligned copy. */
209       ip6_addr_set(ip6_current_dest_addr(), &(na_hdr->target_address));
210
211       /* Find the cache entry corresponding to this na. */
212       i = nd6_find_neighbor_cache_entry(ip6_current_dest_addr());
213       if (i < 0) {
214         /* We no longer care about this target address. drop it. */
215         pbuf_free(p);
216         return;
217       }
218
219       /* Update cache entry. */
220       neighbor_cache[i].netif = inp;
221       neighbor_cache[i].counter.reachable_time = reachable_time;
222       if ((na_hdr->flags & ND6_FLAG_OVERRIDE) ||
223           (neighbor_cache[i].state == ND6_INCOMPLETE)) {
224         /* Check that link-layer address option also fits in packet. */
225         if (p->len < (sizeof(struct na_header) + sizeof(struct lladdr_option))) {
226           /* TODO debug message */
227           pbuf_free(p);
228           ND6_STATS_INC(nd6.lenerr);
229           ND6_STATS_INC(nd6.drop);
230           return;
231         }
232
233         lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
234
235         MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
236       }
237       neighbor_cache[i].state = ND6_REACHABLE;
238
239 #if LWIP_ND6_QUEUEING
240       /* Send queued packets, if any. */
241       if (neighbor_cache[i].q != NULL) {
242         nd6_send_q(i);
243       }
244 #endif /* LWIP_ND6_QUEUEING */
245     }
246
247     break; /* ICMP6_TYPE_NA */
248   }
249   case ICMP6_TYPE_NS: /* Neighbor solicitation. */
250   {
251     struct ns_header * ns_hdr;
252     struct lladdr_option * lladdr_opt;
253     u8_t accepted;
254
255     /* Check that ns header fits in packet. */
256     if (p->len < sizeof(struct ns_header)) {
257       /* TODO debug message */
258       pbuf_free(p);
259       ND6_STATS_INC(nd6.lenerr);
260       ND6_STATS_INC(nd6.drop);
261       return;
262     }
263
264     ns_hdr = (struct ns_header *)p->payload;
265
266     /* Check if there is a link-layer address provided. Only point to it if in this buffer. */
267     lladdr_opt = NULL;
268     if (p->len >= (sizeof(struct ns_header) + sizeof(struct lladdr_option))) {
269       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct ns_header));
270     }
271
272     /* Check if the target address is configured on the receiving netif. */
273     accepted = 0;
274     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
275       if ((ip6_addr_isvalid(netif_ip6_addr_state(inp, i)) ||
276            (ip6_addr_istentative(netif_ip6_addr_state(inp, i)) &&
277             ip6_addr_isany(ip6_current_src_addr()))) &&
278           ip6_addr_cmp(&(ns_hdr->target_address), netif_ip6_addr(inp, i))) {
279         accepted = 1;
280         break;
281       }
282     }
283
284     /* NS not for us? */
285     if (!accepted) {
286       pbuf_free(p);
287       return;
288     }
289
290     /* Check for ANY address in src (DAD algorithm). */
291     if (ip6_addr_isany(ip6_current_src_addr())) {
292       /* Sender is validating this address. */
293       for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
294         if (ip6_addr_cmp(&(ns_hdr->target_address), netif_ip6_addr(inp, i))) {
295           /* Send a NA back so that the sender does not use this address. */
296           nd6_send_na(inp, netif_ip6_addr(inp, i), ND6_FLAG_OVERRIDE | ND6_SEND_FLAG_ALLNODES_DEST);
297           if (ip6_addr_istentative(netif_ip6_addr_state(inp, i))) {
298             /* We shouldn't use this address either. */
299             netif_ip6_addr_set_state(inp, i, IP6_ADDR_INVALID);
300           }
301         }
302       }
303     }
304     else {
305       /* Sender is trying to resolve our address. */
306       /* Verify that they included their own link-layer address. */
307       if (lladdr_opt == NULL) {
308         /* Not a valid message. */
309         pbuf_free(p);
310         ND6_STATS_INC(nd6.proterr);
311         ND6_STATS_INC(nd6.drop);
312         return;
313       }
314
315       i = nd6_find_neighbor_cache_entry(ip6_current_src_addr());
316       if ( i>= 0) {
317         /* We already have a record for the solicitor. */
318         if (neighbor_cache[i].state == ND6_INCOMPLETE) {
319           neighbor_cache[i].netif = inp;
320           MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
321
322           /* Delay probe in case we get confirmation of reachability from upper layer (TCP). */
323           neighbor_cache[i].state = ND6_DELAY;
324           neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
325         }
326       }
327       else
328       {
329         /* Add their IPv6 address and link-layer address to neighbor cache.
330          * We will need it at least to send a unicast NA message, but most
331          * likely we will also be communicating with this node soon. */
332         i = nd6_new_neighbor_cache_entry();
333         if (i < 0) {
334           /* We couldn't assign a cache entry for this neighbor.
335            * we won't be able to reply. drop it. */
336           pbuf_free(p);
337           ND6_STATS_INC(nd6.memerr);
338           return;
339         }
340         neighbor_cache[i].netif = inp;
341         MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
342         ip6_addr_set(&(neighbor_cache[i].next_hop_address), ip6_current_src_addr());
343
344         /* Receiving a message does not prove reachability: only in one direction.
345          * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
346         neighbor_cache[i].state = ND6_DELAY;
347         neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
348       }
349
350       /* Override ip6_current_dest_addr() so that we have an aligned copy. */
351       ip6_addr_set(ip6_current_dest_addr(), &(ns_hdr->target_address));
352
353       /* Send back a NA for us. Allocate the reply pbuf. */
354       nd6_send_na(inp, ip6_current_dest_addr(), ND6_FLAG_SOLICITED | ND6_FLAG_OVERRIDE);
355     }
356
357     break; /* ICMP6_TYPE_NS */
358   }
359   case ICMP6_TYPE_RA: /* Router Advertisement. */
360   {
361     struct ra_header * ra_hdr;
362     u8_t * buffer; /* Used to copy options. */
363     u16_t offset;
364
365     /* Check that RA header fits in packet. */
366     if (p->len < sizeof(struct ra_header)) {
367       /* TODO debug message */
368       pbuf_free(p);
369       ND6_STATS_INC(nd6.lenerr);
370       ND6_STATS_INC(nd6.drop);
371       return;
372     }
373
374     ra_hdr = (struct ra_header *)p->payload;
375
376     /* If we are sending RS messages, stop. */
377 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
378     inp->rs_count = 0;
379 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
380
381     /* Get the matching default router entry. */
382     i = nd6_get_router(ip6_current_src_addr(), inp);
383     if (i < 0) {
384       /* Create a new router entry. */
385       i = nd6_new_router(ip6_current_src_addr(), inp);
386     }
387
388     if (i < 0) {
389       /* Could not create a new router entry. */
390       pbuf_free(p);
391       ND6_STATS_INC(nd6.memerr);
392       return;
393     }
394
395     /* Re-set invalidation timer. */
396     default_router_list[i].invalidation_timer = ra_hdr->router_lifetime;
397
398     /* Re-set default timer values. */
399 #if LWIP_ND6_ALLOW_RA_UPDATES
400     if (ra_hdr->retrans_timer > 0) {
401       retrans_timer = ra_hdr->retrans_timer;
402     }
403     if (ra_hdr->reachable_time > 0) {
404       reachable_time = ra_hdr->reachable_time;
405     }
406 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
407
408     /* TODO set default hop limit... */
409     /* ra_hdr->current_hop_limit;*/
410
411     /* Update flags in local entry (incl. preference). */
412     default_router_list[i].flags = ra_hdr->flags;
413
414     /* Offset to options. */
415     offset = sizeof(struct ra_header);
416
417     /* Process each option. */
418     while ((p->tot_len - offset) > 0) {
419       if (p->len == p->tot_len) {
420         /* no need to copy from contiguous pbuf */
421         buffer = &((u8_t*)p->payload)[offset];
422       } else {
423         buffer = nd6_ra_buffer;
424         pbuf_copy_partial(p, buffer, sizeof(struct prefix_option), offset);
425       }
426       switch (buffer[0]) {
427       case ND6_OPTION_TYPE_SOURCE_LLADDR:
428       {
429         struct lladdr_option * lladdr_opt;
430         lladdr_opt = (struct lladdr_option *)buffer;
431         if ((default_router_list[i].neighbor_entry != NULL) &&
432             (default_router_list[i].neighbor_entry->state == ND6_INCOMPLETE)) {
433           SMEMCPY(default_router_list[i].neighbor_entry->lladdr, lladdr_opt->addr, inp->hwaddr_len);
434           default_router_list[i].neighbor_entry->state = ND6_REACHABLE;
435           default_router_list[i].neighbor_entry->counter.reachable_time = reachable_time;
436         }
437         break;
438       }
439       case ND6_OPTION_TYPE_MTU:
440       {
441         struct mtu_option * mtu_opt;
442         mtu_opt = (struct mtu_option *)buffer;
443         if (mtu_opt->mtu >= 1280) {
444 #if LWIP_ND6_ALLOW_RA_UPDATES
445           inp->mtu = mtu_opt->mtu;
446 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
447         }
448         break;
449       }
450       case ND6_OPTION_TYPE_PREFIX_INFO:
451       {
452         struct prefix_option * prefix_opt;
453         prefix_opt = (struct prefix_option *)buffer;
454
455         if (prefix_opt->flags & ND6_PREFIX_FLAG_ON_LINK) {
456           /* Add to on-link prefix list. */
457
458           /* Get a memory-aligned copy of the prefix. */
459           ip6_addr_set(ip6_current_dest_addr(), &(prefix_opt->prefix));
460
461           /* find cache entry for this prefix. */
462           i = nd6_get_onlink_prefix(ip6_current_dest_addr(), inp);
463           if (i < 0) {
464             /* Create a new cache entry. */
465             i = nd6_new_onlink_prefix(ip6_current_dest_addr(), inp);
466           }
467           if (i >= 0) {
468             prefix_list[i].invalidation_timer = prefix_opt->valid_lifetime;
469
470 #if LWIP_IPV6_AUTOCONFIG
471             if (prefix_opt->flags & ND6_PREFIX_FLAG_AUTONOMOUS) {
472               /* Mark prefix as autonomous, so that address autoconfiguration can take place.
473                * Only OR flag, so that we don't over-write other flags (such as ADDRESS_DUPLICATE)*/
474               prefix_list[i].flags |= ND6_PREFIX_AUTOCONFIG_AUTONOMOUS;
475             }
476 #endif /* LWIP_IPV6_AUTOCONFIG */
477           }
478         }
479
480         break;
481       }
482       case ND6_OPTION_TYPE_ROUTE_INFO:
483       {
484         /* TODO implement preferred routes.
485         struct route_option * route_opt;
486         route_opt = (struct route_option *)buffer;*/
487
488         break;
489       }
490       default:
491         /* Unrecognized option, abort. */
492         ND6_STATS_INC(nd6.proterr);
493         break;
494       }
495       offset += 8 * ((u16_t)buffer[1]);
496     }
497
498     break; /* ICMP6_TYPE_RA */
499   }
500   case ICMP6_TYPE_RD: /* Redirect */
501   {
502     struct redirect_header * redir_hdr;
503     struct lladdr_option * lladdr_opt;
504
505     /* Check that Redir header fits in packet. */
506     if (p->len < sizeof(struct redirect_header)) {
507       /* TODO debug message */
508       pbuf_free(p);
509       ND6_STATS_INC(nd6.lenerr);
510       ND6_STATS_INC(nd6.drop);
511       return;
512     }
513
514     redir_hdr = (struct redirect_header *)p->payload;
515
516     lladdr_opt = NULL;
517     if (p->len >= (sizeof(struct redirect_header) + sizeof(struct lladdr_option))) {
518       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct redirect_header));
519     }
520
521     /* Copy original destination address to current source address, to have an aligned copy. */
522     ip6_addr_set(ip6_current_src_addr(), &(redir_hdr->destination_address));
523
524     /* Find dest address in cache */
525     i = nd6_find_destination_cache_entry(ip6_current_src_addr());
526     if (i < 0) {
527       /* Destination not in cache, drop packet. */
528       pbuf_free(p);
529       return;
530     }
531
532     /* Set the new target address. */
533     ip6_addr_set(&(destination_cache[i].next_hop_addr), &(redir_hdr->target_address));
534
535     /* If Link-layer address of other router is given, try to add to neighbor cache. */
536     if (lladdr_opt != NULL) {
537       if (lladdr_opt->type == ND6_OPTION_TYPE_TARGET_LLADDR) {
538         /* Copy target address to current source address, to have an aligned copy. */
539         ip6_addr_set(ip6_current_src_addr(), &(redir_hdr->target_address));
540
541         i = nd6_find_neighbor_cache_entry(ip6_current_src_addr());
542         if (i < 0) {
543           i = nd6_new_neighbor_cache_entry();
544           if (i >= 0) {
545             neighbor_cache[i].netif = inp;
546             MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
547             ip6_addr_set(&(neighbor_cache[i].next_hop_address), ip6_current_src_addr());
548
549             /* Receiving a message does not prove reachability: only in one direction.
550              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
551             neighbor_cache[i].state = ND6_DELAY;
552             neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
553           }
554         }
555         if (i >= 0) {
556           if (neighbor_cache[i].state == ND6_INCOMPLETE) {
557             MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
558             /* Receiving a message does not prove reachability: only in one direction.
559              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
560             neighbor_cache[i].state = ND6_DELAY;
561             neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME;
562           }
563         }
564       }
565     }
566     break; /* ICMP6_TYPE_RD */
567   }
568   case ICMP6_TYPE_PTB: /* Packet too big */
569   {
570     struct icmp6_hdr *icmp6hdr; /* Packet too big message */
571     struct ip6_hdr * ip6hdr; /* IPv6 header of the packet which caused the error */
572
573     /* Check that ICMPv6 header + IPv6 header fit in payload */
574     if (p->len < (sizeof(struct icmp6_hdr) + IP6_HLEN)) {
575       /* drop short packets */
576       pbuf_free(p);
577       ND6_STATS_INC(nd6.lenerr);
578       ND6_STATS_INC(nd6.drop);
579       return;
580     }
581
582     icmp6hdr = (struct icmp6_hdr *)p->payload;
583     ip6hdr = (struct ip6_hdr *)((u8_t*)p->payload + sizeof(struct icmp6_hdr));
584
585     /* Copy original destination address to current source address, to have an aligned copy. */
586     ip6_addr_set(ip6_current_src_addr(), &(ip6hdr->dest));
587
588     /* Look for entry in destination cache. */
589     i = nd6_find_destination_cache_entry(ip6_current_src_addr());
590     if (i < 0) {
591       /* Destination not in cache, drop packet. */
592       pbuf_free(p);
593       return;
594     }
595
596     /* Change the Path MTU. */
597     destination_cache[i].pmtu = icmp6hdr->data;
598
599     break; /* ICMP6_TYPE_PTB */
600   }
601
602   default:
603     ND6_STATS_INC(nd6.proterr);
604     ND6_STATS_INC(nd6.drop);
605     break; /* default */
606   }
607
608   pbuf_free(p);
609 }
610
611
612 /**
613  * Periodic timer for Neighbor discovery functions:
614  *
615  * - Update neighbor reachability states
616  * - Update destination cache entries age
617  * - Update invalidation timers of default routers and on-link prefixes
618  * - Perform duplicate address detection (DAD) for our addresses
619  * - Send router solicitations
620  */
621 void
622 nd6_tmr(void)
623 {
624   s8_t i, j;
625   struct netif * netif;
626
627   /* Process neighbor entries. */
628   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
629     switch (neighbor_cache[i].state) {
630     case ND6_INCOMPLETE:
631       if (neighbor_cache[i].counter.probes_sent >= LWIP_ND6_MAX_MULTICAST_SOLICIT) {
632         /* Retries exceeded. */
633         nd6_free_neighbor_cache_entry(i);
634       }
635       else {
636         /* Send a NS for this entry. */
637         neighbor_cache[i].counter.probes_sent++;
638         nd6_send_ns(neighbor_cache[i].netif, &(neighbor_cache[i].next_hop_address), ND6_SEND_FLAG_MULTICAST_DEST);
639       }
640       break;
641     case ND6_REACHABLE:
642 #if LWIP_ND6_QUEUEING
643       /* Send queued packets, if any are left. Should have been sent already. */
644       if (neighbor_cache[i].q != NULL) {
645         nd6_send_q(i);
646       }
647 #endif /* LWIP_ND6_QUEUEING */
648       if (neighbor_cache[i].counter.reachable_time <= ND6_TMR_INTERVAL) {
649         /* Change to stale state. */
650         neighbor_cache[i].state = ND6_STALE;
651         neighbor_cache[i].counter.stale_time = 0;
652       }
653       else {
654         neighbor_cache[i].counter.reachable_time -= ND6_TMR_INTERVAL;
655       }
656       break;
657     case ND6_STALE:
658       neighbor_cache[i].counter.stale_time += ND6_TMR_INTERVAL;
659       break;
660     case ND6_DELAY:
661       if (neighbor_cache[i].counter.delay_time <= ND6_TMR_INTERVAL) {
662         /* Change to PROBE state. */
663         neighbor_cache[i].state = ND6_PROBE;
664         neighbor_cache[i].counter.probes_sent = 0;
665       }
666       else {
667         neighbor_cache[i].counter.delay_time -= ND6_TMR_INTERVAL;
668       }
669       break;
670     case ND6_PROBE:
671       if (neighbor_cache[i].counter.probes_sent >= LWIP_ND6_MAX_MULTICAST_SOLICIT) {
672         /* Retries exceeded. */
673         nd6_free_neighbor_cache_entry(i);
674       }
675       else {
676         /* Send a NS for this entry. */
677         neighbor_cache[i].counter.probes_sent++;
678         nd6_send_ns(neighbor_cache[i].netif, &(neighbor_cache[i].next_hop_address), 0);
679       }
680       break;
681     case ND6_NO_ENTRY:
682     default:
683       /* Do nothing. */
684       break;
685     }
686   }
687
688   /* Process destination entries. */
689   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
690     destination_cache[i].age++;
691   }
692
693   /* Process router entries. */
694   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
695     if (default_router_list[i].neighbor_entry != NULL) {
696       /* Active entry. */
697       if (default_router_list[i].invalidation_timer > 0) {
698         default_router_list[i].invalidation_timer -= ND6_TMR_INTERVAL / 1000;
699       }
700       if (default_router_list[i].invalidation_timer < ND6_TMR_INTERVAL / 1000) {
701         /* Less than 1 second remainig. Clear this entry. */
702         default_router_list[i].neighbor_entry->isrouter = 0;
703         default_router_list[i].neighbor_entry = NULL;
704         default_router_list[i].invalidation_timer = 0;
705         default_router_list[i].flags = 0;
706       }
707     }
708   }
709
710   /* Process prefix entries. */
711   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; i++) {
712     if (prefix_list[i].invalidation_timer < ND6_TMR_INTERVAL / 1000) {
713       prefix_list[i].invalidation_timer = 0;
714     }
715     if ((prefix_list[i].invalidation_timer > 0) &&
716         (prefix_list[i].netif != NULL)) {
717       prefix_list[i].invalidation_timer -= ND6_TMR_INTERVAL / 1000;
718
719 #if LWIP_IPV6_AUTOCONFIG
720       /* Initiate address autoconfiguration for this prefix, if conditions are met. */
721       if (prefix_list[i].netif->ip6_autoconfig_enabled &&
722           (prefix_list[i].flags & ND6_PREFIX_AUTOCONFIG_AUTONOMOUS) &&
723           !(prefix_list[i].flags & ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED)) {
724         /* Try to get an address on this netif that is invalid.
725          * Skip 0 index (link-local address) */
726         for (j = 1; j < LWIP_IPV6_NUM_ADDRESSES; j++) {
727           if (netif_ip6_addr_state(prefix_list[i].netif, j) == IP6_ADDRESS_STATE_INVALID) {
728             /* Generate an address using this prefix and interface ID from link-local address. */
729             prefix_list[i].netif->ip6_addr[j].addr[0] = prefix_list[i].prefix.addr[0];
730             prefix_list[i].netif->ip6_addr[j].addr[1] = prefix_list[i].prefix.addr[1];
731             prefix_list[i].netif->ip6_addr[j].addr[2] = prefix_list[i].netif->ip6_addr[0].addr[2];
732             prefix_list[i].netif->ip6_addr[j].addr[3] = prefix_list[i].netif->ip6_addr[0].addr[3];
733
734             /* Mark it as tentative (DAD will be performed if configured). */
735             netif_ip6_addr_set_state(prefix_list[i].netif, j, IP6_ADDR_TENTATIVE);
736
737             /* Mark this prefix with ADDRESS_GENERATED, so that we don't try again. */
738             prefix_list[i].flags |= ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED;
739
740             /* Exit loop. */
741             break;
742           }
743         }
744       }
745 #endif /* LWIP_IPV6_AUTOCONFIG */
746     }
747   }
748
749
750   /* Process our own addresses, if DAD configured. */
751   for (netif = netif_list; netif != NULL; netif = netif->next) {
752     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
753       if (ip6_addr_istentative(netif->ip6_addr_state[i])) {
754         if ((netif->ip6_addr_state[i] & 0x07) >= LWIP_IPV6_DUP_DETECT_ATTEMPTS) {
755           /* No NA received in response. Mark address as valid. */
756           netif->ip6_addr_state[i] = IP6_ADDR_PREFERRED;
757           /* TODO implement preferred and valid lifetimes. */
758         }
759         else if (netif->flags & NETIF_FLAG_UP) {
760 #if LWIP_IPV6_MLD
761           if ((netif->ip6_addr_state[i] & 0x07) == 0) {
762             /* Join solicited node multicast group. */
763             ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(netif, i)->addr[3]);
764             mld6_joingroup(netif_ip6_addr(netif, i), &multicast_address);
765           }
766 #endif /* LWIP_IPV6_MLD */
767           /* Send a NS for this address. */
768           nd6_send_ns(netif, netif_ip6_addr(netif, i), ND6_SEND_FLAG_MULTICAST_DEST);
769           (netif->ip6_addr_state[i])++;
770           /* TODO send max 1 NS per tmr call? enable return*/
771           /*return;*/
772         }
773       }
774     }
775   }
776
777 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
778   /* Send router solicitation messages, if necessary. */
779   for (netif = netif_list; netif != NULL; netif = netif->next) {
780     if ((netif->rs_count > 0) && (netif->flags & NETIF_FLAG_UP)) {
781       nd6_send_rs(netif);
782       netif->rs_count--;
783     }
784   }
785 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
786
787 }
788
789 /**
790  * Send a neighbor solicitation message
791  *
792  * @param netif the netif on which to send the message
793  * @param target_addr the IPv6 target address for the ND message
794  * @param flags one of ND6_SEND_FLAG_*
795  */
796 static void
797 nd6_send_ns(struct netif * netif, ip6_addr_t * target_addr, u8_t flags)
798 {
799   struct ns_header * ns_hdr;
800   struct lladdr_option * lladdr_opt;
801   struct pbuf * p;
802   ip6_addr_t * src_addr;
803
804   if (ip6_addr_isvalid(netif_ip6_addr_state(netif,0))) {
805     /* Use link-local address as source address. */
806     src_addr = netif_ip6_addr(netif, 0);
807   } else {
808     src_addr = IP6_ADDR_ANY;
809   }
810
811   /* Allocate a packet. */
812   p = pbuf_alloc(PBUF_IP, sizeof(struct ns_header) + sizeof(struct lladdr_option), PBUF_RAM);
813   if ((p == NULL) || (p->len < (sizeof(struct ns_header) + sizeof(struct lladdr_option)))) {
814     /* We couldn't allocate a suitable pbuf for the ns. drop it. */
815     if (p != NULL) {
816       pbuf_free(p);
817     }
818     ND6_STATS_INC(nd6.memerr);
819     return;
820   }
821
822   /* Set fields. */
823   ns_hdr = (struct ns_header *)p->payload;
824   lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct ns_header));
825
826   ns_hdr->type = ICMP6_TYPE_NS;
827   ns_hdr->code = 0;
828   ns_hdr->chksum = 0;
829   ns_hdr->reserved = 0;
830   ip6_addr_set(&(ns_hdr->target_address), target_addr);
831
832   lladdr_opt->type = ND6_OPTION_TYPE_SOURCE_LLADDR;
833   lladdr_opt->length = ((netif->hwaddr_len + 2) >> 3) + (((netif->hwaddr_len + 2) & 0x07) ? 1 : 0);
834   SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
835
836   /* Generate the solicited node address for the target address. */
837   if (flags & ND6_SEND_FLAG_MULTICAST_DEST) {
838     ip6_addr_set_solicitednode(&multicast_address, target_addr->addr[3]);
839     target_addr = &multicast_address;
840   }
841
842   ns_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
843     target_addr);
844
845   /* Send the packet out. */
846   ND6_STATS_INC(nd6.xmit);
847   ip6_output_if(p, (src_addr == IP6_ADDR_ANY) ? NULL : src_addr, target_addr,
848       LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, netif);
849   pbuf_free(p);
850 }
851
852 /**
853  * Send a neighbor advertisement message
854  *
855  * @param netif the netif on which to send the message
856  * @param target_addr the IPv6 target address for the ND message
857  * @param flags one of ND6_SEND_FLAG_*
858  */
859 static void
860 nd6_send_na(struct netif * netif, ip6_addr_t * target_addr, u8_t flags)
861 {
862   struct na_header * na_hdr;
863   struct lladdr_option * lladdr_opt;
864   struct pbuf * p;
865   ip6_addr_t * src_addr;
866   ip6_addr_t * dest_addr;
867
868   /* Use link-local address as source address. */
869   /* src_addr = &(netif->ip6_addr[0]); */
870   /* Use target address as source address. */
871   src_addr = target_addr;
872
873   /* Allocate a packet. */
874   p = pbuf_alloc(PBUF_IP, sizeof(struct na_header) + sizeof(struct lladdr_option), PBUF_RAM);
875   if ((p == NULL) || (p->len < (sizeof(struct na_header) + sizeof(struct lladdr_option)))) {
876     /* We couldn't allocate a suitable pbuf for the ns. drop it. */
877     if (p != NULL) {
878       pbuf_free(p);
879     }
880     ND6_STATS_INC(nd6.memerr);
881     return;
882   }
883
884   /* Set fields. */
885   na_hdr = (struct na_header *)p->payload;
886   lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
887
888   na_hdr->type = ICMP6_TYPE_NA;
889   na_hdr->code = 0;
890   na_hdr->chksum = 0;
891   na_hdr->flags = flags & 0xf0;
892   na_hdr->reserved[0] = 0;
893   na_hdr->reserved[1] = 0;
894   na_hdr->reserved[2] = 0;
895   ip6_addr_set(&(na_hdr->target_address), target_addr);
896
897   lladdr_opt->type = ND6_OPTION_TYPE_TARGET_LLADDR;
898   lladdr_opt->length = ((netif->hwaddr_len + 2) >> 3) + (((netif->hwaddr_len + 2) & 0x07) ? 1 : 0);
899   SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
900
901   /* Generate the solicited node address for the target address. */
902   if (flags & ND6_SEND_FLAG_MULTICAST_DEST) {
903     ip6_addr_set_solicitednode(&multicast_address, target_addr->addr[3]);
904     dest_addr = &multicast_address;
905   }
906   else if (flags & ND6_SEND_FLAG_ALLNODES_DEST) {
907     ip6_addr_set_allnodes_linklocal(&multicast_address);
908     dest_addr = &multicast_address;
909   }
910   else {
911     dest_addr = ip6_current_src_addr();
912   }
913
914   na_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
915     dest_addr);
916
917   /* Send the packet out. */
918   ND6_STATS_INC(nd6.xmit);
919   ip6_output_if(p, src_addr, dest_addr,
920       LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, netif);
921   pbuf_free(p);
922 }
923
924 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
925 /**
926  * Send a router solicitation message
927  *
928  * @param netif the netif on which to send the message
929  */
930 static void
931 nd6_send_rs(struct netif * netif)
932 {
933   struct rs_header * rs_hdr;
934   struct lladdr_option * lladdr_opt;
935   struct pbuf * p;
936   ip6_addr_t * src_addr;
937   u16_t packet_len;
938
939   /* Link-local source address, or unspecified address? */
940   if (ip6_addr_isvalid(netif_ip6_addr_state(netif, 0))) {
941     src_addr = netif_ip6_addr(netif, 0);
942   }
943   else {
944     src_addr = IP6_ADDR_ANY;
945   }
946
947   /* Generate the all routers target address. */
948   ip6_addr_set_allrouters_linklocal(&multicast_address);
949
950   /* Allocate a packet. */
951   packet_len = sizeof(struct rs_header);
952   if (src_addr != IP6_ADDR_ANY) {
953     packet_len += sizeof(struct lladdr_option);
954   }
955   p = pbuf_alloc(PBUF_IP, packet_len, PBUF_RAM);
956   if ((p == NULL) || (p->len < packet_len)) {
957     /* We couldn't allocate a suitable pbuf for the ns. drop it. */
958     if (p != NULL) {
959       pbuf_free(p);
960     }
961     ND6_STATS_INC(nd6.memerr);
962     return;
963   }
964
965   /* Set fields. */
966   rs_hdr = (struct rs_header *)p->payload;
967
968   rs_hdr->type = ICMP6_TYPE_RS;
969   rs_hdr->code = 0;
970   rs_hdr->chksum = 0;
971   rs_hdr->reserved = 0;
972
973   if (src_addr != IP6_ADDR_ANY) {
974     /* Include our hw address. */
975     lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct rs_header));
976     lladdr_opt->type = ND6_OPTION_TYPE_SOURCE_LLADDR;
977     lladdr_opt->length = ((netif->hwaddr_len + 2) >> 3) + (((netif->hwaddr_len + 2) & 0x07) ? 1 : 0);
978     SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
979   }
980
981   rs_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
982     &multicast_address);
983
984   /* Send the packet out. */
985   ND6_STATS_INC(nd6.xmit);
986   ip6_output_if(p, src_addr, &multicast_address,
987       LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, netif);
988   pbuf_free(p);
989 }
990 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
991
992 /**
993  * Search for a neighbor cache entry
994  *
995  * @param ip6addr the IPv6 address of the neighbor
996  * @return The neighbor cache entry index that matched, -1 if no
997  * entry is found
998  */
999 static s8_t
1000 nd6_find_neighbor_cache_entry(ip6_addr_t * ip6addr)
1001 {
1002   s8_t i;
1003   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1004     if (ip6_addr_cmp(ip6addr, &(neighbor_cache[i].next_hop_address))) {
1005       return i;
1006     }
1007   }
1008   return -1;
1009 }
1010
1011 /**
1012  * Create a new neighbor cache entry.
1013  *
1014  * If no unused entry is found, will try to recycle an old entry
1015  * according to ad-hoc "age" heuristic.
1016  *
1017  * @return The neighbor cache entry index that was created, -1 if no
1018  * entry could be created
1019  */
1020 static s8_t
1021 nd6_new_neighbor_cache_entry(void)
1022 {
1023   s8_t i;
1024   s8_t j;
1025   u32_t time;
1026
1027
1028   /* First, try to find an empty entry. */
1029   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1030     if (neighbor_cache[i].state == ND6_NO_ENTRY) {
1031       return i;
1032     }
1033   }
1034
1035   /* We need to recycle an entry. in general, do not recycle if it is a router. */
1036
1037   /* Next, try to find a Stale entry. */
1038   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1039     if ((neighbor_cache[i].state == ND6_STALE) &&
1040         (!neighbor_cache[i].isrouter)) {
1041       nd6_free_neighbor_cache_entry(i);
1042       return i;
1043     }
1044   }
1045
1046   /* Next, try to find a Probe entry. */
1047   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1048     if ((neighbor_cache[i].state == ND6_PROBE) &&
1049         (!neighbor_cache[i].isrouter)) {
1050       nd6_free_neighbor_cache_entry(i);
1051       return i;
1052     }
1053   }
1054
1055   /* Next, try to find a Delayed entry. */
1056   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1057     if ((neighbor_cache[i].state == ND6_DELAY) &&
1058         (!neighbor_cache[i].isrouter)) {
1059       nd6_free_neighbor_cache_entry(i);
1060       return i;
1061     }
1062   }
1063
1064   /* Next, try to find the oldest reachable entry. */
1065   time = 0xfffffffful;
1066   j = -1;
1067   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1068     if ((neighbor_cache[i].state == ND6_REACHABLE) &&
1069         (!neighbor_cache[i].isrouter)) {
1070       if (neighbor_cache[i].counter.reachable_time < time) {
1071         j = i;
1072         time = neighbor_cache[i].counter.reachable_time;
1073       }
1074     }
1075   }
1076   if (j >= 0) {
1077     nd6_free_neighbor_cache_entry(j);
1078     return j;
1079   }
1080
1081   /* Next, find oldest incomplete entry without queued packets. */
1082   time = 0;
1083   j = -1;
1084   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1085     if (
1086 #if LWIP_ND6_QUEUEING
1087         (neighbor_cache[i].q == NULL) &&
1088 #endif /* LWIP_ND6_QUEUEING */
1089         (neighbor_cache[i].state == ND6_INCOMPLETE) &&
1090         (!neighbor_cache[i].isrouter)) {
1091       if (neighbor_cache[i].counter.probes_sent >= time) {
1092         j = i;
1093         time = neighbor_cache[i].counter.probes_sent;
1094       }
1095     }
1096   }
1097   if (j >= 0) {
1098     nd6_free_neighbor_cache_entry(j);
1099     return j;
1100   }
1101
1102   /* Next, find oldest incomplete entry with queued packets. */
1103 #if LWIP_ND6_QUEUEING
1104   time = 0;
1105   j = -1;
1106   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1107     if ((neighbor_cache[i].state == ND6_INCOMPLETE) &&
1108         (!neighbor_cache[i].isrouter)) {
1109       if (neighbor_cache[i].counter.probes_sent >= time) {
1110         j = i;
1111         time = neighbor_cache[i].counter.probes_sent;
1112       }
1113     }
1114   }
1115   if (j >= 0) {
1116     nd6_free_neighbor_cache_entry(j);
1117     return j;
1118   }
1119 #endif /* LWIP_ND6_QUEUEING */
1120
1121   /* No more entries to try. */
1122   return -1;
1123 }
1124
1125 /**
1126  * Will free any resources associated with a neighbor cache
1127  * entry, and will mark it as unused.
1128  *
1129  * @param i the neighbor cache entry index to free
1130  */
1131 static void
1132 nd6_free_neighbor_cache_entry(s8_t i)
1133 {
1134   if ((i < 0) || (i >= LWIP_ND6_NUM_NEIGHBORS)) {
1135     return;
1136   }
1137
1138 #if LWIP_ND6_QUEUEING
1139   /* Free any queued packets. */
1140   if (neighbor_cache[i].q != NULL) {
1141     nd6_free_q(neighbor_cache[i].q);
1142     neighbor_cache[i].q = NULL;
1143   }
1144 #endif /* LWIP_ND6_QUEUEING */
1145
1146   neighbor_cache[i].state = ND6_NO_ENTRY;
1147   neighbor_cache[i].isrouter = 0;
1148   neighbor_cache[i].netif = NULL;
1149   neighbor_cache[i].counter.reachable_time = 0;
1150   ip6_addr_set_zero(&(neighbor_cache[i].next_hop_address));
1151 }
1152
1153 /**
1154  * Search for a destination cache entry
1155  *
1156  * @param ip6addr the IPv6 address of the destination
1157  * @return The destination cache entry index that matched, -1 if no
1158  * entry is found
1159  */
1160 static s8_t
1161 nd6_find_destination_cache_entry(ip6_addr_t * ip6addr)
1162 {
1163   s8_t i;
1164   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1165     if (ip6_addr_cmp(ip6addr, &(destination_cache[i].destination_addr))) {
1166       return i;
1167     }
1168   }
1169   return -1;
1170 }
1171
1172 /**
1173  * Create a new destination cache entry. If no unused entry is found,
1174  * will recycle oldest entry.
1175  *
1176  * @return The destination cache entry index that was created, -1 if no
1177  * entry was created
1178  */
1179 static s8_t
1180 nd6_new_destination_cache_entry(void)
1181 {
1182   s8_t i, j;
1183   u32_t age;
1184
1185   /* Find an empty entry. */
1186   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1187     if (ip6_addr_isany(&(destination_cache[i].destination_addr))) {
1188       return i;
1189     }
1190   }
1191
1192   /* Find oldest entry. */
1193   age = 0;
1194   j = LWIP_ND6_NUM_DESTINATIONS - 1;
1195   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1196     if (destination_cache[i].age > age) {
1197       j = i;
1198     }
1199   }
1200
1201   return j;
1202 }
1203
1204 /**
1205  * Determine whether an address matches an on-link prefix.
1206  *
1207  * @param ip6addr the IPv6 address to match
1208  * @return 1 if the address is on-link, 0 otherwise
1209  */
1210 static s8_t
1211 nd6_is_prefix_in_netif(ip6_addr_t * ip6addr, struct netif * netif)
1212 {
1213   s8_t i;
1214   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; i++) {
1215     if ((prefix_list[i].netif == netif) &&
1216         (prefix_list[i].invalidation_timer > 0) &&
1217         ip6_addr_netcmp(ip6addr, &(prefix_list[i].prefix))) {
1218       return 1;
1219     }
1220   }
1221   /* Check to see if address prefix matches a (manually?) configured address. */
1222   for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
1223     if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i)) &&
1224         ip6_addr_netcmp(ip6addr, netif_ip6_addr(netif, i))) {
1225       return 1;
1226     }
1227   }
1228   return 0;
1229 }
1230
1231 /**
1232  * Select a default router for a destination.
1233  *
1234  * @param ip6addr the destination address
1235  * @param netif the netif for the outgoing packet, if known
1236  * @return the default router entry index, or -1 if no suitable
1237  *         router is found
1238  */
1239 s8_t
1240 nd6_select_router(ip6_addr_t * ip6addr, struct netif * netif)
1241 {
1242   s8_t i;
1243   /* last_router is used for round-robin router selection (as recommended
1244    * in RFC). This is more robust in case one router is not reachable,
1245    * we are not stuck trying to resolve it. */
1246   static s8_t last_router;
1247   (void)ip6addr; /* TODO match preferred routes!! (must implement ND6_OPTION_TYPE_ROUTE_INFO) */
1248
1249   /* TODO: implement default router preference */
1250
1251   /* Look for reachable routers. */
1252   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1253     if (++last_router >= LWIP_ND6_NUM_ROUTERS) {
1254       last_router = 0;
1255     }
1256     if ((default_router_list[i].neighbor_entry != NULL) &&
1257         (netif != NULL ? netif == default_router_list[i].neighbor_entry->netif : 1) &&
1258         (default_router_list[i].invalidation_timer > 0) &&
1259         (default_router_list[i].neighbor_entry->state == ND6_REACHABLE)) {
1260       return i;
1261     }
1262   }
1263
1264   /* Look for router in other reachability states, but still valid according to timer. */
1265   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1266     if (++last_router >= LWIP_ND6_NUM_ROUTERS) {
1267       last_router = 0;
1268     }
1269     if ((default_router_list[i].neighbor_entry != NULL) &&
1270         (netif != NULL ? netif == default_router_list[i].neighbor_entry->netif : 1) &&
1271         (default_router_list[i].invalidation_timer > 0)) {
1272       return i;
1273     }
1274   }
1275
1276   /* Look for any router for which we have any information at all. */
1277   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1278     if (++last_router >= LWIP_ND6_NUM_ROUTERS) {
1279       last_router = 0;
1280     }
1281     if (default_router_list[i].neighbor_entry != NULL &&
1282         (netif != NULL ? netif == default_router_list[i].neighbor_entry->netif : 1)) {
1283       return i;
1284     }
1285   }
1286
1287   /* no suitable router found. */
1288   return -1;
1289 }
1290
1291 /**
1292  * Find an entry for a default router.
1293  *
1294  * @param router_addr the IPv6 address of the router
1295  * @param netif the netif on which the router is found, if known
1296  * @return the index of the router entry, or -1 if not found
1297  */
1298 static s8_t
1299 nd6_get_router(ip6_addr_t * router_addr, struct netif * netif)
1300 {
1301   s8_t i;
1302
1303   /* Look for router. */
1304   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1305     if ((default_router_list[i].neighbor_entry != NULL) &&
1306         ((netif != NULL) ? netif == default_router_list[i].neighbor_entry->netif : 1) &&
1307         ip6_addr_cmp(router_addr, &(default_router_list[i].neighbor_entry->next_hop_address))) {
1308       return i;
1309     }
1310   }
1311
1312   /* router not found. */
1313   return -1;
1314 }
1315
1316 /**
1317  * Create a new entry for a default router.
1318  *
1319  * @param router_addr the IPv6 address of the router
1320  * @param netif the netif on which the router is connected, if known
1321  * @return the index on the router table, or -1 if could not be created
1322  */
1323 static s8_t
1324 nd6_new_router(ip6_addr_t * router_addr, struct netif * netif)
1325 {
1326   s8_t router_index;
1327   s8_t neighbor_index;
1328
1329   /* Do we have a neighbor entry for this router? */
1330   neighbor_index = nd6_find_neighbor_cache_entry(router_addr);
1331   if (neighbor_index < 0) {
1332     /* Create a neighbor entry for this router. */
1333     neighbor_index = nd6_new_neighbor_cache_entry();
1334     if (neighbor_index < 0) {
1335       /* Could not create neighbor entry for this router. */
1336       return -1;
1337     }
1338     ip6_addr_set(&(neighbor_cache[neighbor_index].next_hop_address), router_addr);
1339     neighbor_cache[neighbor_index].netif = netif;
1340 #if LWIP_ND6_QUEUEING
1341     neighbor_cache[neighbor_index].q = NULL;
1342 #endif /* LWIP_ND6_QUEUEING */
1343     neighbor_cache[neighbor_index].state = ND6_INCOMPLETE;
1344     neighbor_cache[neighbor_index].counter.probes_sent = 0;
1345   }
1346
1347   /* Mark neighbor as router. */
1348   neighbor_cache[neighbor_index].isrouter = 1;
1349
1350   /* Look for empty entry. */
1351   for (router_index = 0; router_index < LWIP_ND6_NUM_ROUTERS; router_index++) {
1352     if (default_router_list[router_index].neighbor_entry == NULL) {
1353       default_router_list[router_index].neighbor_entry = &(neighbor_cache[neighbor_index]);
1354       return router_index;
1355     }
1356   }
1357
1358   /* Could not create a router entry. */
1359
1360   /* Mark neighbor entry as not-router. Entry might be useful as neighbor still. */
1361   neighbor_cache[neighbor_index].isrouter = 0;
1362
1363   /* router not found. */
1364   return -1;
1365 }
1366
1367 /**
1368  * Find the cached entry for an on-link prefix.
1369  *
1370  * @param prefix the IPv6 prefix that is on-link
1371  * @param netif the netif on which the prefix is on-link
1372  * @return the index on the prefix table, or -1 if not found
1373  */
1374 static s8_t
1375 nd6_get_onlink_prefix(ip6_addr_t * prefix, struct netif * netif)
1376 {
1377   s8_t i;
1378
1379   /* Look for prefix in list. */
1380   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; ++i) {
1381     if ((ip6_addr_netcmp(&(prefix_list[i].prefix), prefix)) &&
1382         (prefix_list[i].netif == netif)) {
1383       return i;
1384     }
1385   }
1386
1387   /* Entry not available. */
1388   return -1;
1389 }
1390
1391 /**
1392  * Creates a new entry for an on-link prefix.
1393  *
1394  * @param prefix the IPv6 prefix that is on-link
1395  * @param netif the netif on which the prefix is on-link
1396  * @return the index on the prefix table, or -1 if not created
1397  */
1398 static s8_t
1399 nd6_new_onlink_prefix(ip6_addr_t * prefix, struct netif * netif)
1400 {
1401   s8_t i;
1402
1403   /* Create new entry. */
1404   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; ++i) {
1405     if ((prefix_list[i].netif == NULL) ||
1406         (prefix_list[i].invalidation_timer == 0)) {
1407       /* Found empty prefix entry. */
1408       prefix_list[i].netif = netif;
1409       ip6_addr_set(&(prefix_list[i].prefix), prefix);
1410       prefix_list[i].flags = 0;
1411       return i;
1412     }
1413   }
1414
1415   /* Entry not available. */
1416   return -1;
1417 }
1418
1419 /**
1420  * Determine the next hop for a destination. Will determine if the
1421  * destination is on-link, else a suitable on-link router is selected.
1422  *
1423  * The last entry index is cached for fast entry search.
1424  *
1425  * @param ip6addr the destination address
1426  * @param netif the netif on which the packet will be sent
1427  * @return the neighbor cache entry for the next hop, ERR_RTE if no
1428  *         suitable next hop was found, ERR_MEM if no cache entry
1429  *         could be created
1430  */
1431 s8_t
1432 nd6_get_next_hop_entry(ip6_addr_t * ip6addr, struct netif * netif)
1433 {
1434   s8_t i;
1435
1436 #if LWIP_NETIF_HWADDRHINT
1437   if (netif->addr_hint != NULL) {
1438     /* per-pcb cached entry was given */
1439     u8_t addr_hint = *(netif->addr_hint);
1440     if (addr_hint < LWIP_ND6_NUM_DESTINATIONS) {
1441       nd6_cached_destination_index = addr_hint;
1442     }
1443   }
1444 #endif /* LWIP_NETIF_HWADDRHINT */
1445
1446   /* Look for ip6addr in destination cache. */
1447   if (ip6_addr_cmp(ip6addr, &(destination_cache[nd6_cached_destination_index].destination_addr))) {
1448     /* the cached entry index is the right one! */
1449     /* do nothing. */
1450     ND6_STATS_INC(nd6.cachehit);
1451   } else {
1452     /* Search destination cache. */
1453     i = nd6_find_destination_cache_entry(ip6addr);
1454     if (i >= 0) {
1455       /* found destination entry. make it our new cached index. */
1456       nd6_cached_destination_index = i;
1457     }
1458     else {
1459       /* Not found. Create a new destination entry. */
1460       i = nd6_new_destination_cache_entry();
1461       if (i >= 0) {
1462         /* got new destination entry. make it our new cached index. */
1463         nd6_cached_destination_index = i;
1464       } else {
1465         /* Could not create a destination cache entry. */
1466         return ERR_MEM;
1467       }
1468
1469       /* Copy dest address to destination cache. */
1470       ip6_addr_set(&(destination_cache[nd6_cached_destination_index].destination_addr), ip6addr);
1471
1472       /* Now find the next hop. is it a neighbor? */
1473       if (ip6_addr_islinklocal(ip6addr) ||
1474           nd6_is_prefix_in_netif(ip6addr, netif)) {
1475         /* Destination in local link. */
1476         destination_cache[nd6_cached_destination_index].pmtu = netif->mtu;
1477         ip6_addr_copy(destination_cache[nd6_cached_destination_index].next_hop_addr, destination_cache[nd6_cached_destination_index].destination_addr);
1478       }
1479       else {
1480         /* We need to select a router. */
1481         i = nd6_select_router(ip6addr, netif);
1482         if (i < 0) {
1483           /* No router found. */
1484           ip6_addr_set_any(&(destination_cache[nd6_cached_destination_index].destination_addr));
1485           return ERR_RTE;
1486         }
1487         destination_cache[nd6_cached_destination_index].pmtu = netif->mtu; /* Start with netif mtu, correct through ICMPv6 if necessary */
1488         ip6_addr_copy(destination_cache[nd6_cached_destination_index].next_hop_addr, default_router_list[i].neighbor_entry->next_hop_address);
1489       }
1490     }
1491   }
1492
1493 #if LWIP_NETIF_HWADDRHINT
1494   if (netif->addr_hint != NULL) {
1495     /* per-pcb cached entry was given */
1496     *(netif->addr_hint) = nd6_cached_destination_index;
1497   }
1498 #endif /* LWIP_NETIF_HWADDRHINT */
1499
1500   /* Look in neighbor cache for the next-hop address. */
1501   if (ip6_addr_cmp(&(destination_cache[nd6_cached_destination_index].next_hop_addr),
1502                    &(neighbor_cache[nd6_cached_neighbor_index].next_hop_address))) {
1503     /* Cache hit. */
1504     /* Do nothing. */
1505     ND6_STATS_INC(nd6.cachehit);
1506   } else {
1507     i = nd6_find_neighbor_cache_entry(&(destination_cache[nd6_cached_destination_index].next_hop_addr));
1508     if (i >= 0) {
1509       /* Found a matching record, make it new cached entry. */
1510       nd6_cached_neighbor_index = i;
1511     }
1512     else {
1513       /* Neighbor not in cache. Make a new entry. */
1514       i = nd6_new_neighbor_cache_entry();
1515       if (i >= 0) {
1516         /* got new neighbor entry. make it our new cached index. */
1517         nd6_cached_neighbor_index = i;
1518       } else {
1519         /* Could not create a neighbor cache entry. */
1520         return ERR_MEM;
1521       }
1522
1523       /* Initialize fields. */
1524       ip6_addr_copy(neighbor_cache[i].next_hop_address,
1525                    destination_cache[nd6_cached_destination_index].next_hop_addr);
1526       neighbor_cache[i].isrouter = 0;
1527       neighbor_cache[i].netif = netif;
1528       neighbor_cache[i].state = ND6_INCOMPLETE;
1529       neighbor_cache[i].counter.probes_sent = 0;
1530     }
1531   }
1532
1533   /* Reset this destination's age. */
1534   destination_cache[nd6_cached_destination_index].age = 0;
1535
1536   return nd6_cached_neighbor_index;
1537 }
1538
1539 #if LWIP_ND6_QUEUEING
1540
1541 /**
1542  * Queue a packet for a neighbor.
1543  *
1544  * @param neighbor_index the index in the neighbor cache table
1545  * @param q packet to be queued
1546  * @return ERR_OK if succeeded, ERR_MEM if out of memory
1547  */
1548 err_t
1549 nd6_queue_packet(s8_t neighbor_index, struct pbuf * q)
1550 {
1551   err_t result = ERR_MEM;
1552   struct pbuf *p;
1553   int copy_needed = 0;
1554   struct nd6_q_entry *new_entry, *r;
1555
1556   if ((neighbor_index < 0) || (neighbor_index >= LWIP_ND6_NUM_NEIGHBORS)) {
1557     return ERR_ARG;
1558   }
1559
1560   /* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but
1561    * to copy the whole queue into a new PBUF_RAM (see bug #11400)
1562    * PBUF_ROMs can be left as they are, since ROM must not get changed. */
1563   p = q;
1564   while (p) {
1565     if(p->type != PBUF_ROM) {
1566       copy_needed = 1;
1567       break;
1568     }
1569     p = p->next;
1570   }
1571   if(copy_needed) {
1572     /* copy the whole packet into new pbufs */
1573     p = pbuf_alloc(PBUF_LINK, q->tot_len, PBUF_RAM);
1574     while ((p == NULL) && (neighbor_cache[neighbor_index].q != NULL)) {
1575       /* Free oldest packet (as per RFC recommendation) */
1576       r = neighbor_cache[neighbor_index].q;
1577       neighbor_cache[neighbor_index].q = r->next;
1578       r->next = NULL;
1579       nd6_free_q(r);
1580       p = pbuf_alloc(PBUF_LINK, q->tot_len, PBUF_RAM);
1581     }
1582     if(p != NULL) {
1583       if (pbuf_copy(p, q) != ERR_OK) {
1584         pbuf_free(p);
1585         p = NULL;
1586       }
1587     }
1588   } else {
1589     /* referencing the old pbuf is enough */
1590     p = q;
1591     pbuf_ref(p);
1592   }
1593   /* packet was copied/ref'd? */
1594   if (p != NULL) {
1595     /* queue packet ... */
1596     /* allocate a new nd6 queue entry */
1597     new_entry = (struct nd6_q_entry *)memp_malloc(MEMP_ND6_QUEUE);
1598     if ((new_entry == NULL) && (neighbor_cache[neighbor_index].q != NULL)) {
1599       /* Free oldest packet (as per RFC recommendation) */
1600       r = neighbor_cache[neighbor_index].q;
1601       neighbor_cache[neighbor_index].q = r->next;
1602       r->next = NULL;
1603       nd6_free_q(r);
1604       new_entry = (struct nd6_q_entry *)memp_malloc(MEMP_ND6_QUEUE);
1605     }
1606     if (new_entry != NULL) {
1607       new_entry->next = NULL;
1608       new_entry->p = p;
1609       if(neighbor_cache[neighbor_index].q != NULL) {
1610         /* queue was already existent, append the new entry to the end */
1611         r = neighbor_cache[neighbor_index].q;
1612         while (r->next != NULL) {
1613           r = r->next;
1614         }
1615         r->next = new_entry;
1616       } else {
1617         /* queue did not exist, first item in queue */
1618         neighbor_cache[neighbor_index].q = new_entry;
1619       }
1620       LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: queued packet %p on neighbor entry %"S16_F"\n", (void *)q, (s16_t)neighbor_index));
1621       result = ERR_OK;
1622     } else {
1623       /* the pool MEMP_ND6_QUEUE is empty */
1624       pbuf_free(p);
1625       LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: could not queue a copy of packet %p (out of memory)\n", (void *)q));
1626       /* { result == ERR_MEM } through initialization */
1627     }
1628   } else {
1629     LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: could not queue a copy of packet %p (out of memory)\n", (void *)q));
1630     /* { result == ERR_MEM } through initialization */
1631   }
1632
1633   return result;
1634 }
1635
1636 /**
1637  * Free a complete queue of nd6 q entries
1638  *
1639  * @param q a queue of nd6_q_entry to free
1640  */
1641 static void
1642 nd6_free_q(struct nd6_q_entry *q)
1643 {
1644   struct nd6_q_entry *r;
1645   LWIP_ASSERT("q != NULL", q != NULL);
1646   LWIP_ASSERT("q->p != NULL", q->p != NULL);
1647   while (q) {
1648     r = q;
1649     q = q->next;
1650     LWIP_ASSERT("r->p != NULL", (r->p != NULL));
1651     pbuf_free(r->p);
1652     memp_free(MEMP_ND6_QUEUE, r);
1653   }
1654 }
1655
1656 /**
1657  * Send queued packets for a neighbor
1658  *
1659  * @param i the neighbor to send packets to
1660  */
1661 static void
1662 nd6_send_q(s8_t i)
1663 {
1664   struct ip6_hdr *ip6hdr;
1665   struct nd6_q_entry *q;
1666
1667   if ((i < 0) || (i >= LWIP_ND6_NUM_NEIGHBORS)) {
1668     return;
1669   }
1670
1671   while (neighbor_cache[i].q != NULL) {
1672     /* remember first in queue */
1673     q = neighbor_cache[i].q;
1674     /* pop first item off the queue */
1675     neighbor_cache[i].q = q->next;
1676     /* Get ipv6 header. */
1677     ip6hdr = (struct ip6_hdr *)(q->p->payload);
1678     /* Override ip6_current_dest_addr() so that we have an aligned copy. */
1679     ip6_addr_set(ip6_current_dest_addr(), &(ip6hdr->dest));
1680     /* send the queued IPv6 packet */
1681     (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, q->p, ip6_current_dest_addr());
1682     /* free the queued IP packet */
1683     pbuf_free(q->p);
1684     /* now queue entry can be freed */
1685     memp_free(MEMP_ND6_QUEUE, q);
1686   }
1687 }
1688
1689 #endif /* LWIP_ND6_QUEUEING */
1690
1691 /**
1692  * Get the Path MTU for a destination.
1693  *
1694  * @param ip6addr the destination address
1695  * @param netif the netif on which the packet will be sent
1696  * @return the Path MTU, if known, or the netif default MTU
1697  */
1698 u16_t
1699 nd6_get_destination_mtu(ip6_addr_t * ip6addr, struct netif * netif)
1700 {
1701   s8_t i;
1702
1703   i = nd6_find_destination_cache_entry(ip6addr);
1704   if (i >= 0) {
1705     if (destination_cache[i].pmtu > 0) {
1706       return destination_cache[i].pmtu;
1707     }
1708   }
1709
1710   if (netif != NULL) {
1711     return netif->mtu;
1712   }
1713
1714   return 1280; /* Minimum MTU */
1715 }
1716
1717
1718 #if LWIP_ND6_TCP_REACHABILITY_HINTS
1719 /**
1720  * Provide the Neighbor discovery process with a hint that a
1721  * destination is reachable. Called by tcp_receive when ACKs are
1722  * received or sent (as per RFC). This is useful to avoid sending
1723  * NS messages every 30 seconds.
1724  *
1725  * @param ip6addr the destination address which is know to be reachable
1726  *                by an upper layer protocol (TCP)
1727  */
1728 void
1729 nd6_reachability_hint(ip6_addr_t * ip6addr)
1730 {
1731   s8_t i;
1732
1733   /* Find destination in cache. */
1734   if (ip6_addr_cmp(ip6addr, &(destination_cache[nd6_cached_destination_index].destination_addr))) {
1735     i = nd6_cached_destination_index;
1736     ND6_STATS_INC(nd6.cachehit);
1737   }
1738   else {
1739     i = nd6_find_destination_cache_entry(ip6addr);
1740   }
1741   if (i < 0) {
1742     return;
1743   }
1744
1745   /* Find next hop neighbor in cache. */
1746   if (ip6_addr_cmp(&(destination_cache[i].next_hop_addr), &(neighbor_cache[nd6_cached_neighbor_index].next_hop_address))) {
1747     i = nd6_cached_neighbor_index;
1748     ND6_STATS_INC(nd6.cachehit);
1749   }
1750   else {
1751     i = nd6_find_neighbor_cache_entry(&(destination_cache[i].next_hop_addr));
1752   }
1753   if (i < 0) {
1754     return;
1755   }
1756
1757   /* Set reachability state. */
1758   neighbor_cache[i].state = ND6_REACHABLE;
1759   neighbor_cache[i].counter.reachable_time = reachable_time;
1760 }
1761 #endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */
1762
1763 #endif /* LWIP_IPV6 */