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