-only trigger check config if we actually need it
[oweals/gnunet.git] / src / fragmentation / fragmentation.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2009-2013 GNUnet e.V.
4
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.
9
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.
14
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.
19 */
20 /**
21  * @file src/fragmentation/fragmentation.c
22  * @brief library to help fragment messages
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_fragmentation_lib.h"
27 #include "gnunet_protocols.h"
28 #include "fragmentation.h"
29
30
31 /**
32  * Absolute minimum delay we impose between sending and expecting ACK to arrive.
33  */
34 #define MIN_ACK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 1)
35
36
37 /**
38  * Fragmentation context.
39  */
40 struct GNUNET_FRAGMENT_Context
41 {
42   /**
43    * Statistics to use.
44    */
45   struct GNUNET_STATISTICS_Handle *stats;
46
47   /**
48    * Tracker for flow control.
49    */
50   struct GNUNET_BANDWIDTH_Tracker *tracker;
51
52   /**
53    * Current expected delay for ACKs.
54    */
55   struct GNUNET_TIME_Relative ack_delay;
56
57   /**
58    * Current expected delay between messages.
59    */
60   struct GNUNET_TIME_Relative msg_delay;
61
62   /**
63    * Next allowed transmission time.
64    */
65   struct GNUNET_TIME_Absolute delay_until;
66
67   /**
68    * Time we transmitted the last message of the last round.
69    */
70   struct GNUNET_TIME_Absolute last_round;
71
72   /**
73    * Message to fragment (allocated at the end of this struct).
74    */
75   const struct GNUNET_MessageHeader *msg;
76
77   /**
78    * Function to call for transmissions.
79    */
80   GNUNET_FRAGMENT_MessageProcessor proc;
81
82   /**
83    * Closure for @e proc.
84    */
85   void *proc_cls;
86
87   /**
88    * Bitfield, set to 1 for each unacknowledged fragment.
89    */
90   uint64_t acks;
91
92   /**
93    * Bitfield with all possible bits for @e acks (used to mask the
94    * ack we get back).
95    */
96   uint64_t acks_mask;
97
98   /**
99    * Task performing work for the fragmenter.
100    */
101   struct GNUNET_SCHEDULER_Task *task;
102
103   /**
104    * Our fragmentation ID. (chosen at random)
105    */
106   uint32_t fragment_id;
107
108   /**
109    * Round-robin selector for the next transmission.
110    */
111   unsigned int next_transmission;
112
113   /**
114    * How many rounds of transmission have we completed so far?
115    */
116   unsigned int num_rounds;
117
118   /**
119    * How many transmission have we completed in this round?
120    */
121   unsigned int num_transmissions;
122
123   /**
124    * #GNUNET_YES if we called @e proc and are now waiting for #GNUNET_FRAGMENT_context_transmission_done()
125    */
126   int8_t proc_busy;
127
128   /**
129    * #GNUNET_YES if we are waiting for an ACK.
130    */
131   int8_t wack;
132
133   /**
134    * Target fragment size.
135    */
136   uint16_t mtu;
137
138 };
139
140
141 /**
142  * Convert an ACK message to a printable format suitable for logging.
143  *
144  * @param ack message to print
145  * @return ack in human-readable format
146  */
147 const char *
148 GNUNET_FRAGMENT_print_ack (const struct GNUNET_MessageHeader *ack)
149 {
150   static char buf[128];
151   const struct FragmentAcknowledgement *fa;
152
153   if (sizeof (struct FragmentAcknowledgement) !=
154       htons (ack->size))
155     return "<malformed ack>";
156   fa = (const struct FragmentAcknowledgement *) ack;
157   GNUNET_snprintf (buf,
158                    sizeof (buf),
159                    "%u-%llX",
160                    ntohl (fa->fragment_id),
161                    GNUNET_ntohll (fa->bits));
162   return buf;
163 }
164
165
166 /**
167  * Transmit the next fragment to the other peer.
168  *
169  * @param cls the `struct GNUNET_FRAGMENT_Context`
170  */
171 static void
172 transmit_next (void *cls)
173 {
174   struct GNUNET_FRAGMENT_Context *fc = cls;
175   char msg[fc->mtu];
176   const char *mbuf;
177   struct FragmentHeader *fh;
178   struct GNUNET_TIME_Relative delay;
179   unsigned int bit;
180   size_t size;
181   size_t fsize;
182   int wrap;
183
184   fc->task = NULL;
185   GNUNET_assert (GNUNET_NO == fc->proc_busy);
186   if (0 == fc->acks)
187     return;                     /* all done */
188   /* calculate delay */
189   wrap = 0;
190   while (0 == (fc->acks & (1LL << fc->next_transmission)))
191   {
192     fc->next_transmission = (fc->next_transmission + 1) % 64;
193     wrap |= (0 == fc->next_transmission);
194   }
195   bit = fc->next_transmission;
196   size = ntohs (fc->msg->size);
197   if (bit == size / (fc->mtu - sizeof (struct FragmentHeader)))
198     fsize =
199         (size % (fc->mtu - sizeof (struct FragmentHeader))) +
200         sizeof (struct FragmentHeader);
201   else
202     fsize = fc->mtu;
203   if (NULL != fc->tracker)
204     delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker,
205                                                 fsize);
206   else
207     delay = GNUNET_TIME_UNIT_ZERO;
208   if (delay.rel_value_us > 0)
209   {
210     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
211                 "Fragmentation logic delays transmission of next fragment by %s\n",
212                 GNUNET_STRINGS_relative_time_to_string (delay,
213                                                         GNUNET_YES));
214     fc->task = GNUNET_SCHEDULER_add_delayed (delay,
215                                              &transmit_next,
216                                              fc);
217     return;
218   }
219   fc->next_transmission = (fc->next_transmission + 1) % 64;
220   wrap |= (0 == fc->next_transmission);
221   while (0 == (fc->acks & (1LL << fc->next_transmission)))
222   {
223     fc->next_transmission = (fc->next_transmission + 1) % 64;
224     wrap |= (0 == fc->next_transmission);
225   }
226
227   /* assemble fragmentation message */
228   mbuf = (const char *) &fc[1];
229   fh = (struct FragmentHeader *) msg;
230   fh->header.size = htons (fsize);
231   fh->header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT);
232   fh->fragment_id = htonl (fc->fragment_id);
233   fh->total_size = fc->msg->size;       /* already in big-endian */
234   fh->offset = htons ((fc->mtu - sizeof (struct FragmentHeader)) * bit);
235   memcpy (&fh[1], &mbuf[bit * (fc->mtu - sizeof (struct FragmentHeader))],
236           fsize - sizeof (struct FragmentHeader));
237   if (NULL != fc->tracker)
238     GNUNET_BANDWIDTH_tracker_consume (fc->tracker, fsize);
239   GNUNET_STATISTICS_update (fc->stats,
240                             _("# fragments transmitted"),
241                             1,
242                             GNUNET_NO);
243   if (0 != fc->last_round.abs_value_us)
244     GNUNET_STATISTICS_update (fc->stats,
245                               _("# fragments retransmitted"),
246                               1,
247                               GNUNET_NO);
248
249   /* select next message to calculate delay */
250   bit = fc->next_transmission;
251   size = ntohs (fc->msg->size);
252   if (bit == size / (fc->mtu - sizeof (struct FragmentHeader)))
253     fsize = size % (fc->mtu - sizeof (struct FragmentHeader));
254   else
255     fsize = fc->mtu;
256   if (NULL != fc->tracker)
257     delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker,
258                                                 fsize);
259   else
260     delay = GNUNET_TIME_UNIT_ZERO;
261   delay = GNUNET_TIME_relative_max (delay,
262                                     GNUNET_TIME_relative_multiply (fc->msg_delay,
263                                                                    (1ULL << fc->num_rounds)));
264   if (wrap)
265   {
266     /* full round transmitted wait 2x delay for ACK before going again */
267     fc->num_rounds++;
268     delay = GNUNET_TIME_relative_multiply (fc->ack_delay, 2);
269     /* never use zero, need some time for ACK always */
270     delay = GNUNET_TIME_relative_max (MIN_ACK_DELAY, delay);
271     fc->wack = GNUNET_YES;
272     fc->last_round = GNUNET_TIME_absolute_get ();
273     GNUNET_STATISTICS_update (fc->stats,
274                               _("# fragments wrap arounds"),
275                               1,
276                               GNUNET_NO);
277   }
278   fc->proc_busy = GNUNET_YES;
279   fc->delay_until = GNUNET_TIME_relative_to_absolute (delay);
280   fc->num_transmissions++;
281   fc->proc (fc->proc_cls,
282             &fh->header);
283 }
284
285
286 /**
287  * Create a fragmentation context for the given message.
288  * Fragments the message into fragments of size @a mtu or
289  * less.  Calls @a proc on each un-acknowledged fragment,
290  * using both the expected @a msg_delay between messages and
291  * acknowledgements and the given @a tracker to guide the
292  * frequency of calls to @a proc.
293  *
294  * @param stats statistics context
295  * @param mtu the maximum message size for each fragment
296  * @param tracker bandwidth tracker to use for flow control (can be NULL)
297  * @param msg_delay initial delay to insert between fragment transmissions
298  *              based on previous messages
299  * @param ack_delay expected delay between fragment transmission
300  *              and ACK based on previous messages
301  * @param msg the message to fragment
302  * @param proc function to call for each fragment to transmit
303  * @param proc_cls closure for @a proc
304  * @return the fragmentation context
305  */
306 struct GNUNET_FRAGMENT_Context *
307 GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
308                                 uint16_t mtu,
309                                 struct GNUNET_BANDWIDTH_Tracker *tracker,
310                                 struct GNUNET_TIME_Relative msg_delay,
311                                 struct GNUNET_TIME_Relative ack_delay,
312                                 const struct GNUNET_MessageHeader *msg,
313                                 GNUNET_FRAGMENT_MessageProcessor proc,
314                                 void *proc_cls)
315 {
316   struct GNUNET_FRAGMENT_Context *fc;
317   size_t size;
318   uint64_t bits;
319
320   GNUNET_STATISTICS_update (stats,
321                             _("# messages fragmented"),
322                             1,
323                             GNUNET_NO);
324   GNUNET_assert (mtu >= 1024 + sizeof (struct FragmentHeader));
325   size = ntohs (msg->size);
326   GNUNET_STATISTICS_update (stats,
327                             _("# total size of fragmented messages"),
328                             size, GNUNET_NO);
329   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
330   fc = GNUNET_malloc (sizeof (struct GNUNET_FRAGMENT_Context) + size);
331   fc->stats = stats;
332   fc->mtu = mtu;
333   fc->tracker = tracker;
334   fc->ack_delay = ack_delay;
335   fc->msg_delay = msg_delay;
336   fc->msg = (const struct GNUNET_MessageHeader *) &fc[1];
337   fc->proc = proc;
338   fc->proc_cls = proc_cls;
339   fc->fragment_id =
340       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
341                                 UINT32_MAX);
342   memcpy (&fc[1], msg, size);
343   bits =
344       (size + mtu - sizeof (struct FragmentHeader) - 1) / (mtu -
345                                                            sizeof (struct
346                                                                    FragmentHeader));
347   GNUNET_assert (bits <= 64);
348   if (bits == 64)
349     fc->acks_mask = UINT64_MAX; /* set all 64 bit */
350   else
351     fc->acks_mask = (1LL << bits) - 1;  /* set lowest 'bits' bit */
352   fc->acks = fc->acks_mask;
353   fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc);
354   return fc;
355 }
356
357
358 /**
359  * Continuation to call from the 'proc' function after the fragment
360  * has been transmitted (and hence the next fragment can now be
361  * given to proc).
362  *
363  * @param fc fragmentation context
364  */
365 void
366 GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc)
367 {
368   GNUNET_assert (fc->proc_busy == GNUNET_YES);
369   fc->proc_busy = GNUNET_NO;
370   GNUNET_assert (fc->task == NULL);
371   fc->task =
372       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
373                                     (fc->delay_until), &transmit_next, fc);
374 }
375
376
377 /**
378  * Process an acknowledgement message we got from the other
379  * side (to control re-transmits).
380  *
381  * @param fc fragmentation context
382  * @param msg acknowledgement message we received
383  * @return #GNUNET_OK if this ack completes the work of the 'fc'
384  *                   (all fragments have been received);
385  *         #GNUNET_NO if more messages are pending
386  *         #GNUNET_SYSERR if this ack is not valid for this fc
387  */
388 int
389 GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc,
390                              const struct GNUNET_MessageHeader *msg)
391 {
392   const struct FragmentAcknowledgement *fa;
393   uint64_t abits;
394   struct GNUNET_TIME_Relative ndelay;
395   unsigned int ack_cnt;
396   unsigned int snd_cnt;
397   unsigned int i;
398
399   if (sizeof (struct FragmentAcknowledgement) != ntohs (msg->size))
400   {
401     GNUNET_break_op (0);
402     return GNUNET_SYSERR;
403   }
404   fa = (const struct FragmentAcknowledgement *) msg;
405   if (ntohl (fa->fragment_id) != fc->fragment_id)
406     return GNUNET_SYSERR;       /* not our ACK */
407   abits = GNUNET_ntohll (fa->bits);
408   if ( (GNUNET_YES == fc->wack) &&
409        (0 != fc->num_transmissions) )
410   {
411     /* normal ACK, can update running average of delay... */
412     fc->wack = GNUNET_NO;
413     ndelay = GNUNET_TIME_absolute_get_duration (fc->last_round);
414     fc->ack_delay.rel_value_us =
415         (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->ack_delay.rel_value_us) / 4;
416     /* calculate ratio msg sent vs. msg acked */
417     ack_cnt = 0;
418     snd_cnt = 0;
419     for (i=0;i<64;i++)
420     {
421       if (1 == (fc->acks_mask & (1ULL << i)))
422       {
423         snd_cnt++;
424         if (0 == (abits & (1ULL << i)))
425           ack_cnt++;
426       }
427     }
428     if (0 == ack_cnt)
429     {
430       /* complete loss */
431       fc->msg_delay = GNUNET_TIME_relative_multiply (fc->msg_delay,
432                                                      snd_cnt);
433     }
434     else if (snd_cnt > ack_cnt)
435     {
436       /* some loss, slow down proportionally */
437       fc->msg_delay.rel_value_us = ((fc->msg_delay.rel_value_us * ack_cnt) / snd_cnt);
438     }
439     else if (snd_cnt == ack_cnt)
440     {
441       fc->msg_delay.rel_value_us =
442         (ndelay.rel_value_us / fc->num_transmissions + 3 * fc->msg_delay.rel_value_us) / 5;
443     }
444     fc->num_transmissions = 0;
445     fc->msg_delay = GNUNET_TIME_relative_min (fc->msg_delay,
446                                               GNUNET_TIME_UNIT_SECONDS);
447     fc->ack_delay = GNUNET_TIME_relative_min (fc->ack_delay,
448                                               GNUNET_TIME_UNIT_SECONDS);
449   }
450   GNUNET_STATISTICS_update (fc->stats,
451                             _("# fragment acknowledgements received"),
452                             1,
453                             GNUNET_NO);
454   if (abits != (fc->acks & abits))
455   {
456     /* ID collission or message reordering, count! This should be rare! */
457     GNUNET_STATISTICS_update (fc->stats,
458                               _("# bits removed from fragmentation ACKs"), 1,
459                               GNUNET_NO);
460   }
461   fc->acks = abits & fc->acks_mask;
462   if (0 != fc->acks)
463   {
464     /* more to transmit, do so right now (if tracker permits...) */
465     if (fc->task != NULL)
466     {
467       /* schedule next transmission now, no point in waiting... */
468       GNUNET_SCHEDULER_cancel (fc->task);
469       fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc);
470     }
471     else
472     {
473       /* only case where there is no task should be if we're waiting
474        * for the right to transmit again (proc_busy set to YES) */
475       GNUNET_assert (GNUNET_YES == fc->proc_busy);
476     }
477     return GNUNET_NO;
478   }
479
480   /* all done */
481   GNUNET_STATISTICS_update (fc->stats,
482                             _("# fragmentation transmissions completed"),
483                             1,
484                             GNUNET_NO);
485   if (NULL != fc->task)
486   {
487     GNUNET_SCHEDULER_cancel (fc->task);
488     fc->task = NULL;
489   }
490   return GNUNET_OK;
491 }
492
493
494 /**
495  * Destroy the given fragmentation context (stop calling 'proc', free
496  * resources).
497  *
498  * @param fc fragmentation context
499  * @param msg_delay where to store average delay between individual message transmissions the
500  *         last message (OUT only)
501  * @param ack_delay where to store average delay between transmission and ACK for the
502  *         last message, set to FOREVER if the message was not fully transmitted (OUT only)
503  */
504 void
505 GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *fc,
506                                  struct GNUNET_TIME_Relative *msg_delay,
507                                  struct GNUNET_TIME_Relative *ack_delay)
508 {
509   if (fc->task != NULL)
510     GNUNET_SCHEDULER_cancel (fc->task);
511   if (NULL != ack_delay)
512     *ack_delay = fc->ack_delay;
513   if (NULL != msg_delay)
514     *msg_delay = GNUNET_TIME_relative_multiply (fc->msg_delay,
515                                                 fc->num_rounds);
516   GNUNET_free (fc);
517 }
518
519
520 /* end of fragmentation.c */