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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
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;
135 * Defragmentation context (one per connection).
137 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.
195 * Create a defragmentation context.
197 * @param stats statistics context
198 * @param mtu the maximum message size for each fragment
199 * @param num_msgs how many fragmented messages
200 * to we defragment at most at the same time?
201 * @param cls closure for @a proc and @a ackp
202 * @param proc function to call with defragmented messages
203 * @param ackp function to call with acknowledgements (to send
204 * back to the other side)
205 * @return the defragmentation context
207 struct GNUNET_DEFRAGMENT_Context *
208 GNUNET_DEFRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
209 uint16_t mtu, unsigned int num_msgs,
211 GNUNET_FRAGMENT_MessageProcessor proc,
212 GNUNET_DEFRAGMENT_AckProcessor ackp)
214 struct GNUNET_DEFRAGMENT_Context *dc;
216 dc = GNUNET_new (struct GNUNET_DEFRAGMENT_Context);
221 dc->num_msgs = num_msgs;
223 dc->latency = GNUNET_TIME_UNIT_SECONDS; /* start with likely overestimate */
229 * Destroy the given defragmentation context.
231 * @param dc defragmentation context
234 GNUNET_DEFRAGMENT_context_destroy (struct GNUNET_DEFRAGMENT_Context *dc)
236 struct MessageContext *mc;
238 while (NULL != (mc = dc->head))
240 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, mc);
242 if (NULL != mc->ack_task)
244 GNUNET_SCHEDULER_cancel (mc->ack_task);
249 GNUNET_assert (0 == dc->list_size);
255 * Send acknowledgement to the other peer now.
257 * @param cls the message context
262 struct MessageContext *mc = cls;
263 struct GNUNET_DEFRAGMENT_Context *dc = mc->dc;
264 struct FragmentAcknowledgement fa;
267 fa.header.size = htons (sizeof(struct FragmentAcknowledgement));
268 fa.header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT_ACK);
269 fa.fragment_id = htonl (mc->fragment_id);
270 fa.bits = GNUNET_htonll (mc->bits);
271 GNUNET_STATISTICS_update (mc->dc->stats,
272 _ ("# acknowledgements sent for fragment"),
275 mc->last_duplicate = GNUNET_NO; /* clear flag */
283 * This function is from the GNU Scientific Library, linear/fit.c,
284 * Copyright (C) 2000 Brian Gough
287 gsl_fit_mul (const double *x, const size_t xstride, const double *y,
288 const size_t ystride, const size_t n, double *c1, double *cov_11,
291 double m_x = 0, m_y = 0, m_dx2 = 0, m_dxdy = 0;
295 for (i = 0; i < n; i++)
297 m_x += (x[i * xstride] - m_x) / (i + 1.0);
298 m_y += (y[i * ystride] - m_y) / (i + 1.0);
301 for (i = 0; i < n; i++)
303 const double dx = x[i * xstride] - m_x;
304 const double dy = y[i * ystride] - m_y;
306 m_dx2 += (dx * dx - m_dx2) / (i + 1.0);
307 m_dxdy += (dx * dy - m_dxdy) / (i + 1.0);
310 /* In terms of y = b x */
313 double s2 = 0, d2 = 0;
314 double b = (m_x * m_y + m_dxdy) / (m_x * m_x + m_dx2);
318 /* Compute chi^2 = \sum (y_i - b * x_i)^2 */
320 for (i = 0; i < n; i++)
322 const double dx = x[i * xstride] - m_x;
323 const double dy = y[i * ystride] - m_y;
324 const double d = (m_y - b * m_x) + dy - b * dx;
329 s2 = d2 / (n - 1.0); /* chisq per degree of freedom */
331 *cov_11 = s2 * 1.0 / (n * (m_x * m_x + m_dx2));
339 * Estimate the latency between messages based on the most recent
340 * message time stamps.
342 * @param mc context with time stamps
343 * @return average delay between time stamps (based on least-squares fit)
345 static struct GNUNET_TIME_Relative
346 estimate_latency (struct MessageContext *mc)
348 struct FragTimes *first;
349 size_t total = mc->frag_times_write_offset - mc->frag_times_start_offset;
356 struct GNUNET_TIME_Relative ret;
358 first = &mc->frag_times[mc->frag_times_start_offset];
359 GNUNET_assert (total > 1);
360 for (i = 0; i < total; i++)
363 y[i] = (double) (first[i].time.abs_value_us - first[0].time.abs_value_us);
365 gsl_fit_mul (x, 1, y, 1, total, &c1, &cov11, &sumsq);
366 c1 += sqrt (sumsq); /* add 1 std dev */
367 ret.rel_value_us = (uint64_t) c1;
368 if (0 == ret.rel_value_us)
369 ret = GNUNET_TIME_UNIT_MICROSECONDS; /* always at least 1 */
375 * Discard the message context that was inactive for the longest time.
377 * @param dc defragmentation context
380 discard_oldest_mc (struct GNUNET_DEFRAGMENT_Context *dc)
382 struct MessageContext *old;
383 struct MessageContext *pos;
390 (old->last_update.abs_value_us > pos->last_update.abs_value_us))
394 GNUNET_assert (NULL != old);
395 GNUNET_CONTAINER_DLL_remove (dc->head, dc->tail, old);
397 if (NULL != old->ack_task)
399 GNUNET_SCHEDULER_cancel (old->ack_task);
400 old->ack_task = NULL;
407 * We have received a fragment. Process it.
409 * @param dc the context
410 * @param msg the message that was received
411 * @return #GNUNET_OK on success,
412 * #GNUNET_NO if this was a duplicate,
413 * #GNUNET_SYSERR on error
416 GNUNET_DEFRAGMENT_process_fragment (struct GNUNET_DEFRAGMENT_Context *dc,
417 const struct GNUNET_MessageHeader *msg)
419 struct MessageContext *mc;
420 const struct FragmentHeader *fh;
426 struct GNUNET_TIME_Absolute now;
427 struct GNUNET_TIME_Relative delay;
431 unsigned int num_fragments;
435 if (ntohs (msg->size) < sizeof(struct FragmentHeader))
438 return GNUNET_SYSERR;
440 if (ntohs (msg->size) > dc->mtu)
443 return GNUNET_SYSERR;
445 fh = (const struct FragmentHeader *) msg;
446 msize = ntohs (fh->total_size);
447 if (msize < sizeof(struct GNUNET_MessageHeader))
450 return GNUNET_SYSERR;
452 fid = ntohl (fh->fragment_id);
453 foff = ntohs (fh->offset);
457 return GNUNET_SYSERR;
459 if (0 != (foff % (dc->mtu - sizeof(struct FragmentHeader))))
462 return GNUNET_SYSERR;
464 GNUNET_STATISTICS_update (dc->stats,
465 _ ("# fragments received"),
468 num_fragments = (ntohs (msg->size) + dc->mtu - sizeof(struct FragmentHeader)
469 - 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))],
523 ntohs (msg->size) - sizeof(struct FragmentHeader));
524 mc->last_update = now;
525 if (bit < mc->last_bit)
526 mc->frag_times_start_offset = mc->frag_times_write_offset;
528 mc->frag_times[mc->frag_times_write_offset].time = now;
529 mc->frag_times[mc->frag_times_write_offset].bit = bit;
530 mc->frag_times_write_offset++;
531 duplicate = GNUNET_NO;
535 duplicate = GNUNET_YES;
536 GNUNET_STATISTICS_update (dc->stats,
537 _ ("# duplicate fragments received"),
542 /* count number of missing fragments after the current one */
544 for (b = bit; b < 64; b++)
545 if (0 != (mc->bits & (1LLU << b)))
550 /* notify about complete message */
551 if ((GNUNET_NO == duplicate) &&
554 GNUNET_STATISTICS_update (dc->stats,
555 _ ("# messages defragmented"),
558 /* message complete, notify! */
559 dc->proc (dc->cls, mc->msg);
562 if (mc->frag_times_write_offset - mc->frag_times_start_offset > 1)
564 dc->latency = estimate_latency (mc);
566 delay = GNUNET_TIME_relative_saturating_multiply (dc->latency,
568 if ((last + fid == num_fragments) ||
570 (GNUNET_YES == duplicate))
572 /* message complete or duplicate or last missing fragment in
573 linear sequence; ACK now! */
574 delay = GNUNET_TIME_UNIT_ZERO;
576 if (NULL != mc->ack_task)
577 GNUNET_SCHEDULER_cancel (mc->ack_task);
578 mc->ack_task = GNUNET_SCHEDULER_add_delayed (delay,
581 if (GNUNET_YES == duplicate)
583 mc->last_duplicate = GNUNET_YES;
590 /* end of defragmentation.c */