A version of LWIP, provided for backwards compatibility.

Dependents:   AA_DemoBoard DemoBoard HelloServerDemo DemoBoard_RangeIndicator ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers ip_frag.c Source File

ip_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 #include "lwip/ip_frag.h"
00043 #include "lwip/ip.h"
00044 #include "lwip/inet.h"
00045 #include "lwip/inet_chksum.h"
00046 #include "lwip/netif.h"
00047 #include "lwip/snmp.h"
00048 #include "lwip/stats.h"
00049 #include "lwip/icmp.h"
00050 
00051 #include <string.h>
00052 
00053 #if IP_REASSEMBLY
00054 /**
00055  * The IP reassembly code currently has the following limitations:
00056  * - IP header options are not supported
00057  * - fragments must not overlap (e.g. due to different routes),
00058  *   currently, overlapping or duplicate fragments are thrown away
00059  *   if IP_REASS_CHECK_OVERLAP=1 (the default)!
00060  *
00061  * @todo: work with IP header options
00062  */
00063 
00064 /** Setting this to 0, you can turn off checking the fragments for overlapping
00065  * regions. The code gets a little smaller. Only use this if you know that
00066  * overlapping won't occur on your network! */
00067 #ifndef IP_REASS_CHECK_OVERLAP
00068 #define IP_REASS_CHECK_OVERLAP 1
00069 #endif /* IP_REASS_CHECK_OVERLAP */
00070 
00071 /** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
00072  * full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
00073  * Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
00074  * is set to 1, so one datagram can be reassembled at a time, only. */
00075 #ifndef IP_REASS_FREE_OLDEST
00076 #define IP_REASS_FREE_OLDEST 1
00077 #endif /* IP_REASS_FREE_OLDEST */
00078 
00079 #define IP_REASS_FLAG_LASTFRAG 0x01
00080 
00081 /** This is a helper struct which holds the starting
00082  * offset and the ending offset of this fragment to
00083  * easily chain the fragments.
00084  */
00085 struct ip_reass_helper {
00086   struct pbuf *next_pbuf;
00087   u16_t start;
00088   u16_t end;
00089 };
00090 
00091 #define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB)  \
00092   (ip_addr_cmp(&(iphdrA)->src, &(iphdrB)->src) && \
00093    ip_addr_cmp(&(iphdrA)->dest, &(iphdrB)->dest) && \
00094    IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0
00095 
00096 /* global variables */
00097 static struct ip_reassdata *reassdatagrams;
00098 static u16_t ip_reass_pbufcount;
00099 
00100 /* function prototypes */
00101 static void ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
00102 static int ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
00103 
00104 /**
00105  * Reassembly timer base function
00106  * for both NO_SYS == 0 and 1 (!).
00107  *
00108  * Should be called every 1000 msec (defined by IP_TMR_INTERVAL).
00109  */
00110 void
00111 ip_reass_tmr(void)
00112 {
00113   struct ip_reassdata *r, *prev = NULL;
00114 
00115   r = reassdatagrams;
00116   while (r != NULL) {
00117     /* Decrement the timer. Once it reaches 0,
00118      * clean up the incomplete fragment assembly */
00119     if (r->timer > 0) {
00120       r->timer--;
00121       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n",(u16_t)r->timer));
00122       prev = r;
00123       r = r->next;
00124     } else {
00125       /* reassembly timed out */
00126       struct ip_reassdata *tmp;
00127       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n"));
00128       tmp = r;
00129       /* get the next pointer before freeing */
00130       r = r->next;
00131       /* free the helper struct and all enqueued pbufs */
00132       ip_reass_free_complete_datagram(tmp, prev);
00133      }
00134    }
00135 }
00136 
00137 /**
00138  * Free a datagram (struct ip_reassdata) and all its pbufs.
00139  * Updates the total count of enqueued pbufs (ip_reass_pbufcount),
00140  * SNMP counters and sends an ICMP time exceeded packet.
00141  *
00142  * @param ipr datagram to free
00143  * @param prev the previous datagram in the linked list
00144  * @return the number of pbufs freed
00145  */
00146 static int
00147 ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
00148 {
00149   int pbufs_freed = 0;
00150   struct pbuf *p;
00151   struct ip_reass_helper *iprh;
00152 
00153   LWIP_ASSERT("prev != ipr", prev != ipr);
00154   if (prev != NULL) {
00155     LWIP_ASSERT("prev->next == ipr", prev->next == ipr);
00156   }
00157 
00158   snmp_inc_ipreasmfails();
00159 #if LWIP_ICMP
00160   iprh = (struct ip_reass_helper *)ipr->p->payload;
00161   if (iprh->start == 0) {
00162     /* The first fragment was received, send ICMP time exceeded. */
00163     /* First, de-queue the first pbuf from r->p. */
00164     p = ipr->p;
00165     ipr->p = iprh->next_pbuf;
00166     /* Then, copy the original header into it. */
00167     SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN);
00168     icmp_time_exceeded(p, ICMP_TE_FRAG);
00169     pbufs_freed += pbuf_clen(p);
00170     pbuf_free(p);
00171   }
00172 #endif /* LWIP_ICMP */
00173 
00174   /* First, free all received pbufs.  The individual pbufs need to be released 
00175      separately as they have not yet been chained */
00176   p = ipr->p;
00177   while (p != NULL) {
00178     struct pbuf *pcur;
00179     iprh = (struct ip_reass_helper *)p->payload;
00180     pcur = p;
00181     /* get the next pointer before freeing */
00182     p = iprh->next_pbuf;
00183     pbufs_freed += pbuf_clen(pcur);
00184     pbuf_free(pcur);    
00185   }
00186   /* Then, unchain the struct ip_reassdata from the list and free it. */
00187   ip_reass_dequeue_datagram(ipr, prev);
00188   LWIP_ASSERT("ip_reass_pbufcount >= clen", ip_reass_pbufcount >= pbufs_freed);
00189   ip_reass_pbufcount -= pbufs_freed;
00190 
00191   return pbufs_freed;
00192 }
00193 
00194 #if IP_REASS_FREE_OLDEST
00195 /**
00196  * Free the oldest datagram to make room for enqueueing new fragments.
00197  * The datagram 'fraghdr' belongs to is not freed!
00198  *
00199  * @param fraghdr IP header of the current fragment
00200  * @param pbufs_needed number of pbufs needed to enqueue
00201  *        (used for freeing other datagrams if not enough space)
00202  * @return the number of pbufs freed
00203  */
00204 static int
00205 ip_reass_remove_oldest_datagram(struct ip_hdr *fraghdr, int pbufs_needed)
00206 {
00207   /* @todo Can't we simply remove the last datagram in the
00208    *       linked list behind reassdatagrams?
00209    */
00210   struct ip_reassdata *r, *oldest, *prev;
00211   int pbufs_freed = 0, pbufs_freed_current;
00212   int other_datagrams;
00213 
00214   /* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
00215    * but don't free the datagram that 'fraghdr' belongs to! */
00216   do {
00217     oldest = NULL;
00218     prev = NULL;
00219     other_datagrams = 0;
00220     r = reassdatagrams;
00221     while (r != NULL) {
00222       if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) {
00223         /* Not the same datagram as fraghdr */
00224         other_datagrams++;
00225         if (oldest == NULL) {
00226           oldest = r;
00227         } else if (r->timer <= oldest->timer) {
00228           /* older than the previous oldest */
00229           oldest = r;
00230         }
00231       }
00232       if (r->next != NULL) {
00233         prev = r;
00234       }
00235       r = r->next;
00236     }
00237     if (oldest != NULL) {
00238       pbufs_freed_current = ip_reass_free_complete_datagram(oldest, prev);
00239       pbufs_freed += pbufs_freed_current;
00240     }
00241   } while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1));
00242   return pbufs_freed;
00243 }
00244 #endif /* IP_REASS_FREE_OLDEST */
00245 
00246 /**
00247  * Enqueues a new fragment into the fragment queue
00248  * @param fraghdr points to the new fragments IP hdr
00249  * @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space)
00250  * @return A pointer to the queue location into which the fragment was enqueued
00251  */
00252 static struct ip_reassdata*
00253 ip_reass_enqueue_new_datagram(struct ip_hdr *fraghdr, int clen)
00254 {
00255   struct ip_reassdata* ipr;
00256   /* No matching previous fragment found, allocate a new reassdata struct */
00257   ipr = static_cast<struct ip_reassdata *>(memp_malloc(MEMP_REASSDATA));
00258   if (ipr == NULL) {
00259 #if IP_REASS_FREE_OLDEST
00260     if (ip_reass_remove_oldest_datagram(fraghdr, clen) >= clen) {
00261       ipr = static_cast<struct ip_reassdata *>(memp_malloc(MEMP_REASSDATA));
00262     }
00263     if (ipr == NULL)
00264 #endif /* IP_REASS_FREE_OLDEST */
00265     {
00266       IPFRAG_STATS_INC(ip_frag.memerr);
00267       LWIP_DEBUGF(IP_REASS_DEBUG,("Failed to alloc reassdata struct\n"));
00268       return NULL;
00269     }
00270   }
00271   memset(ipr, 0, sizeof(struct ip_reassdata));
00272   ipr->timer = IP_REASS_MAXAGE;
00273 
00274   /* enqueue the new structure to the front of the list */
00275   ipr->next = reassdatagrams;
00276   reassdatagrams = ipr;
00277   /* copy the ip header for later tests and input */
00278   /* @todo: no ip options supported? */
00279   SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN);
00280   return ipr;
00281 }
00282 
00283 /**
00284  * Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs.
00285  * @param ipr points to the queue entry to dequeue
00286  */
00287 static void
00288 ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
00289 {
00290   
00291   /* dequeue the reass struct  */
00292   if (reassdatagrams == ipr) {
00293     /* it was the first in the list */
00294     reassdatagrams = ipr->next;
00295   } else {
00296     /* it wasn't the first, so it must have a valid 'prev' */
00297     LWIP_ASSERT("sanity check linked list", prev != NULL);
00298     prev->next = ipr->next;
00299   }
00300 
00301   /* now we can free the ip_reass struct */
00302   memp_free(MEMP_REASSDATA, ipr);
00303 }
00304 
00305 /**
00306  * Chain a new pbuf into the pbuf list that composes the datagram.  The pbuf list
00307  * will grow over time as  new pbufs are rx.
00308  * Also checks that the datagram passes basic continuity checks (if the last
00309  * fragment was received at least once).
00310  * @param root_p points to the 'root' pbuf for the current datagram being assembled.
00311  * @param new_p points to the pbuf for the current fragment
00312  * @return 0 if invalid, >0 otherwise
00313  */
00314 static int
00315 ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct pbuf *new_p)
00316 {
00317   struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
00318   struct pbuf *q;
00319   u16_t offset,len;
00320   struct ip_hdr *fraghdr;
00321   int valid = 1;
00322 
00323   /* Extract length and fragment offset from current fragment */
00324   fraghdr = (struct ip_hdr*)new_p->payload; 
00325   len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
00326   offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
00327 
00328   /* overwrite the fragment's ip header from the pbuf with our helper struct,
00329    * and setup the embedded helper structure. */
00330   /* make sure the struct ip_reass_helper fits into the IP header */
00331   LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN",
00332               sizeof(struct ip_reass_helper) <= IP_HLEN);
00333   iprh = (struct ip_reass_helper*)new_p->payload;
00334   iprh->next_pbuf = NULL;
00335   iprh->start = offset;
00336   iprh->end = offset + len;
00337 
00338   /* Iterate through until we either get to the end of the list (append),
00339    * or we find on with a larger offset (insert). */
00340   for (q = ipr->p; q != NULL;) {
00341     iprh_tmp = (struct ip_reass_helper*)q->payload;
00342     if (iprh->start < iprh_tmp->start) {
00343       /* the new pbuf should be inserted before this */
00344       iprh->next_pbuf = q;
00345       if (iprh_prev != NULL) {
00346         /* not the fragment with the lowest offset */
00347 #if IP_REASS_CHECK_OVERLAP
00348         if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) {
00349           /* fragment overlaps with previous or following, throw away */
00350           goto freepbuf;
00351         }
00352 #endif /* IP_REASS_CHECK_OVERLAP */
00353         iprh_prev->next_pbuf = new_p;
00354       } else {
00355         /* fragment with the lowest offset */
00356         ipr->p = new_p;
00357       }
00358       break;
00359     } else if(iprh->start == iprh_tmp->start) {
00360       /* received the same datagram twice: no need to keep the datagram */
00361       goto freepbuf;
00362 #if IP_REASS_CHECK_OVERLAP
00363     } else if(iprh->start < iprh_tmp->end) {
00364       /* overlap: no need to keep the new datagram */
00365       goto freepbuf;
00366 #endif /* IP_REASS_CHECK_OVERLAP */
00367     } else {
00368       /* Check if the fragments received so far have no wholes. */
00369       if (iprh_prev != NULL) {
00370         if (iprh_prev->end != iprh_tmp->start) {
00371           /* There is a fragment missing between the current
00372            * and the previous fragment */
00373           valid = 0;
00374         }
00375       }
00376     }
00377     q = iprh_tmp->next_pbuf;
00378     iprh_prev = iprh_tmp;
00379   }
00380 
00381   /* If q is NULL, then we made it to the end of the list. Determine what to do now */
00382   if (q == NULL) {
00383     if (iprh_prev != NULL) {
00384       /* this is (for now), the fragment with the highest offset:
00385        * chain it to the last fragment */
00386 #if IP_REASS_CHECK_OVERLAP
00387       LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start);
00388 #endif /* IP_REASS_CHECK_OVERLAP */
00389       iprh_prev->next_pbuf = new_p;
00390       if (iprh_prev->end != iprh->start) {
00391         valid = 0;
00392       }
00393     } else {
00394 #if IP_REASS_CHECK_OVERLAP
00395       LWIP_ASSERT("no previous fragment, this must be the first fragment!",
00396         ipr->p == NULL);
00397 #endif /* IP_REASS_CHECK_OVERLAP */
00398       /* this is the first fragment we ever received for this ip datagram */
00399       ipr->p = new_p;
00400     }
00401   }
00402 
00403   /* At this point, the validation part begins: */
00404   /* If we already received the last fragment */
00405   if ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0) {
00406     /* and had no wholes so far */
00407     if (valid) {
00408       /* then check if the rest of the fragments is here */
00409       /* Check if the queue starts with the first datagram */
00410       if (((struct ip_reass_helper*)ipr->p->payload)->start != 0) {
00411         valid = 0;
00412       } else {
00413         /* and check that there are no wholes after this datagram */
00414         iprh_prev = iprh;
00415         q = iprh->next_pbuf;
00416         while (q != NULL) {
00417           iprh = (struct ip_reass_helper*)q->payload;
00418           if (iprh_prev->end != iprh->start) {
00419             valid = 0;
00420             break;
00421           }
00422           iprh_prev = iprh;
00423           q = iprh->next_pbuf;
00424         }
00425         /* if still valid, all fragments are received
00426          * (because to the MF==0 already arrived */
00427         if (valid) {
00428           LWIP_ASSERT("sanity check", ipr->p != NULL);
00429           LWIP_ASSERT("sanity check",
00430             ((struct ip_reass_helper*)ipr->p->payload) != iprh);
00431           LWIP_ASSERT("validate_datagram:next_pbuf!=NULL",
00432             iprh->next_pbuf == NULL);
00433           LWIP_ASSERT("validate_datagram:datagram end!=datagram len",
00434             iprh->end == ipr->datagram_len);
00435         }
00436       }
00437     }
00438     /* If valid is 0 here, there are some fragments missing in the middle
00439      * (since MF == 0 has already arrived). Such datagrams simply time out if
00440      * no more fragments are received... */
00441     return valid;
00442   }
00443   /* If we come here, not all fragments were received, yet! */
00444   return 0; /* not yet valid! */
00445 #if IP_REASS_CHECK_OVERLAP
00446 freepbuf:
00447   ip_reass_pbufcount -= pbuf_clen(new_p);
00448   pbuf_free(new_p);
00449   return 0;
00450 #endif /* IP_REASS_CHECK_OVERLAP */
00451 }
00452 
00453 /**
00454  * Reassembles incoming IP fragments into an IP datagram.
00455  *
00456  * @param p points to a pbuf chain of the fragment
00457  * @return NULL if reassembly is incomplete, ? otherwise
00458  */
00459 struct pbuf *
00460 ip_reass(struct pbuf *p)
00461 {
00462   struct pbuf *r;
00463   struct ip_hdr *fraghdr;
00464   struct ip_reassdata *ipr;
00465   struct ip_reass_helper *iprh;
00466   u16_t offset, len;
00467   u8_t clen;
00468   struct ip_reassdata *ipr_prev = NULL;
00469 
00470   IPFRAG_STATS_INC(ip_frag.recv);
00471   snmp_inc_ipreasmreqds();
00472 
00473   fraghdr = (struct ip_hdr*)p->payload;
00474 
00475   if ((IPH_HL(fraghdr) * 4) != IP_HLEN) {
00476     LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: IP options currently not supported!\n"));
00477     IPFRAG_STATS_INC(ip_frag.err);
00478     goto nullreturn;
00479   }
00480 
00481   offset = (ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) * 8;
00482   len = ntohs(IPH_LEN(fraghdr)) - IPH_HL(fraghdr) * 4;
00483 
00484   /* Check if we are allowed to enqueue more datagrams. */
00485   clen = pbuf_clen(p);
00486   if ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
00487 #if IP_REASS_FREE_OLDEST
00488     if (!ip_reass_remove_oldest_datagram(fraghdr, clen) ||
00489         ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS))
00490 #endif /* IP_REASS_FREE_OLDEST */
00491     {
00492       /* No datagram could be freed and still too many pbufs enqueued */
00493       LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n",
00494         ip_reass_pbufcount, clen, IP_REASS_MAX_PBUFS));
00495       IPFRAG_STATS_INC(ip_frag.memerr);
00496       /* @todo: send ICMP time exceeded here? */
00497       /* drop this pbuf */
00498       goto nullreturn;
00499     }
00500   }
00501 
00502   /* Look for the datagram the fragment belongs to in the current datagram queue,
00503    * remembering the previous in the queue for later dequeueing. */
00504   for (ipr = reassdatagrams; ipr != NULL; ipr = ipr->next) {
00505     /* Check if the incoming fragment matches the one currently present
00506        in the reassembly buffer. If so, we proceed with copying the
00507        fragment into the buffer. */
00508     if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
00509       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass: matching previous fragment ID=%"X16_F"\n",
00510         ntohs(IPH_ID(fraghdr))));
00511       IPFRAG_STATS_INC(ip_frag.cachehit);
00512       break;
00513     }
00514     ipr_prev = ipr;
00515   }
00516 
00517   if (ipr == NULL) {
00518   /* Enqueue a new datagram into the datagram queue */
00519     ipr = ip_reass_enqueue_new_datagram(fraghdr, clen);
00520     /* Bail if unable to enqueue */
00521     if(ipr == NULL) {
00522       goto nullreturn;
00523     }
00524   } else {
00525     if (((ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) && 
00526       ((ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
00527       /* ipr->iphdr is not the header from the first fragment, but fraghdr is
00528        * -> copy fraghdr into ipr->iphdr since we want to have the header
00529        * of the first fragment (for ICMP time exceeded and later, for copying
00530        * all options, if supported)*/
00531       SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN);
00532     }
00533   }
00534   /* Track the current number of pbufs current 'in-flight', in order to limit 
00535   the number of fragments that may be enqueued at any one time */
00536   ip_reass_pbufcount += clen;
00537 
00538   /* At this point, we have either created a new entry or pointing 
00539    * to an existing one */
00540 
00541   /* check for 'no more fragments', and update queue entry*/
00542   if ((ntohs(IPH_OFFSET(fraghdr)) & IP_MF) == 0) {
00543     ipr->flags |= IP_REASS_FLAG_LASTFRAG;
00544     ipr->datagram_len = offset + len;
00545     LWIP_DEBUGF(IP_REASS_DEBUG,
00546      ("ip_reass: last fragment seen, total len %"S16_F"\n",
00547       ipr->datagram_len));
00548   }
00549   /* find the right place to insert this pbuf */
00550   /* @todo: trim pbufs if fragments are overlapping */
00551   if (ip_reass_chain_frag_into_datagram_and_validate(ipr, p)) {
00552     /* the totally last fragment (flag more fragments = 0) was received at least
00553      * once AND all fragments are received */
00554     ipr->datagram_len += IP_HLEN;
00555 
00556     /* save the second pbuf before copying the header over the pointer */
00557     r = ((struct ip_reass_helper*)ipr->p->payload)->next_pbuf;
00558 
00559     /* copy the original ip header back to the first pbuf */
00560     fraghdr = (struct ip_hdr*)(ipr->p->payload);
00561     SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
00562     IPH_LEN_SET(fraghdr, htons(ipr->datagram_len));
00563     IPH_OFFSET_SET(fraghdr, 0);
00564     IPH_CHKSUM_SET(fraghdr, 0);
00565     /* @todo: do we need to set calculate the correct checksum? */
00566     IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN));
00567 
00568     p = ipr->p;
00569 
00570     /* chain together the pbufs contained within the reass_data list. */
00571     while(r != NULL) {
00572       iprh = (struct ip_reass_helper*)r->payload;
00573 
00574       /* hide the ip header for every succeding fragment */
00575       pbuf_header(r, -IP_HLEN);
00576       pbuf_cat(p, r);
00577       r = iprh->next_pbuf;
00578     }
00579     /* release the sources allocate for the fragment queue entry */
00580     ip_reass_dequeue_datagram(ipr, ipr_prev);
00581 
00582     /* and adjust the number of pbufs currently queued for reassembly. */
00583     ip_reass_pbufcount -= pbuf_clen(p);
00584 
00585     /* Return the pbuf chain */
00586     return p;
00587   }
00588   /* the datagram is not (yet?) reassembled completely */
00589   LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass_pbufcount: %d out\n", ip_reass_pbufcount));
00590   return NULL;
00591 
00592 nullreturn:
00593   LWIP_DEBUGF(IP_REASS_DEBUG,("ip_reass: nullreturn\n"));
00594   IPFRAG_STATS_INC(ip_frag.drop);
00595   pbuf_free(p);
00596   return NULL;
00597 }
00598 #endif /* IP_REASSEMBLY */
00599 
00600 #if IP_FRAG
00601 #if IP_FRAG_USES_STATIC_BUF
00602 static u8_t buf[LWIP_MEM_ALIGN_SIZE(IP_FRAG_MAX_MTU)];
00603 #endif /* IP_FRAG_USES_STATIC_BUF */
00604 
00605 /**
00606  * Fragment an IP datagram if too large for the netif.
00607  *
00608  * Chop the datagram in MTU sized chunks and send them in order
00609  * by using a fixed size static memory buffer (PBUF_REF) or
00610  * point PBUF_REFs into p (depending on IP_FRAG_USES_STATIC_BUF).
00611  *
00612  * @param p ip packet to send
00613  * @param netif the netif on which to send
00614  * @param dest destination ip address to which to send
00615  *
00616  * @return ERR_OK if sent successfully, err_t otherwise
00617  */
00618 err_t 
00619 ip_frag(struct pbuf *p, struct netif *netif, struct ip_addr *dest)
00620 {
00621   struct pbuf *rambuf;
00622 #if IP_FRAG_USES_STATIC_BUF
00623   struct pbuf *header;
00624 #else
00625   struct pbuf *newpbuf;
00626   struct ip_hdr *original_iphdr;
00627 #endif
00628   struct ip_hdr *iphdr;
00629   u16_t nfb;
00630   u16_t left, cop;
00631   u16_t mtu = netif->mtu;
00632   u16_t ofo, omf;
00633   u16_t last;
00634   u16_t poff = IP_HLEN;
00635   u16_t tmp;
00636 #if !IP_FRAG_USES_STATIC_BUF
00637   u16_t newpbuflen = 0;
00638   u16_t left_to_copy;
00639 #endif
00640 
00641   /* Get a RAM based MTU sized pbuf */
00642 #if IP_FRAG_USES_STATIC_BUF
00643   /* When using a static buffer, we use a PBUF_REF, which we will
00644    * use to reference the packet (without link header).
00645    * Layer and length is irrelevant.
00646    */
00647   rambuf = pbuf_alloc(PBUF_LINK, 0, PBUF_REF);
00648   if (rambuf == NULL) {
00649     LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc(PBUF_LINK, 0, PBUF_REF) failed\n"));
00650     return ERR_MEM;
00651   }
00652   rambuf->tot_len = rambuf->len = mtu;
00653   rambuf->payload = LWIP_MEM_ALIGN((void *)buf);
00654 
00655   /* Copy the IP header in it */
00656   iphdr = static_cast<struct ip_hdr *>(rambuf->payload);
00657   SMEMCPY(iphdr, p->payload, IP_HLEN);
00658 #else /* IP_FRAG_USES_STATIC_BUF */
00659   original_iphdr = p->payload;
00660   iphdr = original_iphdr;
00661 #endif /* IP_FRAG_USES_STATIC_BUF */
00662 
00663   /* Save original offset */
00664   tmp = ntohs(IPH_OFFSET(iphdr));
00665   ofo = tmp & IP_OFFMASK;
00666   omf = tmp & IP_MF;
00667 
00668   left = p->tot_len - IP_HLEN;
00669 
00670   nfb = (mtu - IP_HLEN) / 8;
00671 
00672   while (left) {
00673     last = (left <= mtu - IP_HLEN);
00674 
00675     /* Set new offset and MF flag */
00676     tmp = omf | (IP_OFFMASK & (ofo));
00677     if (!last)
00678       tmp = tmp | IP_MF;
00679 
00680     /* Fill this fragment */
00681     cop = last ? left : nfb * 8;
00682 
00683 #if IP_FRAG_USES_STATIC_BUF
00684     poff += pbuf_copy_partial(p, (u8_t*)iphdr + IP_HLEN, cop, poff);
00685 #else /* IP_FRAG_USES_STATIC_BUF */
00686     /* When not using a static buffer, create a chain of pbufs.
00687      * The first will be a PBUF_RAM holding the link and IP header.
00688      * The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
00689      * but limited to the size of an mtu.
00690      */
00691     rambuf = pbuf_alloc(PBUF_LINK, IP_HLEN, PBUF_RAM);
00692     if (rambuf == NULL) {
00693       return ERR_MEM;
00694     }
00695     LWIP_ASSERT("this needs a pbuf in one piece!",
00696                 (p->len >= (IP_HLEN)));
00697     SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
00698     iphdr = rambuf->payload;
00699 
00700     /* Can just adjust p directly for needed offset. */
00701     p->payload = (u8_t *)p->payload + poff;
00702     p->len -= poff;
00703 
00704     left_to_copy = cop;
00705     while (left_to_copy) {
00706       newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
00707       /* Is this pbuf already empty? */
00708       if (!newpbuflen) {
00709         p = p->next;
00710         continue;
00711       }
00712       newpbuf = pbuf_alloc(PBUF_RAW, 0, PBUF_REF);
00713       if (newpbuf == NULL) {
00714         pbuf_free(rambuf);
00715         return ERR_MEM;
00716       }
00717       /* Mirror this pbuf, although we might not need all of it. */
00718       newpbuf->payload = p->payload;
00719       newpbuf->len = newpbuf->tot_len = newpbuflen;
00720       /* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
00721        * so that it is removed when pbuf_dechain is later called on rambuf.
00722        */
00723       pbuf_cat(rambuf, newpbuf);
00724       left_to_copy -= newpbuflen;
00725       if (left_to_copy)
00726         p = p->next;
00727     }
00728     poff = newpbuflen;
00729 #endif /* IP_FRAG_USES_STATIC_BUF */
00730 
00731     /* Correct header */
00732     IPH_OFFSET_SET(iphdr, htons(tmp));
00733     IPH_LEN_SET(iphdr, htons(cop + IP_HLEN));
00734     IPH_CHKSUM_SET(iphdr, 0);
00735     IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN));
00736 
00737 #if IP_FRAG_USES_STATIC_BUF
00738     if (last)
00739       pbuf_realloc(rambuf, left + IP_HLEN);
00740 
00741     /* This part is ugly: we alloc a RAM based pbuf for 
00742      * the link level header for each chunk and then 
00743      * free it.A PBUF_ROM style pbuf for which pbuf_header
00744      * worked would make things simpler.
00745      */
00746     header = pbuf_alloc(PBUF_LINK, 0, PBUF_RAM);
00747     if (header != NULL) {
00748       pbuf_chain(header, rambuf);
00749       netif->output(netif, header, dest);
00750       IPFRAG_STATS_INC(ip_frag.xmit);
00751       snmp_inc_ipfragcreates();
00752       pbuf_free(header);
00753     } else {
00754       LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_frag: pbuf_alloc() for header failed\n"));
00755       pbuf_free(rambuf);
00756       return ERR_MEM;
00757     }
00758 #else /* IP_FRAG_USES_STATIC_BUF */
00759     /* No need for separate header pbuf - we allowed room for it in rambuf
00760      * when allocated.
00761      */
00762     netif->output(netif, rambuf, dest);
00763     IPFRAG_STATS_INC(ip_frag.xmit);
00764 
00765     /* Unfortunately we can't reuse rambuf - the hardware may still be
00766      * using the buffer. Instead we free it (and the ensuing chain) and
00767      * recreate it next time round the loop. If we're lucky the hardware
00768      * will have already sent the packet, the free will really free, and
00769      * there will be zero memory penalty.
00770      */
00771     
00772     pbuf_free(rambuf);
00773 #endif /* IP_FRAG_USES_STATIC_BUF */
00774     left -= cop;
00775     ofo += nfb;
00776   }
00777 #if IP_FRAG_USES_STATIC_BUF
00778   pbuf_free(rambuf);
00779 #endif /* IP_FRAG_USES_STATIC_BUF */
00780   snmp_inc_ipfragoks();
00781   return ERR_OK;
00782 }
00783 #endif /* IP_FRAG */