• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @file
3  *
4  * IPv6 fragmentation and reassembly.
5  */
6 
7 /*
8  * Copyright (c) 2010 Inico Technologies Ltd.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * This file is part of the lwIP TCP/IP stack.
34  *
35  * Author: Ivan Delamer <delamer@inicotech.com>
36  *
37  *
38  * Please coordinate changes and requests with Ivan Delamer
39  * <delamer@inicotech.com>
40  */
41 
42 #include "lwip/opt.h"
43 #include "lwip/ip6_frag.h"
44 #include "lwip/ip6.h"
45 #include "lwip/icmp6.h"
46 #include "lwip/nd6.h"
47 #include "lwip/ip.h"
48 
49 #include "lwip/pbuf.h"
50 #include "lwip/memp.h"
51 #include "lwip/stats.h"
52 
53 #include <string.h>
54 
55 #if LWIP_IPV6 && LWIP_IPV6_REASS  /* don't build if not configured for use in lwipopts.h */
56 
57 
58 /** Setting this to 0, you can turn off checking the fragments for overlapping
59  * regions. The code gets a little smaller. Only use this if you know that
60  * overlapping won't occur on your network! */
61 #ifndef IP_REASS_CHECK_OVERLAP
62 #define IP_REASS_CHECK_OVERLAP 1
63 #endif /* IP_REASS_CHECK_OVERLAP */
64 
65 /** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
66  * full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
67  * Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
68  * is set to 1, so one datagram can be reassembled at a time, only. */
69 #ifndef IP_REASS_FREE_OLDEST
70 #define IP_REASS_FREE_OLDEST 1
71 #endif /* IP_REASS_FREE_OLDEST */
72 
73 #if IPV6_FRAG_COPYHEADER
74 /* The number of bytes we need to "borrow" from (i.e., overwrite in) the header
75  * that precedes the fragment header for reassembly pruposes. */
76 #define IPV6_FRAG_REQROOM ((s16_t)(sizeof(struct ip6_reass_helper) - IP6_FRAG_HLEN))
77 #endif
78 
79 #define IP_REASS_FLAG_LASTFRAG 0x01
80 
81 /** This is a helper struct which holds the starting
82  * offset and the ending offset of this fragment to
83  * easily chain the fragments.
84  * It has the same packing requirements as the IPv6 header, since it replaces
85  * the Fragment Header in memory in incoming fragments to keep
86  * track of the various fragments.
87  */
88 #ifdef PACK_STRUCT_USE_INCLUDES
89 #  include "arch/bpstruct.h"
90 #endif
91 PACK_STRUCT_BEGIN
92 struct ip6_reass_helper {
93   PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
94   PACK_STRUCT_FIELD(u16_t start);
95   PACK_STRUCT_FIELD(u16_t end);
96 } PACK_STRUCT_STRUCT;
97 PACK_STRUCT_END
98 #ifdef PACK_STRUCT_USE_INCLUDES
99 #  include "arch/epstruct.h"
100 #endif
101 
102 /* static variables */
103 static struct ip6_reassdata *reassdatagrams;
104 static u16_t ip6_reass_pbufcount;
105 
106 /* Forward declarations. */
107 static void ip6_reass_free_complete_datagram(struct ip6_reassdata *ipr);
108 #if IP_REASS_FREE_OLDEST
109 static void ip6_reass_remove_oldest_datagram(struct ip6_reassdata *ipr, int pbufs_needed);
110 #endif /* IP_REASS_FREE_OLDEST */
111 
112 void
ip6_reass_tmr(void)113 ip6_reass_tmr(void)
114 {
115   struct ip6_reassdata *r, *tmp;
116 
117 #if !IPV6_FRAG_COPYHEADER
118   LWIP_ASSERT("sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN, set IPV6_FRAG_COPYHEADER to 1",
119     sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN);
120 #endif /* !IPV6_FRAG_COPYHEADER */
121 
122   r = reassdatagrams;
123   while (r != NULL) {
124     /* Decrement the timer. Once it reaches 0,
125      * clean up the incomplete fragment assembly */
126     if (r->timer > 0) {
127       r->timer--;
128       r = r->next;
129     } else {
130       /* reassembly timed out */
131       tmp = r;
132       /* get the next pointer before freeing */
133       r = r->next;
134       /* free the helper struct and all enqueued pbufs */
135       ip6_reass_free_complete_datagram(tmp);
136      }
137    }
138 }
139 
140 #if LWIP_LOWPOWER
141 #include "lwip/lowpower.h"
142 u32_t
ip6_reass_tmr_tick(void)143 ip6_reass_tmr_tick(void)
144 {
145   u32_t tick = 0;
146   u32_t val = 0;
147   struct ip6_reassdata *r = NULL;
148 
149   r = reassdatagrams;
150   while (r != NULL) {
151     val = r->timer + 1;
152     SET_TMR_TICK(tick, val);
153     r = r->next;
154   }
155   LWIP_DEBUGF(LOWPOWER_DEBUG, ("%s tmr tick: %u\n", "ip6_reass_tmr_tick", tick));
156   return tick;
157 }
158 #endif /* LWIP_LOWPOWER */
159 
160 /**
161  * Free a datagram (struct ip6_reassdata) and all its pbufs.
162  * Updates the total count of enqueued pbufs (ip6_reass_pbufcount),
163  * sends an ICMP time exceeded packet.
164  *
165  * @param ipr datagram to free
166  */
167 static void
ip6_reass_free_complete_datagram(struct ip6_reassdata * ipr)168 ip6_reass_free_complete_datagram(struct ip6_reassdata *ipr)
169 {
170   struct ip6_reassdata *prev;
171   u16_t pbufs_freed = 0;
172   u16_t clen;
173   struct pbuf *p;
174   struct ip6_reass_helper *iprh;
175 
176 #if LWIP_ICMP6
177   iprh = (struct ip6_reass_helper *)ipr->p->payload;
178   if (iprh->start == 0) {
179     /* The first fragment was received, send ICMP time exceeded. */
180     /* First, de-queue the first pbuf from r->p. */
181     p = ipr->p;
182     ipr->p = iprh->next_pbuf;
183     /* Restore the part that we've overwritten with our helper structure, or we
184      * might send garbage (and disclose a pointer) in the ICMPv6 reply. */
185     MEMCPY(p->payload, ipr->orig_hdr, sizeof(iprh));
186     /* Then, move back to the original ipv6 header (we are now pointing to Fragment header).
187        This cannot fail since we already checked when receiving this fragment. */
188     if (pbuf_header_force(p, (s16_t)((u8_t*)p->payload - (u8_t*)ipr->iphdr))) {
189       LWIP_ASSERT("ip6_reass_free: moving p->payload to ip6 header failed\n", 0);
190     }
191     else {
192       /* Reconstruct the zoned source and destination addresses, so that we do
193        * not end up sending the ICMP response over the wrong link. */
194       ip6_addr_t src_addr, dest_addr;
195       ip6_addr_copy_from_packed(src_addr, IPV6_FRAG_SRC(ipr));
196       ip6_addr_set_zone(&src_addr, ipr->src_zone);
197       ip6_addr_copy_from_packed(dest_addr, IPV6_FRAG_DEST(ipr));
198       ip6_addr_set_zone(&dest_addr, ipr->dest_zone);
199       /* Send the actual ICMP response. */
200       icmp6_time_exceeded_with_addrs(p, ICMP6_TE_FRAG, &src_addr, &dest_addr);
201     }
202     clen = pbuf_clen(p);
203     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
204     pbufs_freed = (u16_t)(pbufs_freed + clen);
205     pbuf_free(p);
206   }
207 #endif /* LWIP_ICMP6 */
208 
209   /* First, free all received pbufs.  The individual pbufs need to be released
210      separately as they have not yet been chained */
211   p = ipr->p;
212   while (p != NULL) {
213     struct pbuf *pcur;
214     iprh = (struct ip6_reass_helper *)p->payload;
215     pcur = p;
216     /* get the next pointer before freeing */
217     p = iprh->next_pbuf;
218     clen = pbuf_clen(pcur);
219     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
220     pbufs_freed = (u16_t)(pbufs_freed + clen);
221     pbuf_free(pcur);
222   }
223 
224   /* Then, unchain the struct ip6_reassdata from the list and free it. */
225   if (ipr == reassdatagrams) {
226     reassdatagrams = ipr->next;
227   } else {
228     prev = reassdatagrams;
229     while (prev != NULL) {
230       if (prev->next == ipr) {
231         break;
232       }
233       prev = prev->next;
234     }
235     if (prev != NULL) {
236       prev->next = ipr->next;
237     }
238   }
239   memp_free(MEMP_IP6_REASSDATA, ipr);
240 
241   /* Finally, update number of pbufs in reassembly queue */
242   LWIP_ASSERT("ip_reass_pbufcount >= clen", ip6_reass_pbufcount >= pbufs_freed);
243   ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount - pbufs_freed);
244 }
245 
246 #if IP_REASS_FREE_OLDEST
247 /**
248  * Free the oldest datagram to make room for enqueueing new fragments.
249  * The datagram ipr is not freed!
250  *
251  * @param ipr ip6_reassdata for the current fragment
252  * @param pbufs_needed number of pbufs needed to enqueue
253  *        (used for freeing other datagrams if not enough space)
254  */
255 static void
ip6_reass_remove_oldest_datagram(struct ip6_reassdata * ipr,int pbufs_needed)256 ip6_reass_remove_oldest_datagram(struct ip6_reassdata *ipr, int pbufs_needed)
257 {
258   struct ip6_reassdata *r, *oldest;
259 
260   /* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
261    * but don't free the current datagram! */
262   do {
263     r = oldest = reassdatagrams;
264     while (r != NULL) {
265       if (r != ipr) {
266         if (r->timer <= oldest->timer) {
267           /* older than the previous oldest */
268           oldest = r;
269         }
270       }
271       r = r->next;
272     }
273     if (oldest == ipr) {
274       /* nothing to free, ipr is the only element on the list */
275       return;
276     }
277     if (oldest != NULL) {
278       ip6_reass_free_complete_datagram(oldest);
279     }
280   } while (((ip6_reass_pbufcount + pbufs_needed) > IP_REASS_MAX_PBUFS) && (reassdatagrams != NULL));
281 }
282 #endif /* IP_REASS_FREE_OLDEST */
283 
284 /**
285  * Reassembles incoming IPv6 fragments into an IPv6 datagram.
286  *
287  * @param p points to the IPv6 Fragment Header
288  * @return NULL if reassembly is incomplete, pbuf pointing to
289  *         IPv6 Header if reassembly is complete
290  */
291 struct pbuf *
ip6_reass(struct pbuf * p)292 ip6_reass(struct pbuf *p)
293 {
294   struct ip6_reassdata *ipr, *ipr_prev;
295   struct ip6_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
296   struct ip6_frag_hdr *frag_hdr;
297   u16_t offset, len, start, end;
298   ptrdiff_t hdrdiff;
299   u16_t clen;
300   u8_t valid = 1;
301   struct pbuf *q, *next_pbuf;
302 
303   IP6_FRAG_STATS_INC(ip6_frag.recv);
304 
305   /* ip6_frag_hdr must be in the first pbuf, not chained. Checked by caller. */
306   LWIP_ASSERT("IPv6 fragment header does not fit in first pbuf",
307     p->len >= sizeof(struct ip6_frag_hdr));
308 
309   frag_hdr = (struct ip6_frag_hdr *) p->payload;
310 
311   clen = pbuf_clen(p);
312 
313   offset = lwip_ntohs(frag_hdr->_fragment_offset);
314 
315   /* Calculate fragment length from IPv6 payload length.
316    * Adjust for headers before Fragment Header.
317    * And finally adjust by Fragment Header length. */
318   len = lwip_ntohs(ip6_current_header()->_plen);
319   hdrdiff = (u8_t*)p->payload - (const u8_t*)ip6_current_header();
320   LWIP_ASSERT("not a valid pbuf (ip6_input check missing?)", hdrdiff <= 0xFFFF);
321   LWIP_ASSERT("not a valid pbuf (ip6_input check missing?)", hdrdiff >= IP6_HLEN);
322   hdrdiff -= IP6_HLEN;
323   hdrdiff += IP6_FRAG_HLEN;
324   if (hdrdiff > len) {
325     IP6_FRAG_STATS_INC(ip6_frag.proterr);
326     goto nullreturn;
327   }
328   len = (u16_t)(len - hdrdiff);
329   start = (offset & IP6_FRAG_OFFSET_MASK);
330   if (start > (0xFFFF - len)) {
331     /* u16_t overflow, cannot handle this */
332     IP6_FRAG_STATS_INC(ip6_frag.proterr);
333     goto nullreturn;
334   }
335 
336   /* Look for the datagram the fragment belongs to in the current datagram queue,
337    * remembering the previous in the queue for later dequeueing. */
338   for (ipr = reassdatagrams, ipr_prev = NULL; ipr != NULL; ipr = ipr->next) {
339     /* Check if the incoming fragment matches the one currently present
340        in the reassembly buffer. If so, we proceed with copying the
341        fragment into the buffer. */
342     if ((frag_hdr->_identification == ipr->identification) &&
343         ip6_addr_cmp_packed(ip6_current_src_addr(), &(IPV6_FRAG_SRC(ipr)), ipr->src_zone) &&
344         ip6_addr_cmp_packed(ip6_current_dest_addr(), &(IPV6_FRAG_DEST(ipr)), ipr->dest_zone)) {
345       IP6_FRAG_STATS_INC(ip6_frag.cachehit);
346       break;
347     }
348     ipr_prev = ipr;
349   }
350 
351   if (ipr == NULL) {
352   /* Enqueue a new datagram into the datagram queue */
353     ipr = (struct ip6_reassdata *)memp_malloc(MEMP_IP6_REASSDATA);
354     if (ipr == NULL) {
355 #if IP_REASS_FREE_OLDEST
356       /* Make room and try again. */
357       ip6_reass_remove_oldest_datagram(ipr, clen);
358       ipr = (struct ip6_reassdata *)memp_malloc(MEMP_IP6_REASSDATA);
359       if (ipr != NULL) {
360         /* re-search ipr_prev since it might have been removed */
361         for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
362           if (ipr_prev->next == ipr) {
363             break;
364           }
365         }
366       } else
367 #endif /* IP_REASS_FREE_OLDEST */
368       {
369         IP6_FRAG_STATS_INC(ip6_frag.memerr);
370         goto nullreturn;
371       }
372     }
373 
374     memset(ipr, 0, sizeof(struct ip6_reassdata));
375     ipr->timer = IPV6_REASS_MAXAGE;
376 
377     /* enqueue the new structure to the front of the list */
378     ipr->next = reassdatagrams;
379     reassdatagrams = ipr;
380 
381     /* Use the current IPv6 header for src/dest address reference.
382      * Eventually, we will replace it when we get the first fragment
383      * (it might be this one, in any case, it is done later). */
384     /* need to use the none-const pointer here: */
385     ipr->iphdr = ip_data.current_ip6_header;
386 #if IPV6_FRAG_COPYHEADER
387     MEMCPY(&ipr->src, &ip6_current_header()->src, sizeof(ipr->src));
388     MEMCPY(&ipr->dest, &ip6_current_header()->dest, sizeof(ipr->dest));
389 #endif /* IPV6_FRAG_COPYHEADER */
390 #if LWIP_IPV6_SCOPES
391     /* Also store the address zone information.
392      * @todo It is possible that due to netif destruction and recreation, the
393      * stored zones end up resolving to a different interface. In that case, we
394      * risk sending a "time exceeded" ICMP response over the wrong link.
395      * Ideally, netif destruction would clean up matching pending reassembly
396      * structures, but custom zone mappings would make that non-trivial. */
397     ipr->src_zone = ip6_addr_zone(ip6_current_src_addr());
398     ipr->dest_zone = ip6_addr_zone(ip6_current_dest_addr());
399 #endif /* LWIP_IPV6_SCOPES */
400     /* copy the fragmented packet id. */
401     ipr->identification = frag_hdr->_identification;
402 
403     /* copy the nexth field */
404     ipr->nexth = frag_hdr->_nexth;
405   }
406 
407   /* Check if we are allowed to enqueue more datagrams. */
408   if ((ip6_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
409 #if IP_REASS_FREE_OLDEST
410     ip6_reass_remove_oldest_datagram(ipr, clen);
411     if ((ip6_reass_pbufcount + clen) <= IP_REASS_MAX_PBUFS) {
412       /* re-search ipr_prev since it might have been removed */
413       for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
414         if (ipr_prev->next == ipr) {
415           break;
416         }
417       }
418     } else
419 #endif /* IP_REASS_FREE_OLDEST */
420     {
421       /* @todo: send ICMPv6 time exceeded here? */
422       /* drop this pbuf */
423       IP6_FRAG_STATS_INC(ip6_frag.memerr);
424       goto nullreturn;
425     }
426   }
427 
428   /* Overwrite Fragment Header with our own helper struct. */
429 #if IPV6_FRAG_COPYHEADER
430   if (IPV6_FRAG_REQROOM > 0) {
431     /* Make room for struct ip6_reass_helper (only required if sizeof(void*) > 4).
432        This cannot fail since we already checked when receiving this fragment. */
433     u8_t hdrerr = pbuf_header_force(p, IPV6_FRAG_REQROOM);
434     LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
435     LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
436   }
437 #else /* IPV6_FRAG_COPYHEADER */
438   LWIP_ASSERT("sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN, set IPV6_FRAG_COPYHEADER to 1",
439     sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN);
440 #endif /* IPV6_FRAG_COPYHEADER */
441 
442   /* Prepare the pointer to the helper structure, and its initial values.
443    * Do not yet write to the structure itself, as we still have to make a
444    * backup of the original data, and we should not do that until we know for
445    * sure that we are going to add this packet to the list. */
446   iprh = (struct ip6_reass_helper *)p->payload;
447   next_pbuf = NULL;
448   end = (u16_t)(start + len);
449 
450   /* find the right place to insert this pbuf */
451   /* Iterate through until we either get to the end of the list (append),
452    * or we find on with a larger offset (insert). */
453   for (q = ipr->p; q != NULL;) {
454     iprh_tmp = (struct ip6_reass_helper*)q->payload;
455     if (start < iprh_tmp->start) {
456 #if IP_REASS_CHECK_OVERLAP
457       if (end > iprh_tmp->start) {
458         /* fragment overlaps with following, throw away */
459         IP6_FRAG_STATS_INC(ip6_frag.proterr);
460         goto nullreturn;
461       }
462       if (iprh_prev != NULL) {
463         if (start < iprh_prev->end) {
464           /* fragment overlaps with previous, throw away */
465           IP6_FRAG_STATS_INC(ip6_frag.proterr);
466           goto nullreturn;
467         }
468       }
469 #endif /* IP_REASS_CHECK_OVERLAP */
470       /* the new pbuf should be inserted before this */
471       next_pbuf = q;
472       if (iprh_prev != NULL) {
473         /* not the fragment with the lowest offset */
474         iprh_prev->next_pbuf = p;
475       } else {
476         /* fragment with the lowest offset */
477         ipr->p = p;
478       }
479       break;
480     } else if (start == iprh_tmp->start) {
481       /* received the same datagram twice: no need to keep the datagram */
482       goto nullreturn;
483 #if IP_REASS_CHECK_OVERLAP
484     } else if (start < iprh_tmp->end) {
485       /* overlap: no need to keep the new datagram */
486       IP6_FRAG_STATS_INC(ip6_frag.proterr);
487       goto nullreturn;
488 #endif /* IP_REASS_CHECK_OVERLAP */
489     } else {
490       /* Check if the fragments received so far have no gaps. */
491       if (iprh_prev != NULL) {
492         if (iprh_prev->end != iprh_tmp->start) {
493           /* There is a fragment missing between the current
494            * and the previous fragment */
495           valid = 0;
496         }
497       }
498     }
499     q = iprh_tmp->next_pbuf;
500     iprh_prev = iprh_tmp;
501   }
502 
503   /* If q is NULL, then we made it to the end of the list. Determine what to do now */
504   if (q == NULL) {
505     if (iprh_prev != NULL) {
506       /* this is (for now), the fragment with the highest offset:
507        * chain it to the last fragment */
508 #if IP_REASS_CHECK_OVERLAP
509       LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= start);
510 #endif /* IP_REASS_CHECK_OVERLAP */
511       iprh_prev->next_pbuf = p;
512       if (iprh_prev->end != start) {
513         valid = 0;
514       }
515     } else {
516 #if IP_REASS_CHECK_OVERLAP
517       LWIP_ASSERT("no previous fragment, this must be the first fragment!",
518         ipr->p == NULL);
519 #endif /* IP_REASS_CHECK_OVERLAP */
520       /* this is the first fragment we ever received for this ip datagram */
521       ipr->p = p;
522     }
523   }
524 
525   /* Track the current number of pbufs current 'in-flight', in order to limit
526   the number of fragments that may be enqueued at any one time */
527   ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount + clen);
528 
529   /* Remember IPv6 header if this is the first fragment. */
530   if (start == 0) {
531     /* need to use the none-const pointer here: */
532     ipr->iphdr = ip_data.current_ip6_header;
533     /* Make a backup of the part of the packet data that we are about to
534      * overwrite, so that we can restore the original later. */
535     MEMCPY(ipr->orig_hdr, p->payload, sizeof(*iprh));
536     /* For IPV6_FRAG_COPYHEADER there is no need to copy src/dst again, as they
537      * will be the same as they were. With LWIP_IPV6_SCOPES, the same applies
538      * to the source/destination zones. */
539   }
540   /* Only after the backup do we get to fill in the actual helper structure. */
541   iprh->next_pbuf = next_pbuf;
542   iprh->start = start;
543   iprh->end = end;
544 
545   /* If this is the last fragment, calculate total packet length. */
546   if ((offset & IP6_FRAG_MORE_FLAG) == 0) {
547     ipr->datagram_len = iprh->end;
548   }
549 
550   /* Additional validity tests: we have received first and last fragment. */
551   iprh_tmp = (struct ip6_reass_helper*)ipr->p->payload;
552   if (iprh_tmp->start != 0) {
553     valid = 0;
554   }
555   if (ipr->datagram_len == 0) {
556     valid = 0;
557   }
558 
559   /* Final validity test: no gaps between current and last fragment. */
560   iprh_prev = iprh;
561   q = iprh->next_pbuf;
562   while ((q != NULL) && valid) {
563     iprh = (struct ip6_reass_helper*)q->payload;
564     if (iprh_prev->end != iprh->start) {
565       valid = 0;
566       break;
567     }
568     iprh_prev = iprh;
569     q = iprh->next_pbuf;
570   }
571 
572   if (valid) {
573     /* All fragments have been received */
574     struct ip6_hdr* iphdr_ptr;
575 
576     /* chain together the pbufs contained within the ip6_reassdata list. */
577     iprh = (struct ip6_reass_helper*) ipr->p->payload;
578     while (iprh != NULL) {
579       next_pbuf = iprh->next_pbuf;
580       if (next_pbuf != NULL) {
581         /* Save next helper struct (will be hidden in next step). */
582         iprh_tmp = (struct ip6_reass_helper*)next_pbuf->payload;
583 
584         /* hide the fragment header for every succeeding fragment */
585         pbuf_remove_header(next_pbuf, IP6_FRAG_HLEN);
586 #if IPV6_FRAG_COPYHEADER
587         if (IPV6_FRAG_REQROOM > 0) {
588           /* hide the extra bytes borrowed from ip6_hdr for struct ip6_reass_helper */
589           u8_t hdrerr = pbuf_remove_header(next_pbuf, IPV6_FRAG_REQROOM);
590           LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
591           LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
592         }
593 #endif
594         pbuf_cat(ipr->p, next_pbuf);
595       }
596       else {
597         iprh_tmp = NULL;
598       }
599 
600       iprh = iprh_tmp;
601     }
602 
603     /* Get the first pbuf. */
604     p = ipr->p;
605 
606 #if IPV6_FRAG_COPYHEADER
607     if (IPV6_FRAG_REQROOM > 0) {
608       u8_t hdrerr;
609       /* Restore (only) the bytes that we overwrote beyond the fragment header.
610        * Those bytes may belong to either the IPv6 header or an extension
611        * header placed before the fragment header. */
612       MEMCPY(p->payload, ipr->orig_hdr, IPV6_FRAG_REQROOM);
613       /* get back room for struct ip6_reass_helper (only required if sizeof(void*) > 4) */
614       hdrerr = pbuf_remove_header(p, IPV6_FRAG_REQROOM);
615       LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
616       LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
617     }
618 #endif
619 
620     /* We need to get rid of the fragment header itself, which is somewhere in
621      * the middle of the packet (but still in the first pbuf of the chain).
622      * Getting rid of the header is required by RFC 2460 Sec. 4.5 and necessary
623      * in order to be able to reassemble packets that are close to full size
624      * (i.e., around 65535 bytes). We simply move up all the headers before the
625      * fragment header, including the IPv6 header, and adjust the payload start
626      * accordingly. This works because all these headers are in the first pbuf
627      * of the chain, and because the caller adjusts all its pointers on
628      * successful reassembly. */
629     MEMMOVE((u8_t*)ipr->iphdr + sizeof(struct ip6_frag_hdr), ipr->iphdr,
630       (size_t)((u8_t*)p->payload - (u8_t*)ipr->iphdr));
631 
632     /* This is where the IPv6 header is now. */
633     iphdr_ptr = (struct ip6_hdr*)((u8_t*)ipr->iphdr +
634       sizeof(struct ip6_frag_hdr));
635 
636     /* Adjust datagram length by adding header lengths. */
637     ipr->datagram_len = (u16_t)(ipr->datagram_len + ((u8_t*)p->payload - (u8_t*)iphdr_ptr)
638                          - IP6_HLEN);
639 
640     /* Set payload length in ip header. */
641     iphdr_ptr->_plen = lwip_htons(ipr->datagram_len);
642 
643     /* With the fragment header gone, we now need to adjust the next-header
644      * field of whatever header was originally before it. Since the packet made
645      * it through the original header processing routines at least up to the
646      * fragment header, we do not need any further sanity checks here. */
647     if (IP6H_NEXTH(iphdr_ptr) == IP6_NEXTH_FRAGMENT) {
648       iphdr_ptr->_nexth = ipr->nexth;
649     } else {
650       u8_t *ptr = (u8_t *)iphdr_ptr + IP6_HLEN;
651       while (*ptr != IP6_NEXTH_FRAGMENT) {
652         ptr += 8 * (1 + ptr[1]);
653       }
654       *ptr = ipr->nexth;
655     }
656 
657     /* release the resources allocated for the fragment queue entry */
658     if (reassdatagrams == ipr) {
659       /* it was the first in the list */
660       reassdatagrams = ipr->next;
661     } else {
662       /* it wasn't the first, so it must have a valid 'prev' */
663       LWIP_ASSERT("sanity check linked list", ipr_prev != NULL);
664       ipr_prev->next = ipr->next;
665     }
666     memp_free(MEMP_IP6_REASSDATA, ipr);
667 
668     /* adjust the number of pbufs currently queued for reassembly. */
669     clen = pbuf_clen(p);
670     LWIP_ASSERT("ip6_reass_pbufcount >= clen", ip6_reass_pbufcount >= clen);
671     ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount - clen);
672 
673     /* Move pbuf back to IPv6 header. This should never fail. */
674     if (pbuf_header_force(p, (s16_t)((u8_t*)p->payload - (u8_t*)iphdr_ptr))) {
675       LWIP_ASSERT("ip6_reass: moving p->payload to ip6 header failed\n", 0);
676       pbuf_free(p);
677       return NULL;
678     }
679 
680     /* Return the pbuf chain */
681     return p;
682   }
683   /* the datagram is not (yet?) reassembled completely */
684   return NULL;
685 
686 nullreturn:
687   IP6_FRAG_STATS_INC(ip6_frag.drop);
688   pbuf_free(p);
689   return NULL;
690 }
691 
692 #endif /* LWIP_IPV6 && LWIP_IPV6_REASS */
693 
694 #if LWIP_IPV6 && LWIP_IPV6_FRAG
695 
696 #if !LWIP_NETIF_TX_SINGLE_PBUF
697 /** Allocate a new struct pbuf_custom_ref */
698 static struct pbuf_custom_ref*
ip6_frag_alloc_pbuf_custom_ref(void)699 ip6_frag_alloc_pbuf_custom_ref(void)
700 {
701   return (struct pbuf_custom_ref*)memp_malloc(MEMP_FRAG_PBUF);
702 }
703 
704 /** Free a struct pbuf_custom_ref */
705 static void
ip6_frag_free_pbuf_custom_ref(struct pbuf_custom_ref * p)706 ip6_frag_free_pbuf_custom_ref(struct pbuf_custom_ref* p)
707 {
708   LWIP_ASSERT("p != NULL", p != NULL);
709   memp_free(MEMP_FRAG_PBUF, p);
710 }
711 
712 /** Free-callback function to free a 'struct pbuf_custom_ref', called by
713  * pbuf_free. */
714 static void
ip6_frag_free_pbuf_custom(struct pbuf * p)715 ip6_frag_free_pbuf_custom(struct pbuf *p)
716 {
717   struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref*)p;
718   LWIP_ASSERT("pcr != NULL", pcr != NULL);
719   LWIP_ASSERT("pcr == p", (void*)pcr == (void*)p);
720   if (pcr->original != NULL) {
721     pbuf_free(pcr->original);
722   }
723   ip6_frag_free_pbuf_custom_ref(pcr);
724 }
725 #endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
726 
727 /**
728  * Fragment an IPv6 datagram if too large for the netif or path MTU.
729  *
730  * Chop the datagram in MTU sized chunks and send them in order
731  * by pointing PBUF_REFs into p
732  *
733  * @param p ipv6 packet to send
734  * @param netif the netif on which to send
735  * @param dest destination ipv6 address to which to send
736  *
737  * @return ERR_OK if sent successfully, err_t otherwise
738  */
739 err_t
ip6_frag(struct pbuf * p,struct netif * netif,const ip6_addr_t * dest)740 ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
741 {
742   struct ip6_hdr *original_ip6hdr;
743   struct ip6_hdr *ip6hdr;
744   struct ip6_frag_hdr *frag_hdr;
745   struct pbuf *rambuf;
746 #if !LWIP_NETIF_TX_SINGLE_PBUF
747   struct pbuf *newpbuf;
748   u16_t newpbuflen = 0;
749   u16_t left_to_copy;
750 #endif
751   static u32_t identification;
752   u16_t left, cop;
753   const u16_t mtu = nd6_get_destination_mtu(dest, netif);
754   const u16_t nfb = (u16_t)((mtu - (IP6_HLEN + IP6_FRAG_HLEN)) & IP6_FRAG_OFFSET_MASK);
755   u16_t fragment_offset = 0;
756   u16_t last;
757   u16_t poff = IP6_HLEN;
758 
759   identification++;
760 
761   original_ip6hdr = (struct ip6_hdr *)p->payload;
762 
763   /* @todo we assume there are no options in the unfragmentable part (IPv6 header). */
764   LWIP_ASSERT("p->tot_len >= IP6_HLEN", p->tot_len >= IP6_HLEN);
765   left = (u16_t)(p->tot_len - IP6_HLEN);
766 
767   while (left) {
768     last = (left <= nfb);
769 
770     /* Fill this fragment */
771     cop = last ? left : nfb;
772 
773 #if LWIP_NETIF_TX_SINGLE_PBUF
774     rambuf = pbuf_alloc(PBUF_IP, cop + IP6_FRAG_HLEN, PBUF_RAM);
775     if (rambuf == NULL) {
776       IP6_FRAG_STATS_INC(ip6_frag.memerr);
777       return ERR_MEM;
778     }
779     LWIP_ASSERT("this needs a pbuf in one piece!",
780       (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
781     poff += pbuf_copy_partial(p, (u8_t*)rambuf->payload + IP6_FRAG_HLEN, cop, poff);
782     /* make room for the IP header */
783     if (pbuf_add_header(rambuf, IP6_HLEN)) {
784       pbuf_free(rambuf);
785       IP6_FRAG_STATS_INC(ip6_frag.memerr);
786       return ERR_MEM;
787     }
788     /* fill in the IP header */
789     SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
790     ip6hdr = (struct ip6_hdr *)rambuf->payload;
791     frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
792 #else
793     /* When not using a static buffer, create a chain of pbufs.
794      * The first will be a PBUF_RAM holding the link, IPv6, and Fragment header.
795      * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
796      * but limited to the size of an mtu.
797      */
798     rambuf = pbuf_alloc(PBUF_LINK, IP6_HLEN + IP6_FRAG_HLEN, PBUF_RAM);
799     if (rambuf == NULL) {
800       IP6_FRAG_STATS_INC(ip6_frag.memerr);
801       return ERR_MEM;
802     }
803     LWIP_ASSERT("this needs a pbuf in one piece!",
804                 (rambuf->len >= (IP6_HLEN)));
805     SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
806     ip6hdr = (struct ip6_hdr *)rambuf->payload;
807     frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
808 
809     /* Can just adjust p directly for needed offset. */
810     p->payload = (u8_t *)p->payload + poff;
811     p->len = (u16_t)(p->len - poff);
812     p->tot_len = (u16_t)(p->tot_len - poff);
813 
814     left_to_copy = cop;
815     while (left_to_copy) {
816       struct pbuf_custom_ref *pcr;
817       newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
818       /* Is this pbuf already empty? */
819       if (!newpbuflen) {
820         p = p->next;
821         continue;
822       }
823       pcr = ip6_frag_alloc_pbuf_custom_ref();
824       if (pcr == NULL) {
825         pbuf_free(rambuf);
826         IP6_FRAG_STATS_INC(ip6_frag.memerr);
827         return ERR_MEM;
828       }
829       /* Mirror this pbuf, although we might not need all of it. */
830       newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen);
831       if (newpbuf == NULL) {
832         ip6_frag_free_pbuf_custom_ref(pcr);
833         pbuf_free(rambuf);
834         IP6_FRAG_STATS_INC(ip6_frag.memerr);
835         return ERR_MEM;
836       }
837       pbuf_ref(p);
838       pcr->original = p;
839       pcr->pc.custom_free_function = ip6_frag_free_pbuf_custom;
840 
841       /* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
842        * so that it is removed when pbuf_dechain is later called on rambuf.
843        */
844       pbuf_cat(rambuf, newpbuf);
845       left_to_copy = (u16_t)(left_to_copy - newpbuflen);
846       if (left_to_copy) {
847         p = p->next;
848       }
849     }
850     poff = newpbuflen;
851 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
852 
853     /* Set headers */
854     frag_hdr->_nexth = original_ip6hdr->_nexth;
855     frag_hdr->reserved = 0;
856     frag_hdr->_fragment_offset = lwip_htons((u16_t)((fragment_offset & IP6_FRAG_OFFSET_MASK) | (last ? 0 : IP6_FRAG_MORE_FLAG)));
857     frag_hdr->_identification = lwip_htonl(identification);
858 
859     IP6H_NEXTH_SET(ip6hdr, IP6_NEXTH_FRAGMENT);
860     IP6H_PLEN_SET(ip6hdr, (u16_t)(cop + IP6_FRAG_HLEN));
861 
862     /* No need for separate header pbuf - we allowed room for it in rambuf
863      * when allocated.
864      */
865     IP6_FRAG_STATS_INC(ip6_frag.xmit);
866     netif->output_ip6(netif, rambuf, dest);
867 
868     /* Unfortunately we can't reuse rambuf - the hardware may still be
869      * using the buffer. Instead we free it (and the ensuing chain) and
870      * recreate it next time round the loop. If we're lucky the hardware
871      * will have already sent the packet, the free will really free, and
872      * there will be zero memory penalty.
873      */
874 
875     pbuf_free(rambuf);
876     left = (u16_t)(left - cop);
877     fragment_offset = (u16_t)(fragment_offset + cop);
878   }
879   return ERR_OK;
880 }
881 
882 #endif /* LWIP_IPV6 && LWIP_IPV6_FRAG */
883