Kenji Arai / mbed-os_TYBLE16

Dependents:   TYBLE16_simple_data_logger TYBLE16_MP3_Air

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lwip_ip4_frag.c Source File

lwip_ip4_frag.c

Go to the documentation of this file.
00001 /**
00002  * @file
00003  * This is the IPv4 packet segmentation and reassembly implementation.
00004  *
00005  */
00006 
00007 /*
00008  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
00009  * All rights reserved.
00010  *
00011  * Redistribution and use in source and binary forms, with or without modification,
00012  * are permitted provided that the following conditions are met:
00013  *
00014  * 1. Redistributions of source code must retain the above copyright notice,
00015  *    this list of conditions and the following disclaimer.
00016  * 2. Redistributions in binary form must reproduce the above copyright notice,
00017  *    this list of conditions and the following disclaimer in the documentation
00018  *    and/or other materials provided with the distribution.
00019  * 3. The name of the author may not be used to endorse or promote products
00020  *    derived from this software without specific prior written permission.
00021  *
00022  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
00023  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
00024  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
00025  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00026  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
00027  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00028  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00029  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
00030  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
00031  * OF SUCH DAMAGE.
00032  *
00033  * This file is part of the lwIP TCP/IP stack.
00034  *
00035  * Author: Jani Monoses <jani@iv.ro>
00036  *         Simon Goldschmidt
00037  * original reassembly code by Adam Dunkels <adam@sics.se>
00038  *
00039  */
00040 
00041 #include "lwip/opt.h"
00042 
00043 #if LWIP_IPV4
00044 
00045 #include "lwip/ip4_frag.h"
00046 #include "lwip/def.h"
00047 #include "lwip/inet_chksum.h"
00048 #include "lwip/netif.h"
00049 #include "lwip/stats.h"
00050 #include "lwip/icmp.h"
00051 
00052 #include <string.h>
00053 
00054 #if IP_REASSEMBLY
00055 /**
00056  * The IP reassembly code currently has the following limitations:
00057  * - IP header options are not supported
00058  * - fragments must not overlap (e.g. due to different routes),
00059  *   currently, overlapping or duplicate fragments are thrown away
00060  *   if IP_REASS_CHECK_OVERLAP=1 (the default)!
00061  *
00062  * @todo: work with IP header options
00063  */
00064 
00065 /** Setting this to 0, you can turn off checking the fragments for overlapping
00066  * regions. The code gets a little smaller. Only use this if you know that
00067  * overlapping won't occur on your network! */
00068 #ifndef IP_REASS_CHECK_OVERLAP
00069 #define IP_REASS_CHECK_OVERLAP 1
00070 #endif /* IP_REASS_CHECK_OVERLAP */
00071 
00072 /** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
00073  * full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
00074  * Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
00075  * is set to 1, so one datagram can be reassembled at a time, only. */
00076 #ifndef IP_REASS_FREE_OLDEST
00077 #define IP_REASS_FREE_OLDEST 1
00078 #endif /* IP_REASS_FREE_OLDEST */
00079 
00080 #define IP_REASS_FLAG_LASTFRAG 0x01
00081 
00082 #define IP_REASS_VALIDATE_TELEGRAM_FINISHED  1
00083 #define IP_REASS_VALIDATE_PBUF_QUEUED        0
00084 #define IP_REASS_VALIDATE_PBUF_DROPPED       -1
00085 
00086 /** This is a helper struct which holds the starting
00087  * offset and the ending offset of this fragment to
00088  * easily chain the fragments.
00089  * It has the same packing requirements as the IP header, since it replaces
00090  * the IP header in memory in incoming fragments (after copying it) to keep
00091  * track of the various fragments. (-> If the IP header doesn't need packing,
00092  * this struct doesn't need packing, too.)
00093  */
00094 #ifdef PACK_STRUCT_USE_INCLUDES
00095 #  include "arch/bpstruct.h"
00096 #endif
00097 PACK_STRUCT_BEGIN
00098 struct ip_reass_helper {
00099   PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
00100   PACK_STRUCT_FIELD(u16_t start);
00101   PACK_STRUCT_FIELD(u16_t end);
00102 } PACK_STRUCT_STRUCT;
00103 PACK_STRUCT_END
00104 #ifdef PACK_STRUCT_USE_INCLUDES
00105 #  include "arch/epstruct.h"
00106 #endif
00107 
00108 #define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB)  \
00109   (ip4_addr_cmp(&(iphdrA)->src, &(iphdrB)->src) && \
00110    ip4_addr_cmp(&(iphdrA)->dest, &(iphdrB)->dest) && \
00111    IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0
00112 
00113 /* global variables */
00114 static struct ip_reassdata *reassdatagrams;
00115 static u16_t ip_reass_pbufcount;
00116 
00117 /* function prototypes */
00118 static void ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
00119 static int ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
00120 
00121 /**
00122  * Reassembly timer base function
00123  * for both NO_SYS == 0 and 1 (!).
00124  *
00125  * Should be called every 1000 msec (defined by IP_TMR_INTERVAL).
00126  */
00127 void
00128 ip_reass_tmr(void)
00129 {
00130   struct ip_reassdata *r, *prev = NULL;
00131 
00132   r = reassdatagrams;
00133   while (r != NULL) {
00134     /* Decrement the timer. Once it reaches 0,
00135      * clean up the incomplete fragment assembly */
00136     if (r->timer > 0) {
00137       r->timer--;
00138       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n", (u16_t)r->timer));
00139       prev = r;
00140       r = r->next;
00141     } else {
00142       /* reassembly timed out */
00143       struct ip_reassdata *tmp;
00144       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n"));
00145       tmp = r;
00146       /* get the next pointer before freeing */
00147       r = r->next;
00148       /* free the helper struct and all enqueued pbufs */
00149       ip_reass_free_complete_datagram(tmp, prev);
00150     }
00151   }
00152 }
00153 
00154 /**
00155  * Free a datagram (struct ip_reassdata) and all its pbufs.
00156  * Updates the total count of enqueued pbufs (ip_reass_pbufcount),
00157  * SNMP counters and sends an ICMP time exceeded packet.
00158  *
00159  * @param ipr datagram to free
00160  * @param prev the previous datagram in the linked list
00161  * @return the number of pbufs freed
00162  */
00163 static int
00164 ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
00165 {
00166   u16_t pbufs_freed = 0;
00167   u16_t clen;
00168   struct pbuf *p;
00169   struct ip_reass_helper *iprh;
00170 
00171   LWIP_ASSERT("prev != ipr", prev != ipr);
00172   if (prev != NULL) {
00173     LWIP_ASSERT("prev->next == ipr", prev->next == ipr);
00174   }
00175 
00176   MIB2_STATS_INC(mib2.ipreasmfails);
00177 #if LWIP_ICMP
00178   iprh = (struct ip_reass_helper *)ipr->p->payload;
00179   if (iprh->start == 0) {
00180     /* The first fragment was received, send ICMP time exceeded. */
00181     /* First, de-queue the first pbuf from r->p. */
00182     p = ipr->p;
00183     ipr->p = iprh->next_pbuf;
00184     /* Then, copy the original header into it. */
00185     SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN);
00186     icmp_time_exceeded(p, ICMP_TE_FRAG);
00187     clen = pbuf_clen(p);
00188     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
00189     pbufs_freed = (u16_t)(pbufs_freed + clen);
00190     pbuf_free(p);
00191   }
00192 #endif /* LWIP_ICMP */
00193 
00194   /* First, free all received pbufs.  The individual pbufs need to be released
00195      separately as they have not yet been chained */
00196   p = ipr->p;
00197   while (p != NULL) {
00198     struct pbuf *pcur;
00199     iprh = (struct ip_reass_helper *)p->payload;
00200     pcur = p;
00201     /* get the next pointer before freeing */
00202     p = iprh->next_pbuf;
00203     clen = pbuf_clen(pcur);
00204     LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
00205     pbufs_freed = (u16_t)(pbufs_freed + clen);
00206     pbuf_free(pcur);
00207   }
00208   /* Then, unchain the struct ip_reassdata from the list and free it. */
00209   /* coverity [FORWARD_NULL]*/
00210   ip_reass_dequeue_datagram(ipr, prev);
00211   LWIP_ASSERT("ip_reass_pbufcount >= pbufs_freed", ip_reass_pbufcount >= pbufs_freed);
00212   ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount - pbufs_freed);
00213 
00214   return pbufs_freed;
00215 }
00216 
00217 #if IP_REASS_FREE_OLDEST
00218 /**
00219  * Free the oldest datagram to make room for enqueueing new fragments.
00220  * The datagram 'fraghdr' belongs to is not freed!
00221  *
00222  * @param fraghdr IP header of the current fragment
00223  * @param pbufs_needed number of pbufs needed to enqueue
00224  *        (used for freeing other datagrams if not enough space)
00225  * @return the number of pbufs freed
00226  */
00227 static int
00228 ip_reass_remove_oldest_datagram(struct ip_hdr *fraghdr, int pbufs_needed)
00229 {
00230   /* @todo Can't we simply remove the last datagram in the
00231    *       linked list behind reassdatagrams?
00232    */
00233   struct ip_reassdata *r, *oldest, *prev, *oldest_prev;
00234   int pbufs_freed = 0, pbufs_freed_current;
00235   int other_datagrams;
00236 
00237   /* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
00238    * but don't free the datagram that 'fraghdr' belongs to! */
00239   do {
00240     oldest = NULL;
00241     prev = NULL;
00242     oldest_prev = NULL;
00243     other_datagrams = 0;
00244     r = reassdatagrams;
00245     while (r != NULL) {
00246       if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) {
00247         /* Not the same datagram as fraghdr */
00248         other_datagrams++;
00249         if (oldest == NULL) {
00250           oldest = r;
00251           oldest_prev = prev;
00252         } else if (r->timer <= oldest->timer) {
00253           /* older than the previous oldest */
00254           oldest = r;
00255           oldest_prev = prev;
00256         }
00257       }
00258       if (r->next != NULL) {
00259         prev = r;
00260       }
00261       r = r->next;
00262     }
00263     if (oldest != NULL) {
00264       pbufs_freed_current = ip_reass_free_complete_datagram(oldest, oldest_prev);
00265       pbufs_freed += pbufs_freed_current;
00266     }
00267   } while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1));
00268   return pbufs_freed;
00269 }
00270 #endif /* IP_REASS_FREE_OLDEST */
00271 
00272 /**
00273  * Enqueues a new fragment into the fragment queue
00274  * @param fraghdr points to the new fragments IP hdr
00275  * @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space)
00276  * @return A pointer to the queue location into which the fragment was enqueued
00277  */
00278 static struct ip_reassdata *
00279 ip_reass_enqueue_new_datagram(struct ip_hdr *fraghdr, int clen)
00280 {
00281   struct ip_reassdata *ipr;
00282 #if ! IP_REASS_FREE_OLDEST
00283   LWIP_UNUSED_ARG(clen);
00284 #endif
00285 
00286   /* No matching previous fragment found, allocate a new reassdata struct */
00287   ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
00288   if (ipr == NULL) {
00289 #if IP_REASS_FREE_OLDEST
00290     if (ip_reass_remove_oldest_datagram(fraghdr, clen) >= clen) {
00291       ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
00292     }
00293     if (ipr == NULL)
00294 #endif /* IP_REASS_FREE_OLDEST */
00295     {
00296       IPFRAG_STATS_INC(ip_frag.memerr);
00297       LWIP_DEBUGF(IP_REASS_DEBUG, ("Failed to alloc reassdata struct\n"));
00298       return NULL;
00299     }
00300   }
00301   memset(ipr, 0, sizeof(struct ip_reassdata));
00302   ipr->timer = IP_REASS_MAXAGE;
00303 
00304   /* enqueue the new structure to the front of the list */
00305   ipr->next = reassdatagrams;
00306   reassdatagrams = ipr;
00307   /* copy the ip header for later tests and input */
00308   /* @todo: no ip options supported? */
00309   SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN);
00310   return ipr;
00311 }
00312 
00313 /**
00314  * Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs.
00315  * @param ipr points to the queue entry to dequeue
00316  */
00317 static void
00318 ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
00319 {
00320   /* dequeue the reass struct  */
00321   if (reassdatagrams == ipr) {
00322     /* it was the first in the list */
00323     reassdatagrams = ipr->next;
00324   } else {
00325     /* it wasn't the first, so it must have a valid 'prev' */
00326     LWIP_ASSERT("sanity check linked list", prev != NULL);
00327     prev->next = ipr->next;
00328   }
00329 
00330   /* now we can free the ip_reassdata struct */
00331   memp_free(MEMP_REASSDATA, ipr);
00332 }
00333 
00334 /**
00335  * Chain a new pbuf into the pbuf list that composes the datagram.  The pbuf list
00336  * will grow over time as  new pbufs are rx.
00337  * Also checks that the datagram passes basic continuity checks (if the last
00338  * fragment was received at least once).
00339  * @param ipr points to the reassembly state
00340  * @param new_p points to the pbuf for the current fragment
00341  * @param is_last is 1 if this pbuf has MF==0 (ipr->flags not updated yet)
00342  * @return see IP_REASS_VALIDATE_* defines
00343  */
00344 static int
00345 ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct pbuf *new_p, int is_last)
00346 {
00347   struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev = NULL;
00348   struct pbuf *q;
00349   u16_t offset, len;
00350   u8_t hlen;
00351   struct ip_hdr *fraghdr;
00352   int valid = 1;
00353 
00354   /* Extract length and fragment offset from current fragment */
00355   fraghdr = (struct ip_hdr *)new_p->payload;
00356   len = lwip_ntohs(IPH_LEN(fraghdr));
00357   hlen = IPH_HL_BYTES(fraghdr);
00358   if (hlen > len) {
00359     /* invalid datagram */
00360     return IP_REASS_VALIDATE_PBUF_DROPPED;
00361   }
00362   len = (u16_t)(len - hlen);
00363   offset = IPH_OFFSET_BYTES(fraghdr);
00364 
00365   /* overwrite the fragment's ip header from the pbuf with our helper struct,
00366    * and setup the embedded helper structure. */
00367   /* make sure the struct ip_reass_helper fits into the IP header */
00368   LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN",
00369               sizeof(struct ip_reass_helper) <= IP_HLEN);
00370   iprh = (struct ip_reass_helper *)new_p->payload;
00371   iprh->next_pbuf = NULL;
00372   iprh->start = offset;
00373   iprh->end = (u16_t)(offset + len);
00374   if (iprh->end < offset) {
00375     /* u16_t overflow, cannot handle this */
00376     return IP_REASS_VALIDATE_PBUF_DROPPED;
00377   }
00378 
00379   /* Iterate through until we either get to the end of the list (append),
00380    * or we find one with a larger offset (insert). */
00381   for (q = ipr->p; q != NULL;) {
00382     iprh_tmp = (struct ip_reass_helper *)q->payload;
00383     if (iprh->start < iprh_tmp->start) {
00384       /* the new pbuf should be inserted before this */
00385       iprh->next_pbuf = q;
00386       if (iprh_prev != NULL) {
00387         /* not the fragment with the lowest offset */
00388 #if IP_REASS_CHECK_OVERLAP
00389         if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) {
00390           /* fragment overlaps with previous or following, throw away */
00391           return IP_REASS_VALIDATE_PBUF_DROPPED;
00392         }
00393 #endif /* IP_REASS_CHECK_OVERLAP */
00394         iprh_prev->next_pbuf = new_p;
00395         if (iprh_prev->end != iprh->start) {
00396           /* There is a fragment missing between the current
00397            * and the previous fragment */
00398           valid = 0;
00399         }
00400       } else {
00401 #if IP_REASS_CHECK_OVERLAP
00402         if (iprh->end > iprh_tmp->start) {
00403           /* fragment overlaps with following, throw away */
00404           return IP_REASS_VALIDATE_PBUF_DROPPED;
00405         }
00406 #endif /* IP_REASS_CHECK_OVERLAP */
00407         /* fragment with the lowest offset */
00408         ipr->p = new_p;
00409       }
00410       break;
00411     } else if (iprh->start == iprh_tmp->start) {
00412       /* received the same datagram twice: no need to keep the datagram */
00413       return IP_REASS_VALIDATE_PBUF_DROPPED;
00414 #if IP_REASS_CHECK_OVERLAP
00415     } else if (iprh->start < iprh_tmp->end) {
00416       /* overlap: no need to keep the new datagram */
00417       return IP_REASS_VALIDATE_PBUF_DROPPED;
00418 #endif /* IP_REASS_CHECK_OVERLAP */
00419     } else {
00420       /* Check if the fragments received so far have no holes. */
00421       if (iprh_prev != NULL) {
00422         if (iprh_prev->end != iprh_tmp->start) {
00423           /* There is a fragment missing between the current
00424            * and the previous fragment */
00425           valid = 0;
00426         }
00427       }
00428     }
00429     q = iprh_tmp->next_pbuf;
00430     iprh_prev = iprh_tmp;
00431   }
00432 
00433   /* If q is NULL, then we made it to the end of the list. Determine what to do now */
00434   if (q == NULL) {
00435     if (iprh_prev != NULL) {
00436       /* this is (for now), the fragment with the highest offset:
00437        * chain it to the last fragment */
00438 #if IP_REASS_CHECK_OVERLAP
00439       LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start);
00440 #endif /* IP_REASS_CHECK_OVERLAP */
00441       iprh_prev->next_pbuf = new_p;
00442       if (iprh_prev->end != iprh->start) {
00443         valid = 0;
00444       }
00445     } else {
00446 #if IP_REASS_CHECK_OVERLAP
00447       LWIP_ASSERT("no previous fragment, this must be the first fragment!",
00448                   ipr->p == NULL);
00449 #endif /* IP_REASS_CHECK_OVERLAP */
00450       /* this is the first fragment we ever received for this ip datagram */
00451       ipr->p = new_p;
00452     }
00453   }
00454 
00455   /* At this point, the validation part begins: */
00456   /* If we already received the last fragment */
00457   if (is_last || ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0)) {
00458     /* and had no holes so far */
00459     if (valid) {
00460       /* then check if the rest of the fragments is here */
00461       /* Check if the queue starts with the first datagram */
00462       if ((ipr->p == NULL) || (((struct ip_reass_helper *)ipr->p->payload)->start != 0)) {
00463         valid = 0;
00464       } else {
00465         /* and check that there are no holes after this datagram */
00466         iprh_prev = iprh;
00467         q = iprh->next_pbuf;
00468         while (q != NULL) {
00469           iprh = (struct ip_reass_helper *)q->payload;
00470           if (iprh_prev->end != iprh->start) {
00471             valid = 0;
00472             break;
00473           }
00474           iprh_prev = iprh;
00475           q = iprh->next_pbuf;
00476         }
00477         /* if still valid, all fragments are received
00478          * (because to the MF==0 already arrived */
00479         if (valid) {
00480           LWIP_ASSERT("sanity check", ipr->p != NULL);
00481           LWIP_ASSERT("sanity check",
00482                       ((struct ip_reass_helper *)ipr->p->payload) != iprh);
00483           LWIP_ASSERT("validate_datagram:next_pbuf!=NULL",
00484                       iprh->next_pbuf == NULL);
00485         }
00486       }
00487     }
00488     /* If valid is 0 here, there are some fragments missing in the middle
00489      * (since MF == 0 has already arrived). Such datagrams simply time out if
00490      * no more fragments are received... */
00491     return valid ? IP_REASS_VALIDATE_TELEGRAM_FINISHED : IP_REASS_VALIDATE_PBUF_QUEUED;
00492   }
00493   /* If we come here, not all fragments were received, yet! */
00494   return IP_REASS_VALIDATE_PBUF_QUEUED; /* not yet valid! */
00495 }
00496 
00497 /**
00498  * Reassembles incoming IP fragments into an IP datagram.
00499  *
00500  * @param p points to a pbuf chain of the fragment
00501  * @return NULL if reassembly is incomplete, ? otherwise
00502  */
00503 struct pbuf *
00504 ip4_reass(struct pbuf *p)
00505 {
00506   struct pbuf *r;
00507   struct ip_hdr *fraghdr;
00508   struct ip_reassdata *ipr;
00509   struct ip_reass_helper *iprh;
00510   u16_t offset, len, clen;
00511   u8_t hlen;
00512   int valid;
00513   int is_last;
00514 
00515   IPFRAG_STATS_INC(ip_frag.recv);
00516   MIB2_STATS_INC(mib2.ipreasmreqds);
00517 
00518   fraghdr = (struct ip_hdr *)p->payload;
00519 
00520   if (IPH_HL_BYTES(fraghdr) != IP_HLEN) {
00521     LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: IP options currently not supported!\n"));
00522     IPFRAG_STATS_INC(ip_frag.err);
00523     goto nullreturn;
00524   }
00525 
00526   offset = IPH_OFFSET_BYTES(fraghdr);
00527   len = lwip_ntohs(IPH_LEN(fraghdr));
00528   hlen = IPH_HL_BYTES(fraghdr);
00529   if (hlen > len) {
00530     /* invalid datagram */
00531     goto nullreturn;
00532   }
00533   len = (u16_t)(len - hlen);
00534 
00535   /* Check if we are allowed to enqueue more datagrams. */
00536   clen = pbuf_clen(p);
00537   if ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
00538 #if IP_REASS_FREE_OLDEST
00539     if (!ip_reass_remove_oldest_datagram(fraghdr, clen) ||
00540         ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS))
00541 #endif /* IP_REASS_FREE_OLDEST */
00542     {
00543       /* No datagram could be freed and still too many pbufs enqueued */
00544       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n",
00545                                    ip_reass_pbufcount, clen, IP_REASS_MAX_PBUFS));
00546       IPFRAG_STATS_INC(ip_frag.memerr);
00547       /* @todo: send ICMP time exceeded here? */
00548       /* drop this pbuf */
00549       goto nullreturn;
00550     }
00551   }
00552 
00553   /* Look for the datagram the fragment belongs to in the current datagram queue,
00554    * remembering the previous in the queue for later dequeueing. */
00555   for (ipr = reassdatagrams; ipr != NULL; ipr = ipr->next) {
00556     /* Check if the incoming fragment matches the one currently present
00557        in the reassembly buffer. If so, we proceed with copying the
00558        fragment into the buffer. */
00559     if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
00560       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: matching previous fragment ID=%"X16_F"\n",
00561                                    lwip_ntohs(IPH_ID(fraghdr))));
00562       IPFRAG_STATS_INC(ip_frag.cachehit);
00563       break;
00564     }
00565   }
00566 
00567   if (ipr == NULL) {
00568     /* Enqueue a new datagram into the datagram queue */
00569     ipr = ip_reass_enqueue_new_datagram(fraghdr, clen);
00570     /* Bail if unable to enqueue */
00571     if (ipr == NULL) {
00572       goto nullreturn;
00573     }
00574   } else {
00575     if (((lwip_ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
00576         ((lwip_ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
00577       /* ipr->iphdr is not the header from the first fragment, but fraghdr is
00578        * -> copy fraghdr into ipr->iphdr since we want to have the header
00579        * of the first fragment (for ICMP time exceeded and later, for copying
00580        * all options, if supported)*/
00581       SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN);
00582     }
00583   }
00584 
00585   /* At this point, we have either created a new entry or pointing
00586    * to an existing one */
00587 
00588   /* check for 'no more fragments', and update queue entry*/
00589   is_last = (IPH_OFFSET(fraghdr) & PP_NTOHS(IP_MF)) == 0;
00590   if (is_last) {
00591     u16_t datagram_len = (u16_t)(offset + len);
00592     if ((datagram_len < offset) || (datagram_len > (0xFFFF - IP_HLEN))) {
00593       /* u16_t overflow, cannot handle this */
00594       goto nullreturn_ipr;
00595     }
00596   }
00597   /* find the right place to insert this pbuf */
00598   /* @todo: trim pbufs if fragments are overlapping */
00599   valid = ip_reass_chain_frag_into_datagram_and_validate(ipr, p, is_last);
00600   if (valid == IP_REASS_VALIDATE_PBUF_DROPPED) {
00601     goto nullreturn_ipr;
00602   }
00603   /* if we come here, the pbuf has been enqueued */
00604 
00605   /* Track the current number of pbufs current 'in-flight', in order to limit
00606      the number of fragments that may be enqueued at any one time
00607      (overflow checked by testing against IP_REASS_MAX_PBUFS) */
00608   ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount + clen);
00609   if (is_last) {
00610     u16_t datagram_len = (u16_t)(offset + len);
00611     ipr->datagram_len = datagram_len;
00612     ipr->flags |= IP_REASS_FLAG_LASTFRAG;
00613     LWIP_DEBUGF(IP_REASS_DEBUG,
00614                 ("ip4_reass: last fragment seen, total len %"S16_F"\n",
00615                  ipr->datagram_len));
00616   }
00617 
00618   if (valid == IP_REASS_VALIDATE_TELEGRAM_FINISHED) {
00619     struct ip_reassdata *ipr_prev;
00620     /* the totally last fragment (flag more fragments = 0) was received at least
00621      * once AND all fragments are received */
00622     u16_t datagram_len = (u16_t)(ipr->datagram_len + IP_HLEN);
00623 
00624     /* save the second pbuf before copying the header over the pointer */
00625     r = ((struct ip_reass_helper *)ipr->p->payload)->next_pbuf;
00626 
00627     /* copy the original ip header back to the first pbuf */
00628     fraghdr = (struct ip_hdr *)(ipr->p->payload);
00629     SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
00630     IPH_LEN_SET(fraghdr, lwip_htons(datagram_len));
00631     IPH_OFFSET_SET(fraghdr, 0);
00632     IPH_CHKSUM_SET(fraghdr, 0);
00633     /* @todo: do we need to set/calculate the correct checksum? */
00634 #if CHECKSUM_GEN_IP
00635     IF__NETIF_CHECKSUM_ENABLED(ip_current_input_netif(), NETIF_CHECKSUM_GEN_IP) {
00636       IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN));
00637     }
00638 #endif /* CHECKSUM_GEN_IP */
00639 
00640     p = ipr->p;
00641 
00642     /* chain together the pbufs contained within the reass_data list. */
00643     while (r != NULL) {
00644       iprh = (struct ip_reass_helper *)r->payload;
00645 
00646       /* hide the ip header for every succeeding fragment */
00647       pbuf_remove_header(r, IP_HLEN);
00648       pbuf_cat(p, r);
00649       r = iprh->next_pbuf;
00650     }
00651 
00652     /* find the previous entry in the linked list */
00653     if (ipr == reassdatagrams) {
00654       ipr_prev = NULL;
00655     } else {
00656       for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
00657         if (ipr_prev->next == ipr) {
00658           break;
00659         }
00660       }
00661     }
00662 
00663     /* release the sources allocate for the fragment queue entry */
00664     /* coverity [FORWARD_NULL]*/
00665     ip_reass_dequeue_datagram(ipr, ipr_prev);
00666     /* and adjust the number of pbufs currently queued for reassembly. */
00667     clen = pbuf_clen(p);
00668     LWIP_ASSERT("ip_reass_pbufcount >= clen", ip_reass_pbufcount >= clen);
00669     ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount - clen);
00670 
00671     MIB2_STATS_INC(mib2.ipreasmoks);
00672 
00673     /* Return the pbuf chain */
00674     return p;
00675   }
00676   /* the datagram is not (yet?) reassembled completely */
00677   LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_pbufcount: %d out\n", ip_reass_pbufcount));
00678   return NULL;
00679 
00680 nullreturn_ipr:
00681   LWIP_ASSERT("ipr != NULL", ipr != NULL);
00682   if (ipr->p == NULL) {
00683     /* dropped pbuf after creating a new datagram entry: remove the entry, too */
00684     LWIP_ASSERT("not firstalthough just enqueued", ipr == reassdatagrams);
00685     ip_reass_dequeue_datagram(ipr, NULL);
00686   }
00687 
00688 nullreturn:
00689   LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: nullreturn\n"));
00690   IPFRAG_STATS_INC(ip_frag.drop);
00691   pbuf_free(p);
00692   return NULL;
00693 }
00694 #endif /* IP_REASSEMBLY */
00695 
00696 #if IP_FRAG
00697 #if !LWIP_NETIF_TX_SINGLE_PBUF
00698 /** Allocate a new struct pbuf_custom_ref */
00699 static struct pbuf_custom_ref *
00700 ip_frag_alloc_pbuf_custom_ref(void)
00701 {
00702   return (struct pbuf_custom_ref *)memp_malloc(MEMP_FRAG_PBUF);
00703 }
00704 
00705 /** Free a struct pbuf_custom_ref */
00706 static void
00707 ip_frag_free_pbuf_custom_ref(struct pbuf_custom_ref *p)
00708 {
00709   LWIP_ASSERT("p != NULL", p != NULL);
00710   memp_free(MEMP_FRAG_PBUF, p);
00711 }
00712 
00713 /** Free-callback function to free a 'struct pbuf_custom_ref', called by
00714  * pbuf_free. */
00715 static void
00716 ipfrag_free_pbuf_custom(struct pbuf *p)
00717 {
00718   struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref *)p;
00719   LWIP_ASSERT("pcr != NULL", pcr != NULL);
00720   LWIP_ASSERT("pcr == p", (void *)pcr == (void *)p);
00721   if (pcr->original != NULL) {
00722     pbuf_free(pcr->original);
00723   }
00724   ip_frag_free_pbuf_custom_ref(pcr);
00725 }
00726 #endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
00727 
00728 /**
00729  * Fragment an IP datagram if too large for the netif.
00730  *
00731  * Chop the datagram in MTU sized chunks and send them in order
00732  * by pointing PBUF_REFs into p.
00733  *
00734  * @param p ip packet to send
00735  * @param netif the netif on which to send
00736  * @param dest destination ip address to which to send
00737  *
00738  * @return ERR_OK if sent successfully, err_t otherwise
00739  */
00740 err_t
00741 ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
00742 {
00743   struct pbuf *rambuf;
00744 #if !LWIP_NETIF_TX_SINGLE_PBUF
00745   struct pbuf *newpbuf;
00746   u16_t newpbuflen = 0;
00747   u16_t left_to_copy;
00748 #endif
00749   struct ip_hdr *original_iphdr;
00750   struct ip_hdr *iphdr;
00751   const u16_t nfb = (u16_t)((netif->mtu - IP_HLEN) / 8);
00752   u16_t left, fragsize;
00753   u16_t ofo;
00754   int last;
00755   u16_t poff = IP_HLEN;
00756   u16_t tmp;
00757   int mf_set;
00758 
00759   original_iphdr = (struct ip_hdr *)p->payload;
00760   iphdr = original_iphdr;
00761   if (IPH_HL_BYTES(iphdr) != IP_HLEN) {
00762     /* ip4_frag() does not support IP options */
00763     return ERR_VAL;
00764   }
00765   LWIP_ERROR("ip4_frag(): pbuf too short", p->len >= IP_HLEN, return ERR_VAL);
00766 
00767   /* Save original offset */
00768   tmp = lwip_ntohs(IPH_OFFSET(iphdr));
00769   ofo = tmp & IP_OFFMASK;
00770   /* already fragmented? if so, the last fragment we create must have MF, too */
00771   mf_set = tmp & IP_MF;
00772 
00773   left = (u16_t)(p->tot_len - IP_HLEN);
00774 
00775   while (left) {
00776     /* Fill this fragment */
00777     fragsize = LWIP_MIN(left, (u16_t)(nfb * 8));
00778 
00779 #if LWIP_NETIF_TX_SINGLE_PBUF
00780     rambuf = pbuf_alloc(PBUF_IP, fragsize, PBUF_RAM);
00781     if (rambuf == NULL) {
00782       goto memerr;
00783     }
00784     LWIP_ASSERT("this needs a pbuf in one piece!",
00785                 (rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
00786     poff += pbuf_copy_partial(p, rambuf->payload, fragsize, poff);
00787     /* make room for the IP header */
00788     if (pbuf_add_header(rambuf, IP_HLEN)) {
00789       pbuf_free(rambuf);
00790       goto memerr;
00791     }
00792     /* fill in the IP header */
00793     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
00794     iphdr = (struct ip_hdr *)rambuf->payload;
00795 #else /* LWIP_NETIF_TX_SINGLE_PBUF */
00796     /* When not using a static buffer, create a chain of pbufs.
00797      * The first will be a PBUF_RAM holding the link and IP header.
00798      * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
00799      * but limited to the size of an mtu.
00800      */
00801     rambuf = pbuf_alloc(PBUF_LINK, IP_HLEN, PBUF_RAM);
00802     if (rambuf == NULL) {
00803       goto memerr;
00804     }
00805     LWIP_ASSERT("this needs a pbuf in one piece!",
00806                 (rambuf->len >= (IP_HLEN)));
00807     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
00808     iphdr = (struct ip_hdr *)rambuf->payload;
00809 
00810     left_to_copy = fragsize;
00811     while (left_to_copy) {
00812       struct pbuf_custom_ref *pcr;
00813       u16_t plen = (u16_t)(p->len - poff);
00814       LWIP_ASSERT("p->len >= poff", p->len >= poff);
00815       newpbuflen = LWIP_MIN(left_to_copy, plen);
00816       /* Is this pbuf already empty? */
00817       if (!newpbuflen) {
00818         poff = 0;
00819         p = p->next;
00820         continue;
00821       }
00822       pcr = ip_frag_alloc_pbuf_custom_ref();
00823       if (pcr == NULL) {
00824         pbuf_free(rambuf);
00825         goto memerr;
00826       }
00827       /* Mirror this pbuf, although we might not need all of it. */
00828       newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc,
00829                                     (u8_t *)p->payload + poff, newpbuflen);
00830       if (newpbuf == NULL) {
00831         ip_frag_free_pbuf_custom_ref(pcr);
00832         pbuf_free(rambuf);
00833         goto memerr;
00834       }
00835       pbuf_ref(p);
00836       pcr->original = p;
00837       pcr->pc.custom_free_function = ipfrag_free_pbuf_custom;
00838 
00839       /* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
00840        * so that it is removed when pbuf_dechain is later called on rambuf.
00841        */
00842       pbuf_cat(rambuf, newpbuf);
00843       left_to_copy = (u16_t)(left_to_copy - newpbuflen);
00844       if (left_to_copy) {
00845         poff = 0;
00846         p = p->next;
00847       }
00848     }
00849     poff = (u16_t)(poff + newpbuflen);
00850 #endif /* LWIP_NETIF_TX_SINGLE_PBUF */
00851 
00852     /* Correct header */
00853     last = (left <= netif->mtu - IP_HLEN);
00854 
00855     /* Set new offset and MF flag */
00856     tmp = (IP_OFFMASK & (ofo));
00857     if (!last || mf_set) {
00858       /* the last fragment has MF set if the input frame had it */
00859       tmp = tmp | IP_MF;
00860     }
00861     IPH_OFFSET_SET(iphdr, lwip_htons(tmp));
00862     IPH_LEN_SET(iphdr, lwip_htons((u16_t)(fragsize + IP_HLEN)));
00863     IPH_CHKSUM_SET(iphdr, 0);
00864 #if CHECKSUM_GEN_IP
00865     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_IP) {
00866       IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN));
00867     }
00868 #endif /* CHECKSUM_GEN_IP */
00869 
00870     /* No need for separate header pbuf - we allowed room for it in rambuf
00871      * when allocated.
00872      */
00873     netif->output(netif, rambuf, dest);
00874     IPFRAG_STATS_INC(ip_frag.xmit);
00875 
00876     /* Unfortunately we can't reuse rambuf - the hardware may still be
00877      * using the buffer. Instead we free it (and the ensuing chain) and
00878      * recreate it next time round the loop. If we're lucky the hardware
00879      * will have already sent the packet, the free will really free, and
00880      * there will be zero memory penalty.
00881      */
00882 
00883     pbuf_free(rambuf);
00884     left = (u16_t)(left - fragsize);
00885     ofo = (u16_t)(ofo + nfb);
00886   }
00887   MIB2_STATS_INC(mib2.ipfragoks);
00888   return ERR_OK;
00889 memerr:
00890   MIB2_STATS_INC(mib2.ipfragfails);
00891   return ERR_MEM;
00892 }
00893 #endif /* IP_FRAG */
00894 
00895 #endif /* LWIP_IPV4 */