]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/lwip/lib/contrib/src/core/ipv4/ip_frag.c
Update
[l4.git] / l4 / pkg / lwip / lib / contrib / src / core / ipv4 / ip_frag.c
1 /**
2  * @file
3  * This is the IPv4 packet segmentation and reassembly implementation.
4  *
5  */
6
7 /*
8  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
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: Jani Monoses <jani@iv.ro>
36  *         Simon Goldschmidt
37  * original reassembly code by Adam Dunkels <adam@sics.se>
38  *
39  */
40
41 #include "lwip/opt.h"
42
43 #if LWIP_IPV4
44
45 #include "lwip/ip_frag.h"
46 #include "lwip/def.h"
47 #include "lwip/inet_chksum.h"
48 #include "lwip/netif.h"
49 #include "lwip/stats.h"
50 #include "lwip/icmp.h"
51
52 #include <string.h>
53
54 #if IP_REASSEMBLY
55 /**
56  * The IP reassembly code currently has the following limitations:
57  * - IP header options are not supported
58  * - fragments must not overlap (e.g. due to different routes),
59  *   currently, overlapping or duplicate fragments are thrown away
60  *   if IP_REASS_CHECK_OVERLAP=1 (the default)!
61  *
62  * @todo: work with IP header options
63  */
64
65 /** Setting this to 0, you can turn off checking the fragments for overlapping
66  * regions. The code gets a little smaller. Only use this if you know that
67  * overlapping won't occur on your network! */
68 #ifndef IP_REASS_CHECK_OVERLAP
69 #define IP_REASS_CHECK_OVERLAP 1
70 #endif /* IP_REASS_CHECK_OVERLAP */
71
72 /** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
73  * full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
74  * Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
75  * is set to 1, so one datagram can be reassembled at a time, only. */
76 #ifndef IP_REASS_FREE_OLDEST
77 #define IP_REASS_FREE_OLDEST 1
78 #endif /* IP_REASS_FREE_OLDEST */
79
80 #define IP_REASS_FLAG_LASTFRAG 0x01
81
82 /** This is a helper struct which holds the starting
83  * offset and the ending offset of this fragment to
84  * easily chain the fragments.
85  * It has the same packing requirements as the IP header, since it replaces
86  * the IP header in memory in incoming fragments (after copying it) to keep
87  * track of the various fragments. (-> If the IP header doesn't need packing,
88  * this struct doesn't need packing, too.)
89  */
90 #ifdef PACK_STRUCT_USE_INCLUDES
91 #  include "arch/bpstruct.h"
92 #endif
93 PACK_STRUCT_BEGIN
94 struct ip_reass_helper {
95   PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
96   PACK_STRUCT_FIELD(u16_t start);
97   PACK_STRUCT_FIELD(u16_t end);
98 } PACK_STRUCT_STRUCT;
99 PACK_STRUCT_END
100 #ifdef PACK_STRUCT_USE_INCLUDES
101 #  include "arch/epstruct.h"
102 #endif
103
104 #define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB)  \
105   (ip4_addr_cmp(&(iphdrA)->src, &(iphdrB)->src) && \
106    ip4_addr_cmp(&(iphdrA)->dest, &(iphdrB)->dest) && \
107    IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0
108
109 /* global variables */
110 static struct ip_reassdata *reassdatagrams;
111 static u16_t ip_reass_pbufcount;
112
113 /* function prototypes */
114 static void ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
115 static int ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
116
117 /**
118  * Reassembly timer base function
119  * for both NO_SYS == 0 and 1 (!).
120  *
121  * Should be called every 1000 msec (defined by IP_TMR_INTERVAL).
122  */
123 void
124 ip_reass_tmr(void)
125 {
126   struct ip_reassdata *r, *prev = NULL;
127
128   r = reassdatagrams;
129   while (r != NULL) {
130     /* Decrement the timer. Once it reaches 0,
131      * clean up the incomplete fragment assembly */
132     if (r->timer > 0) {
133       r->timer--;
134       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n",(u16_t)r->timer));
135       prev = r;
136       r = r->next;
137     } else {
138       /* reassembly timed out */
139       struct ip_reassdata *tmp;
140       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n"));
141       tmp = r;
142       /* get the next pointer before freeing */
143       r = r->next;
144       /* free the helper struct and all enqueued pbufs */
145       ip_reass_free_complete_datagram(tmp, prev);
146      }
147    }
148 }
149
150 /**
151  * Free a datagram (struct ip_reassdata) and all its pbufs.
152  * Updates the total count of enqueued pbufs (ip_reass_pbufcount),
153  * SNMP counters and sends an ICMP time exceeded packet.
154  *
155  * @param ipr datagram to free
156  * @param prev the previous datagram in the linked list
157  * @return the number of pbufs freed
158  */
159 static int
160 ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
161 {
162   u16_t pbufs_freed = 0;
163   u8_t clen;
164   struct pbuf *p;
165   struct ip_reass_helper *iprh;
166
167   LWIP_ASSERT("prev != ipr", prev != ipr);
168   if (prev != NULL) {
169     LWIP_ASSERT("prev->next == ipr", prev->next == ipr);
170   }
171
172   MIB2_STATS_INC(mib2.ipreasmfails);
173 #if LWIP_ICMP
174   iprh = (struct ip_reass_helper *)ipr->p->payload;
175   if (iprh->start == 0) {
176     /* The first fragment was received, send ICMP time exceeded. */
177     /* First, de-queue the first pbuf from r->p. */
178     p = ipr->p;
179     ipr->p = iprh->next_pbuf;
180     /* Then, copy the original header into it. */
181     SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN);
182     icmp_time_exceeded(p, ICMP_TE_FRAG);
183     clen = pbuf_clen(p);
184     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
185     pbufs_freed += clen;
186     pbuf_free(p);
187   }
188 #endif /* LWIP_ICMP */
189
190   /* First, free all received pbufs.  The individual pbufs need to be released
191      separately as they have not yet been chained */
192   p = ipr->p;
193   while (p != NULL) {
194     struct pbuf *pcur;
195     iprh = (struct ip_reass_helper *)p->payload;
196     pcur = p;
197     /* get the next pointer before freeing */
198     p = iprh->next_pbuf;
199     clen = pbuf_clen(pcur);
200     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
201     pbufs_freed += clen;
202     pbuf_free(pcur);
203   }
204   /* Then, unchain the struct ip_reassdata from the list and free it. */
205   ip_reass_dequeue_datagram(ipr, prev);
206   LWIP_ASSERT("ip_reass_pbufcount >= clen", ip_reass_pbufcount >= pbufs_freed);
207   ip_reass_pbufcount -= pbufs_freed;
208
209   return pbufs_freed;
210 }
211
212 #if IP_REASS_FREE_OLDEST
213 /**
214  * Free the oldest datagram to make room for enqueueing new fragments.
215  * The datagram 'fraghdr' belongs to is not freed!
216  *
217  * @param fraghdr IP header of the current fragment
218  * @param pbufs_needed number of pbufs needed to enqueue
219  *        (used for freeing other datagrams if not enough space)
220  * @return the number of pbufs freed
221  */
222 static int
223 ip_reass_remove_oldest_datagram(struct ip_hdr *fraghdr, int pbufs_needed)
224 {
225   /* @todo Can't we simply remove the last datagram in the
226    *       linked list behind reassdatagrams?
227    */
228   struct ip_reassdata *r, *oldest, *prev, *oldest_prev;
229   int pbufs_freed = 0, pbufs_freed_current;
230   int other_datagrams;
231
232   /* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
233    * but don't free the datagram that 'fraghdr' belongs to! */
234   do {
235     oldest = NULL;
236     prev = NULL;
237     oldest_prev = NULL;
238     other_datagrams = 0;
239     r = reassdatagrams;
240     while (r != NULL) {
241       if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) {
242         /* Not the same datagram as fraghdr */
243         other_datagrams++;
244         if (oldest == NULL) {
245           oldest = r;
246           oldest_prev = prev;
247         } else if (r->timer <= oldest->timer) {
248           /* older than the previous oldest */
249           oldest = r;
250           oldest_prev = prev;
251         }
252       }
253       if (r->next != NULL) {
254         prev = r;
255       }
256       r = r->next;
257     }
258     if (oldest != NULL) {
259       pbufs_freed_current = ip_reass_free_complete_datagram(oldest, oldest_prev);
260       pbufs_freed += pbufs_freed_current;
261     }
262   } while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1));
263   return pbufs_freed;
264 }
265 #endif /* IP_REASS_FREE_OLDEST */
266
267 /**
268  * Enqueues a new fragment into the fragment queue
269  * @param fraghdr points to the new fragments IP hdr
270  * @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space)
271  * @return A pointer to the queue location into which the fragment was enqueued
272  */
273 static struct ip_reassdata*
274 ip_reass_enqueue_new_datagram(struct ip_hdr *fraghdr, int clen)
275 {
276   struct ip_reassdata* ipr;
277   /* No matching previous fragment found, allocate a new reassdata struct */
278   ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
279   if (ipr == NULL) {
280 #if IP_REASS_FREE_OLDEST
281     if (ip_reass_remove_oldest_datagram(fraghdr, clen) >= clen) {
282       ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
283     }
284     if (ipr == NULL)
285 #endif /* IP_REASS_FREE_OLDEST */
286     {
287       IPFRAG_STATS_INC(ip_frag.memerr);
288       LWIP_DEBUGF(IP_REASS_DEBUG,("Failed to alloc reassdata struct\n"));
289       return NULL;
290     }
291   }
292   memset(ipr, 0, sizeof(struct ip_reassdata));
293   ipr->timer = IP_REASS_MAXAGE;
294
295   /* enqueue the new structure to the front of the list */
296   ipr->next = reassdatagrams;
297   reassdatagrams = ipr;
298   /* copy the ip header for later tests and input */
299   /* @todo: no ip options supported? */
300   SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN);
301   return ipr;
302 }
303
304 /**
305  * Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs.
306  * @param ipr points to the queue entry to dequeue
307  */
308 static void
309 ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
310 {
311   /* dequeue the reass struct  */
312   if (reassdatagrams == ipr) {
313     /* it was the first in the list */
314     reassdatagrams = ipr->next;
315   } else {
316     /* it wasn't the first, so it must have a valid 'prev' */
317     LWIP_ASSERT("sanity check linked list", prev != NULL);
318     prev->next = ipr->next;
319   }
320
321   /* now we can free the ip_reassdata struct */
322   memp_free(MEMP_REASSDATA, ipr);
323 }
324
325 /**
326  * Chain a new pbuf into the pbuf list that composes the datagram.  The pbuf list
327  * will grow over time as  new pbufs are rx.
328  * Also checks that the datagram passes basic continuity checks (if the last
329  * fragment was received at least once).
330  * @param root_p points to the 'root' pbuf for the current datagram being assembled.
331  * @param new_p points to the pbuf for the current fragment
332  * @return 0 if invalid, >0 otherwise
333  */
334 static int
335 ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct pbuf *new_p)
336 {
337   struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
338   struct pbuf *q;
339   u16_t offset,len;
340   struct ip_hdr *fraghdr;
341   int valid = 1;
342
343   /* Extract length and fragment offset from current fragment */
344   fraghdr = (struct ip_hdr*)new_p->payload;
345   len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
346   offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
347
348   /* overwrite the fragment's ip header from the pbuf with our helper struct,
349    * and setup the embedded helper structure. */
350   /* make sure the struct ip_reass_helper fits into the IP header */
351   LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN",
352               sizeof(struct ip_reass_helper) <= IP_HLEN);
353   iprh = (struct ip_reass_helper*)new_p->payload;
354   iprh->next_pbuf = NULL;
355   iprh->start = offset;
356   iprh->end = offset + len;
357
358   /* Iterate through until we either get to the end of the list (append),
359    * or we find on with a larger offset (insert). */
360   for (q = ipr->p; q != NULL;) {
361     iprh_tmp = (struct ip_reass_helper*)q->payload;
362     if (iprh->start < iprh_tmp->start) {
363       /* the new pbuf should be inserted before this */
364       iprh->next_pbuf = q;
365       if (iprh_prev != NULL) {
366         /* not the fragment with the lowest offset */
367 #if IP_REASS_CHECK_OVERLAP
368         if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) {
369           /* fragment overlaps with previous or following, throw away */
370           goto freepbuf;
371         }
372 #endif /* IP_REASS_CHECK_OVERLAP */
373         iprh_prev->next_pbuf = new_p;
374       } else {
375         /* fragment with the lowest offset */
376         ipr->p = new_p;
377       }
378       break;
379     } else if (iprh->start == iprh_tmp->start) {
380       /* received the same datagram twice: no need to keep the datagram */
381       goto freepbuf;
382 #if IP_REASS_CHECK_OVERLAP
383     } else if (iprh->start < iprh_tmp->end) {
384       /* overlap: no need to keep the new datagram */
385       goto freepbuf;
386 #endif /* IP_REASS_CHECK_OVERLAP */
387     } else {
388       /* Check if the fragments received so far have no wholes. */
389       if (iprh_prev != NULL) {
390         if (iprh_prev->end != iprh_tmp->start) {
391           /* There is a fragment missing between the current
392            * and the previous fragment */
393           valid = 0;
394         }
395       }
396     }
397     q = iprh_tmp->next_pbuf;
398     iprh_prev = iprh_tmp;
399   }
400
401   /* If q is NULL, then we made it to the end of the list. Determine what to do now */
402   if (q == NULL) {
403     if (iprh_prev != NULL) {
404       /* this is (for now), the fragment with the highest offset:
405        * chain it to the last fragment */
406 #if IP_REASS_CHECK_OVERLAP
407       LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start);
408 #endif /* IP_REASS_CHECK_OVERLAP */
409       iprh_prev->next_pbuf = new_p;
410       if (iprh_prev->end != iprh->start) {
411         valid = 0;
412       }
413     } else {
414 #if IP_REASS_CHECK_OVERLAP
415       LWIP_ASSERT("no previous fragment, this must be the first fragment!",
416         ipr->p == NULL);
417 #endif /* IP_REASS_CHECK_OVERLAP */
418       /* this is the first fragment we ever received for this ip datagram */
419       ipr->p = new_p;
420     }
421   }
422
423   /* At this point, the validation part begins: */
424   /* If we already received the last fragment */
425   if ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0) {
426     /* and had no wholes so far */
427     if (valid) {
428       /* then check if the rest of the fragments is here */
429       /* Check if the queue starts with the first datagram */
430       if ((ipr->p == NULL) || (((struct ip_reass_helper*)ipr->p->payload)->start != 0)) {
431         valid = 0;
432       } else {
433         /* and check that there are no wholes after this datagram */
434         iprh_prev = iprh;
435         q = iprh->next_pbuf;
436         while (q != NULL) {
437           iprh = (struct ip_reass_helper*)q->payload;
438           if (iprh_prev->end != iprh->start) {
439             valid = 0;
440             break;
441           }
442           iprh_prev = iprh;
443           q = iprh->next_pbuf;
444         }
445         /* if still valid, all fragments are received
446          * (because to the MF==0 already arrived */
447         if (valid) {
448           LWIP_ASSERT("sanity check", ipr->p != NULL);
449           LWIP_ASSERT("sanity check",
450             ((struct ip_reass_helper*)ipr->p->payload) != iprh);
451           LWIP_ASSERT("validate_datagram:next_pbuf!=NULL",
452             iprh->next_pbuf == NULL);
453           LWIP_ASSERT("validate_datagram:datagram end!=datagram len",
454             iprh->end == ipr->datagram_len);
455         }
456       }
457     }
458     /* If valid is 0 here, there are some fragments missing in the middle
459      * (since MF == 0 has already arrived). Such datagrams simply time out if
460      * no more fragments are received... */
461     return valid;
462   }
463   /* If we come here, not all fragments were received, yet! */
464   return 0; /* not yet valid! */
465 #if IP_REASS_CHECK_OVERLAP
466 freepbuf:
467   ip_reass_pbufcount -= pbuf_clen(new_p);
468   pbuf_free(new_p);
469   return 0;
470 #endif /* IP_REASS_CHECK_OVERLAP */
471 }
472
473 /**
474  * Reassembles incoming IP fragments into an IP datagram.
475  *
476  * @param p points to a pbuf chain of the fragment
477  * @return NULL if reassembly is incomplete, ? otherwise
478  */
479 struct pbuf *
480 ip4_reass(struct pbuf *p)
481 {
482   struct pbuf *r;
483   struct ip_hdr *fraghdr;
484   struct ip_reassdata *ipr;
485   struct ip_reass_helper *iprh;
486   u16_t offset, len;
487   u8_t clen;
488
489   IPFRAG_STATS_INC(ip_frag.recv);
490   MIB2_STATS_INC(mib2.ipreasmreqds);
491
492   fraghdr = (struct ip_hdr*)p->payload;
493
494   if ((IPH_HL(fraghdr) * 4) != IP_HLEN) {
495     LWIP_DEBUGF(IP_REASS_DEBUG,("ip4_reass: IP options currently not supported!\n"));
496     IPFRAG_STATS_INC(ip_frag.err);
497     goto nullreturn;
498   }
499
500   offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
501   len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
502
503   /* Check if we are allowed to enqueue more datagrams. */
504   clen = pbuf_clen(p);
505   if ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
506 #if IP_REASS_FREE_OLDEST
507     if (!ip_reass_remove_oldest_datagram(fraghdr, clen) ||
508         ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS))
509 #endif /* IP_REASS_FREE_OLDEST */
510     {
511       /* No datagram could be freed and still too many pbufs enqueued */
512       LWIP_DEBUGF(IP_REASS_DEBUG,("ip4_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n",
513         ip_reass_pbufcount, clen, IP_REASS_MAX_PBUFS));
514       IPFRAG_STATS_INC(ip_frag.memerr);
515       /* @todo: send ICMP time exceeded here? */
516       /* drop this pbuf */
517       goto nullreturn;
518     }
519   }
520
521   /* Look for the datagram the fragment belongs to in the current datagram queue,
522    * remembering the previous in the queue for later dequeueing. */
523   for (ipr = reassdatagrams; ipr != NULL; ipr = ipr->next) {
524     /* Check if the incoming fragment matches the one currently present
525        in the reassembly buffer. If so, we proceed with copying the
526        fragment into the buffer. */
527     if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
528       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: matching previous fragment ID=%"X16_F"\n",
529         ntohs(IPH_ID(fraghdr))));
530       IPFRAG_STATS_INC(ip_frag.cachehit);
531       break;
532     }
533   }
534
535   if (ipr == NULL) {
536   /* Enqueue a new datagram into the datagram queue */
537     ipr = ip_reass_enqueue_new_datagram(fraghdr, clen);
538     /* Bail if unable to enqueue */
539     if (ipr == NULL) {
540       goto nullreturn;
541     }
542   } else {
543     if (((ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
544       ((ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
545       /* ipr->iphdr is not the header from the first fragment, but fraghdr is
546        * -> copy fraghdr into ipr->iphdr since we want to have the header
547        * of the first fragment (for ICMP time exceeded and later, for copying
548        * all options, if supported)*/
549       SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN);
550     }
551   }
552   /* Track the current number of pbufs current 'in-flight', in order to limit
553   the number of fragments that may be enqueued at any one time */
554   ip_reass_pbufcount += clen;
555
556   /* At this point, we have either created a new entry or pointing
557    * to an existing one */
558
559   /* check for 'no more fragments', and update queue entry*/
560   if ((IPH_OFFSET(fraghdr) & PP_NTOHS(IP_MF)) == 0) {
561     ipr->flags |= IP_REASS_FLAG_LASTFRAG;
562     ipr->datagram_len = offset + len;
563     LWIP_DEBUGF(IP_REASS_DEBUG,
564      ("ip4_reass: last fragment seen, total len %"S16_F"\n",
565       ipr->datagram_len));
566   }
567   /* find the right place to insert this pbuf */
568   /* @todo: trim pbufs if fragments are overlapping */
569   if (ip_reass_chain_frag_into_datagram_and_validate(ipr, p)) {
570     struct ip_reassdata *ipr_prev;
571     /* the totally last fragment (flag more fragments = 0) was received at least
572      * once AND all fragments are received */
573     ipr->datagram_len += IP_HLEN;
574
575     /* save the second pbuf before copying the header over the pointer */
576     r = ((struct ip_reass_helper*)ipr->p->payload)->next_pbuf;
577
578     /* copy the original ip header back to the first pbuf */
579     fraghdr = (struct ip_hdr*)(ipr->p->payload);
580     SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
581     IPH_LEN_SET(fraghdr, htons(ipr->datagram_len));
582     IPH_OFFSET_SET(fraghdr, 0);
583     IPH_CHKSUM_SET(fraghdr, 0);
584     /* @todo: do we need to set/calculate the correct checksum? */
585 #if CHECKSUM_GEN_IP
586     IF__NETIF_CHECKSUM_ENABLED(ip_current_input_netif(), NETIF_CHECKSUM_GEN_IP) {
587       IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN));
588     }
589 #endif /* CHECKSUM_GEN_IP */
590
591     p = ipr->p;
592
593     /* chain together the pbufs contained within the reass_data list. */
594     while (r != NULL) {
595       iprh = (struct ip_reass_helper*)r->payload;
596
597       /* hide the ip header for every succeeding fragment */
598       pbuf_header(r, -IP_HLEN);
599       pbuf_cat(p, r);
600       r = iprh->next_pbuf;
601     }
602
603     /* find the previous entry in the linked list */
604     if (ipr == reassdatagrams) {
605       ipr_prev = NULL;
606     } else {
607       for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
608         if (ipr_prev->next == ipr) {
609           break;
610         }
611       }
612     }
613
614     /* release the sources allocate for the fragment queue entry */
615     ip_reass_dequeue_datagram(ipr, ipr_prev);
616
617     /* and adjust the number of pbufs currently queued for reassembly. */
618     ip_reass_pbufcount -= pbuf_clen(p);
619
620     MIB2_STATS_INC(mib2.ipreasmoks);
621
622     /* Return the pbuf chain */
623     return p;
624   }
625   /* the datagram is not (yet?) reassembled completely */
626   LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass_pbufcount: %d out\n", ip_reass_pbufcount));
627   return NULL;
628
629 nullreturn:
630   LWIP_DEBUGF(IP_REASS_DEBUG,("ip4_reass: nullreturn\n"));
631   IPFRAG_STATS_INC(ip_frag.drop);
632   pbuf_free(p);
633   return NULL;
634 }
635 #endif /* IP_REASSEMBLY */
636
637 #if IP_FRAG
638 #if IP_FRAG_USES_STATIC_BUF
639 static u8_t buf[LWIP_MEM_ALIGN_SIZE(IP_FRAG_MAX_MTU + MEM_ALIGNMENT - 1)];
640 #else /* IP_FRAG_USES_STATIC_BUF */
641
642 #if !LWIP_NETIF_TX_SINGLE_PBUF
643 /** Allocate a new struct pbuf_custom_ref */
644 static struct pbuf_custom_ref*
645 ip_frag_alloc_pbuf_custom_ref(void)
646 {
647   return (struct pbuf_custom_ref*)memp_malloc(MEMP_FRAG_PBUF);
648 }
649
650 /** Free a struct pbuf_custom_ref */
651 static void
652 ip_frag_free_pbuf_custom_ref(struct pbuf_custom_ref* p)
653 {
654   LWIP_ASSERT("p != NULL", p != NULL);
655   memp_free(MEMP_FRAG_PBUF, p);
656 }
657
658 /** Free-callback function to free a 'struct pbuf_custom_ref', called by
659  * pbuf_free. */
660 static void
661 ipfrag_free_pbuf_custom(struct pbuf *p)
662 {
663   struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref*)p;
664   LWIP_ASSERT("pcr != NULL", pcr != NULL);
665   LWIP_ASSERT("pcr == p", (void*)pcr == (void*)p);
666   if (pcr->original != NULL) {
667     pbuf_free(pcr->original);
668   }
669   ip_frag_free_pbuf_custom_ref(pcr);
670 }
671 #endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
672 #endif /* IP_FRAG_USES_STATIC_BUF */
673
674 /**
675  * Fragment an IP datagram if too large for the netif.
676  *
677  * Chop the datagram in MTU sized chunks and send them in order
678  * by using a fixed size static memory buffer (PBUF_REF) or
679  * point PBUF_REFs into p (depending on IP_FRAG_USES_STATIC_BUF).
680  *
681  * @param p ip packet to send
682  * @param netif the netif on which to send
683  * @param dest destination ip address to which to send
684  *
685  * @return ERR_OK if sent successfully, err_t otherwise
686  */
687 err_t
688 ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
689 {
690   struct pbuf *rambuf;
691 #if IP_FRAG_USES_STATIC_BUF
692   struct pbuf *header;
693 #else
694 #if !LWIP_NETIF_TX_SINGLE_PBUF
695   struct pbuf *newpbuf;
696 #endif
697   struct ip_hdr *original_iphdr;
698 #endif
699   struct ip_hdr *iphdr;
700   u16_t nfb;
701   u16_t left, cop;
702   u16_t mtu = netif->mtu;
703   u16_t ofo, omf;
704   u16_t last;
705   u16_t poff = IP_HLEN;
706   u16_t tmp;
707 #if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF
708   u16_t newpbuflen = 0;
709   u16_t left_to_copy;
710 #endif
711
712   /* Get a RAM based MTU sized pbuf */
713 #if IP_FRAG_USES_STATIC_BUF
714   /* When using a static buffer, we use a PBUF_REF, which we will
715    * use to reference the packet (without link header).
716    * Layer and length is irrelevant.
717    */
718   rambuf = pbuf_alloc(PBUF_LINK, 0, PBUF_REF);
719   if (rambuf == NULL) {
720     LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc(PBUF_LINK, 0, PBUF_REF) failed\n"));
721     goto memerr;
722   }
723   rambuf->tot_len = rambuf->len = mtu;
724   rambuf->payload = LWIP_MEM_ALIGN((void *)buf);
725
726   /* Copy the IP header in it */
727   iphdr = (struct ip_hdr *)rambuf->payload;
728   SMEMCPY(iphdr, p->payload, IP_HLEN);
729 #else /* IP_FRAG_USES_STATIC_BUF */
730   original_iphdr = (struct ip_hdr *)p->payload;
731   iphdr = original_iphdr;
732 #endif /* IP_FRAG_USES_STATIC_BUF */
733
734   /* Save original offset */
735   tmp = ntohs(IPH_OFFSET(iphdr));
736   ofo = tmp & IP_OFFMASK;
737   omf = tmp & IP_MF;
738
739   left = p->tot_len - IP_HLEN;
740
741   nfb = (mtu - IP_HLEN) / 8;
742
743   while (left) {
744     last = (left <= mtu - IP_HLEN);
745
746     /* Set new offset and MF flag */
747     tmp = omf | (IP_OFFMASK & (ofo));
748     if (!last) {
749       tmp = tmp | IP_MF;
750     }
751
752     /* Fill this fragment */
753     cop = last ? left : nfb * 8;
754
755 #if IP_FRAG_USES_STATIC_BUF
756     poff += pbuf_copy_partial(p, (u8_t*)iphdr + IP_HLEN, cop, poff);
757 #else /* IP_FRAG_USES_STATIC_BUF */
758 #if LWIP_NETIF_TX_SINGLE_PBUF
759     rambuf = pbuf_alloc(PBUF_IP, cop, PBUF_RAM);
760     if (rambuf == NULL) {
761       goto memerr;
762     }
763     LWIP_ASSERT("this needs a pbuf in one piece!",
764       (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
765     poff += pbuf_copy_partial(p, rambuf->payload, cop, poff);
766     /* make room for the IP header */
767     if (pbuf_header(rambuf, IP_HLEN)) {
768       pbuf_free(rambuf);
769       goto memerr;
770     }
771     /* fill in the IP header */
772     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
773     iphdr = (struct ip_hdr*)rambuf->payload;
774 #else /* LWIP_NETIF_TX_SINGLE_PBUF */
775     /* When not using a static buffer, create a chain of pbufs.
776      * The first will be a PBUF_RAM holding the link and IP header.
777      * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
778      * but limited to the size of an mtu.
779      */
780     rambuf = pbuf_alloc(PBUF_LINK, IP_HLEN, PBUF_RAM);
781     if (rambuf == NULL) {
782       goto memerr;
783     }
784     LWIP_ASSERT("this needs a pbuf in one piece!",
785                 (p->len >= (IP_HLEN)));
786     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
787     iphdr = (struct ip_hdr *)rambuf->payload;
788
789     /* Can just adjust p directly for needed offset. */
790     p->payload = (u8_t *)p->payload + poff;
791     p->len -= poff;
792
793     left_to_copy = cop;
794     while (left_to_copy) {
795       struct pbuf_custom_ref *pcr;
796       newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
797       /* Is this pbuf already empty? */
798       if (!newpbuflen) {
799         p = p->next;
800         continue;
801       }
802       pcr = ip_frag_alloc_pbuf_custom_ref();
803       if (pcr == NULL) {
804         pbuf_free(rambuf);
805         goto memerr;
806       }
807       /* Mirror this pbuf, although we might not need all of it. */
808       newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen);
809       if (newpbuf == NULL) {
810         ip_frag_free_pbuf_custom_ref(pcr);
811         pbuf_free(rambuf);
812         goto memerr;
813       }
814       pbuf_ref(p);
815       pcr->original = p;
816       pcr->pc.custom_free_function = ipfrag_free_pbuf_custom;
817
818       /* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
819        * so that it is removed when pbuf_dechain is later called on rambuf.
820        */
821       pbuf_cat(rambuf, newpbuf);
822       left_to_copy -= newpbuflen;
823       if (left_to_copy) {
824         p = p->next;
825       }
826     }
827     poff = newpbuflen;
828 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
829 #endif /* IP_FRAG_USES_STATIC_BUF */
830
831     /* Correct header */
832     IPH_OFFSET_SET(iphdr, htons(tmp));
833     IPH_LEN_SET(iphdr, htons(cop + IP_HLEN));
834     IPH_CHKSUM_SET(iphdr, 0);
835 #if CHECKSUM_GEN_IP
836     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_IP) {
837       IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN));
838     }
839 #endif /* CHECKSUM_GEN_IP */
840
841 #if IP_FRAG_USES_STATIC_BUF
842     if (last) {
843       pbuf_realloc(rambuf, left + IP_HLEN);
844     }
845
846     /* This part is ugly: we alloc a RAM based pbuf for
847      * the link level header for each chunk and then
848      * free it. A PBUF_ROM style pbuf for which pbuf_header
849      * worked would make things simpler.
850      */
851     header = pbuf_alloc(PBUF_LINK, 0, PBUF_RAM);
852     if (header != NULL) {
853       pbuf_chain(header, rambuf);
854       netif->output(netif, header, dest);
855       IPFRAG_STATS_INC(ip_frag.xmit);
856       MIB2_STATS_INC(mib2.ipfragcreates);
857       pbuf_free(header);
858     } else {
859       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc() for header failed\n"));
860       pbuf_free(rambuf);
861       goto memerr;
862     }
863 #else /* IP_FRAG_USES_STATIC_BUF */
864     /* No need for separate header pbuf - we allowed room for it in rambuf
865      * when allocated.
866      */
867     netif->output(netif, rambuf, dest);
868     IPFRAG_STATS_INC(ip_frag.xmit);
869
870     /* Unfortunately we can't reuse rambuf - the hardware may still be
871      * using the buffer. Instead we free it (and the ensuing chain) and
872      * recreate it next time round the loop. If we're lucky the hardware
873      * will have already sent the packet, the free will really free, and
874      * there will be zero memory penalty.
875      */
876
877     pbuf_free(rambuf);
878 #endif /* IP_FRAG_USES_STATIC_BUF */
879     left -= cop;
880     ofo += nfb;
881   }
882 #if IP_FRAG_USES_STATIC_BUF
883   pbuf_free(rambuf);
884 #endif /* IP_FRAG_USES_STATIC_BUF */
885   MIB2_STATS_INC(mib2.ipfragoks);
886   return ERR_OK;
887 memerr:
888   MIB2_STATS_INC(mib2.ipfragfails);
889   return ERR_MEM;
890 }
891 #endif /* IP_FRAG */
892
893 #endif /* LWIP_IPV4 */