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