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
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, 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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
21 * @file src/fragmentation/defragmentation.c
22 * @brief library to help defragment messages
23 * @author Christian Grothoff
26 #include "gnunet_fragmentation_lib.h"
27 #include "fragmentation.h"
30 * Timestamps for fragments.
35 * The time the fragment was received.
37 struct GNUNET_TIME_Absolute time;
40 * Number of the bit for the fragment (in [0,..,63]).
47 * Information we keep for one message that is being assembled. Note
48 * that we keep the context around even after the assembly is done to
49 * handle 'stray' messages that are received 'late'. A message
50 * context is ONLY discarded when the queue gets too big.
57 struct MessageContext *next;
62 struct MessageContext *prev;
65 * Associated defragmentation context.
67 struct GNUNET_DEFRAGMENT_Context *dc;
70 * Pointer to the assembled message, allocated at the
73 const struct GNUNET_MessageHeader *msg;
76 * Last time we received any update for this message
77 * (least-recently updated message will be discarded
78 * if we hit the queue size).
80 struct GNUNET_TIME_Absolute last_update;
83 * Task scheduled for transmitting the next ACK to the
86 struct GNUNET_SCHEDULER_Task * ack_task;
89 * When did we receive which fragment? Used to calculate
90 * the time we should send the ACK.
92 struct FragTimes frag_times[64];
95 * Which fragments have we gotten yet? bits that are 1
96 * indicate missing fragments.
101 * Unique ID for this message.
103 uint32_t fragment_id;
106 * Which 'bit' did the last fragment we received correspond to?
108 unsigned int last_bit;
111 * For the current ACK round, which is the first relevant
112 * offset in @e frag_times?
114 unsigned int frag_times_start_offset;
117 * Which offset whould we write the next frag value into
118 * in the @e frag_times array? All smaller entries are valid.
120 unsigned int frag_times_write_offset;
123 * Total size of the message that we are assembling.
128 * Was the last fragment we got a duplicate?
130 int16_t last_duplicate;
136 * Defragmentation context (one per connection).
138 struct GNUNET_DEFRAGMENT_Context
144 struct GNUNET_STATISTICS_Handle *stats;
147 * Head of list of messages we're defragmenting.
149 struct MessageContext *head;
152 * Tail of list of messages we're defragmenting.
154 struct MessageContext *tail;
157 * Closure for @e proc and @e ackp.
162 * Function to call with defragmented messages.
164 GNUNET_FRAGMENT_MessageProcessor proc;
167 * Function to call with acknowledgements.
169 GNUNET_DEFRAGMENT_AckProcessor ackp;
172 * Running average of the latency (delay between messages) for this
175 struct GNUNET_TIME_Relative latency;
178 * num_msgs how many fragmented messages
179 * to we defragment at most at the same time?
181 unsigned int num_msgs;
184 * Current number of messages in the 'struct MessageContext'
185 * DLL (smaller or equal to 'num_msgs').
187 unsigned int list_size;
190 * Maximum message size for each fragment.
198 * Create a defragmentation context.
200 * @param stats statistics context
201 * @param mtu the maximum message size for each fragment
202 * @param num_msgs how many fragmented messages
203 * to we defragment at most at the same time?
204 * @param cls closure for @a proc and @a ackp
205 * @param proc function to call with defragmented messages
206 * @param ackp function to call with acknowledgements (to send
207 * back to the other side)
208 * @return the defragmentation context
210 struct GNUNET_DEFRAGMENT_Context *
211 GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
212 uint16_t mtu, unsigned int num_msgs,
214 GNUNET_FRAGMENT_MessageProcessor proc,
215 GNUNET_DEFRAGMENT_AckProcessor ackp)
217 struct GNUNET_DEFRAGMENT_Context *dc;
219 dc = GNUNET_new (struct GNUNET_DEFRAGMENT_Context);
224 dc->num_msgs = num_msgs;
226 dc->latency = GNUNET_TIME_UNIT_SECONDS; /* start with likely overestimate */
232 * Destroy the given defragmentation context.
234 * @param dc defragmentation context
237 GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc)
239 struct MessageContext *mc;
241 while (NULL != (mc = dc->head))
243 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, mc);
245 if (NULL != mc->ack_task)
247 GNUNET_SCHEDULER_cancel (mc->ack_task);
252 GNUNET_assert (0 == dc->list_size);
258 * Send acknowledgement to the other peer now.
260 * @param cls the message context
265 struct MessageContext *mc = cls;
266 struct GNUNET_DEFRAGMENT_Context *dc = mc->dc;
267 struct FragmentAcknowledgement fa;
270 fa.header.size = htons (sizeof (struct FragmentAcknowledgement));
271 fa.header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT_ACK);
272 fa.fragment_id = htonl (mc->fragment_id);
273 fa.bits = GNUNET_htonll (mc->bits);
274 GNUNET_STATISTICS_update (mc->dc->stats,
275 _("# acknowledgements sent for fragment"),
278 mc->last_duplicate = GNUNET_NO; /* clear flag */
286 * This function is from the GNU Scientific Library, linear/fit.c,
287 * Copyright (C) 2000 Brian Gough
290 gsl_fit_mul (const double *x, const size_t xstride, const double *y,
291 const size_t ystride, const size_t n, double *c1, double *cov_11,
294 double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;
298 for (i = 0; i < n; i++)
300 m_x += (x[i * xstride] - m_x) / (i + 1.0);
301 m_y += (y[i * ystride] - m_y) / (i + 1.0);
304 for (i = 0; i < n; i++)
306 const double dx = x[i * xstride] - m_x;
307 const double dy = y[i * ystride] - m_y;
309 m_dx2 += (dx * dx - m_dx2) / (i + 1.0);
310 m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);
313 /* In terms of y = b x */
316 double s2 = 0, d2 = 0;
317 double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2);
321 /* Compute chi^2 = \sum (y_i - b * x_i)^2 */
323 for (i = 0; i < n; i++)
325 const double dx = x[i * xstride] - m_x;
326 const double dy = y[i * ystride] - m_y;
327 const double d = (m_y - b * m_x) + dy - b * dx;
332 s2 = d2 / (n - 1.0); /* chisq per degree of freedom */
334 *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2));
342 * Estimate the latency between messages based on the most recent
343 * message time stamps.
345 * @param mc context with time stamps
346 * @return average delay between time stamps (based on least-squares fit)
348 static struct GNUNET_TIME_Relative
349 estimate_latency (struct MessageContext *mc)
351 struct FragTimes *first;
352 size_t total = mc->frag_times_write_offset - mc->frag_times_start_offset;
359 struct GNUNET_TIME_Relative ret;
361 first = &mc->frag_times[mc->frag_times_start_offset];
362 GNUNET_assert (total > 1);
363 for (i = 0; i < total; i++)
366 y[i] = (double) (first[i].time.abs_value_us - first[0].time.abs_value_us);
368 gsl_fit_mul (x, 1, y, 1, total, &c1, &cov11, &sumsq);
369 c1 += sqrt (sumsq); /* add 1 std dev */
370 ret.rel_value_us = (uint64_t) c1;
371 if (0 == ret.rel_value_us)
372 ret = GNUNET_TIME_UNIT_MICROSECONDS; /* always at least 1 */
378 * Discard the message context that was inactive for the longest time.
380 * @param dc defragmentation context
383 discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc)
385 struct MessageContext *old;
386 struct MessageContext *pos;
393 (old->last_update.abs_value_us > pos->last_update.abs_value_us))
397 GNUNET_assert (NULL != old);
398 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, old);
400 if (NULL != old->ack_task)
402 GNUNET_SCHEDULER_cancel (old->ack_task);
403 old->ack_task = NULL;
410 * We have received a fragment. Process it.
412 * @param dc the context
413 * @param msg the message that was received
414 * @return #GNUNET_OK on success,
415 * #GNUNET_NO if this was a duplicate,
416 * #GNUNET_SYSERR on error
419 GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc,
420 const struct GNUNET_MessageHeader *msg)
422 struct MessageContext *mc;
423 const struct FragmentHeader *fh;
429 struct GNUNET_TIME_Absolute now;
430 struct GNUNET_TIME_Relative delay;
434 unsigned int num_fragments;
438 if (ntohs (msg->size) < sizeof (struct FragmentHeader))
441 return GNUNET_SYSERR;
443 if (ntohs (msg->size) > dc->mtu)
446 return GNUNET_SYSERR;
448 fh = (const struct FragmentHeader *) msg;
449 msize = ntohs (fh->total_size);
450 if (msize < sizeof (struct GNUNET_MessageHeader))
453 return GNUNET_SYSERR;
455 fid = ntohl (fh->fragment_id);
456 foff = ntohs (fh->offset);
460 return GNUNET_SYSERR;
462 if (0 != (foff % (dc->mtu - sizeof (struct FragmentHeader))))
465 return GNUNET_SYSERR;
467 GNUNET_STATISTICS_update (dc->stats,
468 _("# fragments received"),
471 num_fragments = (ntohs (msg->size) + dc->mtu - sizeof (struct FragmentHeader)-1) / (dc->mtu - sizeof (struct FragmentHeader));
473 for (mc = dc->head; NULL != mc; mc = mc->next)
474 if (mc->fragment_id > fid)
478 while ((NULL != mc) && (fid != mc->fragment_id))
480 bit = foff / (dc->mtu - sizeof (struct FragmentHeader));
481 if (bit * (dc->mtu - sizeof (struct FragmentHeader)) + ntohs (msg->size) -
482 sizeof (struct FragmentHeader) > msize)
484 /* payload extends past total message size */
486 return GNUNET_SYSERR;
488 if ((NULL != mc) && (msize != mc->total_size))
490 /* inconsistent message size */
492 return GNUNET_SYSERR;
494 now = GNUNET_TIME_absolute_get ();
497 mc = GNUNET_malloc (sizeof (struct MessageContext) + msize);
498 mc->msg = (const struct GNUNET_MessageHeader *) &mc[1];
500 mc->total_size = msize;
501 mc->fragment_id = fid;
502 mc->last_update = now;
503 n = (msize + dc->mtu - sizeof (struct FragmentHeader) - 1) / (dc->mtu -
507 mc->bits = UINT64_MAX; /* set all 64 bit */
509 mc->bits = (1LLU << n) - 1; /* set lowest 'bits' bit */
510 if (dc->list_size >= dc->num_msgs)
511 discard_oldest_mc (dc);
512 GNUNET_CONTAINER_DLL_insert (dc->head,
518 /* copy data to 'mc' */
519 if (0 != (mc->bits & (1LLU << bit)))
521 mc->bits -= 1LLU << bit;
522 mbuf = (char *) &mc[1];
523 GNUNET_memcpy (&mbuf[bit * (dc->mtu - sizeof (struct FragmentHeader))], &fh[1],
524 ntohs (msg->size) - sizeof (struct FragmentHeader));
525 mc->last_update = now;
526 if (bit < mc->last_bit)
527 mc->frag_times_start_offset = mc->frag_times_write_offset;
529 mc->frag_times[mc->frag_times_write_offset].time = now;
530 mc->frag_times[mc->frag_times_write_offset].bit = bit;
531 mc->frag_times_write_offset++;
532 duplicate = GNUNET_NO;
536 duplicate = GNUNET_YES;
537 GNUNET_STATISTICS_update (dc->stats,
538 _("# duplicate fragments received"),
543 /* count number of missing fragments after the current one */
545 for (b = bit; b < 64; b++)
546 if (0 != (mc->bits & (1LLU << b)))
551 /* notify about complete message */
552 if ( (GNUNET_NO == duplicate) &&
555 GNUNET_STATISTICS_update (dc->stats,
556 _("# messages defragmented"),
559 /* message complete, notify! */
560 dc->proc (dc->cls, mc->msg);
563 if (mc->frag_times_write_offset - mc->frag_times_start_offset > 1)
565 dc->latency = estimate_latency (mc);
567 delay = GNUNET_TIME_relative_saturating_multiply (dc->latency,
569 if ( (last + fid == num_fragments) ||
571 (GNUNET_YES == duplicate) )
573 /* message complete or duplicate or last missing fragment in
574 linear sequence; ACK now! */
575 delay = GNUNET_TIME_UNIT_ZERO;
577 if (NULL != mc->ack_task)
578 GNUNET_SCHEDULER_cancel (mc->ack_task);
579 mc->ack_task = GNUNET_SCHEDULER_add_delayed (delay,
582 if (GNUNET_YES == duplicate)
584 mc->last_duplicate = GNUNET_YES;
590 /* end of defragmentation.c */