2 This file is part of GNUnet
3 (C) 2004, 2006, 2009 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file fragmentation/fragmentation.c
22 * @brief fragmentation and defragmentation, this code allows
23 * sending and receiving messages that are larger than
24 * the MTU of the transport. Messages are still limited
25 * to a maximum size of 65535 bytes, which is a good
26 * idea because otherwise we may need ungainly fragmentation
27 * buffers. Each connected peer can have at most one
28 * fragmented packet at any given point in time (prevents
29 * DoS attacks). Fragmented messages that have not been
30 * completed after a certain amount of time are discarded.
31 * @author Christian Grothoff
35 #include "gnunet_fragmentation_lib.h"
36 #include "gnunet_protocols.h"
37 #include "gnunet_util_lib.h"
39 * Message fragment. This header is followed
40 * by the actual data of the fragment.
45 struct GNUNET_MessageHeader header;
50 uint32_t off GNUNET_PACKED;
53 * "unique" id for the fragment
55 uint64_t id GNUNET_PACKED;
62 struct GNUNET_FRAGEMENT_Ctxbuffer{
67 struct GNUNET_TIME_Absolute receivedTime;
68 struct GNUNET_PeerIdentity *peerID;
69 struct GNUNET_FRAGEMENT_Ctxbuffer *next;
75 * Defragmentation context.
77 struct GNUNET_FRAGMENT_Context
80 struct GNUNET_FRAGEMENT_Ctxbuffer *buffer;
85 * Fragment an over-sized message.
87 * @param msg the message to fragment
88 * @param mtu the maximum message size
89 * @param proc function to call for each fragment
90 * @param proc_cls closure for proc
93 GNUNET_FRAGMENT_fragment (const struct GNUNET_MessageHeader *msg,
95 GNUNET_FRAGMENT_MessageProcessor proc,
98 uint32_t id = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 256);
99 size_t size = sizeof(struct Fragment);
101 uint16_t lastSize = (msg->size) % (mtu-size);
102 int num = ceil(msg->size / mtu - size);
104 for(i = 0; i<num; i++){
105 struct Fragment *frag = (struct Fragment *)GNUNET_malloc(size);
106 frag->header.type = htons(GNUNET_MESSAGE_TYPE_FRAGMENT);
107 frag->id = htonl(id);
108 frag->off = htons(mtu*i);
109 frag->mtu = htons(mtu);
111 frag->totalNum = htons(num+1);
114 frag->totalNum = htons(num);
117 frag->header.size = htons(mtu - size);
118 memcpy((char*)&frag[1], (char *)&msg[1]+frag->off, mtu - size);
121 frag->header.size = htons(lastSize);
122 memcpy((char*)&frag[1], (char *)&msg[1]+frag->off, lastSize);
124 proc(proc_cls, &frag->header);
132 * Create a defragmentation context.
134 * @param stats statistics context
135 * @param proc function to call with defragmented messages
136 * @param proc_cls closure for proc
137 * @return the defragmentation context
139 struct GNUNET_FRAGMENT_Context *
140 GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
141 GNUNET_FRAGMENT_MessageProcessor proc,
144 struct GNUNET_FRAGMENT_Context *ctx = (struct GNUNET_FRAGMENT_Context*)GNUNET_malloc(sizeof(struct GNUNET_FRAGMENT_Context));
152 * Destroy the given defragmentation context.
155 GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *ctx)
157 struct GNUNET_FRAGEMENT_Ctxbuffer *buffer;
158 for(buffer = ctx->buffer; buffer!=NULL; buffer = buffer->next){
159 GNUNET_free(buffer->num);
168 * We have received a fragment. Process it.
170 * @param ctx the context
171 * @param sender who transmitted the fragment
172 * @param msg the message that was received
175 GNUNET_FRAGMENT_process (struct GNUNET_FRAGMENT_Context *ctx,
176 const struct GNUNET_PeerIdentity *sender,
177 const struct GNUNET_MessageHeader *msg)
179 uint16_t type = ntohs(msg->type);
180 int exited = 0, received = 0;
181 if(type!=GNUNET_MESSAGE_TYPE_FRAGMENT){
184 struct Fragment *frag = (struct Fragment *)msg;
185 struct GNUNET_FRAGEMENT_Ctxbuffer* buffer;
186 for(buffer = ctx->buffer; buffer!= NULL; buffer = buffer->next){
187 if(ctx->buffer->counter == ntohs(frag->totalNum)){return;}
188 if(buffer->id == ntohl(frag->id)&&(buffer->peerID==sender)){
191 for(i = 0; i<ntohs(frag->totalNum); i++){
192 if(buffer->num[i]==ntohs(frag->off)/ntohs(frag->mtu)){
198 buffer->num[buffer->counter++]=ntohs(frag->off)/ntohs(frag->mtu);
200 buffer->receivedTime = GNUNET_TIME_absolute_get ();
201 uint16_t size = ntohs(frag->header.size);
202 memcpy(&buffer->buff[ntohs(frag->off)], &frag[1], size);
207 buffer = (struct GNUNET_FRAGEMENT_Ctxbuffer* )GNUNET_malloc(sizeof(struct GNUNET_FRAGEMENT_Ctxbuffer));
208 buffer->num = (int*)GNUNET_malloc(ntohs(frag->totalNum)*sizeof(int));
209 buffer->num[buffer->counter++]=ntohs(frag->off)/ntohs(frag->mtu);
210 memcpy(buffer->peerID,sender,sizeof(struct GNUNET_PeerIdentity));
211 buffer->receivedTime = GNUNET_TIME_absolute_get ();
212 uint16_t size = ntohs(frag->header.size);
213 memcpy(&buffer->buff[ntohs(frag->off)], &frag[1], size);
223 * How many buckets does the fragment hash table
226 #define DEFRAG_BUCKET_COUNT 16
229 * After how long do fragments time out?
231 #ifndef DEFRAGMENTATION_TIMEOUT
232 #define DEFRAGMENTATION_TIMEOUT (3 * GNUNET_CRON_MINUTES)
236 * Entry in the linked list of fragments.
241 P2P_fragmentation_MESSAGE *frag;
245 * Entry in the GNUNET_hash table of fragments.
251 GNUNET_PeerIdentity sender;
256 #define FRAGSIZE(fl) ((ntohs(fl->frag->header.size)-sizeof(P2P_fragmentation_MESSAGE)))
258 static GNUNET_CoreAPIForPlugins *coreAPI;
260 static GNUNET_Stats_ServiceAPI *stats;
262 static int stat_defragmented;
264 static int stat_fragmented;
266 static int stat_discarded;
269 * Hashtable *with* collision management!
271 static FC *defragmentationCache[DEFRAG_BUCKET_COUNT];
274 * Lock for the defragmentation cache.
276 static struct GNUNET_Mutex *defragCacheLock;
279 freeFL (FL * fl, int c)
285 stats->change (stat_discarded, c);
286 GNUNET_free (fl->frag);
293 * This cron job ensures that we purge buffers of fragments
294 * that have timed out. It can run in much longer intervals
295 * than the defragmentationCron, e.g. every 60s.
297 * This method goes through the hashtable, finds entries that
298 * have timed out and removes them (and all the fragments that
299 * belong to the entry). It's a bit more complicated as the
300 * collision list is also collapsed.
303 defragmentationPurgeCron (void *unused)
310 GNUNET_mutex_lock (defragCacheLock);
311 for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
314 smf = defragmentationCache[i];
317 if (smf->ttl < GNUNET_get_time ())
319 /* free linked list of fragments */
320 freeFL (smf->head, 1);
324 defragmentationCache[i] = next;
334 } /* while smf != NULL */
335 } /* for all buckets */
336 GNUNET_mutex_unlock (defragCacheLock);
340 * Check if this fragment-list is complete. If yes, put it together,
341 * process and free all buffers. Does not free the pep
342 * itself (but sets the TTL to 0 to have the cron free it
343 * in the next iteration).
345 * @param pep the entry in the GNUNET_hash table
348 checkComplete (FC * pep)
355 GNUNET_GE_ASSERT (NULL, pep != NULL);
359 len = ntohs (pos->frag->len);
361 goto CLEANUP; /* really bad error! */
363 while ((pos != NULL) && (ntohs (pos->frag->off) <= off))
365 if (off >= off + FRAGSIZE (pos))
366 goto CLEANUP; /* error! */
367 if (ntohs (pos->frag->off) + FRAGSIZE (pos) > off)
368 off = ntohs (pos->frag->off) + FRAGSIZE (pos);
370 goto CLEANUP; /* error! */
374 return; /* some fragment is still missing */
376 msg = GNUNET_malloc (len);
380 memcpy (&msg[ntohs (pos->frag->off)], &pos->frag[1], FRAGSIZE (pos));
384 stats->change (stat_defragmented, 1);
386 printf ("Finished defragmentation!\n");
388 /* handle message! */
389 coreAPI->loopback_send (&pep->sender, msg, len, GNUNET_YES, NULL);
392 /* free fragment buffers */
393 freeFL (pep->head, 0);
399 * See if the new fragment is a part of this entry and join them if
400 * yes. Return GNUNET_SYSERR if the fragments do not match. Return GNUNET_OK if
401 * the fragments do match and the fragment has been processed. The
402 * defragCacheLock is already acquired by the caller whenever this
403 * method is called.<p>
405 * @param entry the entry in the cache
406 * @param pep the new entry
407 * @param packet the ip part in the new entry
411 const GNUNET_PeerIdentity * sender,
412 const P2P_fragmentation_MESSAGE * packet)
414 /* frame before ours; may end in the middle of
415 our frame or before it starts; NULL if we are
416 the earliest position we have received so far */
418 /* frame after ours; may start in the middle of
419 our frame or after it; NULL if we are the last
420 fragment we have received so far */
422 /* current position in the frame-list */
424 /* the new entry that we're inserting */
429 GNUNET_GE_ASSERT (NULL, entry != NULL);
430 if (0 != memcmp (sender, &entry->sender, sizeof (GNUNET_PeerIdentity)))
431 return GNUNET_SYSERR; /* wrong fragment list, try another! */
432 if (ntohl (packet->id) != entry->id)
433 return GNUNET_SYSERR; /* wrong fragment list, try another! */
435 printf ("Received fragment %u from %u to %u\n",
438 ntohs (packet->off) + ntohs (packet->header.size) -
439 sizeof (P2P_fragmentation_MESSAGE));
442 if ((pos != NULL) && (packet->len != pos->frag->len))
443 return GNUNET_SYSERR; /* wrong fragment size */
446 /* find the before-frame */
447 while ((pos != NULL) && (ntohs (pos->frag->off) < ntohs (packet->off)))
453 /* find the after-frame */
455 ntohs (packet->off) + ntohs (packet->header.size) -
456 sizeof (P2P_fragmentation_MESSAGE);
457 if (end <= ntohs (packet->off))
460 GNUNET_GE_DEVELOPER | GNUNET_GE_DEBUG | GNUNET_GE_BULK,
461 "Received invalid fragment at %s:%d\n", __FILE__,
463 return GNUNET_SYSERR; /* yuck! integer overflow! */
470 while ((after != NULL) && (ntohs (after->frag->off) < end))
473 if ((before != NULL) && (before == after))
475 /* this implies after or before != NULL and thereby the new
476 fragment is redundant as it is fully enclosed in an earlier
479 stats->change (stat_defragmented, 1);
480 return GNUNET_OK; /* drop, there is a packet that spans our range! */
483 if ((before != NULL) &&
485 ((htons (before->frag->off) +
486 FRAGSIZE (before)) >= htons (after->frag->off)))
488 /* this implies that the fragment that starts before us and the
489 fragment that comes after this one leave no space in the middle
490 or even overlap; thus we can drop this redundant piece */
492 stats->change (stat_defragmented, 1);
497 pep = GNUNET_malloc (sizeof (FC));
498 pep->frag = GNUNET_malloc (ntohs (packet->header.size));
499 memcpy (pep->frag, packet, ntohs (packet->header.size));
509 GNUNET_free (pos->frag);
515 /* end of insert first */
520 /* insert last: find the end, free everything after it */
521 freeFL (before->link, 1);
526 /* ok, we are filling the middle between two fragments; insert. If
527 there is anything else in the middle, it can be dropped as we're
528 bigger & cover that area as well */
529 /* free everything between before and after */
534 GNUNET_free (pos->frag);
542 entry->ttl = GNUNET_get_time () + DEFRAGMENTATION_TIMEOUT;
543 checkComplete (entry);
548 * Defragment the given fragment and pass to handler once
549 * defragmentation is complete.
551 * @param frag the packet to defragment
552 * @return GNUNET_SYSERR if the fragment is invalid
555 processFragment (const GNUNET_PeerIdentity * sender,
556 const GNUNET_MessageHeader * frag)
561 if (ntohs (frag->size) < sizeof (P2P_fragmentation_MESSAGE))
562 return GNUNET_SYSERR;
564 GNUNET_mutex_lock (defragCacheLock);
565 hash = sender->hashPubKey.bits[0] % DEFRAG_BUCKET_COUNT;
566 smf = defragmentationCache[hash];
570 tryJoin (smf, sender, (P2P_fragmentation_MESSAGE *) frag))
572 GNUNET_mutex_unlock (defragCacheLock);
575 if (0 == memcmp (sender, &smf->sender, sizeof (GNUNET_PeerIdentity)))
577 freeFL (smf->head, 1);
584 smf = GNUNET_malloc (sizeof (FC));
585 smf->next = defragmentationCache[hash];
586 defragmentationCache[hash] = smf;
587 smf->ttl = GNUNET_get_time () + DEFRAGMENTATION_TIMEOUT;
588 smf->sender = *sender;
590 smf->id = ntohl (((P2P_fragmentation_MESSAGE *) frag)->id);
591 smf->head = GNUNET_malloc (sizeof (FL));
592 smf->head->link = NULL;
593 smf->head->frag = GNUNET_malloc (ntohs (frag->size));
594 memcpy (smf->head->frag, frag, ntohs (frag->size));
596 GNUNET_mutex_unlock (defragCacheLock);
602 GNUNET_PeerIdentity sender;
603 /* maximums size of each fragment */
605 /** how long is this message part expected to be? */
607 /** when did we intend to transmit? */
608 GNUNET_CronTime transmissionTime;
612 * Send a message that had to be fragmented (right now!). First grabs
613 * the first part of the message (obtained from ctx->se) and stores
614 * that in a P2P_fragmentation_MESSAGE envelope. The remaining fragments are
615 * added to the send queue with GNUNET_EXTREME_PRIORITY (to ensure that they
616 * will be transmitted next). The logic here is that if the priority
617 * for the first fragment was sufficiently high, the priority should
618 * also have been sufficiently high for all of the other fragments (at
619 * this time) since they have the same priority. And we want to make
620 * sure that we send all of them since just sending the first fragment
621 * and then going to other messages of equal priority would not be
622 * such a great idea (i.e. would just waste bandwidth).
625 fragmentBMC (void *buf, void *cls, unsigned short len)
627 FragmentBMC *ctx = cls;
628 static int idGen = 0;
629 P2P_fragmentation_MESSAGE *frag;
634 if ((len < ctx->mtu) || (buf == NULL))
637 return GNUNET_SYSERR;
640 stats->change (stat_fragmented, 1);
641 id = (idGen++) + GNUNET_random_u32 (GNUNET_RANDOM_QUALITY_WEAK, 512);
642 /* write first fragment to buf */
643 frag = (P2P_fragmentation_MESSAGE *) buf;
644 frag->header.size = htons (len);
645 frag->header.type = htons (GNUNET_P2P_PROTO_MESSAGE_FRAGMENT);
647 frag->off = htons (0);
648 frag->len = htons (ctx->len);
649 memcpy (&frag[1], &ctx[1], len - sizeof (P2P_fragmentation_MESSAGE));
651 /* create remaining fragments, add to queue! */
652 pos = len - sizeof (P2P_fragmentation_MESSAGE);
653 frag = GNUNET_malloc (ctx->mtu);
654 while (pos < ctx->len)
656 mlen = sizeof (P2P_fragmentation_MESSAGE) + ctx->len - pos;
659 GNUNET_GE_ASSERT (NULL, mlen > sizeof (P2P_fragmentation_MESSAGE));
660 frag->header.size = htons (mlen);
661 frag->header.type = htons (GNUNET_P2P_PROTO_MESSAGE_FRAGMENT);
663 frag->off = htons (pos);
664 frag->len = htons (ctx->len);
666 &((char *) (&ctx[1]))[pos],
667 mlen - sizeof (P2P_fragmentation_MESSAGE));
668 coreAPI->ciphertext_send (&ctx->sender,
670 GNUNET_EXTREME_PRIORITY,
671 ctx->transmissionTime - GNUNET_get_time ());
672 pos += mlen - sizeof (P2P_fragmentation_MESSAGE);
674 GNUNET_GE_ASSERT (NULL, pos == ctx->len);
681 * The given message must be fragmented. Produce a placeholder that
682 * corresponds to the first fragment. Once that fragment is scheduled
683 * for transmission, the placeholder should automatically add all of
684 * the other fragments (with very high priority).
687 fragment (const GNUNET_PeerIdentity * peer,
690 unsigned int targetTime,
691 unsigned int len, GNUNET_BuildMessageCallback bmc, void *bmcClosure)
696 GNUNET_GE_ASSERT (NULL, len > mtu);
697 GNUNET_GE_ASSERT (NULL, mtu > sizeof (P2P_fragmentation_MESSAGE));
698 fbmc = GNUNET_malloc (sizeof (FragmentBMC) + len);
700 fbmc->sender = *peer;
701 fbmc->transmissionTime = targetTime;
705 memcpy (&fbmc[1], bmcClosure, len);
706 GNUNET_free (bmcClosure);
710 if (GNUNET_SYSERR == bmc (&fbmc[1], bmcClosure, len))
716 xlen = mtu - sizeof (P2P_fragmentation_MESSAGE);
717 coreAPI->ciphertext_send_with_callback (peer, &fragmentBMC, fbmc, mtu, prio * xlen / len, /* compute new priority */
722 * Initialize Fragmentation module.
724 GNUNET_Fragmentation_ServiceAPI *
725 provide_module_fragmentation (GNUNET_CoreAPIForPlugins * capi)
727 static GNUNET_Fragmentation_ServiceAPI ret;
731 stats = coreAPI->service_request ("stats");
735 stats->create (gettext_noop ("# messages defragmented"));
737 stats->create (gettext_noop ("# messages fragmented"));
738 stat_discarded = stats->create (gettext_noop ("# fragments discarded"));
740 for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
741 defragmentationCache[i] = NULL;
742 defragCacheLock = GNUNET_mutex_create (GNUNET_NO);
743 GNUNET_cron_add_job (coreAPI->cron,
744 &defragmentationPurgeCron,
745 60 * GNUNET_CRON_SECONDS, 60 * GNUNET_CRON_SECONDS,
747 GNUNET_GE_LOG (capi->ectx,
748 GNUNET_GE_INFO | GNUNET_GE_USER | GNUNET_GE_REQUEST,
749 _("`%s' registering handler %d\n"), "fragmentation",
750 GNUNET_P2P_PROTO_MESSAGE_FRAGMENT);
751 capi->p2p_ciphertext_handler_register (GNUNET_P2P_PROTO_MESSAGE_FRAGMENT,
754 ret.fragment = &fragment;
759 * Shutdown fragmentation.
762 release_module_fragmentation ()
766 coreAPI->p2p_ciphertext_handler_unregister
767 (GNUNET_P2P_PROTO_MESSAGE_FRAGMENT, &processFragment);
768 GNUNET_cron_del_job (coreAPI->cron, &defragmentationPurgeCron,
769 60 * GNUNET_CRON_SECONDS, NULL);
770 for (i = 0; i < DEFRAG_BUCKET_COUNT; i++)
772 FC *pos = defragmentationCache[i];
775 FC *next = pos->next;
776 freeFL (pos->head, 1);
783 coreAPI->service_release (stats);
786 GNUNET_mutex_destroy (defragCacheLock);
787 defragCacheLock = NULL;
793 /* end of fragmentation.c */