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