• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/priv/nd6_priv.h"
50 #include "lwip/prot/nd6.h"
51 #include "lwip/prot/icmp6.h"
52 #include "lwip/pbuf.h"
53 #include "lwip/mem.h"
54 #include "lwip/memp.h"
55 #include "lwip/ip6.h"
56 #include "lwip/ip6_addr.h"
57 #include "lwip/inet_chksum.h"
58 #include "lwip/netif.h"
59 #include "lwip/icmp6.h"
60 #include "lwip/mld6.h"
61 #include "lwip/dhcp6.h"
62 #include "lwip/ip.h"
63 #include "lwip/stats.h"
64 #include "lwip/dns.h"
65 
66 #include <string.h>
67 
68 #ifdef LWIP_HOOK_FILENAME
69 #include LWIP_HOOK_FILENAME
70 #endif
71 
72 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS > IP6_ADDR_TENTATIVE_COUNT_MASK
73 #error LWIP_IPV6_DUP_DETECT_ATTEMPTS > IP6_ADDR_TENTATIVE_COUNT_MASK
74 #endif
75 
76 /* Router tables. */
77 struct nd6_neighbor_cache_entry neighbor_cache[LWIP_ND6_NUM_NEIGHBORS];
78 struct nd6_destination_cache_entry destination_cache[LWIP_ND6_NUM_DESTINATIONS];
79 struct nd6_prefix_list_entry prefix_list[LWIP_ND6_NUM_PREFIXES];
80 struct nd6_router_list_entry default_router_list[LWIP_ND6_NUM_ROUTERS];
81 
82 /* Default values, can be updated by a RA message. */
83 u32_t reachable_time = LWIP_ND6_REACHABLE_TIME;
84 u32_t retrans_timer = LWIP_ND6_RETRANS_TIMER; /* @todo implement this value in timer */
85 
86 /* Index for cache entries. */
87 static u8_t nd6_cached_neighbor_index;
88 static netif_addr_idx_t nd6_cached_destination_index;
89 
90 /* Multicast address holder. */
91 static ip6_addr_t multicast_address;
92 
93 static u8_t nd6_tmr_rs_reduction;
94 
95 /* Static buffer to parse RA packet options */
96 union ra_options {
97   struct lladdr_option  lladdr;
98   struct mtu_option     mtu;
99   struct prefix_option  prefix;
100 #if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
101   struct rdnss_option   rdnss;
102 #endif
103 };
104 static union ra_options nd6_ra_buffer;
105 
106 /* Forward declarations. */
107 static s8_t nd6_find_neighbor_cache_entry(const ip6_addr_t *ip6addr);
108 static s8_t nd6_new_neighbor_cache_entry(void);
109 static void nd6_free_neighbor_cache_entry(s8_t i);
110 static s16_t nd6_find_destination_cache_entry(const ip6_addr_t *ip6addr);
111 static s16_t nd6_new_destination_cache_entry(void);
112 static int nd6_is_prefix_in_netif(const ip6_addr_t *ip6addr, struct netif *netif);
113 static s8_t nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif);
114 static s8_t nd6_get_router(const ip6_addr_t *router_addr, struct netif *netif);
115 static s8_t nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif);
116 static s8_t nd6_get_onlink_prefix(const ip6_addr_t *prefix, struct netif *netif);
117 static s8_t nd6_new_onlink_prefix(const ip6_addr_t *prefix, struct netif *netif);
118 static s8_t nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif);
119 static err_t nd6_queue_packet(s8_t neighbor_index, struct pbuf *q);
120 
121 #define ND6_SEND_FLAG_MULTICAST_DEST 0x01
122 #define ND6_SEND_FLAG_ALLNODES_DEST 0x02
123 #define ND6_SEND_FLAG_ANY_SRC 0x04
124 static void nd6_send_ns(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags);
125 static void nd6_send_na(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags);
126 static void nd6_send_neighbor_cache_probe(struct nd6_neighbor_cache_entry *entry, u8_t flags);
127 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
128 static err_t nd6_send_rs(struct netif *netif);
129 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
130 
131 #if LWIP_ND6_QUEUEING
132 static void nd6_free_q(struct nd6_q_entry *q);
133 #else /* LWIP_ND6_QUEUEING */
134 #define nd6_free_q(q) pbuf_free(q)
135 #endif /* LWIP_ND6_QUEUEING */
136 static void nd6_send_q(s8_t i);
137 
138 
139 /**
140  * A local address has been determined to be a duplicate. Take the appropriate
141  * action(s) on the address and the interface as a whole.
142  *
143  * @param netif the netif that owns the address
144  * @param addr_idx the index of the address detected to be a duplicate
145  */
146 static void
nd6_duplicate_addr_detected(struct netif * netif,s8_t addr_idx)147 nd6_duplicate_addr_detected(struct netif *netif, s8_t addr_idx)
148 {
149 
150   /* Mark the address as duplicate, but leave its lifetimes alone. If this was
151    * a manually assigned address, it will remain in existence as duplicate, and
152    * as such be unusable for any practical purposes until manual intervention.
153    * If this was an autogenerated address, the address will follow normal
154    * expiration rules, and thus disappear once its valid lifetime expires. */
155   netif_ip6_addr_set_state(netif, addr_idx, IP6_ADDR_DUPLICATED);
156 
157 #if LWIP_IPV6_AUTOCONFIG
158   /* If the affected address was the link-local address that we use to generate
159    * all other addresses, then we should not continue to use those derived
160    * addresses either, so mark them as duplicate as well. For autoconfig-only
161    * setups, this will make the interface effectively unusable, approaching the
162    * intention of RFC 4862 Sec. 5.4.5. @todo implement the full requirements */
163   if (addr_idx == 0) {
164     s8_t i;
165     for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
166       if (!ip6_addr_isinvalid(netif_ip6_addr_state(netif, i)) &&
167           !netif_ip6_addr_isstatic(netif, i)) {
168         netif_ip6_addr_set_state(netif, i, IP6_ADDR_DUPLICATED);
169       }
170     }
171   }
172 #endif /* LWIP_IPV6_AUTOCONFIG */
173 }
174 
175 #if LWIP_IPV6_AUTOCONFIG
176 /**
177  * We received a router advertisement that contains a prefix with the
178  * autoconfiguration flag set. Add or update an associated autogenerated
179  * address.
180  *
181  * @param netif the netif on which the router advertisement arrived
182  * @param prefix_opt a pointer to the prefix option data
183  * @param prefix_addr an aligned copy of the prefix address
184  */
185 static void
nd6_process_autoconfig_prefix(struct netif * netif,struct prefix_option * prefix_opt,const ip6_addr_t * prefix_addr)186 nd6_process_autoconfig_prefix(struct netif *netif,
187   struct prefix_option *prefix_opt, const ip6_addr_t *prefix_addr)
188 {
189   ip6_addr_t ip6addr;
190   u32_t valid_life, pref_life;
191   u8_t addr_state;
192   s8_t i, free_idx;
193 
194   /* The caller already checks RFC 4862 Sec. 5.5.3 points (a) and (b). We do
195    * the rest, starting with checks for (c) and (d) here. */
196   valid_life = lwip_htonl(prefix_opt->valid_lifetime);
197   pref_life = lwip_htonl(prefix_opt->preferred_lifetime);
198   if (pref_life > valid_life || prefix_opt->prefix_length != 64) {
199     return; /* silently ignore this prefix for autoconfiguration purposes */
200   }
201 
202   /* If an autogenerated address already exists for this prefix, update its
203    * lifetimes. An address is considered autogenerated if 1) it is not static
204    * (i.e., manually assigned), and 2) there is an advertised autoconfiguration
205    * prefix for it (the one we are processing here). This does not necessarily
206    * exclude the possibility that the address was actually assigned by, say,
207    * DHCPv6. If that distinction becomes important in the future, more state
208    * must be kept. As explained elsewhere we also update lifetimes of tentative
209    * and duplicate addresses. Skip address slot 0 (the link-local address). */
210   for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
211     addr_state = netif_ip6_addr_state(netif, i);
212     if (!ip6_addr_isinvalid(addr_state) && !netif_ip6_addr_isstatic(netif, i) &&
213         ip6_addr_netcmp(prefix_addr, netif_ip6_addr(netif, i))) {
214       /* Update the valid lifetime, as per RFC 4862 Sec. 5.5.3 point (e).
215        * The valid lifetime will never drop to zero as a result of this. */
216       u32_t remaining_life = netif_ip6_addr_valid_life(netif, i);
217       if (valid_life > ND6_2HRS || valid_life > remaining_life) {
218         netif_ip6_addr_set_valid_life(netif, i, valid_life);
219       } else if (remaining_life > ND6_2HRS) {
220         netif_ip6_addr_set_valid_life(netif, i, ND6_2HRS);
221       }
222       LWIP_ASSERT("bad valid lifetime", !netif_ip6_addr_isstatic(netif, i));
223       /* Update the preferred lifetime. No bounds checks are needed here. In
224        * rare cases the advertisement may un-deprecate the address, though.
225        * Deprecation is left to the timer code where it is handled anyway. */
226       if (pref_life > 0 && addr_state == IP6_ADDR_DEPRECATED) {
227         netif_ip6_addr_set_state(netif, i, IP6_ADDR_PREFERRED);
228       }
229       netif_ip6_addr_set_pref_life(netif, i, pref_life);
230       return; /* there should be at most one matching address */
231     }
232   }
233 
234   /* No autogenerated address exists for this prefix yet. See if we can add a
235    * new one. However, if IPv6 autoconfiguration is administratively disabled,
236    * do not generate new addresses, but do keep updating lifetimes for existing
237    * addresses. Also, when adding new addresses, we must protect explicitly
238    * against a valid lifetime of zero, because again, we use that as a special
239    * value. The generated address would otherwise expire immediately anyway.
240    * Finally, the original link-local address must be usable at all. We start
241    * creating addresses even if the link-local address is still in tentative
242    * state though, and deal with the fallout of that upon DAD collision. */
243   addr_state = netif_ip6_addr_state(netif, 0);
244   if (!netif->ip6_autoconfig_enabled || valid_life == IP6_ADDR_LIFE_STATIC ||
245       ip6_addr_isinvalid(addr_state) || ip6_addr_isduplicated(addr_state)) {
246     return;
247   }
248 
249   /* Construct the new address that we intend to use, and then see if that
250    * address really does not exist. It might have been added manually, after
251    * all. As a side effect, find a free slot. Note that we cannot use
252    * netif_add_ip6_address() here, as it would return ERR_OK if the address
253    * already did exist, resulting in that address being given lifetimes. */
254   IP6_ADDR(&ip6addr, prefix_addr->addr[0], prefix_addr->addr[1],
255     netif_ip6_addr(netif, 0)->addr[2], netif_ip6_addr(netif, 0)->addr[3]);
256   ip6_addr_assign_zone(&ip6addr, IP6_UNICAST, netif);
257 
258   free_idx = 0;
259   for (i = 1; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
260     if (!ip6_addr_isinvalid(netif_ip6_addr_state(netif, i))) {
261       if (ip6_addr_cmp(&ip6addr, netif_ip6_addr(netif, i))) {
262         return; /* formed address already exists */
263       }
264     } else if (free_idx == 0) {
265       free_idx = i;
266     }
267   }
268   if (free_idx == 0) {
269     return; /* no address slots available, try again on next advertisement */
270   }
271 
272   /* Assign the new address to the interface. */
273   ip_addr_copy_from_ip6(netif->ip6_addr[free_idx], ip6addr);
274   netif_ip6_addr_set_valid_life(netif, free_idx, valid_life);
275   netif_ip6_addr_set_pref_life(netif, free_idx, pref_life);
276   netif_ip6_addr_set_state(netif, free_idx, IP6_ADDR_TENTATIVE);
277 }
278 #endif /* LWIP_IPV6_AUTOCONFIG */
279 
280 /**
281  * Process an incoming neighbor discovery message
282  *
283  * @param p the nd packet, p->payload pointing to the icmpv6 header
284  * @param inp the netif on which this packet was received
285  */
286 void
nd6_input(struct pbuf * p,struct netif * inp)287 nd6_input(struct pbuf *p, struct netif *inp)
288 {
289   u8_t msg_type;
290   s8_t i;
291   s16_t dest_idx;
292 
293   ND6_STATS_INC(nd6.recv);
294 
295   msg_type = *((u8_t *)p->payload);
296   switch (msg_type) {
297   case ICMP6_TYPE_NA: /* Neighbor Advertisement. */
298   {
299     struct na_header *na_hdr;
300     struct lladdr_option *lladdr_opt;
301     ip6_addr_t target_address;
302 
303     /* Check that na header fits in packet. */
304     if (p->len < (sizeof(struct na_header))) {
305       /* @todo debug message */
306       pbuf_free(p);
307       ND6_STATS_INC(nd6.lenerr);
308       ND6_STATS_INC(nd6.drop);
309       return;
310     }
311 
312     na_hdr = (struct na_header *)p->payload;
313 
314     /* Create an aligned, zoned copy of the target address. */
315     ip6_addr_copy_from_packed(target_address, na_hdr->target_address);
316     ip6_addr_assign_zone(&target_address, IP6_UNICAST, inp);
317 
318     /* Check a subset of the other RFC 4861 Sec. 7.1.2 requirements. */
319     if (IP6H_HOPLIM(ip6_current_header()) != ND6_HOPLIM || na_hdr->code != 0 ||
320         ip6_addr_ismulticast(&target_address)) {
321       pbuf_free(p);
322       ND6_STATS_INC(nd6.proterr);
323       ND6_STATS_INC(nd6.drop);
324       return;
325     }
326 
327     /* @todo RFC MUST: if IP destination is multicast, Solicited flag is zero */
328     /* @todo RFC MUST: all included options have a length greater than zero */
329 
330     /* Unsolicited NA?*/
331     if (ip6_addr_ismulticast(ip6_current_dest_addr())) {
332       /* This is an unsolicited NA.
333        * link-layer changed?
334        * part of DAD mechanism? */
335 
336 #if LWIP_IPV6_DUP_DETECT_ATTEMPTS
337       /* If the target address matches this netif, it is a DAD response. */
338       for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
339         if (!ip6_addr_isinvalid(netif_ip6_addr_state(inp, i)) &&
340             !ip6_addr_isduplicated(netif_ip6_addr_state(inp, i)) &&
341             ip6_addr_cmp(&target_address, netif_ip6_addr(inp, i))) {
342           /* We are using a duplicate address. */
343           nd6_duplicate_addr_detected(inp, i);
344 
345           pbuf_free(p);
346           return;
347         }
348       }
349 #endif /* LWIP_IPV6_DUP_DETECT_ATTEMPTS */
350 
351       /* Check that link-layer address option also fits in packet. */
352       if (p->len < (sizeof(struct na_header) + 2)) {
353         /* @todo debug message */
354         pbuf_free(p);
355         ND6_STATS_INC(nd6.lenerr);
356         ND6_STATS_INC(nd6.drop);
357         return;
358       }
359 
360       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
361 
362       if (p->len < (sizeof(struct na_header) + (lladdr_opt->length << 3))) {
363         /* @todo debug message */
364         pbuf_free(p);
365         ND6_STATS_INC(nd6.lenerr);
366         ND6_STATS_INC(nd6.drop);
367         return;
368       }
369 
370       /* This is an unsolicited NA, most likely there was a LLADDR change. */
371       i = nd6_find_neighbor_cache_entry(&target_address);
372       if (i >= 0) {
373         if (na_hdr->flags & ND6_FLAG_OVERRIDE) {
374           MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
375         }
376       }
377     } else {
378       /* This is a solicited NA.
379        * neighbor address resolution response?
380        * neighbor unreachability detection response? */
381 
382       /* Find the cache entry corresponding to this na. */
383       i = nd6_find_neighbor_cache_entry(&target_address);
384       if (i < 0) {
385         /* We no longer care about this target address. drop it. */
386         pbuf_free(p);
387         return;
388       }
389 
390       /* Update cache entry. */
391       if ((na_hdr->flags & ND6_FLAG_OVERRIDE) ||
392           (neighbor_cache[i].state == ND6_INCOMPLETE)) {
393         /* Check that link-layer address option also fits in packet. */
394         if (p->len < (sizeof(struct na_header) + 2)) {
395           /* @todo debug message */
396           pbuf_free(p);
397           ND6_STATS_INC(nd6.lenerr);
398           ND6_STATS_INC(nd6.drop);
399           return;
400         }
401 
402         lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
403 
404         if (p->len < (sizeof(struct na_header) + (lladdr_opt->length << 3))) {
405           /* @todo debug message */
406           pbuf_free(p);
407           ND6_STATS_INC(nd6.lenerr);
408           ND6_STATS_INC(nd6.drop);
409           return;
410         }
411 
412         MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
413       }
414 
415       neighbor_cache[i].netif = inp;
416       neighbor_cache[i].state = ND6_REACHABLE;
417       neighbor_cache[i].counter.reachable_time = reachable_time;
418 
419       /* Send queued packets, if any. */
420       if (neighbor_cache[i].q != NULL) {
421         nd6_send_q(i);
422       }
423     }
424 
425     break; /* ICMP6_TYPE_NA */
426   }
427   case ICMP6_TYPE_NS: /* Neighbor solicitation. */
428   {
429     struct ns_header *ns_hdr;
430     struct lladdr_option *lladdr_opt;
431     ip6_addr_t target_address;
432     u8_t accepted;
433 
434     /* Check that ns header fits in packet. */
435     if (p->len < sizeof(struct ns_header)) {
436       /* @todo debug message */
437       pbuf_free(p);
438       ND6_STATS_INC(nd6.lenerr);
439       ND6_STATS_INC(nd6.drop);
440       return;
441     }
442 
443     ns_hdr = (struct ns_header *)p->payload;
444 
445     /* Create an aligned, zoned copy of the target address. */
446     ip6_addr_copy_from_packed(target_address, ns_hdr->target_address);
447     ip6_addr_assign_zone(&target_address, IP6_UNICAST, inp);
448 
449     /* Check a subset of the other RFC 4861 Sec. 7.1.1 requirements. */
450     if (IP6H_HOPLIM(ip6_current_header()) != ND6_HOPLIM || ns_hdr->code != 0 ||
451        ip6_addr_ismulticast(&target_address)) {
452       pbuf_free(p);
453       ND6_STATS_INC(nd6.proterr);
454       ND6_STATS_INC(nd6.drop);
455       return;
456     }
457 
458     /* @todo RFC MUST: all included options have a length greater than zero */
459     /* @todo RFC MUST: if IP source is 'any', destination is solicited-node multicast address */
460     /* @todo RFC MUST: if IP source is 'any', there is no source LL address option */
461 
462     /* Check if there is a link-layer address provided. Only point to it if in this buffer. */
463     if (p->len >= (sizeof(struct ns_header) + 2)) {
464       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct ns_header));
465       if (p->len < (sizeof(struct ns_header) + (lladdr_opt->length << 3))) {
466         lladdr_opt = NULL;
467       }
468     } else {
469       lladdr_opt = NULL;
470     }
471 
472     /* Check if the target address is configured on the receiving netif. */
473     accepted = 0;
474     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
475       if ((ip6_addr_isvalid(netif_ip6_addr_state(inp, i)) ||
476            (ip6_addr_istentative(netif_ip6_addr_state(inp, i)) &&
477             ip6_addr_isany(ip6_current_src_addr()))) &&
478           ip6_addr_cmp(&target_address, netif_ip6_addr(inp, i))) {
479         accepted = 1;
480         break;
481       }
482     }
483 
484     /* NS not for us? */
485     if (!accepted) {
486       pbuf_free(p);
487       return;
488     }
489 
490     /* Check for ANY address in src (DAD algorithm). */
491     if (ip6_addr_isany(ip6_current_src_addr())) {
492       /* Sender is validating this address. */
493       for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
494         if (!ip6_addr_isinvalid(netif_ip6_addr_state(inp, i)) &&
495             ip6_addr_cmp(&target_address, netif_ip6_addr(inp, i))) {
496           /* Send a NA back so that the sender does not use this address. */
497           nd6_send_na(inp, netif_ip6_addr(inp, i), ND6_FLAG_OVERRIDE | ND6_SEND_FLAG_ALLNODES_DEST);
498           if (ip6_addr_istentative(netif_ip6_addr_state(inp, i))) {
499             /* We shouldn't use this address either. */
500             nd6_duplicate_addr_detected(inp, i);
501           }
502         }
503       }
504     } else {
505       /* Sender is trying to resolve our address. */
506       /* Verify that they included their own link-layer address. */
507       if (lladdr_opt == NULL) {
508         /* Not a valid message. */
509         pbuf_free(p);
510         ND6_STATS_INC(nd6.proterr);
511         ND6_STATS_INC(nd6.drop);
512         return;
513       }
514 
515       i = nd6_find_neighbor_cache_entry(ip6_current_src_addr());
516       if (i>= 0) {
517         /* We already have a record for the solicitor. */
518         if (neighbor_cache[i].state == ND6_INCOMPLETE) {
519           neighbor_cache[i].netif = inp;
520           MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
521 
522           /* Delay probe in case we get confirmation of reachability from upper layer (TCP). */
523           neighbor_cache[i].state = ND6_DELAY;
524           neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
525         }
526       } else {
527         /* Add their IPv6 address and link-layer address to neighbor cache.
528          * We will need it at least to send a unicast NA message, but most
529          * likely we will also be communicating with this node soon. */
530         i = nd6_new_neighbor_cache_entry();
531         if (i < 0) {
532           /* We couldn't assign a cache entry for this neighbor.
533            * we won't be able to reply. drop it. */
534           pbuf_free(p);
535           ND6_STATS_INC(nd6.memerr);
536           return;
537         }
538         neighbor_cache[i].netif = inp;
539         MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
540         ip6_addr_set(&(neighbor_cache[i].next_hop_address), ip6_current_src_addr());
541 
542         /* Receiving a message does not prove reachability: only in one direction.
543          * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
544         neighbor_cache[i].state = ND6_DELAY;
545         neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
546       }
547 
548       /* Send back a NA for us. Allocate the reply pbuf. */
549       nd6_send_na(inp, &target_address, ND6_FLAG_SOLICITED | ND6_FLAG_OVERRIDE);
550     }
551 
552     break; /* ICMP6_TYPE_NS */
553   }
554   case ICMP6_TYPE_RA: /* Router Advertisement. */
555   {
556     struct ra_header *ra_hdr;
557     u8_t *buffer; /* Used to copy options. */
558     u16_t offset;
559 #if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
560     /* There can be multiple RDNSS options per RA */
561     u8_t rdnss_server_idx = 0;
562 #endif /* LWIP_ND6_RDNSS_MAX_DNS_SERVERS */
563 
564     /* Check that RA header fits in packet. */
565     if (p->len < sizeof(struct ra_header)) {
566       /* @todo debug message */
567       pbuf_free(p);
568       ND6_STATS_INC(nd6.lenerr);
569       ND6_STATS_INC(nd6.drop);
570       return;
571     }
572 
573     ra_hdr = (struct ra_header *)p->payload;
574 
575     /* Check a subset of the other RFC 4861 Sec. 6.1.2 requirements. */
576     if (!ip6_addr_islinklocal(ip6_current_src_addr()) ||
577         IP6H_HOPLIM(ip6_current_header()) != ND6_HOPLIM || ra_hdr->code != 0) {
578       pbuf_free(p);
579       ND6_STATS_INC(nd6.proterr);
580       ND6_STATS_INC(nd6.drop);
581       return;
582     }
583 
584     /* @todo RFC MUST: all included options have a length greater than zero */
585 
586     /* If we are sending RS messages, stop. */
587 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
588     /* ensure at least one solicitation is sent (see RFC 4861, ch. 6.3.7) */
589     if ((inp->rs_count < LWIP_ND6_MAX_MULTICAST_SOLICIT) ||
590         (nd6_send_rs(inp) == ERR_OK)) {
591       inp->rs_count = 0;
592     } else {
593       inp->rs_count = 1;
594     }
595 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
596 
597     /* Get the matching default router entry. */
598     i = nd6_get_router(ip6_current_src_addr(), inp);
599     if (i < 0) {
600       /* Create a new router entry. */
601       i = nd6_new_router(ip6_current_src_addr(), inp);
602     }
603 
604     if (i < 0) {
605       /* Could not create a new router entry. */
606       pbuf_free(p);
607       ND6_STATS_INC(nd6.memerr);
608       return;
609     }
610 
611     /* Re-set invalidation timer. */
612     default_router_list[i].invalidation_timer = lwip_htons(ra_hdr->router_lifetime);
613 
614     /* Re-set default timer values. */
615 #if LWIP_ND6_ALLOW_RA_UPDATES
616     if (ra_hdr->retrans_timer > 0) {
617       retrans_timer = lwip_htonl(ra_hdr->retrans_timer);
618     }
619     if (ra_hdr->reachable_time > 0) {
620       reachable_time = lwip_htonl(ra_hdr->reachable_time);
621     }
622 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
623 
624     /* @todo set default hop limit... */
625     /* ra_hdr->current_hop_limit;*/
626 
627     /* Update flags in local entry (incl. preference). */
628     default_router_list[i].flags = ra_hdr->flags;
629 
630 #if LWIP_IPV6_DHCP6
631     /* Trigger DHCPv6 if enabled */
632     dhcp6_nd6_ra_trigger(inp, ra_hdr->flags & ND6_RA_FLAG_MANAGED_ADDR_CONFIG,
633       ra_hdr->flags & ND6_RA_FLAG_OTHER_CONFIG);
634 #endif
635 
636     /* Offset to options. */
637     offset = sizeof(struct ra_header);
638 
639     /* Process each option. */
640     while ((p->tot_len - offset) >= 2) {
641       u8_t option_type;
642       u16_t option_len;
643       int option_len8 = pbuf_try_get_at(p, offset + 1);
644       if (option_len8 <= 0) {
645         /* read beyond end or zero length */
646         goto lenerr_drop_free_return;
647       }
648       option_len = ((u8_t)option_len8) << 3;
649       if (option_len > p->tot_len - offset) {
650         /* short packet (option does not fit in) */
651         goto lenerr_drop_free_return;
652       }
653       if (p->len == p->tot_len) {
654         /* no need to copy from contiguous pbuf */
655         buffer = &((u8_t*)p->payload)[offset];
656       } else {
657         /* check if this option fits into our buffer */
658         if (option_len > sizeof(nd6_ra_buffer)) {
659           option_type = pbuf_get_at(p, offset);
660           /* invalid option length */
661           if (option_type != ND6_OPTION_TYPE_RDNSS) {
662             goto lenerr_drop_free_return;
663           }
664           /* we allow RDNSS option to be longer - we'll just drop some servers */
665           option_len = sizeof(nd6_ra_buffer);
666         }
667         buffer = (u8_t*)&nd6_ra_buffer;
668         option_len = pbuf_copy_partial(p, &nd6_ra_buffer, option_len, offset);
669       }
670       option_type = buffer[0];
671       switch (option_type) {
672       case ND6_OPTION_TYPE_SOURCE_LLADDR:
673       {
674         struct lladdr_option *lladdr_opt;
675         if (option_len < sizeof(struct lladdr_option)) {
676           goto lenerr_drop_free_return;
677         }
678         lladdr_opt = (struct lladdr_option *)buffer;
679         if ((default_router_list[i].neighbor_entry != NULL) &&
680             (default_router_list[i].neighbor_entry->state == ND6_INCOMPLETE)) {
681           SMEMCPY(default_router_list[i].neighbor_entry->lladdr, lladdr_opt->addr, inp->hwaddr_len);
682           default_router_list[i].neighbor_entry->state = ND6_REACHABLE;
683           default_router_list[i].neighbor_entry->counter.reachable_time = reachable_time;
684         }
685         break;
686       }
687       case ND6_OPTION_TYPE_MTU:
688       {
689         struct mtu_option *mtu_opt;
690         u32_t mtu32;
691         if (option_len < sizeof(struct mtu_option)) {
692           goto lenerr_drop_free_return;
693         }
694         mtu_opt = (struct mtu_option *)buffer;
695         mtu32 = lwip_htonl(mtu_opt->mtu);
696         if ((mtu32 >= IP6_MIN_MTU_LENGTH) && (mtu32 <= 0xffff)) {
697 #if LWIP_ND6_ALLOW_RA_UPDATES
698           if (inp->mtu) {
699             /* don't set the mtu for IPv6 higher than the netif driver supports */
700             inp->mtu6 = LWIP_MIN(LWIP_MIN(inp->mtu, inp->mtu6), (u16_t)mtu32);
701           } else {
702             inp->mtu6 = (u16_t)mtu32;
703           }
704 #endif /* LWIP_ND6_ALLOW_RA_UPDATES */
705         }
706         break;
707       }
708       case ND6_OPTION_TYPE_PREFIX_INFO:
709       {
710         struct prefix_option *prefix_opt;
711         ip6_addr_t prefix_addr;
712         if (option_len < sizeof(struct prefix_option)) {
713           goto lenerr_drop_free_return;
714         }
715 
716         prefix_opt = (struct prefix_option *)buffer;
717 
718         /* Get a memory-aligned copy of the prefix. */
719         ip6_addr_copy_from_packed(prefix_addr, prefix_opt->prefix);
720         ip6_addr_assign_zone(&prefix_addr, IP6_UNICAST, inp);
721 
722         if (!ip6_addr_islinklocal(&prefix_addr)) {
723           if ((prefix_opt->flags & ND6_PREFIX_FLAG_ON_LINK) &&
724               (prefix_opt->prefix_length == 64)) {
725             /* Add to on-link prefix list. */
726             u32_t valid_life;
727             s8_t prefix;
728 
729             valid_life = lwip_htonl(prefix_opt->valid_lifetime);
730 
731             /* find cache entry for this prefix. */
732             prefix = nd6_get_onlink_prefix(&prefix_addr, inp);
733             if (prefix < 0 && valid_life > 0) {
734               /* Create a new cache entry. */
735               prefix = nd6_new_onlink_prefix(&prefix_addr, inp);
736             }
737             if (prefix >= 0) {
738               prefix_list[prefix].invalidation_timer = valid_life;
739             }
740           }
741 #if LWIP_IPV6_AUTOCONFIG
742           if (prefix_opt->flags & ND6_PREFIX_FLAG_AUTONOMOUS) {
743             /* Perform processing for autoconfiguration. */
744             nd6_process_autoconfig_prefix(inp, prefix_opt, &prefix_addr);
745           }
746 #endif /* LWIP_IPV6_AUTOCONFIG */
747         }
748 
749         break;
750       }
751       case ND6_OPTION_TYPE_ROUTE_INFO:
752         /* @todo implement preferred routes.
753         struct route_option * route_opt;
754         route_opt = (struct route_option *)buffer;*/
755 
756         break;
757 #if LWIP_ND6_RDNSS_MAX_DNS_SERVERS
758       case ND6_OPTION_TYPE_RDNSS:
759       {
760         u8_t num, n;
761         u16_t copy_offset = offset + SIZEOF_RDNSS_OPTION_BASE;
762         struct rdnss_option * rdnss_opt;
763         if (option_len < SIZEOF_RDNSS_OPTION_BASE) {
764           goto lenerr_drop_free_return;
765         }
766 
767         rdnss_opt = (struct rdnss_option *)buffer;
768         num = (rdnss_opt->length - 1) / 2;
769         for (n = 0; (rdnss_server_idx < DNS_MAX_SERVERS) && (n < num); n++, copy_offset += sizeof(ip6_addr_p_t)) {
770           ip_addr_t rdnss_address;
771 
772           /* Copy directly from pbuf to get an aligned, zoned copy of the prefix. */
773           if (pbuf_copy_partial(p, &rdnss_address, sizeof(ip6_addr_p_t), copy_offset) == sizeof(ip6_addr_p_t)) {
774             IP_SET_TYPE_VAL(rdnss_address, IPADDR_TYPE_V6);
775             ip6_addr_assign_zone(ip_2_ip6(&rdnss_address), IP6_UNKNOWN, inp);
776 
777             if (htonl(rdnss_opt->lifetime) > 0) {
778               /* TODO implement Lifetime > 0 */
779               dns_setserver(rdnss_server_idx++, &rdnss_address);
780             } else {
781               /* TODO implement DNS removal in dns.c */
782               u8_t s;
783               for (s = 0; s < DNS_MAX_SERVERS; s++) {
784                 const ip_addr_t *addr = dns_getserver(s);
785                 if(ip_addr_cmp(addr, &rdnss_address)) {
786                   dns_setserver(s, NULL);
787                 }
788               }
789             }
790           }
791         }
792         break;
793       }
794 #endif /* LWIP_ND6_RDNSS_MAX_DNS_SERVERS */
795       default:
796         /* Unrecognized option, abort. */
797         ND6_STATS_INC(nd6.proterr);
798         break;
799       }
800       /* option length is checked earlier to be non-zero to make sure loop ends */
801       offset += 8 * (u8_t)option_len8;
802     }
803 
804     break; /* ICMP6_TYPE_RA */
805   }
806   case ICMP6_TYPE_RD: /* Redirect */
807   {
808     struct redirect_header *redir_hdr;
809     struct lladdr_option *lladdr_opt;
810     ip6_addr_t destination_address, target_address;
811 
812     /* Check that Redir header fits in packet. */
813     if (p->len < sizeof(struct redirect_header)) {
814       /* @todo debug message */
815       pbuf_free(p);
816       ND6_STATS_INC(nd6.lenerr);
817       ND6_STATS_INC(nd6.drop);
818       return;
819     }
820 
821     redir_hdr = (struct redirect_header *)p->payload;
822 
823     /* Create an aligned, zoned copy of the destination address. */
824     ip6_addr_copy_from_packed(destination_address, redir_hdr->destination_address);
825     ip6_addr_assign_zone(&destination_address, IP6_UNICAST, inp);
826 
827     /* Check a subset of the other RFC 4861 Sec. 8.1 requirements. */
828     if (!ip6_addr_islinklocal(ip6_current_src_addr()) ||
829         IP6H_HOPLIM(ip6_current_header()) != ND6_HOPLIM ||
830         redir_hdr->code != 0 || ip6_addr_ismulticast(&destination_address)) {
831       pbuf_free(p);
832       ND6_STATS_INC(nd6.proterr);
833       ND6_STATS_INC(nd6.drop);
834       return;
835     }
836 
837     /* @todo RFC MUST: IP source address equals first-hop router for destination_address */
838     /* @todo RFC MUST: ICMP target address is either link-local address or same as destination_address */
839     /* @todo RFC MUST: all included options have a length greater than zero */
840 
841     if (p->len >= (sizeof(struct redirect_header) + 2)) {
842       lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct redirect_header));
843       if (p->len < (sizeof(struct redirect_header) + (lladdr_opt->length << 3))) {
844         lladdr_opt = NULL;
845       }
846     } else {
847       lladdr_opt = NULL;
848     }
849 
850     /* Find dest address in cache */
851     dest_idx = nd6_find_destination_cache_entry(&destination_address);
852     if (dest_idx < 0) {
853       /* Destination not in cache, drop packet. */
854       pbuf_free(p);
855       return;
856     }
857 
858     /* Create an aligned, zoned copy of the target address. */
859     ip6_addr_copy_from_packed(target_address, redir_hdr->target_address);
860     ip6_addr_assign_zone(&target_address, IP6_UNICAST, inp);
861 
862     /* Set the new target address. */
863     ip6_addr_copy(destination_cache[dest_idx].next_hop_addr, target_address);
864 
865     /* If Link-layer address of other router is given, try to add to neighbor cache. */
866     if (lladdr_opt != NULL) {
867       if (lladdr_opt->type == ND6_OPTION_TYPE_TARGET_LLADDR) {
868         i = nd6_find_neighbor_cache_entry(&target_address);
869         if (i < 0) {
870           i = nd6_new_neighbor_cache_entry();
871           if (i >= 0) {
872             neighbor_cache[i].netif = inp;
873             MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
874             ip6_addr_copy(neighbor_cache[i].next_hop_address, target_address);
875 
876             /* Receiving a message does not prove reachability: only in one direction.
877              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
878             neighbor_cache[i].state = ND6_DELAY;
879             neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
880           }
881         }
882         if (i >= 0) {
883           if (neighbor_cache[i].state == ND6_INCOMPLETE) {
884             MEMCPY(neighbor_cache[i].lladdr, lladdr_opt->addr, inp->hwaddr_len);
885             /* Receiving a message does not prove reachability: only in one direction.
886              * Delay probe in case we get confirmation of reachability from upper layer (TCP). */
887             neighbor_cache[i].state = ND6_DELAY;
888             neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
889           }
890         }
891       }
892     }
893     break; /* ICMP6_TYPE_RD */
894   }
895   case ICMP6_TYPE_PTB: /* Packet too big */
896   {
897     struct icmp6_hdr *icmp6hdr; /* Packet too big message */
898     struct ip6_hdr *ip6hdr; /* IPv6 header of the packet which caused the error */
899     u32_t pmtu;
900     ip6_addr_t destination_address;
901 
902     /* Check that ICMPv6 header + IPv6 header fit in payload */
903     if (p->len < (sizeof(struct icmp6_hdr) + IP6_HLEN)) {
904       /* drop short packets */
905       pbuf_free(p);
906       ND6_STATS_INC(nd6.lenerr);
907       ND6_STATS_INC(nd6.drop);
908       return;
909     }
910 
911     icmp6hdr = (struct icmp6_hdr *)p->payload;
912     ip6hdr = (struct ip6_hdr *)((u8_t*)p->payload + sizeof(struct icmp6_hdr));
913 
914     /* Create an aligned, zoned copy of the destination address. */
915     ip6_addr_copy_from_packed(destination_address, ip6hdr->dest);
916     ip6_addr_assign_zone(&destination_address, IP6_UNKNOWN, inp);
917 
918     /* Look for entry in destination cache. */
919     dest_idx = nd6_find_destination_cache_entry(&destination_address);
920     if (dest_idx < 0) {
921       /* Destination not in cache, drop packet. */
922       pbuf_free(p);
923       return;
924     }
925 
926     /* Change the Path MTU. */
927     pmtu = lwip_htonl(icmp6hdr->data);
928     destination_cache[dest_idx].pmtu = (u16_t)LWIP_MIN(pmtu, 0xFFFF);
929 
930     break; /* ICMP6_TYPE_PTB */
931   }
932 
933   default:
934     ND6_STATS_INC(nd6.proterr);
935     ND6_STATS_INC(nd6.drop);
936     break; /* default */
937   }
938 
939   pbuf_free(p);
940   return;
941 lenerr_drop_free_return:
942   ND6_STATS_INC(nd6.lenerr);
943   ND6_STATS_INC(nd6.drop);
944   pbuf_free(p);
945 }
946 
947 
948 /**
949  * Periodic timer for Neighbor discovery functions:
950  *
951  * - Update neighbor reachability states
952  * - Update destination cache entries age
953  * - Update invalidation timers of default routers and on-link prefixes
954  * - Update lifetimes of our addresses
955  * - Perform duplicate address detection (DAD) for our addresses
956  * - Send router solicitations
957  */
958 void
nd6_tmr(void)959 nd6_tmr(void)
960 {
961   s8_t i;
962   struct netif *netif;
963 
964   /* Process neighbor entries. */
965   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
966     switch (neighbor_cache[i].state) {
967     case ND6_INCOMPLETE:
968       if ((neighbor_cache[i].counter.probes_sent >= LWIP_ND6_MAX_MULTICAST_SOLICIT) &&
969           (!neighbor_cache[i].isrouter)) {
970         /* Retries exceeded. */
971         nd6_free_neighbor_cache_entry(i);
972       } else {
973         /* Send a NS for this entry. */
974         neighbor_cache[i].counter.probes_sent++;
975         nd6_send_neighbor_cache_probe(&neighbor_cache[i], ND6_SEND_FLAG_MULTICAST_DEST);
976       }
977       break;
978     case ND6_REACHABLE:
979       /* Send queued packets, if any are left. Should have been sent already. */
980       if (neighbor_cache[i].q != NULL) {
981         nd6_send_q(i);
982       }
983       if (neighbor_cache[i].counter.reachable_time <= ND6_TMR_INTERVAL) {
984         /* Change to stale state. */
985         neighbor_cache[i].state = ND6_STALE;
986         neighbor_cache[i].counter.stale_time = 0;
987       } else {
988         neighbor_cache[i].counter.reachable_time -= ND6_TMR_INTERVAL;
989       }
990       break;
991     case ND6_STALE:
992       neighbor_cache[i].counter.stale_time++;
993       break;
994     case ND6_DELAY:
995       if (neighbor_cache[i].counter.delay_time <= 1) {
996         /* Change to PROBE state. */
997         neighbor_cache[i].state = ND6_PROBE;
998         neighbor_cache[i].counter.probes_sent = 0;
999       } else {
1000         neighbor_cache[i].counter.delay_time--;
1001       }
1002       break;
1003     case ND6_PROBE:
1004       if ((neighbor_cache[i].counter.probes_sent >= LWIP_ND6_MAX_MULTICAST_SOLICIT) &&
1005           (!neighbor_cache[i].isrouter)) {
1006         /* Retries exceeded. */
1007         nd6_free_neighbor_cache_entry(i);
1008       } else {
1009         /* Send a NS for this entry. */
1010         neighbor_cache[i].counter.probes_sent++;
1011         nd6_send_neighbor_cache_probe(&neighbor_cache[i], 0);
1012       }
1013       break;
1014     case ND6_NO_ENTRY:
1015     default:
1016       /* Do nothing. */
1017       break;
1018     }
1019   }
1020 
1021   /* Process destination entries. */
1022   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1023     destination_cache[i].age++;
1024   }
1025 
1026   /* Process router entries. */
1027   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1028     if (default_router_list[i].neighbor_entry != NULL) {
1029       /* Active entry. */
1030       if (default_router_list[i].invalidation_timer <= ND6_TMR_INTERVAL / 1000) {
1031         /* No more than 1 second remaining. Clear this entry. Also clear any of
1032          * its destination cache entries, as per RFC 4861 Sec. 5.3 and 6.3.5. */
1033         s8_t j;
1034         for (j = 0; j < LWIP_ND6_NUM_DESTINATIONS; j++) {
1035           if (ip6_addr_cmp(&destination_cache[j].next_hop_addr,
1036                &default_router_list[i].neighbor_entry->next_hop_address)) {
1037              ip6_addr_set_any(&destination_cache[j].destination_addr);
1038           }
1039         }
1040         default_router_list[i].neighbor_entry->isrouter = 0;
1041         default_router_list[i].neighbor_entry = NULL;
1042         default_router_list[i].invalidation_timer = 0;
1043         default_router_list[i].flags = 0;
1044       } else {
1045         default_router_list[i].invalidation_timer -= ND6_TMR_INTERVAL / 1000;
1046       }
1047     }
1048   }
1049 
1050   /* Process prefix entries. */
1051   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; i++) {
1052     if (prefix_list[i].netif != NULL) {
1053       if (prefix_list[i].invalidation_timer <= ND6_TMR_INTERVAL / 1000) {
1054         /* Entry timed out, remove it */
1055         prefix_list[i].invalidation_timer = 0;
1056         prefix_list[i].netif = NULL;
1057       } else {
1058         prefix_list[i].invalidation_timer -= ND6_TMR_INTERVAL / 1000;
1059       }
1060     }
1061   }
1062 
1063   /* Process our own addresses, updating address lifetimes and/or DAD state. */
1064   NETIF_FOREACH(netif) {
1065     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; ++i) {
1066       u8_t addr_state;
1067 #if LWIP_IPV6_ADDRESS_LIFETIMES
1068       /* Step 1: update address lifetimes (valid and preferred). */
1069       addr_state = netif_ip6_addr_state(netif, i);
1070       /* RFC 4862 is not entirely clear as to whether address lifetimes affect
1071        * tentative addresses, and is even less clear as to what should happen
1072        * with duplicate addresses. We choose to track and update lifetimes for
1073        * both those types, although for different reasons:
1074        * - for tentative addresses, the line of thought of Sec. 5.7 combined
1075        *   with the potentially long period that an address may be in tentative
1076        *   state (due to the interface being down) suggests that lifetimes
1077        *   should be independent of external factors which would include DAD;
1078        * - for duplicate addresses, retiring them early could result in a new
1079        *   but unwanted attempt at marking them as valid, while retiring them
1080        *   late/never could clog up address slots on the netif.
1081        * As a result, we may end up expiring addresses of either type here.
1082        */
1083       if (!ip6_addr_isinvalid(addr_state) &&
1084           !netif_ip6_addr_isstatic(netif, i)) {
1085         u32_t life = netif_ip6_addr_valid_life(netif, i);
1086         if (life <= ND6_TMR_INTERVAL / 1000) {
1087           /* The address has expired. */
1088           netif_ip6_addr_set_valid_life(netif, i, 0);
1089           netif_ip6_addr_set_pref_life(netif, i, 0);
1090           netif_ip6_addr_set_state(netif, i, IP6_ADDR_INVALID);
1091         } else {
1092           if (!ip6_addr_life_isinfinite(life)) {
1093             life -= ND6_TMR_INTERVAL / 1000;
1094             LWIP_ASSERT("bad valid lifetime", life != IP6_ADDR_LIFE_STATIC);
1095             netif_ip6_addr_set_valid_life(netif, i, life);
1096           }
1097           /* The address is still here. Update the preferred lifetime too. */
1098           life = netif_ip6_addr_pref_life(netif, i);
1099           if (life <= ND6_TMR_INTERVAL / 1000) {
1100             /* This case must also trigger if 'life' was already zero, so as to
1101              * deal correctly with advertised preferred-lifetime reductions. */
1102             netif_ip6_addr_set_pref_life(netif, i, 0);
1103             if (addr_state == IP6_ADDR_PREFERRED)
1104               netif_ip6_addr_set_state(netif, i, IP6_ADDR_DEPRECATED);
1105           } else if (!ip6_addr_life_isinfinite(life)) {
1106             life -= ND6_TMR_INTERVAL / 1000;
1107             netif_ip6_addr_set_pref_life(netif, i, life);
1108           }
1109         }
1110       }
1111       /* The address state may now have changed, so reobtain it next. */
1112 #endif /* LWIP_IPV6_ADDRESS_LIFETIMES */
1113       /* Step 2: update DAD state. */
1114       addr_state = netif_ip6_addr_state(netif, i);
1115       if (ip6_addr_istentative(addr_state)) {
1116         if ((addr_state & IP6_ADDR_TENTATIVE_COUNT_MASK) >= LWIP_IPV6_DUP_DETECT_ATTEMPTS) {
1117           /* No NA received in response. Mark address as valid. For dynamic
1118            * addresses with an expired preferred lifetime, the state is set to
1119            * deprecated right away. That should almost never happen, though. */
1120           addr_state = IP6_ADDR_PREFERRED;
1121 #if LWIP_IPV6_ADDRESS_LIFETIMES
1122           if (!netif_ip6_addr_isstatic(netif, i) &&
1123               netif_ip6_addr_pref_life(netif, i) == 0) {
1124             addr_state = IP6_ADDR_DEPRECATED;
1125           }
1126 #endif /* LWIP_IPV6_ADDRESS_LIFETIMES */
1127           netif_ip6_addr_set_state(netif, i, addr_state);
1128         } else if (netif_is_up(netif) && netif_is_link_up(netif)) {
1129           /* tentative: set next state by increasing by one */
1130           netif_ip6_addr_set_state(netif, i, addr_state + 1);
1131           /* Send a NS for this address. Use the unspecified address as source
1132            * address in all cases (RFC 4862 Sec. 5.4.2), not in the least
1133            * because as it is, we only consider multicast replies for DAD. */
1134           nd6_send_ns(netif, netif_ip6_addr(netif, i),
1135             ND6_SEND_FLAG_MULTICAST_DEST | ND6_SEND_FLAG_ANY_SRC);
1136         }
1137       }
1138     }
1139   }
1140 
1141 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
1142   /* Send router solicitation messages, if necessary. */
1143   if (!nd6_tmr_rs_reduction) {
1144     nd6_tmr_rs_reduction = (ND6_RTR_SOLICITATION_INTERVAL / ND6_TMR_INTERVAL) - 1;
1145     NETIF_FOREACH(netif) {
1146       if ((netif->rs_count > 0) && netif_is_up(netif) &&
1147           netif_is_link_up(netif) &&
1148           !ip6_addr_isinvalid(netif_ip6_addr_state(netif, 0)) &&
1149           !ip6_addr_isduplicated(netif_ip6_addr_state(netif, 0))) {
1150         if (nd6_send_rs(netif) == ERR_OK) {
1151           netif->rs_count--;
1152         }
1153       }
1154     }
1155   } else {
1156     nd6_tmr_rs_reduction--;
1157   }
1158 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
1159 
1160 }
1161 
1162 /** Send a neighbor solicitation message for a specific neighbor cache entry
1163  *
1164  * @param entry the neightbor cache entry for wich to send the message
1165  * @param flags one of ND6_SEND_FLAG_*
1166  */
1167 static void
nd6_send_neighbor_cache_probe(struct nd6_neighbor_cache_entry * entry,u8_t flags)1168 nd6_send_neighbor_cache_probe(struct nd6_neighbor_cache_entry *entry, u8_t flags)
1169 {
1170   nd6_send_ns(entry->netif, &entry->next_hop_address, flags);
1171 }
1172 
1173 /**
1174  * Send a neighbor solicitation message
1175  *
1176  * @param netif the netif on which to send the message
1177  * @param target_addr the IPv6 target address for the ND message
1178  * @param flags one of ND6_SEND_FLAG_*
1179  */
1180 static void
nd6_send_ns(struct netif * netif,const ip6_addr_t * target_addr,u8_t flags)1181 nd6_send_ns(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags)
1182 {
1183   struct ns_header *ns_hdr;
1184   struct pbuf *p;
1185   const ip6_addr_t *src_addr = NULL;
1186   u16_t lladdr_opt_len;
1187 
1188   LWIP_ASSERT("target address is required", target_addr != NULL);
1189 
1190   if (!(flags & ND6_SEND_FLAG_ANY_SRC)) {
1191     int i;
1192     for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
1193       if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i)) &&
1194             ip6_addr_netcmp(target_addr, netif_ip6_addr(netif, i))) {
1195         src_addr = netif_ip6_addr(netif, i);
1196         break;
1197       }
1198     }
1199 
1200     if (i == LWIP_IPV6_NUM_ADDRESSES) {
1201       LWIP_DEBUGF(IP6_DEBUG | LWIP_DBG_LEVEL_WARNING, ("ICMPv6 NS: no available src address\n"));
1202       ND6_STATS_INC(nd6.err);
1203       return;
1204     }
1205 
1206     /* calculate option length (in 8-byte-blocks) */
1207     lladdr_opt_len = ((netif->hwaddr_len + 2) + 7) >> 3;
1208   } else {
1209     src_addr = IP6_ADDR_ANY6;
1210     /* Option "MUST NOT be included when the source IP address is the unspecified address." */
1211     lladdr_opt_len = 0;
1212   }
1213 
1214   /* Allocate a packet. */
1215   p = pbuf_alloc(PBUF_IP, sizeof(struct ns_header) + (lladdr_opt_len << 3), PBUF_RAM);
1216   if (p == NULL) {
1217     ND6_STATS_INC(nd6.memerr);
1218     return;
1219   }
1220 
1221   /* Set fields. */
1222   ns_hdr = (struct ns_header *)p->payload;
1223 
1224   ns_hdr->type = ICMP6_TYPE_NS;
1225   ns_hdr->code = 0;
1226   ns_hdr->chksum = 0;
1227   ns_hdr->reserved = 0;
1228   ip6_addr_copy_to_packed(ns_hdr->target_address, *target_addr);
1229 
1230   if (lladdr_opt_len != 0) {
1231     struct lladdr_option *lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct ns_header));
1232     lladdr_opt->type = ND6_OPTION_TYPE_SOURCE_LLADDR;
1233     lladdr_opt->length = (u8_t)lladdr_opt_len;
1234     SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
1235   }
1236 
1237   /* Generate the solicited node address for the target address. */
1238   if (flags & ND6_SEND_FLAG_MULTICAST_DEST) {
1239     ip6_addr_set_solicitednode(&multicast_address, target_addr->addr[3]);
1240     ip6_addr_assign_zone(&multicast_address, IP6_MULTICAST, netif);
1241     target_addr = &multicast_address;
1242   }
1243 
1244 #if CHECKSUM_GEN_ICMP6
1245   IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
1246     ns_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
1247       target_addr);
1248   }
1249 #endif /* CHECKSUM_GEN_ICMP6 */
1250 
1251   /* Send the packet out. */
1252   ND6_STATS_INC(nd6.xmit);
1253   ip6_output_if(p, (src_addr == IP6_ADDR_ANY6) ? NULL : src_addr, target_addr,
1254       ND6_HOPLIM, 0, IP6_NEXTH_ICMP6, netif);
1255   pbuf_free(p);
1256 }
1257 
1258 /**
1259  * Send a neighbor advertisement message
1260  *
1261  * @param netif the netif on which to send the message
1262  * @param target_addr the IPv6 target address for the ND message
1263  * @param flags one of ND6_SEND_FLAG_*
1264  */
1265 static void
nd6_send_na(struct netif * netif,const ip6_addr_t * target_addr,u8_t flags)1266 nd6_send_na(struct netif *netif, const ip6_addr_t *target_addr, u8_t flags)
1267 {
1268   struct na_header *na_hdr;
1269   struct lladdr_option *lladdr_opt;
1270   struct pbuf *p;
1271   const ip6_addr_t *src_addr;
1272   const ip6_addr_t *dest_addr;
1273   u16_t lladdr_opt_len;
1274 
1275   LWIP_ASSERT("target address is required", target_addr != NULL);
1276 
1277   /* Use link-local address as source address. */
1278   /* src_addr = netif_ip6_addr(netif, 0); */
1279   /* Use target address as source address. */
1280   src_addr = target_addr;
1281 
1282   /* Allocate a packet. */
1283   lladdr_opt_len = ((netif->hwaddr_len + 2) >> 3) + (((netif->hwaddr_len + 2) & 0x07) ? 1 : 0);
1284   p = pbuf_alloc(PBUF_IP, sizeof(struct na_header) + (lladdr_opt_len << 3), PBUF_RAM);
1285   if (p == NULL) {
1286     ND6_STATS_INC(nd6.memerr);
1287     return;
1288   }
1289 
1290   /* Set fields. */
1291   na_hdr = (struct na_header *)p->payload;
1292   lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct na_header));
1293 
1294   na_hdr->type = ICMP6_TYPE_NA;
1295   na_hdr->code = 0;
1296   na_hdr->chksum = 0;
1297   na_hdr->flags = flags & 0xf0;
1298   na_hdr->reserved[0] = 0;
1299   na_hdr->reserved[1] = 0;
1300   na_hdr->reserved[2] = 0;
1301   ip6_addr_copy_to_packed(na_hdr->target_address, *target_addr);
1302 
1303   lladdr_opt->type = ND6_OPTION_TYPE_TARGET_LLADDR;
1304   lladdr_opt->length = (u8_t)lladdr_opt_len;
1305   SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
1306 
1307   /* Generate the solicited node address for the target address. */
1308   if (flags & ND6_SEND_FLAG_MULTICAST_DEST) {
1309     ip6_addr_set_solicitednode(&multicast_address, target_addr->addr[3]);
1310     ip6_addr_assign_zone(&multicast_address, IP6_MULTICAST, netif);
1311     dest_addr = &multicast_address;
1312   } else if (flags & ND6_SEND_FLAG_ALLNODES_DEST) {
1313     ip6_addr_set_allnodes_linklocal(&multicast_address);
1314     ip6_addr_assign_zone(&multicast_address, IP6_MULTICAST, netif);
1315     dest_addr = &multicast_address;
1316   } else {
1317     dest_addr = ip6_current_src_addr();
1318   }
1319 
1320 #if CHECKSUM_GEN_ICMP6
1321   IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
1322     na_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
1323       dest_addr);
1324   }
1325 #endif /* CHECKSUM_GEN_ICMP6 */
1326 
1327   /* Send the packet out. */
1328   ND6_STATS_INC(nd6.xmit);
1329   ip6_output_if(p, src_addr, dest_addr,
1330       ND6_HOPLIM, 0, IP6_NEXTH_ICMP6, netif);
1331   pbuf_free(p);
1332 }
1333 
1334 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
1335 /**
1336  * Send a router solicitation message
1337  *
1338  * @param netif the netif on which to send the message
1339  */
1340 static err_t
nd6_send_rs(struct netif * netif)1341 nd6_send_rs(struct netif *netif)
1342 {
1343   struct rs_header *rs_hdr;
1344   struct lladdr_option *lladdr_opt;
1345   struct pbuf *p;
1346   const ip6_addr_t *src_addr;
1347   err_t err;
1348   u16_t lladdr_opt_len = 0;
1349 
1350   /* Link-local source address, or unspecified address? */
1351   if (ip6_addr_isvalid(netif_ip6_addr_state(netif, 0))) {
1352     src_addr = netif_ip6_addr(netif, 0);
1353   } else {
1354     src_addr = IP6_ADDR_ANY6;
1355   }
1356 
1357   /* Generate the all routers target address. */
1358   ip6_addr_set_allrouters_linklocal(&multicast_address);
1359   ip6_addr_assign_zone(&multicast_address, IP6_MULTICAST, netif);
1360 
1361   /* Allocate a packet. */
1362   if (src_addr != IP6_ADDR_ANY6) {
1363     lladdr_opt_len = ((netif->hwaddr_len + 2) >> 3) + (((netif->hwaddr_len + 2) & 0x07) ? 1 : 0);
1364   }
1365   p = pbuf_alloc(PBUF_IP, sizeof(struct rs_header) + (lladdr_opt_len << 3), PBUF_RAM);
1366   if (p == NULL) {
1367     ND6_STATS_INC(nd6.memerr);
1368     return ERR_BUF;
1369   }
1370 
1371   /* Set fields. */
1372   rs_hdr = (struct rs_header *)p->payload;
1373 
1374   rs_hdr->type = ICMP6_TYPE_RS;
1375   rs_hdr->code = 0;
1376   rs_hdr->chksum = 0;
1377   rs_hdr->reserved = 0;
1378 
1379   if (src_addr != IP6_ADDR_ANY6) {
1380     /* Include our hw address. */
1381     lladdr_opt = (struct lladdr_option *)((u8_t*)p->payload + sizeof(struct rs_header));
1382     lladdr_opt->type = ND6_OPTION_TYPE_SOURCE_LLADDR;
1383     lladdr_opt->length = (u8_t)lladdr_opt_len;
1384     SMEMCPY(lladdr_opt->addr, netif->hwaddr, netif->hwaddr_len);
1385   }
1386 
1387 #if CHECKSUM_GEN_ICMP6
1388   IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
1389     rs_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len, src_addr,
1390       &multicast_address);
1391   }
1392 #endif /* CHECKSUM_GEN_ICMP6 */
1393 
1394   /* Send the packet out. */
1395   ND6_STATS_INC(nd6.xmit);
1396 
1397   err = ip6_output_if(p, (src_addr == IP6_ADDR_ANY6) ? NULL : src_addr, &multicast_address,
1398       ND6_HOPLIM, 0, IP6_NEXTH_ICMP6, netif);
1399   pbuf_free(p);
1400 
1401   return err;
1402 }
1403 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
1404 
1405 /**
1406  * Search for a neighbor cache entry
1407  *
1408  * @param ip6addr the IPv6 address of the neighbor
1409  * @return The neighbor cache entry index that matched, -1 if no
1410  * entry is found
1411  */
1412 static s8_t
nd6_find_neighbor_cache_entry(const ip6_addr_t * ip6addr)1413 nd6_find_neighbor_cache_entry(const ip6_addr_t *ip6addr)
1414 {
1415   s8_t i;
1416   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1417     if (ip6_addr_cmp(ip6addr, &(neighbor_cache[i].next_hop_address))) {
1418       return i;
1419     }
1420   }
1421   return -1;
1422 }
1423 
1424 /**
1425  * Create a new neighbor cache entry.
1426  *
1427  * If no unused entry is found, will try to recycle an old entry
1428  * according to ad-hoc "age" heuristic.
1429  *
1430  * @return The neighbor cache entry index that was created, -1 if no
1431  * entry could be created
1432  */
1433 static s8_t
nd6_new_neighbor_cache_entry(void)1434 nd6_new_neighbor_cache_entry(void)
1435 {
1436   s8_t i;
1437   s8_t j;
1438   u32_t time;
1439 
1440 
1441   /* First, try to find an empty entry. */
1442   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1443     if (neighbor_cache[i].state == ND6_NO_ENTRY) {
1444       return i;
1445     }
1446   }
1447 
1448   /* We need to recycle an entry. in general, do not recycle if it is a router. */
1449 
1450   /* Next, try to find a Stale entry. */
1451   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1452     if ((neighbor_cache[i].state == ND6_STALE) &&
1453         (!neighbor_cache[i].isrouter)) {
1454       nd6_free_neighbor_cache_entry(i);
1455       return i;
1456     }
1457   }
1458 
1459   /* Next, try to find a Probe entry. */
1460   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1461     if ((neighbor_cache[i].state == ND6_PROBE) &&
1462         (!neighbor_cache[i].isrouter)) {
1463       nd6_free_neighbor_cache_entry(i);
1464       return i;
1465     }
1466   }
1467 
1468   /* Next, try to find a Delayed entry. */
1469   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1470     if ((neighbor_cache[i].state == ND6_DELAY) &&
1471         (!neighbor_cache[i].isrouter)) {
1472       nd6_free_neighbor_cache_entry(i);
1473       return i;
1474     }
1475   }
1476 
1477   /* Next, try to find the oldest reachable entry. */
1478   time = 0xfffffffful;
1479   j = -1;
1480   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1481     if ((neighbor_cache[i].state == ND6_REACHABLE) &&
1482         (!neighbor_cache[i].isrouter)) {
1483       if (neighbor_cache[i].counter.reachable_time < time) {
1484         j = i;
1485         time = neighbor_cache[i].counter.reachable_time;
1486       }
1487     }
1488   }
1489   if (j >= 0) {
1490     nd6_free_neighbor_cache_entry(j);
1491     return j;
1492   }
1493 
1494   /* Next, find oldest incomplete entry without queued packets. */
1495   time = 0;
1496   j = -1;
1497   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1498     if (
1499         (neighbor_cache[i].q == NULL) &&
1500         (neighbor_cache[i].state == ND6_INCOMPLETE) &&
1501         (!neighbor_cache[i].isrouter)) {
1502       if (neighbor_cache[i].counter.probes_sent >= time) {
1503         j = i;
1504         time = neighbor_cache[i].counter.probes_sent;
1505       }
1506     }
1507   }
1508   if (j >= 0) {
1509     nd6_free_neighbor_cache_entry(j);
1510     return j;
1511   }
1512 
1513   /* Next, find oldest incomplete entry with queued packets. */
1514   time = 0;
1515   j = -1;
1516   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
1517     if ((neighbor_cache[i].state == ND6_INCOMPLETE) &&
1518         (!neighbor_cache[i].isrouter)) {
1519       if (neighbor_cache[i].counter.probes_sent >= time) {
1520         j = i;
1521         time = neighbor_cache[i].counter.probes_sent;
1522       }
1523     }
1524   }
1525   if (j >= 0) {
1526     nd6_free_neighbor_cache_entry(j);
1527     return j;
1528   }
1529 
1530   /* No more entries to try. */
1531   return -1;
1532 }
1533 
1534 /**
1535  * Will free any resources associated with a neighbor cache
1536  * entry, and will mark it as unused.
1537  *
1538  * @param i the neighbor cache entry index to free
1539  */
1540 static void
nd6_free_neighbor_cache_entry(s8_t i)1541 nd6_free_neighbor_cache_entry(s8_t i)
1542 {
1543   if ((i < 0) || (i >= LWIP_ND6_NUM_NEIGHBORS)) {
1544     return;
1545   }
1546   if (neighbor_cache[i].isrouter) {
1547     /* isrouter needs to be cleared before deleting a neighbor cache entry */
1548     return;
1549   }
1550 
1551   /* Free any queued packets. */
1552   if (neighbor_cache[i].q != NULL) {
1553     nd6_free_q(neighbor_cache[i].q);
1554     neighbor_cache[i].q = NULL;
1555   }
1556 
1557   neighbor_cache[i].state = ND6_NO_ENTRY;
1558   neighbor_cache[i].isrouter = 0;
1559   neighbor_cache[i].netif = NULL;
1560   neighbor_cache[i].counter.reachable_time = 0;
1561   ip6_addr_set_zero(&(neighbor_cache[i].next_hop_address));
1562 }
1563 
1564 /**
1565  * Search for a destination cache entry
1566  *
1567  * @param ip6addr the IPv6 address of the destination
1568  * @return The destination cache entry index that matched, -1 if no
1569  * entry is found
1570  */
1571 static s16_t
nd6_find_destination_cache_entry(const ip6_addr_t * ip6addr)1572 nd6_find_destination_cache_entry(const ip6_addr_t *ip6addr)
1573 {
1574   s16_t i;
1575 
1576   IP6_ADDR_ZONECHECK(ip6addr);
1577 
1578   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1579     if (ip6_addr_cmp(ip6addr, &(destination_cache[i].destination_addr))) {
1580       return i;
1581     }
1582   }
1583   return -1;
1584 }
1585 
1586 /**
1587  * Create a new destination cache entry. If no unused entry is found,
1588  * will recycle oldest entry.
1589  *
1590  * @return The destination cache entry index that was created, -1 if no
1591  * entry was created
1592  */
1593 static s16_t
nd6_new_destination_cache_entry(void)1594 nd6_new_destination_cache_entry(void)
1595 {
1596   s16_t i, j;
1597   u32_t age;
1598 
1599   /* Find an empty entry. */
1600   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1601     if (ip6_addr_isany(&(destination_cache[i].destination_addr))) {
1602       return i;
1603     }
1604   }
1605 
1606   /* Find oldest entry. */
1607   age = 0;
1608   j = LWIP_ND6_NUM_DESTINATIONS - 1;
1609   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1610     if (destination_cache[i].age > age) {
1611       j = i;
1612     }
1613   }
1614 
1615   return j;
1616 }
1617 
1618 /**
1619  * Clear the destination cache.
1620  *
1621  * This operation may be necessary for consistency in the light of changing
1622  * local addresses and/or use of the gateway hook.
1623  */
1624 void
nd6_clear_destination_cache(void)1625 nd6_clear_destination_cache(void)
1626 {
1627   int i;
1628 
1629   for (i = 0; i < LWIP_ND6_NUM_DESTINATIONS; i++) {
1630     ip6_addr_set_any(&destination_cache[i].destination_addr);
1631   }
1632 }
1633 
1634 /**
1635  * Determine whether an address matches an on-link prefix or the subnet of a
1636  * statically assigned address.
1637  *
1638  * @param ip6addr the IPv6 address to match
1639  * @return 1 if the address is on-link, 0 otherwise
1640  */
1641 static int
nd6_is_prefix_in_netif(const ip6_addr_t * ip6addr,struct netif * netif)1642 nd6_is_prefix_in_netif(const ip6_addr_t *ip6addr, struct netif *netif)
1643 {
1644   s8_t i;
1645 
1646   /* Check to see if the address matches an on-link prefix. */
1647   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; i++) {
1648     if ((prefix_list[i].netif == netif) &&
1649         (prefix_list[i].invalidation_timer > 0) &&
1650         ip6_addr_netcmp(ip6addr, &(prefix_list[i].prefix))) {
1651       return 1;
1652     }
1653   }
1654   /* Check to see if address prefix matches a manually configured (= static)
1655    * address. Static addresses have an implied /64 subnet assignment. Dynamic
1656    * addresses (from autoconfiguration) have no implied subnet assignment, and
1657    * are thus effectively /128 assignments. See RFC 5942 for more on this. */
1658   for (i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++) {
1659     if (ip6_addr_isvalid(netif_ip6_addr_state(netif, i)) &&
1660         netif_ip6_addr_isstatic(netif, i) &&
1661         ip6_addr_netcmp(ip6addr, netif_ip6_addr(netif, i))) {
1662       return 1;
1663     }
1664   }
1665   return 0;
1666 }
1667 
1668 /**
1669  * Select a default router for a destination.
1670  *
1671  * This function is used both for routing and for finding a next-hop target for
1672  * a packet. In the former case, the given netif is NULL, and the returned
1673  * router entry must be for a netif suitable for sending packets (up, link up).
1674  * In the latter case, the given netif is not NULL and restricts router choice.
1675  *
1676  * @param ip6addr the destination address
1677  * @param netif the netif for the outgoing packet, if known
1678  * @return the default router entry index, or -1 if no suitable
1679  *         router is found
1680  */
1681 static s8_t
nd6_select_router(const ip6_addr_t * ip6addr,struct netif * netif)1682 nd6_select_router(const ip6_addr_t *ip6addr, struct netif *netif)
1683 {
1684   struct netif *router_netif;
1685   s8_t i, j, valid_router;
1686   static s8_t last_router;
1687 
1688   LWIP_UNUSED_ARG(ip6addr); /* @todo match preferred routes!! (must implement ND6_OPTION_TYPE_ROUTE_INFO) */
1689 
1690   /* @todo: implement default router preference */
1691 
1692   /* Look for valid routers. A reachable router is preferred. */
1693   valid_router = -1;
1694   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1695     /* Is the router netif both set and apppropriate? */
1696     if (default_router_list[i].neighbor_entry != NULL) {
1697       router_netif = default_router_list[i].neighbor_entry->netif;
1698       if ((router_netif != NULL) && (netif != NULL ? netif == router_netif :
1699           (netif_is_up(router_netif) && netif_is_link_up(router_netif)))) {
1700         /* Is the router valid, i.e., reachable or probably reachable as per
1701          * RFC 4861 Sec. 6.3.6? Note that we will never return a router that
1702          * has no neighbor cache entry, due to the netif association tests. */
1703         if (default_router_list[i].neighbor_entry->state != ND6_INCOMPLETE) {
1704           /* Is the router known to be reachable? */
1705           if (default_router_list[i].neighbor_entry->state == ND6_REACHABLE) {
1706             return i; /* valid and reachable - done! */
1707           } else if (valid_router < 0) {
1708             valid_router = i; /* valid but not known to be reachable */
1709           }
1710         }
1711       }
1712     }
1713   }
1714   if (valid_router >= 0) {
1715     return valid_router;
1716   }
1717 
1718   /* Look for any router for which we have any information at all. */
1719   /* last_router is used for round-robin selection of incomplete routers, as
1720    * recommended in RFC 4861 Sec. 6.3.6 point (2). Advance only when picking a
1721    * route, to select the same router as next-hop target in the common case. */
1722   if ((netif == NULL) && (++last_router >= LWIP_ND6_NUM_ROUTERS)) {
1723     last_router = 0;
1724   }
1725   i = last_router;
1726   for (j = 0; j < LWIP_ND6_NUM_ROUTERS; j++) {
1727     if (default_router_list[i].neighbor_entry != NULL) {
1728       router_netif = default_router_list[i].neighbor_entry->netif;
1729       if ((router_netif != NULL) && (netif != NULL ? netif == router_netif :
1730           (netif_is_up(router_netif) && netif_is_link_up(router_netif)))) {
1731         return i;
1732       }
1733     }
1734     if (++i >= LWIP_ND6_NUM_ROUTERS) {
1735       i = 0;
1736     }
1737   }
1738 
1739   /* no suitable router found. */
1740   return -1;
1741 }
1742 
1743 /**
1744  * Find a router-announced route to the given destination. This route may be
1745  * based on an on-link prefix or a default router.
1746  *
1747  * If a suitable route is found, the returned netif is guaranteed to be in a
1748  * suitable state (up, link up) to be used for packet transmission.
1749  *
1750  * @param ip6addr the destination IPv6 address
1751  * @return the netif to use for the destination, or NULL if none found
1752  */
1753 struct netif *
nd6_find_route(const ip6_addr_t * ip6addr)1754 nd6_find_route(const ip6_addr_t *ip6addr)
1755 {
1756   struct netif *netif;
1757   s8_t i;
1758 
1759   /* @todo decide if it makes sense to check the destination cache first */
1760 
1761   /* Check if there is a matching on-link prefix. There may be multiple
1762    * matches. Pick the first one that is associated with a suitable netif. */
1763   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; ++i) {
1764     netif = prefix_list[i].netif;
1765     if ((netif != NULL) && ip6_addr_netcmp(&prefix_list[i].prefix, ip6addr) &&
1766         netif_is_up(netif) && netif_is_link_up(netif)) {
1767       return netif;
1768     }
1769   }
1770 
1771   /* No on-link prefix match. Find a router that can forward the packet. */
1772   i = nd6_select_router(ip6addr, NULL);
1773   if (i >= 0) {
1774     LWIP_ASSERT("selected router must have a neighbor entry",
1775       default_router_list[i].neighbor_entry != NULL);
1776     return default_router_list[i].neighbor_entry->netif;
1777   }
1778 
1779   return NULL;
1780 }
1781 
1782 /**
1783  * Find an entry for a default router.
1784  *
1785  * @param router_addr the IPv6 address of the router
1786  * @param netif the netif on which the router is found, if known
1787  * @return the index of the router entry, or -1 if not found
1788  */
1789 static s8_t
nd6_get_router(const ip6_addr_t * router_addr,struct netif * netif)1790 nd6_get_router(const ip6_addr_t *router_addr, struct netif *netif)
1791 {
1792   s8_t i;
1793 
1794   IP6_ADDR_ZONECHECK_NETIF(router_addr, netif);
1795 
1796   /* Look for router. */
1797   for (i = 0; i < LWIP_ND6_NUM_ROUTERS; i++) {
1798     if ((default_router_list[i].neighbor_entry != NULL) &&
1799         ((netif != NULL) ? netif == default_router_list[i].neighbor_entry->netif : 1) &&
1800         ip6_addr_cmp(router_addr, &(default_router_list[i].neighbor_entry->next_hop_address))) {
1801       return i;
1802     }
1803   }
1804 
1805   /* router not found. */
1806   return -1;
1807 }
1808 
1809 /**
1810  * Create a new entry for a default router.
1811  *
1812  * @param router_addr the IPv6 address of the router
1813  * @param netif the netif on which the router is connected, if known
1814  * @return the index on the router table, or -1 if could not be created
1815  */
1816 static s8_t
nd6_new_router(const ip6_addr_t * router_addr,struct netif * netif)1817 nd6_new_router(const ip6_addr_t *router_addr, struct netif *netif)
1818 {
1819   s8_t router_index;
1820   s8_t free_router_index;
1821   s8_t neighbor_index;
1822 
1823   IP6_ADDR_ZONECHECK_NETIF(router_addr, netif);
1824 
1825   /* Do we have a neighbor entry for this router? */
1826   neighbor_index = nd6_find_neighbor_cache_entry(router_addr);
1827   if (neighbor_index < 0) {
1828     /* Create a neighbor entry for this router. */
1829     neighbor_index = nd6_new_neighbor_cache_entry();
1830     if (neighbor_index < 0) {
1831       /* Could not create neighbor entry for this router. */
1832       return -1;
1833     }
1834     ip6_addr_set(&(neighbor_cache[neighbor_index].next_hop_address), router_addr);
1835     neighbor_cache[neighbor_index].netif = netif;
1836     neighbor_cache[neighbor_index].q = NULL;
1837     neighbor_cache[neighbor_index].state = ND6_INCOMPLETE;
1838     neighbor_cache[neighbor_index].counter.probes_sent = 1;
1839     nd6_send_neighbor_cache_probe(&neighbor_cache[neighbor_index], ND6_SEND_FLAG_MULTICAST_DEST);
1840   }
1841 
1842   /* Mark neighbor as router. */
1843   neighbor_cache[neighbor_index].isrouter = 1;
1844 
1845   /* Look for empty entry. */
1846   free_router_index = LWIP_ND6_NUM_ROUTERS;
1847   for (router_index = LWIP_ND6_NUM_ROUTERS - 1; router_index >= 0; router_index--) {
1848     /* check if router already exists (this is a special case for 2 netifs on the same subnet
1849        - e.g. wifi and cable) */
1850     if(default_router_list[router_index].neighbor_entry == &(neighbor_cache[neighbor_index])){
1851       return router_index;
1852     }
1853     if (default_router_list[router_index].neighbor_entry == NULL) {
1854       /* remember lowest free index to create a new entry */
1855       free_router_index = router_index;
1856     }
1857   }
1858   if (free_router_index < LWIP_ND6_NUM_ROUTERS) {
1859     default_router_list[free_router_index].neighbor_entry = &(neighbor_cache[neighbor_index]);
1860     return free_router_index;
1861   }
1862 
1863   /* Could not create a router entry. */
1864 
1865   /* Mark neighbor entry as not-router. Entry might be useful as neighbor still. */
1866   neighbor_cache[neighbor_index].isrouter = 0;
1867 
1868   /* router not found. */
1869   return -1;
1870 }
1871 
1872 /**
1873  * Find the cached entry for an on-link prefix.
1874  *
1875  * @param prefix the IPv6 prefix that is on-link
1876  * @param netif the netif on which the prefix is on-link
1877  * @return the index on the prefix table, or -1 if not found
1878  */
1879 static s8_t
nd6_get_onlink_prefix(const ip6_addr_t * prefix,struct netif * netif)1880 nd6_get_onlink_prefix(const ip6_addr_t *prefix, struct netif *netif)
1881 {
1882   s8_t i;
1883 
1884   /* Look for prefix in list. */
1885   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; ++i) {
1886     if ((ip6_addr_netcmp(&(prefix_list[i].prefix), prefix)) &&
1887         (prefix_list[i].netif == netif)) {
1888       return i;
1889     }
1890   }
1891 
1892   /* Entry not available. */
1893   return -1;
1894 }
1895 
1896 /**
1897  * Creates a new entry for an on-link prefix.
1898  *
1899  * @param prefix the IPv6 prefix that is on-link
1900  * @param netif the netif on which the prefix is on-link
1901  * @return the index on the prefix table, or -1 if not created
1902  */
1903 static s8_t
nd6_new_onlink_prefix(const ip6_addr_t * prefix,struct netif * netif)1904 nd6_new_onlink_prefix(const ip6_addr_t *prefix, struct netif *netif)
1905 {
1906   s8_t i;
1907 
1908   /* Create new entry. */
1909   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; ++i) {
1910     if ((prefix_list[i].netif == NULL) ||
1911         (prefix_list[i].invalidation_timer == 0)) {
1912       /* Found empty prefix entry. */
1913       prefix_list[i].netif = netif;
1914       ip6_addr_set(&(prefix_list[i].prefix), prefix);
1915       return i;
1916     }
1917   }
1918 
1919   /* Entry not available. */
1920   return -1;
1921 }
1922 
1923 /**
1924  * Determine the next hop for a destination. Will determine if the
1925  * destination is on-link, else a suitable on-link router is selected.
1926  *
1927  * The last entry index is cached for fast entry search.
1928  *
1929  * @param ip6addr the destination address
1930  * @param netif the netif on which the packet will be sent
1931  * @return the neighbor cache entry for the next hop, ERR_RTE if no
1932  *         suitable next hop was found, ERR_MEM if no cache entry
1933  *         could be created
1934  */
1935 static s8_t
nd6_get_next_hop_entry(const ip6_addr_t * ip6addr,struct netif * netif)1936 nd6_get_next_hop_entry(const ip6_addr_t *ip6addr, struct netif *netif)
1937 {
1938 #ifdef LWIP_HOOK_ND6_GET_GW
1939   const ip6_addr_t *next_hop_addr;
1940 #endif /* LWIP_HOOK_ND6_GET_GW */
1941   s8_t i;
1942   s16_t dst_idx;
1943 
1944   IP6_ADDR_ZONECHECK_NETIF(ip6addr, netif);
1945 
1946 #if LWIP_NETIF_HWADDRHINT
1947   if (netif->hints != NULL) {
1948     /* per-pcb cached entry was given */
1949     netif_addr_idx_t addr_hint = netif->hints->addr_hint;
1950     if (addr_hint < LWIP_ND6_NUM_DESTINATIONS) {
1951       nd6_cached_destination_index = addr_hint;
1952     }
1953   }
1954 #endif /* LWIP_NETIF_HWADDRHINT */
1955 
1956   /* Look for ip6addr in destination cache. */
1957   if (ip6_addr_cmp(ip6addr, &(destination_cache[nd6_cached_destination_index].destination_addr))) {
1958     /* the cached entry index is the right one! */
1959     /* do nothing. */
1960     ND6_STATS_INC(nd6.cachehit);
1961   } else {
1962     /* Search destination cache. */
1963     dst_idx = nd6_find_destination_cache_entry(ip6addr);
1964     if (dst_idx >= 0) {
1965       /* found destination entry. make it our new cached index. */
1966       LWIP_ASSERT("type overflow", (size_t)dst_idx < NETIF_ADDR_IDX_MAX);
1967       nd6_cached_destination_index = (netif_addr_idx_t)dst_idx;
1968     } else {
1969       /* Not found. Create a new destination entry. */
1970       dst_idx = nd6_new_destination_cache_entry();
1971       if (dst_idx >= 0) {
1972         /* got new destination entry. make it our new cached index. */
1973         LWIP_ASSERT("type overflow", (size_t)dst_idx < NETIF_ADDR_IDX_MAX);
1974         nd6_cached_destination_index = (netif_addr_idx_t)dst_idx;
1975       } else {
1976         /* Could not create a destination cache entry. */
1977         return ERR_MEM;
1978       }
1979 
1980       /* Copy dest address to destination cache. */
1981       ip6_addr_set(&(destination_cache[nd6_cached_destination_index].destination_addr), ip6addr);
1982 
1983       /* Now find the next hop. is it a neighbor? */
1984       if (ip6_addr_islinklocal(ip6addr) ||
1985           nd6_is_prefix_in_netif(ip6addr, netif)) {
1986         /* Destination in local link. */
1987         destination_cache[nd6_cached_destination_index].pmtu = netif_mtu6(netif);
1988         ip6_addr_copy(destination_cache[nd6_cached_destination_index].next_hop_addr, destination_cache[nd6_cached_destination_index].destination_addr);
1989 #ifdef LWIP_HOOK_ND6_GET_GW
1990       } else if ((next_hop_addr = LWIP_HOOK_ND6_GET_GW(netif, ip6addr)) != NULL) {
1991         /* Next hop for destination provided by hook function. */
1992         destination_cache[nd6_cached_destination_index].pmtu = netif->mtu;
1993         ip6_addr_set(&destination_cache[nd6_cached_destination_index].next_hop_addr, next_hop_addr);
1994 #endif /* LWIP_HOOK_ND6_GET_GW */
1995       } else {
1996         /* We need to select a router. */
1997         i = nd6_select_router(ip6addr, netif);
1998         if (i < 0) {
1999           /* No router found. */
2000           ip6_addr_set_any(&(destination_cache[nd6_cached_destination_index].destination_addr));
2001           return ERR_RTE;
2002         }
2003         destination_cache[nd6_cached_destination_index].pmtu = netif_mtu6(netif); /* Start with netif mtu, correct through ICMPv6 if necessary */
2004         ip6_addr_copy(destination_cache[nd6_cached_destination_index].next_hop_addr, default_router_list[i].neighbor_entry->next_hop_address);
2005       }
2006     }
2007   }
2008 
2009 #if LWIP_NETIF_HWADDRHINT
2010   if (netif->hints != NULL) {
2011     /* per-pcb cached entry was given */
2012     netif->hints->addr_hint = nd6_cached_destination_index;
2013   }
2014 #endif /* LWIP_NETIF_HWADDRHINT */
2015 
2016   /* Look in neighbor cache for the next-hop address. */
2017   if (ip6_addr_cmp(&(destination_cache[nd6_cached_destination_index].next_hop_addr),
2018                    &(neighbor_cache[nd6_cached_neighbor_index].next_hop_address))) {
2019     /* Cache hit. */
2020     /* Do nothing. */
2021     ND6_STATS_INC(nd6.cachehit);
2022   } else {
2023     i = nd6_find_neighbor_cache_entry(&(destination_cache[nd6_cached_destination_index].next_hop_addr));
2024     if (i >= 0) {
2025       /* Found a matching record, make it new cached entry. */
2026       nd6_cached_neighbor_index = i;
2027     } else {
2028       /* Neighbor not in cache. Make a new entry. */
2029       i = nd6_new_neighbor_cache_entry();
2030       if (i >= 0) {
2031         /* got new neighbor entry. make it our new cached index. */
2032         nd6_cached_neighbor_index = i;
2033       } else {
2034         /* Could not create a neighbor cache entry. */
2035         return ERR_MEM;
2036       }
2037 
2038       /* Initialize fields. */
2039       ip6_addr_copy(neighbor_cache[i].next_hop_address,
2040                    destination_cache[nd6_cached_destination_index].next_hop_addr);
2041       neighbor_cache[i].isrouter = 0;
2042       neighbor_cache[i].netif = netif;
2043       neighbor_cache[i].state = ND6_INCOMPLETE;
2044       neighbor_cache[i].counter.probes_sent = 1;
2045       nd6_send_neighbor_cache_probe(&neighbor_cache[i], ND6_SEND_FLAG_MULTICAST_DEST);
2046     }
2047   }
2048 
2049   /* Reset this destination's age. */
2050   destination_cache[nd6_cached_destination_index].age = 0;
2051 
2052   return nd6_cached_neighbor_index;
2053 }
2054 
2055 /**
2056  * Queue a packet for a neighbor.
2057  *
2058  * @param neighbor_index the index in the neighbor cache table
2059  * @param q packet to be queued
2060  * @return ERR_OK if succeeded, ERR_MEM if out of memory
2061  */
2062 static err_t
nd6_queue_packet(s8_t neighbor_index,struct pbuf * q)2063 nd6_queue_packet(s8_t neighbor_index, struct pbuf *q)
2064 {
2065   err_t result = ERR_MEM;
2066   struct pbuf *p;
2067   int copy_needed = 0;
2068 #if LWIP_ND6_QUEUEING
2069   struct nd6_q_entry *new_entry, *r;
2070 #endif /* LWIP_ND6_QUEUEING */
2071 
2072   if ((neighbor_index < 0) || (neighbor_index >= LWIP_ND6_NUM_NEIGHBORS)) {
2073     return ERR_ARG;
2074   }
2075 
2076   /* IF q includes a pbuf that must be copied, we have to copy the whole chain
2077    * into a new PBUF_RAM. See the definition of PBUF_NEEDS_COPY for details. */
2078   p = q;
2079   while (p) {
2080     if (PBUF_NEEDS_COPY(p)) {
2081       copy_needed = 1;
2082       break;
2083     }
2084     p = p->next;
2085   }
2086   if (copy_needed) {
2087     /* copy the whole packet into new pbufs */
2088     p = pbuf_clone(PBUF_LINK, PBUF_RAM, q);
2089     while ((p == NULL) && (neighbor_cache[neighbor_index].q != NULL)) {
2090       /* Free oldest packet (as per RFC recommendation) */
2091 #if LWIP_ND6_QUEUEING
2092       r = neighbor_cache[neighbor_index].q;
2093       neighbor_cache[neighbor_index].q = r->next;
2094       r->next = NULL;
2095       nd6_free_q(r);
2096 #else /* LWIP_ND6_QUEUEING */
2097       pbuf_free(neighbor_cache[neighbor_index].q);
2098       neighbor_cache[neighbor_index].q = NULL;
2099 #endif /* LWIP_ND6_QUEUEING */
2100       p = pbuf_clone(PBUF_LINK, PBUF_RAM, q);
2101     }
2102   } else {
2103     /* referencing the old pbuf is enough */
2104     p = q;
2105     pbuf_ref(p);
2106   }
2107   /* packet was copied/ref'd? */
2108   if (p != NULL) {
2109     /* queue packet ... */
2110 #if LWIP_ND6_QUEUEING
2111     /* allocate a new nd6 queue entry */
2112     new_entry = (struct nd6_q_entry *)memp_malloc(MEMP_ND6_QUEUE);
2113     if ((new_entry == NULL) && (neighbor_cache[neighbor_index].q != NULL)) {
2114       /* Free oldest packet (as per RFC recommendation) */
2115       r = neighbor_cache[neighbor_index].q;
2116       neighbor_cache[neighbor_index].q = r->next;
2117       r->next = NULL;
2118       nd6_free_q(r);
2119       new_entry = (struct nd6_q_entry *)memp_malloc(MEMP_ND6_QUEUE);
2120     }
2121     if (new_entry != NULL) {
2122       new_entry->next = NULL;
2123       new_entry->p = p;
2124       if (neighbor_cache[neighbor_index].q != NULL) {
2125         /* queue was already existent, append the new entry to the end */
2126         r = neighbor_cache[neighbor_index].q;
2127         while (r->next != NULL) {
2128           r = r->next;
2129         }
2130         r->next = new_entry;
2131       } else {
2132         /* queue did not exist, first item in queue */
2133         neighbor_cache[neighbor_index].q = new_entry;
2134       }
2135       LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: queued packet %p on neighbor entry %"S16_F"\n", (void *)p, (s16_t)neighbor_index));
2136       result = ERR_OK;
2137     } else {
2138       /* the pool MEMP_ND6_QUEUE is empty */
2139       pbuf_free(p);
2140       LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: could not queue a copy of packet %p (out of memory)\n", (void *)p));
2141       /* { result == ERR_MEM } through initialization */
2142     }
2143 #else /* LWIP_ND6_QUEUEING */
2144     /* Queue a single packet. If an older packet is already queued, free it as per RFC. */
2145     if (neighbor_cache[neighbor_index].q != NULL) {
2146       pbuf_free(neighbor_cache[neighbor_index].q);
2147     }
2148     neighbor_cache[neighbor_index].q = p;
2149     LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: queued packet %p on neighbor entry %"S16_F"\n", (void *)p, (s16_t)neighbor_index));
2150     result = ERR_OK;
2151 #endif /* LWIP_ND6_QUEUEING */
2152   } else {
2153     LWIP_DEBUGF(LWIP_DBG_TRACE, ("ipv6: could not queue a copy of packet %p (out of memory)\n", (void *)q));
2154     /* { result == ERR_MEM } through initialization */
2155   }
2156 
2157   return result;
2158 }
2159 
2160 #if LWIP_ND6_QUEUEING
2161 /**
2162  * Free a complete queue of nd6 q entries
2163  *
2164  * @param q a queue of nd6_q_entry to free
2165  */
2166 static void
nd6_free_q(struct nd6_q_entry * q)2167 nd6_free_q(struct nd6_q_entry *q)
2168 {
2169   struct nd6_q_entry *r;
2170   LWIP_ASSERT("q != NULL", q != NULL);
2171   LWIP_ASSERT("q->p != NULL", q->p != NULL);
2172   while (q) {
2173     r = q;
2174     q = q->next;
2175     LWIP_ASSERT("r->p != NULL", (r->p != NULL));
2176     pbuf_free(r->p);
2177     memp_free(MEMP_ND6_QUEUE, r);
2178   }
2179 }
2180 #endif /* LWIP_ND6_QUEUEING */
2181 
2182 /**
2183  * Send queued packets for a neighbor
2184  *
2185  * @param i the neighbor to send packets to
2186  */
2187 static void
nd6_send_q(s8_t i)2188 nd6_send_q(s8_t i)
2189 {
2190   struct ip6_hdr *ip6hdr;
2191   ip6_addr_t dest;
2192 #if LWIP_ND6_QUEUEING
2193   struct nd6_q_entry *q;
2194 #endif /* LWIP_ND6_QUEUEING */
2195 
2196   if ((i < 0) || (i >= LWIP_ND6_NUM_NEIGHBORS)) {
2197     return;
2198   }
2199 
2200 #if LWIP_ND6_QUEUEING
2201   while (neighbor_cache[i].q != NULL) {
2202     /* remember first in queue */
2203     q = neighbor_cache[i].q;
2204     /* pop first item off the queue */
2205     neighbor_cache[i].q = q->next;
2206     /* Get ipv6 header. */
2207     ip6hdr = (struct ip6_hdr *)(q->p->payload);
2208     /* Create an aligned copy. */
2209     ip6_addr_copy_from_packed(dest, ip6hdr->dest);
2210     /* Restore the zone, if applicable. */
2211     ip6_addr_assign_zone(&dest, IP6_UNKNOWN, neighbor_cache[i].netif);
2212     /* send the queued IPv6 packet */
2213     (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, q->p, &dest);
2214     /* free the queued IP packet */
2215     pbuf_free(q->p);
2216     /* now queue entry can be freed */
2217     memp_free(MEMP_ND6_QUEUE, q);
2218   }
2219 #else /* LWIP_ND6_QUEUEING */
2220   if (neighbor_cache[i].q != NULL) {
2221     /* Get ipv6 header. */
2222     ip6hdr = (struct ip6_hdr *)(neighbor_cache[i].q->payload);
2223     /* Create an aligned copy. */
2224     ip6_addr_copy_from_packed(dest, ip6hdr->dest);
2225     /* Restore the zone, if applicable. */
2226     ip6_addr_assign_zone(&dest, IP6_UNKNOWN, neighbor_cache[i].netif);
2227     /* send the queued IPv6 packet */
2228     (neighbor_cache[i].netif)->output_ip6(neighbor_cache[i].netif, neighbor_cache[i].q, &dest);
2229     /* free the queued IP packet */
2230     pbuf_free(neighbor_cache[i].q);
2231     neighbor_cache[i].q = NULL;
2232   }
2233 #endif /* LWIP_ND6_QUEUEING */
2234 }
2235 
2236 /**
2237  * A packet is to be transmitted to a specific IPv6 destination on a specific
2238  * interface. Check if we can find the hardware address of the next hop to use
2239  * for the packet. If so, give the hardware address to the caller, which should
2240  * use it to send the packet right away. Otherwise, enqueue the packet for
2241  * later transmission while looking up the hardware address, if possible.
2242  *
2243  * As such, this function returns one of three different possible results:
2244  *
2245  * - ERR_OK with a non-NULL 'hwaddrp': the caller should send the packet now.
2246  * - ERR_OK with a NULL 'hwaddrp': the packet has been enqueued for later.
2247  * - not ERR_OK: something went wrong; forward the error upward in the stack.
2248  *
2249  * @param netif The lwIP network interface on which the IP packet will be sent.
2250  * @param q The pbuf(s) containing the IP packet to be sent.
2251  * @param ip6addr The destination IPv6 address of the packet.
2252  * @param hwaddrp On success, filled with a pointer to a HW address or NULL (meaning
2253  *        the packet has been queued).
2254  * @return
2255  * - ERR_OK on success, ERR_RTE if no route was found for the packet,
2256  * or ERR_MEM if low memory conditions prohibit sending the packet at all.
2257  */
2258 err_t
nd6_get_next_hop_addr_or_queue(struct netif * netif,struct pbuf * q,const ip6_addr_t * ip6addr,const u8_t ** hwaddrp)2259 nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, const u8_t **hwaddrp)
2260 {
2261   s8_t i;
2262 
2263   /* Get next hop record. */
2264   i = nd6_get_next_hop_entry(ip6addr, netif);
2265   if (i < 0) {
2266     /* failed to get a next hop neighbor record. */
2267     return i;
2268   }
2269 
2270   /* Now that we have a destination record, send or queue the packet. */
2271   if (neighbor_cache[i].state == ND6_STALE) {
2272     /* Switch to delay state. */
2273     neighbor_cache[i].state = ND6_DELAY;
2274     neighbor_cache[i].counter.delay_time = LWIP_ND6_DELAY_FIRST_PROBE_TIME / ND6_TMR_INTERVAL;
2275   }
2276   /* @todo should we send or queue if PROBE? send for now, to let unicast NS pass. */
2277   if ((neighbor_cache[i].state == ND6_REACHABLE) ||
2278       (neighbor_cache[i].state == ND6_DELAY) ||
2279       (neighbor_cache[i].state == ND6_PROBE)) {
2280 
2281     /* Tell the caller to send out the packet now. */
2282     *hwaddrp = neighbor_cache[i].lladdr;
2283     return ERR_OK;
2284   }
2285 
2286   /* We should queue packet on this interface. */
2287   *hwaddrp = NULL;
2288   return nd6_queue_packet(i, q);
2289 }
2290 
2291 
2292 /**
2293  * Get the Path MTU for a destination.
2294  *
2295  * @param ip6addr the destination address
2296  * @param netif the netif on which the packet will be sent
2297  * @return the Path MTU, if known, or the netif default MTU
2298  */
2299 u16_t
nd6_get_destination_mtu(const ip6_addr_t * ip6addr,struct netif * netif)2300 nd6_get_destination_mtu(const ip6_addr_t *ip6addr, struct netif *netif)
2301 {
2302   s16_t i;
2303 
2304   i = nd6_find_destination_cache_entry(ip6addr);
2305   if (i >= 0) {
2306     if (destination_cache[i].pmtu > 0) {
2307       return destination_cache[i].pmtu;
2308     }
2309   }
2310 
2311   if (netif != NULL) {
2312     return netif_mtu6(netif);
2313   }
2314 
2315   return IP6_MIN_MTU_LENGTH; /* Minimum MTU */
2316 }
2317 
2318 
2319 #if LWIP_ND6_TCP_REACHABILITY_HINTS
2320 /**
2321  * Provide the Neighbor discovery process with a hint that a
2322  * destination is reachable. Called by tcp_receive when ACKs are
2323  * received or sent (as per RFC). This is useful to avoid sending
2324  * NS messages every 30 seconds.
2325  *
2326  * @param ip6addr the destination address which is know to be reachable
2327  *                by an upper layer protocol (TCP)
2328  */
2329 void
nd6_reachability_hint(const ip6_addr_t * ip6addr)2330 nd6_reachability_hint(const ip6_addr_t *ip6addr)
2331 {
2332   s8_t i;
2333   s16_t dst_idx;
2334 
2335   /* Find destination in cache. */
2336   if (ip6_addr_cmp(ip6addr, &(destination_cache[nd6_cached_destination_index].destination_addr))) {
2337     dst_idx = nd6_cached_destination_index;
2338     ND6_STATS_INC(nd6.cachehit);
2339   } else {
2340     dst_idx = nd6_find_destination_cache_entry(ip6addr);
2341   }
2342   if (dst_idx < 0) {
2343     return;
2344   }
2345 
2346   /* Find next hop neighbor in cache. */
2347   if (ip6_addr_cmp(&(destination_cache[dst_idx].next_hop_addr), &(neighbor_cache[nd6_cached_neighbor_index].next_hop_address))) {
2348     i = nd6_cached_neighbor_index;
2349     ND6_STATS_INC(nd6.cachehit);
2350   } else {
2351     i = nd6_find_neighbor_cache_entry(&(destination_cache[dst_idx].next_hop_addr));
2352   }
2353   if (i < 0) {
2354     return;
2355   }
2356 
2357   /* For safety: don't set as reachable if we don't have a LL address yet. Misuse protection. */
2358   if (neighbor_cache[i].state == ND6_INCOMPLETE || neighbor_cache[i].state == ND6_NO_ENTRY) {
2359     return;
2360   }
2361 
2362   /* Set reachability state. */
2363   neighbor_cache[i].state = ND6_REACHABLE;
2364   neighbor_cache[i].counter.reachable_time = reachable_time;
2365 }
2366 #endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */
2367 
2368 /**
2369  * Remove all prefix, neighbor_cache and router entries of the specified netif.
2370  *
2371  * @param netif points to a network interface
2372  */
2373 void
nd6_cleanup_netif(struct netif * netif)2374 nd6_cleanup_netif(struct netif *netif)
2375 {
2376   u8_t i;
2377   s8_t router_index;
2378   for (i = 0; i < LWIP_ND6_NUM_PREFIXES; i++) {
2379     if (prefix_list[i].netif == netif) {
2380       prefix_list[i].netif = NULL;
2381     }
2382   }
2383   for (i = 0; i < LWIP_ND6_NUM_NEIGHBORS; i++) {
2384     if (neighbor_cache[i].netif == netif) {
2385       for (router_index = 0; router_index < LWIP_ND6_NUM_ROUTERS; router_index++) {
2386         if (default_router_list[router_index].neighbor_entry == &neighbor_cache[i]) {
2387           default_router_list[router_index].neighbor_entry = NULL;
2388           default_router_list[router_index].flags = 0;
2389         }
2390       }
2391       neighbor_cache[i].isrouter = 0;
2392       nd6_free_neighbor_cache_entry(i);
2393     }
2394   }
2395   /* Clear the destination cache, since many entries may now have become
2396    * invalid for one of several reasons. As destination cache entries have no
2397    * netif association, use a sledgehammer approach (this can be improved). */
2398   nd6_clear_destination_cache();
2399 }
2400 
2401 #if LWIP_IPV6_MLD
2402 /**
2403  * The state of a local IPv6 address entry is about to change. If needed, join
2404  * or leave the solicited-node multicast group for the address.
2405  *
2406  * @param netif The netif that owns the address.
2407  * @param addr_idx The index of the address.
2408  * @param new_state The new (IP6_ADDR_) state for the address.
2409  */
2410 void
nd6_adjust_mld_membership(struct netif * netif,s8_t addr_idx,u8_t new_state)2411 nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state)
2412 {
2413   u8_t old_state, old_member, new_member;
2414 
2415   old_state = netif_ip6_addr_state(netif, addr_idx);
2416 
2417   /* Determine whether we were, and should be, a member of the solicited-node
2418    * multicast group for this address. For tentative addresses, the group is
2419    * not joined until the address enters the TENTATIVE_1 (or VALID) state. */
2420   old_member = (old_state != IP6_ADDR_INVALID && old_state != IP6_ADDR_DUPLICATED && old_state != IP6_ADDR_TENTATIVE);
2421   new_member = (new_state != IP6_ADDR_INVALID && new_state != IP6_ADDR_DUPLICATED && new_state != IP6_ADDR_TENTATIVE);
2422 
2423   if (old_member != new_member) {
2424     ip6_addr_set_solicitednode(&multicast_address, netif_ip6_addr(netif, addr_idx)->addr[3]);
2425     ip6_addr_assign_zone(&multicast_address, IP6_MULTICAST, netif);
2426 
2427     if (new_member) {
2428       mld6_joingroup_netif(netif, &multicast_address);
2429     } else {
2430       mld6_leavegroup_netif(netif, &multicast_address);
2431     }
2432   }
2433 }
2434 #endif /* LWIP_IPV6_MLD */
2435 
2436 /** Netif was added, set up, or reconnected (link up) */
2437 void
nd6_restart_netif(struct netif * netif)2438 nd6_restart_netif(struct netif *netif)
2439 {
2440 #if LWIP_IPV6_SEND_ROUTER_SOLICIT
2441   /* Send Router Solicitation messages (see RFC 4861, ch. 6.3.7). */
2442   netif->rs_count = LWIP_ND6_MAX_MULTICAST_SOLICIT;
2443 #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */
2444 }
2445 
2446 #endif /* LWIP_IPV6 */
2447