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.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * @file src/fragmentation/defragmentation.c
20 * @brief library to help defragment messages
21 * @author Christian Grothoff
24 #include "gnunet_fragmentation_lib.h"
25 #include "fragmentation.h"
28 * Timestamps for fragments.
33 * The time the fragment was received.
35 struct GNUNET_TIME_Absolute time;
38 * Number of the bit for the fragment (in [0,..,63]).
45 * Information we keep for one message that is being assembled. Note
46 * that we keep the context around even after the assembly is done to
47 * handle 'stray' messages that are received 'late'. A message
48 * context is ONLY discarded when the queue gets too big.
55 struct MessageContext *next;
60 struct MessageContext *prev;
63 * Associated defragmentation context.
65 struct GNUNET_DEFRAGMENT_Context *dc;
68 * Pointer to the assembled message, allocated at the
71 const struct GNUNET_MessageHeader *msg;
74 * Last time we received any update for this message
75 * (least-recently updated message will be discarded
76 * if we hit the queue size).
78 struct GNUNET_TIME_Absolute last_update;
81 * Task scheduled for transmitting the next ACK to the
84 struct GNUNET_SCHEDULER_Task * ack_task;
87 * When did we receive which fragment? Used to calculate
88 * the time we should send the ACK.
90 struct FragTimes frag_times[64];
93 * Which fragments have we gotten yet? bits that are 1
94 * indicate missing fragments.
99 * Unique ID for this message.
101 uint32_t fragment_id;
104 * Which 'bit' did the last fragment we received correspond to?
106 unsigned int last_bit;
109 * For the current ACK round, which is the first relevant
110 * offset in @e frag_times?
112 unsigned int frag_times_start_offset;
115 * Which offset whould we write the next frag value into
116 * in the @e frag_times array? All smaller entries are valid.
118 unsigned int frag_times_write_offset;
121 * Total size of the message that we are assembling.
126 * Was the last fragment we got a duplicate?
128 int16_t last_duplicate;
134 * Defragmentation context (one per connection).
136 struct GNUNET_DEFRAGMENT_Context
142 struct GNUNET_STATISTICS_Handle *stats;
145 * Head of list of messages we're defragmenting.
147 struct MessageContext *head;
150 * Tail of list of messages we're defragmenting.
152 struct MessageContext *tail;
155 * Closure for @e proc and @e ackp.
160 * Function to call with defragmented messages.
162 GNUNET_FRAGMENT_MessageProcessor proc;
165 * Function to call with acknowledgements.
167 GNUNET_DEFRAGMENT_AckProcessor ackp;
170 * Running average of the latency (delay between messages) for this
173 struct GNUNET_TIME_Relative latency;
176 * num_msgs how many fragmented messages
177 * to we defragment at most at the same time?
179 unsigned int num_msgs;
182 * Current number of messages in the 'struct MessageContext'
183 * DLL (smaller or equal to 'num_msgs').
185 unsigned int list_size;
188 * Maximum message size for each fragment.
196 * Create a defragmentation context.
198 * @param stats statistics context
199 * @param mtu the maximum message size for each fragment
200 * @param num_msgs how many fragmented messages
201 * to we defragment at most at the same time?
202 * @param cls closure for @a proc and @a ackp
203 * @param proc function to call with defragmented messages
204 * @param ackp function to call with acknowledgements (to send
205 * back to the other side)
206 * @return the defragmentation context
208 struct GNUNET_DEFRAGMENT_Context *
209 GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
210 uint16_t mtu, unsigned int num_msgs,
212 GNUNET_FRAGMENT_MessageProcessor proc,
213 GNUNET_DEFRAGMENT_AckProcessor ackp)
215 struct GNUNET_DEFRAGMENT_Context *dc;
217 dc = GNUNET_new (struct GNUNET_DEFRAGMENT_Context);
222 dc->num_msgs = num_msgs;
224 dc->latency = GNUNET_TIME_UNIT_SECONDS; /* start with likely overestimate */
230 * Destroy the given defragmentation context.
232 * @param dc defragmentation context
235 GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc)
237 struct MessageContext *mc;
239 while (NULL != (mc = dc->head))
241 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, mc);
243 if (NULL != mc->ack_task)
245 GNUNET_SCHEDULER_cancel (mc->ack_task);
250 GNUNET_assert (0 == dc->list_size);
256 * Send acknowledgement to the other peer now.
258 * @param cls the message context
263 struct MessageContext *mc = cls;
264 struct GNUNET_DEFRAGMENT_Context *dc = mc->dc;
265 struct FragmentAcknowledgement fa;
268 fa.header.size = htons (sizeof (struct FragmentAcknowledgement));
269 fa.header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT_ACK);
270 fa.fragment_id = htonl (mc->fragment_id);
271 fa.bits = GNUNET_htonll (mc->bits);
272 GNUNET_STATISTICS_update (mc->dc->stats,
273 _("# acknowledgements sent for fragment"),
276 mc->last_duplicate = GNUNET_NO; /* clear flag */
284 * This function is from the GNU Scientific Library, linear/fit.c,
285 * Copyright (C) 2000 Brian Gough
288 gsl_fit_mul (const double *x, const size_t xstride, const double *y,
289 const size_t ystride, const size_t n, double *c1, double *cov_11,
292 double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;
296 for (i = 0; i < n; i++)
298 m_x += (x[i * xstride] - m_x) / (i + 1.0);
299 m_y += (y[i * ystride] - m_y) / (i + 1.0);
302 for (i = 0; i < n; i++)
304 const double dx = x[i * xstride] - m_x;
305 const double dy = y[i * ystride] - m_y;
307 m_dx2 += (dx * dx - m_dx2) / (i + 1.0);
308 m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);
311 /* In terms of y = b x */
314 double s2 = 0, d2 = 0;
315 double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2);
319 /* Compute chi^2 = \sum (y_i - b * x_i)^2 */
321 for (i = 0; i < n; i++)
323 const double dx = x[i * xstride] - m_x;
324 const double dy = y[i * ystride] - m_y;
325 const double d = (m_y - b * m_x) + dy - b * dx;
330 s2 = d2 / (n - 1.0); /* chisq per degree of freedom */
332 *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2));
340 * Estimate the latency between messages based on the most recent
341 * message time stamps.
343 * @param mc context with time stamps
344 * @return average delay between time stamps (based on least-squares fit)
346 static struct GNUNET_TIME_Relative
347 estimate_latency (struct MessageContext *mc)
349 struct FragTimes *first;
350 size_t total = mc->frag_times_write_offset - mc->frag_times_start_offset;
357 struct GNUNET_TIME_Relative ret;
359 first = &mc->frag_times[mc->frag_times_start_offset];
360 GNUNET_assert (total > 1);
361 for (i = 0; i < total; i++)
364 y[i] = (double) (first[i].time.abs_value_us - first[0].time.abs_value_us);
366 gsl_fit_mul (x, 1, y, 1, total, &c1, &cov11, &sumsq);
367 c1 += sqrt (sumsq); /* add 1 std dev */
368 ret.rel_value_us = (uint64_t) c1;
369 if (0 == ret.rel_value_us)
370 ret = GNUNET_TIME_UNIT_MICROSECONDS; /* always at least 1 */
376 * Discard the message context that was inactive for the longest time.
378 * @param dc defragmentation context
381 discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc)
383 struct MessageContext *old;
384 struct MessageContext *pos;
391 (old->last_update.abs_value_us > pos->last_update.abs_value_us))
395 GNUNET_assert (NULL != old);
396 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, old);
398 if (NULL != old->ack_task)
400 GNUNET_SCHEDULER_cancel (old->ack_task);
401 old->ack_task = NULL;
408 * We have received a fragment. Process it.
410 * @param dc the context
411 * @param msg the message that was received
412 * @return #GNUNET_OK on success,
413 * #GNUNET_NO if this was a duplicate,
414 * #GNUNET_SYSERR on error
417 GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc,
418 const struct GNUNET_MessageHeader *msg)
420 struct MessageContext *mc;
421 const struct FragmentHeader *fh;
427 struct GNUNET_TIME_Absolute now;
428 struct GNUNET_TIME_Relative delay;
432 unsigned int num_fragments;
436 if (ntohs (msg->size) < sizeof (struct FragmentHeader))
439 return GNUNET_SYSERR;
441 if (ntohs (msg->size) > dc->mtu)
444 return GNUNET_SYSERR;
446 fh = (const struct FragmentHeader *) msg;
447 msize = ntohs (fh->total_size);
448 if (msize < sizeof (struct GNUNET_MessageHeader))
451 return GNUNET_SYSERR;
453 fid = ntohl (fh->fragment_id);
454 foff = ntohs (fh->offset);
458 return GNUNET_SYSERR;
460 if (0 != (foff % (dc->mtu - sizeof (struct FragmentHeader))))
463 return GNUNET_SYSERR;
465 GNUNET_STATISTICS_update (dc->stats,
466 _("# fragments received"),
469 num_fragments = (ntohs (msg->size) + dc->mtu - sizeof (struct FragmentHeader)-1) / (dc->mtu - sizeof (struct FragmentHeader));
471 for (mc = dc->head; NULL != mc; mc = mc->next)
472 if (mc->fragment_id > fid)
476 while ((NULL != mc) && (fid != mc->fragment_id))
478 bit = foff / (dc->mtu - sizeof (struct FragmentHeader));
479 if (bit * (dc->mtu - sizeof (struct FragmentHeader)) + ntohs (msg->size) -
480 sizeof (struct FragmentHeader) > msize)
482 /* payload extends past total message size */
484 return GNUNET_SYSERR;
486 if ((NULL != mc) && (msize != mc->total_size))
488 /* inconsistent message size */
490 return GNUNET_SYSERR;
492 now = GNUNET_TIME_absolute_get ();
495 mc = GNUNET_malloc (sizeof (struct MessageContext) + msize);
496 mc->msg = (const struct GNUNET_MessageHeader *) &mc[1];
498 mc->total_size = msize;
499 mc->fragment_id = fid;
500 mc->last_update = now;
501 n = (msize + dc->mtu - sizeof (struct FragmentHeader) - 1) / (dc->mtu -
505 mc->bits = UINT64_MAX; /* set all 64 bit */
507 mc->bits = (1LLU << n) - 1; /* set lowest 'bits' bit */
508 if (dc->list_size >= dc->num_msgs)
509 discard_oldest_mc (dc);
510 GNUNET_CONTAINER_DLL_insert (dc->head,
516 /* copy data to 'mc' */
517 if (0 != (mc->bits & (1LLU << bit)))
519 mc->bits -= 1LLU << bit;
520 mbuf = (char *) &mc[1];
521 GNUNET_memcpy (&mbuf[bit * (dc->mtu - sizeof (struct FragmentHeader))], &fh[1],
522 ntohs (msg->size) - sizeof (struct FragmentHeader));
523 mc->last_update = now;
524 if (bit < mc->last_bit)
525 mc->frag_times_start_offset = mc->frag_times_write_offset;
527 mc->frag_times[mc->frag_times_write_offset].time = now;
528 mc->frag_times[mc->frag_times_write_offset].bit = bit;
529 mc->frag_times_write_offset++;
530 duplicate = GNUNET_NO;
534 duplicate = GNUNET_YES;
535 GNUNET_STATISTICS_update (dc->stats,
536 _("# duplicate fragments received"),
541 /* count number of missing fragments after the current one */
543 for (b = bit; b < 64; b++)
544 if (0 != (mc->bits & (1LLU << b)))
549 /* notify about complete message */
550 if ( (GNUNET_NO == duplicate) &&
553 GNUNET_STATISTICS_update (dc->stats,
554 _("# messages defragmented"),
557 /* message complete, notify! */
558 dc->proc (dc->cls, mc->msg);
561 if (mc->frag_times_write_offset - mc->frag_times_start_offset > 1)
563 dc->latency = estimate_latency (mc);
565 delay = GNUNET_TIME_relative_saturating_multiply (dc->latency,
567 if ( (last + fid == num_fragments) ||
569 (GNUNET_YES == duplicate) )
571 /* message complete or duplicate or last missing fragment in
572 linear sequence; ACK now! */
573 delay = GNUNET_TIME_UNIT_ZERO;
575 if (NULL != mc->ack_task)
576 GNUNET_SCHEDULER_cancel (mc->ack_task);
577 mc->ack_task = GNUNET_SCHEDULER_add_delayed (delay,
580 if (GNUNET_YES == duplicate)
582 mc->last_duplicate = GNUNET_YES;
588 /* end of defragmentation.c */