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