2 This file is part of GNUnet
3 Copyright (C) 2009, 2011 GNUnet e.V.
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
16 * @file src/fragmentation/defragmentation.c
17 * @brief library to help defragment messages
18 * @author Christian Grothoff
21 #include "gnunet_fragmentation_lib.h"
22 #include "fragmentation.h"
25 * Timestamps for fragments.
30 * The time the fragment was received.
32 struct GNUNET_TIME_Absolute time;
35 * Number of the bit for the fragment (in [0,..,63]).
42 * Information we keep for one message that is being assembled. Note
43 * that we keep the context around even after the assembly is done to
44 * handle 'stray' messages that are received 'late'. A message
45 * context is ONLY discarded when the queue gets too big.
52 struct MessageContext *next;
57 struct MessageContext *prev;
60 * Associated defragmentation context.
62 struct GNUNET_DEFRAGMENT_Context *dc;
65 * Pointer to the assembled message, allocated at the
68 const struct GNUNET_MessageHeader *msg;
71 * Last time we received any update for this message
72 * (least-recently updated message will be discarded
73 * if we hit the queue size).
75 struct GNUNET_TIME_Absolute last_update;
78 * Task scheduled for transmitting the next ACK to the
81 struct GNUNET_SCHEDULER_Task * ack_task;
84 * When did we receive which fragment? Used to calculate
85 * the time we should send the ACK.
87 struct FragTimes frag_times[64];
90 * Which fragments have we gotten yet? bits that are 1
91 * indicate missing fragments.
96 * Unique ID for this message.
101 * Which 'bit' did the last fragment we received correspond to?
103 unsigned int last_bit;
106 * For the current ACK round, which is the first relevant
107 * offset in @e frag_times?
109 unsigned int frag_times_start_offset;
112 * Which offset whould we write the next frag value into
113 * in the @e frag_times array? All smaller entries are valid.
115 unsigned int frag_times_write_offset;
118 * Total size of the message that we are assembling.
123 * Was the last fragment we got a duplicate?
125 int16_t last_duplicate;
131 * Defragmentation context (one per connection).
133 struct GNUNET_DEFRAGMENT_Context
139 struct GNUNET_STATISTICS_Handle *stats;
142 * Head of list of messages we're defragmenting.
144 struct MessageContext *head;
147 * Tail of list of messages we're defragmenting.
149 struct MessageContext *tail;
152 * Closure for @e proc and @e ackp.
157 * Function to call with defragmented messages.
159 GNUNET_FRAGMENT_MessageProcessor proc;
162 * Function to call with acknowledgements.
164 GNUNET_DEFRAGMENT_AckProcessor ackp;
167 * Running average of the latency (delay between messages) for this
170 struct GNUNET_TIME_Relative latency;
173 * num_msgs how many fragmented messages
174 * to we defragment at most at the same time?
176 unsigned int num_msgs;
179 * Current number of messages in the 'struct MessageContext'
180 * DLL (smaller or equal to 'num_msgs').
182 unsigned int list_size;
185 * Maximum message size for each fragment.
193 * Create a defragmentation context.
195 * @param stats statistics context
196 * @param mtu the maximum message size for each fragment
197 * @param num_msgs how many fragmented messages
198 * to we defragment at most at the same time?
199 * @param cls closure for @a proc and @a ackp
200 * @param proc function to call with defragmented messages
201 * @param ackp function to call with acknowledgements (to send
202 * back to the other side)
203 * @return the defragmentation context
205 struct GNUNET_DEFRAGMENT_Context *
206 GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
207 uint16_t mtu, unsigned int num_msgs,
209 GNUNET_FRAGMENT_MessageProcessor proc,
210 GNUNET_DEFRAGMENT_AckProcessor ackp)
212 struct GNUNET_DEFRAGMENT_Context *dc;
214 dc = GNUNET_new (struct GNUNET_DEFRAGMENT_Context);
219 dc->num_msgs = num_msgs;
221 dc->latency = GNUNET_TIME_UNIT_SECONDS; /* start with likely overestimate */
227 * Destroy the given defragmentation context.
229 * @param dc defragmentation context
232 GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc)
234 struct MessageContext *mc;
236 while (NULL != (mc = dc->head))
238 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, mc);
240 if (NULL != mc->ack_task)
242 GNUNET_SCHEDULER_cancel (mc->ack_task);
247 GNUNET_assert (0 == dc->list_size);
253 * Send acknowledgement to the other peer now.
255 * @param cls the message context
260 struct MessageContext *mc = cls;
261 struct GNUNET_DEFRAGMENT_Context *dc = mc->dc;
262 struct FragmentAcknowledgement fa;
265 fa.header.size = htons (sizeof (struct FragmentAcknowledgement));
266 fa.header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT_ACK);
267 fa.fragment_id = htonl (mc->fragment_id);
268 fa.bits = GNUNET_htonll (mc->bits);
269 GNUNET_STATISTICS_update (mc->dc->stats,
270 _("# acknowledgements sent for fragment"),
273 mc->last_duplicate = GNUNET_NO; /* clear flag */
281 * This function is from the GNU Scientific Library, linear/fit.c,
282 * Copyright (C) 2000 Brian Gough
285 gsl_fit_mul (const double *x, const size_t xstride, const double *y,
286 const size_t ystride, const size_t n, double *c1, double *cov_11,
289 double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;
293 for (i = 0; i < n; i++)
295 m_x += (x[i * xstride] - m_x) / (i + 1.0);
296 m_y += (y[i * ystride] - m_y) / (i + 1.0);
299 for (i = 0; i < n; i++)
301 const double dx = x[i * xstride] - m_x;
302 const double dy = y[i * ystride] - m_y;
304 m_dx2 += (dx * dx - m_dx2) / (i + 1.0);
305 m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);
308 /* In terms of y = b x */
311 double s2 = 0, d2 = 0;
312 double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2);
316 /* Compute chi^2 = \sum (y_i - b * x_i)^2 */
318 for (i = 0; i < n; i++)
320 const double dx = x[i * xstride] - m_x;
321 const double dy = y[i * ystride] - m_y;
322 const double d = (m_y - b * m_x) + dy - b * dx;
327 s2 = d2 / (n - 1.0); /* chisq per degree of freedom */
329 *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2));
337 * Estimate the latency between messages based on the most recent
338 * message time stamps.
340 * @param mc context with time stamps
341 * @return average delay between time stamps (based on least-squares fit)
343 static struct GNUNET_TIME_Relative
344 estimate_latency (struct MessageContext *mc)
346 struct FragTimes *first;
347 size_t total = mc->frag_times_write_offset - mc->frag_times_start_offset;
354 struct GNUNET_TIME_Relative ret;
356 first = &mc->frag_times[mc->frag_times_start_offset];
357 GNUNET_assert (total > 1);
358 for (i = 0; i < total; i++)
361 y[i] = (double) (first[i].time.abs_value_us - first[0].time.abs_value_us);
363 gsl_fit_mul (x, 1, y, 1, total, &c1, &cov11, &sumsq);
364 c1 += sqrt (sumsq); /* add 1 std dev */
365 ret.rel_value_us = (uint64_t) c1;
366 if (0 == ret.rel_value_us)
367 ret = GNUNET_TIME_UNIT_MICROSECONDS; /* always at least 1 */
373 * Discard the message context that was inactive for the longest time.
375 * @param dc defragmentation context
378 discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc)
380 struct MessageContext *old;
381 struct MessageContext *pos;
388 (old->last_update.abs_value_us > pos->last_update.abs_value_us))
392 GNUNET_assert (NULL != old);
393 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, old);
395 if (NULL != old->ack_task)
397 GNUNET_SCHEDULER_cancel (old->ack_task);
398 old->ack_task = NULL;
405 * We have received a fragment. Process it.
407 * @param dc the context
408 * @param msg the message that was received
409 * @return #GNUNET_OK on success,
410 * #GNUNET_NO if this was a duplicate,
411 * #GNUNET_SYSERR on error
414 GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc,
415 const struct GNUNET_MessageHeader *msg)
417 struct MessageContext *mc;
418 const struct FragmentHeader *fh;
424 struct GNUNET_TIME_Absolute now;
425 struct GNUNET_TIME_Relative delay;
429 unsigned int num_fragments;
433 if (ntohs (msg->size) < sizeof (struct FragmentHeader))
436 return GNUNET_SYSERR;
438 if (ntohs (msg->size) > dc->mtu)
441 return GNUNET_SYSERR;
443 fh = (const struct FragmentHeader *) msg;
444 msize = ntohs (fh->total_size);
445 if (msize < sizeof (struct GNUNET_MessageHeader))
448 return GNUNET_SYSERR;
450 fid = ntohl (fh->fragment_id);
451 foff = ntohs (fh->offset);
455 return GNUNET_SYSERR;
457 if (0 != (foff % (dc->mtu - sizeof (struct FragmentHeader))))
460 return GNUNET_SYSERR;
462 GNUNET_STATISTICS_update (dc->stats,
463 _("# fragments received"),
466 num_fragments = (ntohs (msg->size) + dc->mtu - sizeof (struct FragmentHeader)-1) / (dc->mtu - sizeof (struct FragmentHeader));
468 for (mc = dc->head; NULL != mc; mc = mc->next)
469 if (mc->fragment_id > fid)
473 while ((NULL != mc) && (fid != mc->fragment_id))
475 bit = foff / (dc->mtu - sizeof (struct FragmentHeader));
476 if (bit * (dc->mtu - sizeof (struct FragmentHeader)) + ntohs (msg->size) -
477 sizeof (struct FragmentHeader) > msize)
479 /* payload extends past total message size */
481 return GNUNET_SYSERR;
483 if ((NULL != mc) && (msize != mc->total_size))
485 /* inconsistent message size */
487 return GNUNET_SYSERR;
489 now = GNUNET_TIME_absolute_get ();
492 mc = GNUNET_malloc (sizeof (struct MessageContext) + msize);
493 mc->msg = (const struct GNUNET_MessageHeader *) &mc[1];
495 mc->total_size = msize;
496 mc->fragment_id = fid;
497 mc->last_update = now;
498 n = (msize + dc->mtu - sizeof (struct FragmentHeader) - 1) / (dc->mtu -
502 mc->bits = UINT64_MAX; /* set all 64 bit */
504 mc->bits = (1LLU << n) - 1; /* set lowest 'bits' bit */
505 if (dc->list_size >= dc->num_msgs)
506 discard_oldest_mc (dc);
507 GNUNET_CONTAINER_DLL_insert (dc->head,
513 /* copy data to 'mc' */
514 if (0 != (mc->bits & (1LLU << bit)))
516 mc->bits -= 1LLU << bit;
517 mbuf = (char *) &mc[1];
518 GNUNET_memcpy (&mbuf[bit * (dc->mtu - sizeof (struct FragmentHeader))], &fh[1],
519 ntohs (msg->size) - sizeof (struct FragmentHeader));
520 mc->last_update = now;
521 if (bit < mc->last_bit)
522 mc->frag_times_start_offset = mc->frag_times_write_offset;
524 mc->frag_times[mc->frag_times_write_offset].time = now;
525 mc->frag_times[mc->frag_times_write_offset].bit = bit;
526 mc->frag_times_write_offset++;
527 duplicate = GNUNET_NO;
531 duplicate = GNUNET_YES;
532 GNUNET_STATISTICS_update (dc->stats,
533 _("# duplicate fragments received"),
538 /* count number of missing fragments after the current one */
540 for (b = bit; b < 64; b++)
541 if (0 != (mc->bits & (1LLU << b)))
546 /* notify about complete message */
547 if ( (GNUNET_NO == duplicate) &&
550 GNUNET_STATISTICS_update (dc->stats,
551 _("# messages defragmented"),
554 /* message complete, notify! */
555 dc->proc (dc->cls, mc->msg);
558 if (mc->frag_times_write_offset - mc->frag_times_start_offset > 1)
560 dc->latency = estimate_latency (mc);
562 delay = GNUNET_TIME_relative_saturating_multiply (dc->latency,
564 if ( (last + fid == num_fragments) ||
566 (GNUNET_YES == duplicate) )
568 /* message complete or duplicate or last missing fragment in
569 linear sequence; ACK now! */
570 delay = GNUNET_TIME_UNIT_ZERO;
572 if (NULL != mc->ack_task)
573 GNUNET_SCHEDULER_cancel (mc->ack_task);
574 mc->ack_task = GNUNET_SCHEDULER_add_delayed (delay,
577 if (GNUNET_YES == duplicate)
579 mc->last_duplicate = GNUNET_YES;
585 /* end of defragmentation.c */