-clean up WLAN plugin
[oweals/gnunet.git] / src / fragmentation / fragmentation.c
1 /*
2      This file is part of GNUnet
3      (C) 2009, 2011 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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 delay;
56
57   /**
58    * Next allowed transmission time.
59    */
60   struct GNUNET_TIME_Absolute delay_until;
61
62   /**
63    * Time we transmitted the last message of the last round.
64    */
65   struct GNUNET_TIME_Absolute last_round;
66
67   /**
68    * Message to fragment (allocated at the end of this struct).
69    */
70   const struct GNUNET_MessageHeader *msg;
71
72   /**
73    * Function to call for transmissions.
74    */
75   GNUNET_FRAGMENT_MessageProcessor proc;
76
77   /**
78    * Closure for 'proc'.
79    */
80   void *proc_cls;
81
82   /**
83    * Bitfield, set to 1 for each unacknowledged fragment.
84    */
85   uint64_t acks;
86
87   /**
88    * Bitfield with all possible bits for 'acks' (used to mask the
89    * ack we get back).
90    */
91   uint64_t acks_mask;
92
93   /**
94    * Task performing work for the fragmenter.
95    */
96   GNUNET_SCHEDULER_TaskIdentifier task;
97
98   /**
99    * Our fragmentation ID. (chosen at random)
100    */
101   uint32_t fragment_id;
102
103   /**
104    * Round-robin selector for the next transmission.
105    */
106   unsigned int next_transmission;
107
108   /**
109    * How many rounds of transmission have we completed so far?
110    */
111   unsigned int num_rounds;
112
113   /**
114    * GNUNET_YES if we called 'proc' and are now waiting for 'GNUNET_FRAGMENT_transmission_done'
115    */
116   int8_t proc_busy;
117
118   /**
119    * GNUNET_YES if we are waiting for an ACK.
120    */
121   int8_t wack;
122
123   /**
124    * Target fragment size.
125    */
126   uint16_t mtu;
127
128 };
129
130
131 /**
132  * Transmit the next fragment to the other peer.
133  *
134  * @param cls the 'struct GNUNET_FRAGMENT_Context'
135  * @param tc scheduler context
136  */
137 static void
138 transmit_next (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
139 {
140   struct GNUNET_FRAGMENT_Context *fc = cls;
141   char msg[fc->mtu];
142   const char *mbuf;
143   struct FragmentHeader *fh;
144   struct GNUNET_TIME_Relative delay;
145   unsigned int bit;
146   size_t size;
147   size_t fsize;
148   int wrap;
149
150   fc->task = GNUNET_SCHEDULER_NO_TASK;
151   GNUNET_assert (GNUNET_NO == fc->proc_busy);
152   if (0 == fc->acks)
153     return;                     /* all done */
154
155   /* calculate delay */
156   wrap = 0;
157   while (0 == (fc->acks & (1LL << fc->next_transmission)))
158   {
159     fc->next_transmission = (fc->next_transmission + 1) % 64;
160     wrap |= (fc->next_transmission == 0);
161   }
162   bit = fc->next_transmission;
163   size = ntohs (fc->msg->size);
164   if (bit == size / (fc->mtu - sizeof (struct FragmentHeader)))
165     fsize =
166         (size % (fc->mtu - sizeof (struct FragmentHeader))) +
167         sizeof (struct FragmentHeader);
168   else
169     fsize = fc->mtu;
170   if (fc->tracker != NULL)
171     delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker, fsize);
172   else
173     delay = GNUNET_TIME_UNIT_ZERO;
174   if (delay.rel_value > 0)
175   {
176     fc->task = GNUNET_SCHEDULER_add_delayed (delay, &transmit_next, fc);
177     return;
178   }
179   fc->next_transmission = (fc->next_transmission + 1) % 64;
180   wrap |= (fc->next_transmission == 0);
181   while (0 == (fc->acks & (1LL << fc->next_transmission)))
182   {
183     fc->next_transmission = (fc->next_transmission + 1) % 64;
184     wrap |= (fc->next_transmission == 0);
185   }
186
187   /* assemble fragmentation message */
188   mbuf = (const char *) &fc[1];
189   fh = (struct FragmentHeader *) msg;
190   fh->header.size = htons (fsize);
191   fh->header.type = htons (GNUNET_MESSAGE_TYPE_FRAGMENT);
192   fh->fragment_id = htonl (fc->fragment_id);
193   fh->total_size = fc->msg->size;       /* already in big-endian */
194   fh->offset = htons ((fc->mtu - sizeof (struct FragmentHeader)) * bit);
195   memcpy (&fh[1], &mbuf[bit * (fc->mtu - sizeof (struct FragmentHeader))],
196           fsize - sizeof (struct FragmentHeader));
197   if (NULL != fc->tracker)
198     GNUNET_BANDWIDTH_tracker_consume (fc->tracker, fsize);
199   GNUNET_STATISTICS_update (fc->stats, _("# fragments transmitted"), 1,
200                             GNUNET_NO);
201   if (0 != fc->last_round.abs_value)
202     GNUNET_STATISTICS_update (fc->stats, _("# fragments retransmitted"), 1,
203                               GNUNET_NO);
204
205   /* select next message to calculate delay */
206   bit = fc->next_transmission;
207   size = ntohs (fc->msg->size);
208   if (bit == size / (fc->mtu - sizeof (struct FragmentHeader)))
209     fsize = size % (fc->mtu - sizeof (struct FragmentHeader));
210   else
211     fsize = fc->mtu;
212   if (NULL != fc->tracker)
213     delay = GNUNET_BANDWIDTH_tracker_get_delay (fc->tracker, fsize);
214   else
215     delay = GNUNET_TIME_UNIT_ZERO;
216   if (wrap)
217   {
218     /* full round transmitted wait 2x delay for ACK before going again */
219     fc->num_rounds++;
220     delay =
221         GNUNET_TIME_relative_max (GNUNET_TIME_relative_multiply (delay, 2),
222                                   GNUNET_TIME_relative_multiply (fc->delay,
223                                                                  fc->num_rounds));
224     /* never use zero, need some time for ACK always */
225     delay = GNUNET_TIME_relative_max (MIN_ACK_DELAY, delay);
226     fc->last_round = GNUNET_TIME_absolute_get ();
227     fc->wack = GNUNET_YES;
228   }
229   fc->proc_busy = GNUNET_YES;
230   fc->delay_until = GNUNET_TIME_relative_to_absolute (delay);
231   fc->proc (fc->proc_cls, &fh->header);
232 }
233
234
235 /**
236  * Create a fragmentation context for the given message.
237  * Fragments the message into fragments of size "mtu" or
238  * less.  Calls 'proc' on each un-acknowledged fragment,
239  * using both the expected 'delay' between messages and
240  * acknowledgements and the given 'tracker' to guide the
241  * frequency of calls to 'proc'.
242  *
243  * @param stats statistics context
244  * @param mtu the maximum message size for each fragment
245  * @param tracker bandwidth tracker to use for flow control (can be NULL)
246  * @param delay expected delay between fragment transmission
247  *              and ACK based on previous messages
248  * @param msg the message to fragment
249  * @param proc function to call for each fragment to transmit
250  * @param proc_cls closure for proc
251  * @return the fragmentation context
252  */
253 struct GNUNET_FRAGMENT_Context *
254 GNUNET_FRAGMENT_context_create (struct GNUNET_STATISTICS_Handle *stats,
255                                 uint16_t mtu,
256                                 struct GNUNET_BANDWIDTH_Tracker *tracker,
257                                 struct GNUNET_TIME_Relative delay,
258                                 const struct GNUNET_MessageHeader *msg,
259                                 GNUNET_FRAGMENT_MessageProcessor proc,
260                                 void *proc_cls)
261 {
262   struct GNUNET_FRAGMENT_Context *fc;
263   size_t size;
264   uint64_t bits;
265
266   GNUNET_STATISTICS_update (stats, _("# messages fragmented"), 1, GNUNET_NO);
267   GNUNET_assert (mtu >= 1024 + sizeof (struct FragmentHeader));
268   size = ntohs (msg->size);
269   GNUNET_STATISTICS_update (stats, _("# total size of fragmented messages"),
270                             size, GNUNET_NO);
271   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
272   fc = GNUNET_malloc (sizeof (struct GNUNET_FRAGMENT_Context) + size);
273   fc->stats = stats;
274   fc->mtu = mtu;
275   fc->tracker = tracker;
276   fc->delay = delay;
277   fc->msg = (const struct GNUNET_MessageHeader *) &fc[1];
278   fc->proc = proc;
279   fc->proc_cls = proc_cls;
280   fc->fragment_id =
281       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
282   memcpy (&fc[1], msg, size);
283   bits =
284       (size + mtu - sizeof (struct FragmentHeader) - 1) / (mtu -
285                                                            sizeof (struct
286                                                                    FragmentHeader));
287   GNUNET_assert (bits <= 64);
288   if (bits == 64)
289     fc->acks_mask = UINT64_MAX; /* set all 64 bit */
290   else
291     fc->acks_mask = (1LL << bits) - 1;  /* set lowest 'bits' bit */
292   fc->acks = fc->acks_mask;
293   fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc);
294   return fc;
295 }
296
297
298 /**
299  * Continuation to call from the 'proc' function after the fragment
300  * has been transmitted (and hence the next fragment can now be
301  * given to proc).
302  *
303  * @param fc fragmentation context
304  */
305 void
306 GNUNET_FRAGMENT_context_transmission_done (struct GNUNET_FRAGMENT_Context *fc)
307 {
308   GNUNET_assert (fc->proc_busy == GNUNET_YES);
309   fc->proc_busy = GNUNET_NO;
310   GNUNET_assert (fc->task == GNUNET_SCHEDULER_NO_TASK);
311   fc->task =
312       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
313                                     (fc->delay_until), &transmit_next, fc);
314 }
315
316
317 /**
318  * Process an acknowledgement message we got from the other
319  * side (to control re-transmits).
320  *
321  * @param fc fragmentation context
322  * @param msg acknowledgement message we received
323  * @return GNUNET_OK if this ack completes the work of the 'fc'
324  *                   (all fragments have been received);
325  *         GNUNET_NO if more messages are pending
326  *         GNUNET_SYSERR if this ack is not valid for this fc
327  */
328 int
329 GNUNET_FRAGMENT_process_ack (struct GNUNET_FRAGMENT_Context *fc,
330                              const struct GNUNET_MessageHeader *msg)
331 {
332   const struct FragmentAcknowledgement *fa;
333   uint64_t abits;
334   struct GNUNET_TIME_Relative ndelay;
335
336   if (sizeof (struct FragmentAcknowledgement) != ntohs (msg->size))
337   {
338     GNUNET_break_op (0);
339     return GNUNET_SYSERR;
340   }
341   fa = (const struct FragmentAcknowledgement *) msg;
342   if (ntohl (fa->fragment_id) != fc->fragment_id)
343     return GNUNET_SYSERR;       /* not our ACK */
344   abits = GNUNET_ntohll (fa->bits);
345   if ((GNUNET_YES == fc->wack) && (abits == (fc->acks & abits)))
346   {
347     /* normal ACK, can update running average of delay... */
348     fc->wack = GNUNET_NO;
349     ndelay = GNUNET_TIME_absolute_get_duration (fc->last_round);
350     fc->delay.rel_value =
351         (ndelay.rel_value * fc->num_rounds + 3 * fc->delay.rel_value) / 4;
352   }
353   GNUNET_STATISTICS_update (fc->stats,
354                             _("# fragment acknowledgements received"), 1,
355                             GNUNET_NO);
356   if (abits != (fc->acks & abits))
357   {
358     /* ID collission or message reordering, count! This should be rare! */
359     GNUNET_STATISTICS_update (fc->stats,
360                               _("# bits removed from fragmentation ACKs"), 1,
361                               GNUNET_NO);
362   }
363   fc->acks = abits & fc->acks_mask;
364   if (0 != fc->acks)
365   {
366     /* more to transmit, do so right now (if tracker permits...) */
367     if (fc->task != GNUNET_SCHEDULER_NO_TASK)
368     {
369       /* schedule next transmission now, no point in waiting... */
370       GNUNET_SCHEDULER_cancel (fc->task);
371       fc->task = GNUNET_SCHEDULER_add_now (&transmit_next, fc);
372     }
373     else
374     {
375       /* only case where there is no task should be if we're waiting
376        * for the right to transmit again (proc_busy set to YES) */
377       GNUNET_assert (GNUNET_YES == fc->proc_busy);
378     }
379     return GNUNET_NO;
380   }
381
382   /* all done */
383   GNUNET_STATISTICS_update (fc->stats,
384                             _("# fragmentation transmissions completed"), 1,
385                             GNUNET_NO);
386   if (fc->task != GNUNET_SCHEDULER_NO_TASK)
387   {
388     GNUNET_SCHEDULER_cancel (fc->task);
389     fc->task = GNUNET_SCHEDULER_NO_TASK;
390   }
391   return GNUNET_OK;
392 }
393
394
395 /**
396  * Destroy the given fragmentation context (stop calling 'proc', free
397  * resources).
398  *
399  * @param fc fragmentation context
400  * @return average delay between transmission and ACK for the
401  *         last message, FOREVER if the message was not fully transmitted
402  */
403 struct GNUNET_TIME_Relative
404 GNUNET_FRAGMENT_context_destroy (struct GNUNET_FRAGMENT_Context *fc)
405 {
406   struct GNUNET_TIME_Relative ret;
407
408   if (fc->task != GNUNET_SCHEDULER_NO_TASK)
409     GNUNET_SCHEDULER_cancel (fc->task);
410   ret = fc->delay;
411   GNUNET_free (fc);
412   return ret;
413 }
414
415
416 /* end of fragmentation.c */