indentation
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 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 /**
22  * @file transport/transport_api.c
23  * @brief library to access the low-level P2P IO service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - adjust testcases to use new 'try connect' style (should be easy, breaks API compatibility!)
28  * - adjust core service to use new 'try connect' style (should be MUCH nicer there as well!)
29  * - test test test
30  */
31 #include "platform.h"
32 #include "gnunet_bandwidth_lib.h"
33 #include "gnunet_client_lib.h"
34 #include "gnunet_constants.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet_arm_service.h"
37 #include "gnunet_hello_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_server_lib.h"
40 #include "gnunet_time_lib.h"
41 #include "gnunet_transport_service.h"
42 #include "transport.h"
43
44 /**
45  * How large to start with for the hashmap of neighbours.
46  */
47 #define STARTING_NEIGHBOURS_SIZE 16
48
49
50 /**
51  * Handle for a message that should be transmitted to the service.
52  * Used for both control messages and normal messages.
53  */
54 struct GNUNET_TRANSPORT_TransmitHandle
55 {
56
57   /**
58    * We keep all requests in a DLL.
59    */
60   struct GNUNET_TRANSPORT_TransmitHandle *next;
61
62   /**
63    * We keep all requests in a DLL.
64    */
65   struct GNUNET_TRANSPORT_TransmitHandle *prev;
66
67   /**
68    * Neighbour for this handle, NULL for control messages.
69    */
70   struct Neighbour *neighbour;
71
72   /**
73    * Function to call when notify_size bytes are available
74    * for transmission.
75    */
76   GNUNET_CONNECTION_TransmitReadyNotify notify;
77
78   /**
79    * Closure for notify.
80    */
81   void *notify_cls;
82
83   /**
84    * Timeout for this request, 0 for control messages.
85    */
86   struct GNUNET_TIME_Absolute timeout;
87
88   /**
89    * Task to trigger request timeout if the request is stalled due to 
90    * congestion.
91    */
92   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
93
94   /**
95    * How many bytes is our notify callback waiting for?
96    */
97   size_t notify_size;
98
99   /**
100    * How important is this message? Not used for control messages.
101    */
102   uint32_t priority;
103
104 };
105
106
107 /**
108  * Entry in hash table of all of our current neighbours.
109  */
110 struct Neighbour
111 {
112   /**
113    * Overall transport handle.
114    */
115   struct GNUNET_TRANSPORT_Handle *h;
116
117   /**
118    * Active transmit handle or NULL.
119    */
120   struct GNUNET_TRANSPORT_TransmitHandle *th;
121
122   /**
123    * Identity of this neighbour.
124    */
125   struct GNUNET_PeerIdentity id;
126
127   /**
128    * Outbound bandwidh tracker.
129    */
130   struct GNUNET_BANDWIDTH_Tracker out_tracker;
131
132   /**
133    * Entry in our readyness heap (which is sorted by 'next_ready'
134    * value).  NULL if there is no pending transmission request for
135    * this neighbour or if we're waiting for 'is_ready' to become
136    * true AFTER the 'out_tracker' suggested that this peer's quota
137    * has been satisfied (so once 'is_ready' goes to GNUNET_YES,
138    * we should immediately go back into the heap).
139    */
140   struct GNUNET_CONTAINER_HeapNode *hn;
141
142   /**
143    * Is this peer currently ready to receive a message?
144    */
145   int is_ready;
146
147 };
148
149
150 /**
151  * Linked list of functions to call whenever our HELLO is updated.
152  */
153 struct HelloWaitList
154 {
155
156   /**
157    * This is a doubly linked list.
158    */
159   struct HelloWaitList *next;
160
161   /**
162    * This is a doubly linked list.
163    */
164   struct HelloWaitList *prev;
165
166   /**
167    * Callback to call once we got our HELLO.
168    */
169   GNUNET_TRANSPORT_HelloUpdateCallback rec;
170
171   /**
172    * Closure for rec.
173    */
174   void *rec_cls;
175
176 };
177
178
179 /**
180  * Handle for the transport service (includes all of the
181  * state for the transport service).
182  */
183 struct GNUNET_TRANSPORT_Handle
184 {
185
186   /**
187    * Closure for the callbacks.
188    */
189   void *cls;
190
191   /**
192    * Function to call for received data.
193    */
194   GNUNET_TRANSPORT_ReceiveCallback rec;
195
196   /**
197    * function to call on connect events
198    */
199   GNUNET_TRANSPORT_NotifyConnect nc_cb;
200
201   /**
202    * function to call on disconnect events
203    */
204   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
205
206   /**
207    * Head of DLL of control messages.
208    */
209   struct GNUNET_TRANSPORT_TransmitHandle *control_head;
210
211   /**
212    * Tail of DLL of control messages.
213    */
214   struct GNUNET_TRANSPORT_TransmitHandle *control_tail;
215
216   /**
217    * The current HELLO message for this peer.  Updated
218    * whenever transports change their addresses.
219    */
220   struct GNUNET_HELLO_Message *my_hello;
221
222   /**
223    * My client connection to the transport service.
224    */
225   struct GNUNET_CLIENT_Connection *client;
226
227   /**
228    * Handle to our registration with the client for notification.
229    */
230   struct GNUNET_CLIENT_TransmitHandle *cth;
231
232   /**
233    * Linked list of pending requests for our HELLO.
234    */
235   struct HelloWaitList *hwl_head;
236
237   /**
238    * Linked list of pending requests for our HELLO.
239    */
240   struct HelloWaitList *hwl_tail;
241
242   /**
243    * My configuration.
244    */
245   const struct GNUNET_CONFIGURATION_Handle *cfg;
246
247   /**
248    * Hash map of the current connected neighbours of this peer.
249    * Maps peer identities to 'struct Neighbour' entries.
250    */
251   struct GNUNET_CONTAINER_MultiHashMap *neighbours;
252
253   /**
254    * Heap sorting peers with pending messages by the timestamps that
255    * specify when we could next send a message to the respective peer.
256    * Excludes control messages (which can always go out immediately).
257    * Maps time stamps to 'struct Neighbour' entries.
258    */
259   struct GNUNET_CONTAINER_Heap *ready_heap;
260
261   /**
262    * Peer identity as assumed by this process, or all zeros.
263    */
264   struct GNUNET_PeerIdentity self;
265
266   /**
267    * ID of the task trying to reconnect to the service.
268    */
269   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
270
271   /**
272    * ID of the task trying to trigger transmission for a peer while
273    * maintaining bandwidth quotas.  In use if there are no control
274    * messages and the smallest entry in the 'ready_heap' has a time
275    * stamp in the future.
276    */
277   GNUNET_SCHEDULER_TaskIdentifier quota_task;
278
279   /**
280    * Delay until we try to reconnect.
281    */
282   struct GNUNET_TIME_Relative reconnect_delay;
283
284   /**
285    * Should we check that 'self' matches what the service thinks?
286    * (if GNUNET_NO, then 'self' is all zeros!).
287    */
288   int check_self;
289 };
290
291
292 /**
293  * Schedule the task to send one message, either from the control
294  * list or the peer message queues  to the service.
295  *
296  * @param h transport service to schedule a transmission for
297  */
298 static void schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
299
300
301 /**
302  * Function that will schedule the job that will try
303  * to connect us again to the client.
304  *
305  * @param h transport service to reconnect
306  */
307 static void disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle
308                                                *h);
309
310
311 /**
312  * Get the neighbour list entry for the given peer
313  *
314  * @param h our context
315  * @param peer peer to look up
316  * @return NULL if no such peer entry exists
317  */
318 static struct Neighbour *
319 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
320                 const struct GNUNET_PeerIdentity *peer)
321 {
322   return GNUNET_CONTAINER_multihashmap_get (h->neighbours, &peer->hashPubKey);
323 }
324
325
326 /**
327  * Add neighbour to our list
328  *
329  * @return NULL if this API is currently disconnecting from the service
330  */
331 static struct Neighbour *
332 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
333                const struct GNUNET_PeerIdentity *pid)
334 {
335   struct Neighbour *n;
336
337 #if DEBUG_TRANSPORT
338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating entry for neighbour `%4s'.\n",
339               GNUNET_i2s (pid));
340 #endif
341   n = GNUNET_malloc (sizeof (struct Neighbour));
342   n->id = *pid;
343   n->h = h;
344   n->is_ready = GNUNET_YES;
345   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
346                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
347                                  MAX_BANDWIDTH_CARRY_S);
348   GNUNET_assert (GNUNET_OK ==
349                  GNUNET_CONTAINER_multihashmap_put (h->neighbours,
350                                                     &pid->hashPubKey, n,
351                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
352   return n;
353 }
354
355
356 /**
357  * Iterator over hash map entries, for deleting state of a neighbour.
358  *
359  * @param cls the 'struct GNUNET_TRANSPORT_Handle*'
360  * @param key peer identity
361  * @param value value in the hash map, the neighbour entry to delete
362  * @return GNUNET_YES if we should continue to
363  *         iterate,
364  *         GNUNET_NO if not.
365  */
366 static int
367 neighbour_delete (void *cls, const GNUNET_HashCode * key, void *value)
368 {
369   struct GNUNET_TRANSPORT_Handle *handle = cls;
370   struct Neighbour *n = value;
371
372   if (NULL != handle->nd_cb)
373     handle->nd_cb (handle->cls, &n->id);
374   GNUNET_assert (NULL == n->th);
375   GNUNET_assert (NULL == n->hn);
376   GNUNET_assert (GNUNET_YES ==
377                  GNUNET_CONTAINER_multihashmap_remove (handle->neighbours, key,
378                                                        n));
379   GNUNET_free (n);
380   return GNUNET_YES;
381 }
382
383
384 /**
385  * Function we use for handling incoming messages.
386  *
387  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
388  * @param msg message received, NULL on timeout or fatal error
389  */
390 static void
391 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
392 {
393   struct GNUNET_TRANSPORT_Handle *h = cls;
394   const struct DisconnectInfoMessage *dim;
395   const struct ConnectInfoMessage *cim;
396   const struct InboundMessage *im;
397   const struct GNUNET_MessageHeader *imm;
398   const struct SendOkMessage *okm;
399   struct HelloWaitList *hwl;
400   struct HelloWaitList *next_hwl;
401   struct Neighbour *n;
402   struct GNUNET_PeerIdentity me;
403   uint16_t size;
404   uint32_t ats_count;
405
406   GNUNET_assert (h->client != NULL);
407   if (msg == NULL)
408   {
409 #if DEBUG_TRANSPORT
410     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
411                 "Error receiving from transport service, disconnecting temporarily.\n");
412 #endif
413     disconnect_and_schedule_reconnect (h);
414     return;
415   }
416   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
417                          GNUNET_TIME_UNIT_FOREVER_REL);
418   size = ntohs (msg->size);
419   switch (ntohs (msg->type))
420   {
421   case GNUNET_MESSAGE_TYPE_HELLO:
422     if (GNUNET_OK !=
423         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
424     {
425       GNUNET_break (0);
426       break;
427     }
428 #if DEBUG_TRANSPORT
429     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
430                 "Receiving (my own) `%s' message, I am `%4s'.\n", "HELLO",
431                 GNUNET_i2s (&me));
432 #endif
433     GNUNET_free_non_null (h->my_hello);
434     h->my_hello = NULL;
435     if (size < sizeof (struct GNUNET_MessageHeader))
436     {
437       GNUNET_break (0);
438       break;
439     }
440     h->my_hello = GNUNET_malloc (size);
441     memcpy (h->my_hello, msg, size);
442     hwl = h->hwl_head;
443     while (NULL != hwl)
444     {
445       next_hwl = hwl->next;
446       hwl->rec (hwl->rec_cls,
447                 (const struct GNUNET_MessageHeader *) h->my_hello);
448       hwl = next_hwl;
449     }
450     break;
451   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
452     if (size < sizeof (struct ConnectInfoMessage))
453     {
454       GNUNET_break (0);
455       break;
456     }
457     cim = (const struct ConnectInfoMessage *) msg;
458     ats_count = ntohl (cim->ats_count);
459     if (size !=
460         sizeof (struct ConnectInfoMessage) +
461         ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information))
462     {
463       GNUNET_break (0);
464       break;
465     }
466 #if DEBUG_TRANSPORT
467     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
468                 "CONNECT", GNUNET_i2s (&cim->id));
469 #endif
470     n = neighbour_find (h, &cim->id);
471     if (n != NULL)
472     {
473       GNUNET_break (0);
474       break;
475     }
476     n = neighbour_add (h, &cim->id);
477     if (h->nc_cb != NULL)
478       h->nc_cb (h->cls, &n->id, &cim->ats, ats_count);
479     break;
480   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
481     if (size != sizeof (struct DisconnectInfoMessage))
482     {
483       GNUNET_break (0);
484       break;
485     }
486     dim = (const struct DisconnectInfoMessage *) msg;
487     GNUNET_break (ntohl (dim->reserved) == 0);
488 #if DEBUG_TRANSPORT_DISCONNECT
489     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
490                 "DISCONNECT", GNUNET_i2s (&dim->peer));
491 #endif
492     n = neighbour_find (h, &dim->peer);
493     if (n == NULL)
494     {
495       GNUNET_break (0);
496       break;
497     }
498     neighbour_delete (h, &dim->peer.hashPubKey, n);
499     break;
500   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
501     if (size != sizeof (struct SendOkMessage))
502     {
503       GNUNET_break (0);
504       break;
505     }
506     okm = (const struct SendOkMessage *) msg;
507 #if DEBUG_TRANSPORT
508     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
509                 "Receiving `%s' message, transmission %s.\n", "SEND_OK",
510                 ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
511 #endif
512     n = neighbour_find (h, &okm->peer);
513     if (n == NULL)
514       break;
515     GNUNET_break (GNUNET_NO == n->is_ready);
516     n->is_ready = GNUNET_YES;
517     if ((n->th != NULL) && (n->hn == NULL))
518     {
519       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->th->timeout_task);
520       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
521       n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
522       /* we've been waiting for this (congestion, not quota, 
523        * caused delayed transmission) */
524       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
525       schedule_transmission (h);
526     }
527     break;
528   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
529 #if DEBUG_TRANSPORT
530     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message.\n", "RECV");
531 #endif
532     if (size <
533         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
534     {
535       GNUNET_break (0);
536       break;
537     }
538     im = (const struct InboundMessage *) msg;
539     GNUNET_break (0 == ntohl (im->reserved));
540     ats_count = ntohl (im->ats_count);
541     imm = (const struct GNUNET_MessageHeader *) &((&(im->ats))[ats_count + 1]);
542
543     if (ntohs (imm->size) + sizeof (struct InboundMessage) +
544         ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) != size)
545     {
546       GNUNET_break (0);
547       break;
548     }
549 #if DEBUG_TRANSPORT
550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551                 "Received message of type %u from `%4s'.\n", ntohs (imm->type),
552                 GNUNET_i2s (&im->peer));
553 #endif
554     n = neighbour_find (h, &im->peer);
555     if (n == NULL)
556     {
557       GNUNET_break (0);
558       break;
559     }
560     if (h->rec != NULL)
561       h->rec (h->cls, &im->peer, imm, &im->ats, ats_count);
562     break;
563   default:
564     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
565                 _("Received unexpected message of type %u in %s:%u\n"),
566                 ntohs (msg->type), __FILE__, __LINE__);
567     GNUNET_break (0);
568     break;
569   }
570 }
571
572
573 /**
574  * A transmission request could not be satisfied because of
575  * network congestion.  Notify the initiator and clean up.
576  *
577  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle'
578  * @param tc scheduler context
579  */
580 static void
581 timeout_request_due_to_congestion (void *cls,
582                                    const struct GNUNET_SCHEDULER_TaskContext
583                                    *tc)
584 {
585   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
586   struct Neighbour *n = th->neighbour;
587
588   n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
589   GNUNET_assert (th == n->th);
590   GNUNET_assert (NULL == n->hn);
591   n->th = NULL;
592   th->notify (th->notify_cls, 0, NULL);
593   GNUNET_free (th);
594 }
595
596
597 /**
598  * Transmit message(s) to service.
599  *
600  * @param cls handle to transport
601  * @param size number of bytes available in buf
602  * @param buf where to copy the message
603  * @return number of bytes copied to buf
604  */
605 static size_t
606 transport_notify_ready (void *cls, size_t size, void *buf)
607 {
608   struct GNUNET_TRANSPORT_Handle *h = cls;
609   struct GNUNET_TRANSPORT_TransmitHandle *th;
610   struct Neighbour *n;
611   char *cbuf;
612   struct OutboundMessage obm;
613   size_t ret;
614   size_t nret;
615   size_t mret;
616
617   GNUNET_assert (NULL != h->client);
618   h->cth = NULL;
619   if (NULL == buf)
620   {
621     /* transmission failed */
622     disconnect_and_schedule_reconnect (h);
623     return 0;
624   }
625
626   cbuf = buf;
627   ret = 0;
628   /* first send control messages */
629   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
630   {
631     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
632     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
633 #if DEBUG_TRANSPORT
634     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
635                 "Added %u bytes of control message at %u\n", nret, ret);
636 #endif
637     GNUNET_free (th);
638     ret += nret;
639     size -= nret;
640   }
641
642   /* then, if possible and no control messages pending, send data messages */
643   while ((NULL == h->control_head) &&
644          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
645   {
646     if (GNUNET_YES != n->is_ready)
647     {
648       /* peer not ready, wait for notification! */
649       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
650       n->hn = NULL;
651       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->th->timeout_task);
652       n->th->timeout_task =
653           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
654                                         (n->th->timeout),
655                                         &timeout_request_due_to_congestion,
656                                         n->th);
657       continue;
658     }
659     th = n->th;
660     if (th->notify_size + sizeof (struct OutboundMessage) > size)
661       break;                    /* does not fit */
662     if (GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, th->notify_size).
663         rel_value > 0)
664       break;                    /* too early */
665     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
666     n->hn = NULL;
667     n->th = NULL;
668     n->is_ready = GNUNET_NO;
669     GNUNET_assert (size >= sizeof (struct OutboundMessage));
670     mret =
671         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
672                     &cbuf[ret + sizeof (struct OutboundMessage)]);
673     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
674     if (mret != 0)
675     {
676       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
677                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
678       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
679       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
680       obm.priority = htonl (th->priority);
681       obm.timeout =
682           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
683                                      (th->timeout));
684       obm.peer = n->id;
685       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
686       ret += (mret + sizeof (struct OutboundMessage));
687       size -= (mret + sizeof (struct OutboundMessage));
688       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
689     }
690     GNUNET_free (th);
691   }
692   /* if there are more pending messages, try to schedule those */
693   schedule_transmission (h);
694 #if DEBUG_TRANSPORT
695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
696               "Transmitting %u bytes to transport service\n", ret);
697 #endif
698   return ret;
699 }
700
701
702 /**
703  * Schedule the task to send one message, either from the control
704  * list or the peer message queues  to the service.
705  *
706  * @param cls transport service to schedule a transmission for
707  * @param tc scheduler context
708  */
709 static void
710 schedule_transmission_task (void *cls,
711                             const struct GNUNET_SCHEDULER_TaskContext *tc)
712 {
713   struct GNUNET_TRANSPORT_Handle *h = cls;
714   size_t size;
715   struct GNUNET_TRANSPORT_TransmitHandle *th;
716   struct Neighbour *n;
717
718   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
719   GNUNET_assert (NULL != h->client);
720   /* destroy all requests that have timed out */
721   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
722          (GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value == 0))
723   {
724     /* notify client that the request could not be satisfied within
725      * the given time constraints */
726     th = n->th;
727     n->th = NULL;
728     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
729     n->hn = NULL;
730 #if DEBUG_TRANSPORT
731     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
732                 "Signalling timeout for transmission to peer %s due to congestion\n",
733                 GNUNET_i2s (&n->id));
734 #endif
735     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
736     GNUNET_free (th);
737   }
738   if (NULL != h->cth)
739     return;
740   if (NULL != h->control_head)
741   {
742     size = h->control_head->notify_size;
743   }
744   else
745   {
746     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
747     if (NULL == n)
748       return;                   /* no pending messages */
749     size = n->th->notify_size + sizeof (struct OutboundMessage);
750   }
751 #if DEBUG_TRANSPORT
752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Calling notify_transmit_ready\n");
753 #endif
754   h->cth =
755       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
756                                            GNUNET_TIME_UNIT_FOREVER_REL,
757                                            GNUNET_NO, &transport_notify_ready,
758                                            h);
759   GNUNET_assert (NULL != h->cth);
760 }
761
762
763 /**
764  * Schedule the task to send one message, either from the control
765  * list or the peer message queues  to the service.
766  *
767  * @param h transport service to schedule a transmission for
768  */
769 static void
770 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
771 {
772   struct GNUNET_TIME_Relative delay;
773   struct Neighbour *n;
774
775   GNUNET_assert (NULL != h->client);
776   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
777   {
778     GNUNET_SCHEDULER_cancel (h->quota_task);
779     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
780   }
781   if (NULL != h->control_head)
782     delay = GNUNET_TIME_UNIT_ZERO;
783   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
784     delay =
785         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
786                                             n->th->notify_size);
787   else
788     return;                     /* no work to be done */
789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
790               "Scheduling next transmission to service in %llu ms\n",
791               (unsigned long long) delay.rel_value);
792   h->quota_task =
793       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
794 }
795
796
797 /**
798  * Queue control request for transmission to the transport
799  * service.
800  *
801  * @param h handle to the transport service
802  * @param size number of bytes to be transmitted
803  * @param notify function to call to get the content
804  * @param notify_cls closure for notify
805  */
806 static void
807 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
808                            GNUNET_CONNECTION_TransmitReadyNotify notify,
809                            void *notify_cls)
810 {
811   struct GNUNET_TRANSPORT_TransmitHandle *th;
812
813 #if DEBUG_TRANSPORT
814   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
815               "Control transmit of %u bytes requested\n", size);
816 #endif
817   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
818   th->notify = notify;
819   th->notify_cls = notify_cls;
820   th->notify_size = size;
821   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
822   schedule_transmission (h);
823 }
824
825
826 /**
827  * Transmit START message to service.
828  *
829  * @param cls unused
830  * @param size number of bytes available in buf
831  * @param buf where to copy the message
832  * @return number of bytes copied to buf
833  */
834 static size_t
835 send_start (void *cls, size_t size, void *buf)
836 {
837   struct GNUNET_TRANSPORT_Handle *h = cls;
838   struct StartMessage s;
839
840   if (buf == NULL)
841   {
842     /* Can only be shutdown, just give up */
843 #if DEBUG_TRANSPORT
844     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
845                 "Shutdown while trying to transmit `%s' request.\n", "START");
846 #endif
847     return 0;
848   }
849 #if DEBUG_TRANSPORT
850   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "START");
851 #endif
852   GNUNET_assert (size >= sizeof (struct StartMessage));
853   s.header.size = htons (sizeof (struct StartMessage));
854   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
855   s.do_check = htonl (h->check_self);
856   s.self = h->self;
857   memcpy (buf, &s, sizeof (struct StartMessage));
858   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
859                          GNUNET_TIME_UNIT_FOREVER_REL);
860   return sizeof (struct StartMessage);
861 }
862
863
864 /**
865  * Try again to connect to transport service.
866  *
867  * @param cls the handle to the transport service
868  * @param tc scheduler context
869  */
870 static void
871 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
872 {
873   struct GNUNET_TRANSPORT_Handle *h = cls;
874
875   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
876   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
877   {
878     /* shutdown, just give up */
879     return;
880   }
881 #if DEBUG_TRANSPORT
882   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to transport service.\n");
883 #endif
884   GNUNET_assert (h->client == NULL);
885   GNUNET_assert (h->control_head == NULL);
886   GNUNET_assert (h->control_tail == NULL);
887   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
888   GNUNET_assert (h->client != NULL);
889   schedule_control_transmit (h, sizeof (struct StartMessage), &send_start, h);
890 }
891
892
893 /**
894  * Function that will schedule the job that will try
895  * to connect us again to the client.
896  *
897  * @param h transport service to reconnect
898  */
899 static void
900 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
901 {
902   struct GNUNET_TRANSPORT_TransmitHandle *th;
903
904   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
905   /* Forget about all neighbours that we used to be connected to */
906   GNUNET_CONTAINER_multihashmap_iterate (h->neighbours, &neighbour_delete, h);
907   if (NULL != h->cth)
908   {
909     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
910     h->cth = NULL;
911   }
912   if (NULL != h->client)
913   {
914     GNUNET_CLIENT_disconnect (h->client, GNUNET_YES);
915     h->client = NULL;
916   }
917   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
918   {
919     GNUNET_SCHEDULER_cancel (h->quota_task);
920     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
921   }
922   while ((NULL != (th = h->control_head)))
923   {
924     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
925     th->notify (th->notify_cls, 0, NULL);
926     GNUNET_free (th);
927   }
928 #if DEBUG_TRANSPORT
929   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930               "Scheduling task to reconnect to transport service in %llu ms.\n",
931               h->reconnect_delay.rel_value);
932 #endif
933   h->reconnect_task =
934       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
935   if (h->reconnect_delay.rel_value == 0)
936   {
937     h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
938   }
939   else
940   {
941     h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
942     h->reconnect_delay =
943         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS, h->reconnect_delay);
944   }
945 }
946
947
948 /**
949  * Closure for 'send_set_quota'.
950  */
951 struct SetQuotaContext
952 {
953
954   /**
955    * Identity of the peer impacted by the quota change.
956    */
957   struct GNUNET_PeerIdentity target;
958
959   /**
960    * Quota to transmit.
961    */
962   struct GNUNET_BANDWIDTH_Value32NBO quota_in;
963 };
964
965
966 /**
967  * Send SET_QUOTA message to the service.
968  *
969  * @param cls the 'struct SetQuotaContext'
970  * @param size number of bytes available in buf
971  * @param buf where to copy the message
972  * @return number of bytes copied to buf
973  */
974 static size_t
975 send_set_quota (void *cls, size_t size, void *buf)
976 {
977   struct SetQuotaContext *sqc = cls;
978   struct QuotaSetMessage msg;
979
980   if (buf == NULL)
981   {
982     GNUNET_free (sqc);
983     return 0;
984   }
985 #if DEBUG_TRANSPORT
986   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987               "Transmitting `%s' request with respect to `%4s'.\n", "SET_QUOTA",
988               GNUNET_i2s (&sqc->target));
989 #endif
990   GNUNET_assert (size >= sizeof (struct QuotaSetMessage));
991   msg.header.size = htons (sizeof (struct QuotaSetMessage));
992   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
993   msg.quota = sqc->quota_in;
994   msg.peer = sqc->target;
995   memcpy (buf, &msg, sizeof (msg));
996   GNUNET_free (sqc);
997   return sizeof (struct QuotaSetMessage);
998 }
999
1000
1001 /**
1002  * Set the share of incoming bandwidth for the given
1003  * peer to the specified amount.
1004  *
1005  * @param handle connection to transport service
1006  * @param target who's bandwidth quota is being changed
1007  * @param quota_in incoming bandwidth quota in bytes per ms
1008  * @param quota_out outgoing bandwidth quota in bytes per ms
1009  */
1010 void
1011 GNUNET_TRANSPORT_set_quota (struct GNUNET_TRANSPORT_Handle *handle,
1012                             const struct GNUNET_PeerIdentity *target,
1013                             struct GNUNET_BANDWIDTH_Value32NBO quota_in,
1014                             struct GNUNET_BANDWIDTH_Value32NBO quota_out)
1015 {
1016   struct Neighbour *n;
1017   struct SetQuotaContext *sqc;
1018
1019   n = neighbour_find (handle, target);
1020   if (NULL == n)
1021   {
1022     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1023                 "Quota changed to %u for peer `%s', but I have no such neighbour!\n",
1024                 (unsigned int) ntohl (quota_out.value__), GNUNET_i2s (target));
1025     return;
1026   }
1027   GNUNET_assert (NULL != handle->client);
1028 #if DEBUG_TRANSPORT
1029   if (ntohl (quota_out.value__) != n->out_tracker.available_bytes_per_s__)
1030     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1031                 "Quota changed from %u to %u for peer `%s'\n",
1032                 (unsigned int) n->out_tracker.available_bytes_per_s__,
1033                 (unsigned int) ntohl (quota_out.value__), GNUNET_i2s (target));
1034   else
1035     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Quota remains at %u for peer `%s'\n",
1036                 (unsigned int) n->out_tracker.available_bytes_per_s__,
1037                 GNUNET_i2s (target));
1038 #endif
1039   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, quota_out);
1040   sqc = GNUNET_malloc (sizeof (struct SetQuotaContext));
1041   sqc->target = *target;
1042   sqc->quota_in = quota_in;
1043   schedule_control_transmit (handle, sizeof (struct QuotaSetMessage),
1044                              &send_set_quota, sqc);
1045 }
1046
1047
1048 /**
1049  * Send REQUEST_CONNECT message to the service.
1050  *
1051  * @param cls the 'struct GNUNET_PeerIdentity'
1052  * @param size number of bytes available in buf
1053  * @param buf where to copy the message
1054  * @return number of bytes copied to buf
1055  */
1056 static size_t
1057 send_try_connect (void *cls, size_t size, void *buf)
1058 {
1059   struct GNUNET_PeerIdentity *pid = cls;
1060   struct TransportRequestConnectMessage msg;
1061
1062   if (buf == NULL)
1063   {
1064     GNUNET_free (pid);
1065     return 0;
1066   }
1067 #if DEBUG_TRANSPORT
1068   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1069               "Transmitting `%s' request with respect to `%4s'.\n",
1070               "REQUEST_CONNECT", GNUNET_i2s (pid));
1071 #endif
1072   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1073   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1074   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1075   msg.reserved = htonl (0);
1076   msg.peer = *pid;
1077   memcpy (buf, &msg, sizeof (msg));
1078   GNUNET_free (pid);
1079   return sizeof (struct TransportRequestConnectMessage);
1080 }
1081
1082
1083 /**
1084  * Ask the transport service to establish a connection to 
1085  * the given peer.
1086  *
1087  * @param handle connection to transport service
1088  * @param target who we should try to connect to
1089  */
1090 void
1091 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1092                               const struct GNUNET_PeerIdentity *target)
1093 {
1094   struct GNUNET_PeerIdentity *pid;
1095
1096   if (NULL == handle->client)
1097     return;
1098   pid = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1099   *pid = *target;
1100   schedule_control_transmit (handle,
1101                              sizeof (struct TransportRequestConnectMessage),
1102                              &send_try_connect, pid);
1103 }
1104
1105
1106 /**
1107  * Send HELLO message to the service.
1108  *
1109  * @param cls the HELLO message to send
1110  * @param size number of bytes available in buf
1111  * @param buf where to copy the message
1112  * @return number of bytes copied to buf
1113  */
1114 static size_t
1115 send_hello (void *cls, size_t size, void *buf)
1116 {
1117   struct GNUNET_MessageHeader *msg = cls;
1118   uint16_t ssize;
1119
1120   if (buf == NULL)
1121   {
1122 #if DEBUG_TRANSPORT_TIMEOUT
1123     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1124                 "Timeout while trying to transmit `%s' request.\n", "HELLO");
1125 #endif
1126     GNUNET_free (msg);
1127     return 0;
1128   }
1129 #if DEBUG_TRANSPORT
1130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "HELLO");
1131 #endif
1132   ssize = ntohs (msg->size);
1133   GNUNET_assert (size >= ssize);
1134   memcpy (buf, msg, ssize);
1135   GNUNET_free (msg);
1136   return ssize;
1137 }
1138
1139
1140 /**
1141  * Offer the transport service the HELLO of another peer.  Note that
1142  * the transport service may just ignore this message if the HELLO is
1143  * malformed or useless due to our local configuration.
1144  *
1145  * @param handle connection to transport service
1146  * @param hello the hello message
1147  * @param cont continuation to call when HELLO has been sent
1148  * @param cls closure for continuation
1149  *
1150  */
1151 void
1152 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1153                               const struct GNUNET_MessageHeader *hello,
1154                               GNUNET_SCHEDULER_Task cont, void *cls)
1155 {
1156   uint16_t size;
1157   struct GNUNET_PeerIdentity peer;
1158   struct GNUNET_MessageHeader *msg;
1159
1160   if (NULL == handle->client)
1161     return;
1162   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1163   size = ntohs (hello->size);
1164   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1165   if (GNUNET_OK !=
1166       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1167   {
1168     GNUNET_break (0);
1169     return;
1170   }
1171   msg = GNUNET_malloc (size);
1172   memcpy (msg, hello, size);
1173 #if DEBUG_TRANSPORT
1174   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175               "Offering `%s' message of `%4s' to transport for validation.\n",
1176               "HELLO", GNUNET_i2s (&peer));
1177 #endif
1178   schedule_control_transmit (handle, size, &send_hello, msg);
1179 }
1180
1181
1182 /**
1183  * Obtain the HELLO message for this peer.
1184  *
1185  * @param handle connection to transport service
1186  * @param rec function to call with the HELLO, sender will be our peer
1187  *            identity; message and sender will be NULL on timeout
1188  *            (handshake with transport service pending/failed).
1189  *             cost estimate will be 0.
1190  * @param rec_cls closure for rec
1191  */
1192 void
1193 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1194                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1195                             void *rec_cls)
1196 {
1197   struct HelloWaitList *hwl;
1198
1199   hwl = GNUNET_malloc (sizeof (struct HelloWaitList));
1200   hwl->rec = rec;
1201   hwl->rec_cls = rec_cls;
1202   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1203   if (handle->my_hello == NULL)
1204     return;
1205   rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
1206 }
1207
1208
1209 /**
1210  * Stop receiving updates about changes to our HELLO message.
1211  *
1212  * @param handle connection to transport service
1213  * @param rec function previously registered to be called with the HELLOs
1214  * @param rec_cls closure for rec
1215  */
1216 void
1217 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_Handle *handle,
1218                                    GNUNET_TRANSPORT_HelloUpdateCallback rec,
1219                                    void *rec_cls)
1220 {
1221   struct HelloWaitList *pos;
1222
1223   pos = handle->hwl_head;
1224   while (pos != NULL)
1225   {
1226     if ((pos->rec == rec) && (pos->rec_cls == rec_cls))
1227       break;
1228     pos = pos->next;
1229   }
1230   GNUNET_break (pos != NULL);
1231   if (pos == NULL)
1232     return;
1233   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, pos);
1234   GNUNET_free (pos);
1235 }
1236
1237
1238 /**
1239  * Connect to the transport service.  Note that the connection may
1240  * complete (or fail) asynchronously.
1241  *
1242  * @param cfg configuration to use
1243  * @param self our own identity (API should check that it matches
1244  *             the identity found by transport), or NULL (no check)
1245  * @param cls closure for the callbacks
1246  * @param rec receive function to call
1247  * @param nc function to call on connect events
1248  * @param nd function to call on disconnect events
1249  */
1250 struct GNUNET_TRANSPORT_Handle *
1251 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1252                           const struct GNUNET_PeerIdentity *self, void *cls,
1253                           GNUNET_TRANSPORT_ReceiveCallback rec,
1254                           GNUNET_TRANSPORT_NotifyConnect nc,
1255                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1256 {
1257   struct GNUNET_TRANSPORT_Handle *ret;
1258
1259   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1260   if (self != NULL)
1261   {
1262     ret->self = *self;
1263     ret->check_self = GNUNET_YES;
1264   }
1265   ret->cfg = cfg;
1266   ret->cls = cls;
1267   ret->rec = rec;
1268   ret->nc_cb = nc;
1269   ret->nd_cb = nd;
1270   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1271   ret->neighbours =
1272       GNUNET_CONTAINER_multihashmap_create (STARTING_NEIGHBOURS_SIZE);
1273   ret->ready_heap =
1274       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1275   ret->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, ret);
1276   return ret;
1277 }
1278
1279
1280 /**
1281  * Disconnect from the transport service.
1282  *
1283  * @param handle handle to the service as returned from GNUNET_TRANSPORT_connect
1284  */
1285 void
1286 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1287 {
1288 #if DEBUG_TRANSPORT
1289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1290 #endif
1291   /* this disconnects all neighbours... */
1292   if (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1293     disconnect_and_schedule_reconnect (handle);
1294   /* and now we stop trying to connect again... */
1295   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1296   {
1297     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1298     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1299   }
1300   GNUNET_CONTAINER_multihashmap_destroy (handle->neighbours);
1301   handle->neighbours = NULL;
1302   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1303   {
1304     GNUNET_SCHEDULER_cancel (handle->quota_task);
1305     handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1306   }
1307   GNUNET_free_non_null (handle->my_hello);
1308   handle->my_hello = NULL;
1309   GNUNET_assert (handle->hwl_head == NULL);
1310   GNUNET_assert (handle->hwl_tail == NULL);
1311   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1312   handle->ready_heap = NULL;
1313   GNUNET_free (handle);
1314 }
1315
1316
1317 /**
1318  * Check if we could queue a message of the given size for
1319  * transmission.  The transport service will take both its
1320  * internal buffers and bandwidth limits imposed by the
1321  * other peer into consideration when answering this query.
1322  *
1323  * @param handle connection to transport service
1324  * @param target who should receive the message
1325  * @param size how big is the message we want to transmit?
1326  * @param priority how important is the message?
1327  * @param timeout after how long should we give up (and call
1328  *        notify with buf NULL and size 0)?
1329  * @param notify function to call when we are ready to
1330  *        send such a message
1331  * @param notify_cls closure for notify
1332  * @return NULL if someone else is already waiting to be notified
1333  *         non-NULL if the notify callback was queued (can be used to cancel
1334  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1335  */
1336 struct GNUNET_TRANSPORT_TransmitHandle *
1337 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1338                                         const struct GNUNET_PeerIdentity
1339                                         *target, size_t size, uint32_t priority,
1340                                         struct GNUNET_TIME_Relative timeout,
1341                                         GNUNET_CONNECTION_TransmitReadyNotify
1342                                         notify, void *notify_cls)
1343 {
1344   struct Neighbour *n;
1345   struct GNUNET_TRANSPORT_TransmitHandle *th;
1346   struct GNUNET_TIME_Relative delay;
1347
1348   n = neighbour_find (handle, target);
1349   if (NULL == n)
1350   {
1351     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1352      * once a connection has been established */
1353     GNUNET_assert (0);
1354     return NULL;
1355   }
1356   if (NULL != n->th)
1357   {
1358     /* attempt to send two messages at the same time to the same peer */
1359     GNUNET_assert (0);
1360     return NULL;
1361   }
1362   GNUNET_assert (NULL == n->hn);
1363   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
1364   th->neighbour = n;
1365   th->notify = notify;
1366   th->notify_cls = notify_cls;
1367   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1368   th->notify_size = size;
1369   th->priority = priority;
1370   n->th = th;
1371   /* calculate when our transmission should be ready */
1372   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size);
1373   if (delay.rel_value > timeout.rel_value)
1374     delay.rel_value = 0;        /* notify immediately (with failure) */
1375 #if DEBUG_TRANSPORT
1376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377               "Bandwidth tracker allows next transmission to peer %s in %llu ms\n",
1378               GNUNET_i2s (target), (unsigned long long) delay.rel_value);
1379 #endif
1380   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value);
1381   schedule_transmission (handle);
1382   return th;
1383 }
1384
1385
1386 /**
1387  * Cancel the specified transmission-ready notification.
1388  *
1389  * @param th handle returned from GNUNET_TRANSPORT_notify_transmit_ready
1390  */
1391 void
1392 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1393                                                GNUNET_TRANSPORT_TransmitHandle
1394                                                *th)
1395 {
1396   struct Neighbour *n;
1397
1398   GNUNET_assert (NULL == th->next);
1399   GNUNET_assert (NULL == th->prev);
1400   n = th->neighbour;
1401   GNUNET_assert (th == n->th);
1402   n->th = NULL;
1403   if (n->hn != NULL)
1404   {
1405     GNUNET_CONTAINER_heap_remove_node (n->hn);
1406     n->hn = NULL;
1407   }
1408   else
1409   {
1410     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != th->timeout_task);
1411     GNUNET_SCHEDULER_cancel (th->timeout_task);
1412     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1413   }
1414   GNUNET_free (th);
1415 }
1416
1417
1418 /* end of transport_api.c */