run indent twice, it alternates between two 'canonical' forms, also run whitespace...
[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
299 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
300
301
302 /**
303  * Function that will schedule the job that will try
304  * to connect us again to the client.
305  *
306  * @param h transport service to reconnect
307  */
308 static void
309 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h);
310
311
312 /**
313  * Get the neighbour list entry for the given peer
314  *
315  * @param h our context
316  * @param peer peer to look up
317  * @return NULL if no such peer entry exists
318  */
319 static struct Neighbour *
320 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
321                 const struct GNUNET_PeerIdentity *peer)
322 {
323   return GNUNET_CONTAINER_multihashmap_get (h->neighbours, &peer->hashPubKey);
324 }
325
326
327 /**
328  * Add neighbour to our list
329  *
330  * @return NULL if this API is currently disconnecting from the service
331  */
332 static struct Neighbour *
333 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
334                const struct GNUNET_PeerIdentity *pid)
335 {
336   struct Neighbour *n;
337
338 #if DEBUG_TRANSPORT
339   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating entry for neighbour `%4s'.\n",
340               GNUNET_i2s (pid));
341 #endif
342   n = GNUNET_malloc (sizeof (struct Neighbour));
343   n->id = *pid;
344   n->h = h;
345   n->is_ready = GNUNET_YES;
346   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
347                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
348                                  MAX_BANDWIDTH_CARRY_S);
349   GNUNET_assert (GNUNET_OK ==
350                  GNUNET_CONTAINER_multihashmap_put (h->neighbours,
351                                                     &pid->hashPubKey, n,
352                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
353   return n;
354 }
355
356
357 /**
358  * Iterator over hash map entries, for deleting state of a neighbour.
359  *
360  * @param cls the 'struct GNUNET_TRANSPORT_Handle*'
361  * @param key peer identity
362  * @param value value in the hash map, the neighbour entry to delete
363  * @return GNUNET_YES if we should continue to
364  *         iterate,
365  *         GNUNET_NO if not.
366  */
367 static int
368 neighbour_delete (void *cls, const GNUNET_HashCode * key, void *value)
369 {
370   struct GNUNET_TRANSPORT_Handle *handle = cls;
371   struct Neighbour *n = value;
372
373   if (NULL != handle->nd_cb)
374     handle->nd_cb (handle->cls, &n->id);
375   GNUNET_assert (NULL == n->th);
376   GNUNET_assert (NULL == n->hn);
377   GNUNET_assert (GNUNET_YES ==
378                  GNUNET_CONTAINER_multihashmap_remove (handle->neighbours, key,
379                                                        n));
380   GNUNET_free (n);
381   return GNUNET_YES;
382 }
383
384
385 /**
386  * Function we use for handling incoming messages.
387  *
388  * @param cls closure (struct GNUNET_TRANSPORT_Handle *)
389  * @param msg message received, NULL on timeout or fatal error
390  */
391 static void
392 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
393 {
394   struct GNUNET_TRANSPORT_Handle *h = cls;
395   const struct DisconnectInfoMessage *dim;
396   const struct ConnectInfoMessage *cim;
397   const struct InboundMessage *im;
398   const struct GNUNET_MessageHeader *imm;
399   const struct SendOkMessage *okm;
400   struct HelloWaitList *hwl;
401   struct HelloWaitList *next_hwl;
402   struct Neighbour *n;
403   struct GNUNET_PeerIdentity me;
404   uint16_t size;
405   uint32_t ats_count;
406
407   GNUNET_assert (h->client != NULL);
408   if (msg == NULL)
409   {
410 #if DEBUG_TRANSPORT
411     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
412                 "Error receiving from transport service, disconnecting temporarily.\n");
413 #endif
414     disconnect_and_schedule_reconnect (h);
415     return;
416   }
417   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
418                          GNUNET_TIME_UNIT_FOREVER_REL);
419   size = ntohs (msg->size);
420   switch (ntohs (msg->type))
421   {
422   case GNUNET_MESSAGE_TYPE_HELLO:
423     if (GNUNET_OK !=
424         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
425     {
426       GNUNET_break (0);
427       break;
428     }
429 #if DEBUG_TRANSPORT
430     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431                 "Receiving (my own) `%s' message, I am `%4s'.\n", "HELLO",
432                 GNUNET_i2s (&me));
433 #endif
434     GNUNET_free_non_null (h->my_hello);
435     h->my_hello = NULL;
436     if (size < sizeof (struct GNUNET_MessageHeader))
437     {
438       GNUNET_break (0);
439       break;
440     }
441     h->my_hello = GNUNET_malloc (size);
442     memcpy (h->my_hello, msg, size);
443     hwl = h->hwl_head;
444     while (NULL != hwl)
445     {
446       next_hwl = hwl->next;
447       hwl->rec (hwl->rec_cls,
448                 (const struct GNUNET_MessageHeader *) h->my_hello);
449       hwl = next_hwl;
450     }
451     break;
452   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
453     if (size < sizeof (struct ConnectInfoMessage))
454     {
455       GNUNET_break (0);
456       break;
457     }
458     cim = (const struct ConnectInfoMessage *) msg;
459     ats_count = ntohl (cim->ats_count);
460     if (size !=
461         sizeof (struct ConnectInfoMessage) +
462         ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information))
463     {
464       GNUNET_break (0);
465       break;
466     }
467 #if DEBUG_TRANSPORT
468     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
469                 "CONNECT", GNUNET_i2s (&cim->id));
470 #endif
471     n = neighbour_find (h, &cim->id);
472     if (n != NULL)
473     {
474       GNUNET_break (0);
475       break;
476     }
477     n = neighbour_add (h, &cim->id);
478     if (h->nc_cb != NULL)
479       h->nc_cb (h->cls, &n->id, &cim->ats, ats_count);
480     break;
481   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
482     if (size != sizeof (struct DisconnectInfoMessage))
483     {
484       GNUNET_break (0);
485       break;
486     }
487     dim = (const struct DisconnectInfoMessage *) msg;
488     GNUNET_break (ntohl (dim->reserved) == 0);
489 #if DEBUG_TRANSPORT_DISCONNECT
490     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message for `%4s'.\n",
491                 "DISCONNECT", GNUNET_i2s (&dim->peer));
492 #endif
493     n = neighbour_find (h, &dim->peer);
494     if (n == NULL)
495     {
496       GNUNET_break (0);
497       break;
498     }
499     neighbour_delete (h, &dim->peer.hashPubKey, n);
500     break;
501   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
502     if (size != sizeof (struct SendOkMessage))
503     {
504       GNUNET_break (0);
505       break;
506     }
507     okm = (const struct SendOkMessage *) msg;
508 #if DEBUG_TRANSPORT
509     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510                 "Receiving `%s' message, transmission %s.\n", "SEND_OK",
511                 ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
512 #endif
513     n = neighbour_find (h, &okm->peer);
514     if (n == NULL)
515       break;
516     GNUNET_break (GNUNET_NO == n->is_ready);
517     n->is_ready = GNUNET_YES;
518     if ((n->th != NULL) && (n->hn == NULL))
519     {
520       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->th->timeout_task);
521       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
522       n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
523       /* we've been waiting for this (congestion, not quota,
524        * caused delayed transmission) */
525       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
526       schedule_transmission (h);
527     }
528     break;
529   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
530 #if DEBUG_TRANSPORT
531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving `%s' message.\n", "RECV");
532 #endif
533     if (size <
534         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
535     {
536       GNUNET_break (0);
537       break;
538     }
539     im = (const struct InboundMessage *) msg;
540     GNUNET_break (0 == ntohl (im->reserved));
541     ats_count = ntohl (im->ats_count);
542     imm = (const struct GNUNET_MessageHeader *) &((&(im->ats))[ats_count + 1]);
543
544     if (ntohs (imm->size) + sizeof (struct InboundMessage) +
545         ats_count * sizeof (struct GNUNET_TRANSPORT_ATS_Information) != size)
546     {
547       GNUNET_break (0);
548       break;
549     }
550 #if DEBUG_TRANSPORT
551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
552                 "Received message of type %u from `%4s'.\n", ntohs (imm->type),
553                 GNUNET_i2s (&im->peer));
554 #endif
555     n = neighbour_find (h, &im->peer);
556     if (n == NULL)
557     {
558       GNUNET_break (0);
559       break;
560     }
561     if (h->rec != NULL)
562       h->rec (h->cls, &im->peer, imm, &im->ats, ats_count);
563     break;
564   default:
565     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
566                 _("Received unexpected message of type %u in %s:%u\n"),
567                 ntohs (msg->type), __FILE__, __LINE__);
568     GNUNET_break (0);
569     break;
570   }
571 }
572
573
574 /**
575  * A transmission request could not be satisfied because of
576  * network congestion.  Notify the initiator and clean up.
577  *
578  * @param cls the 'struct GNUNET_TRANSPORT_TransmitHandle'
579  * @param tc scheduler context
580  */
581 static void
582 timeout_request_due_to_congestion (void *cls,
583                                    const struct GNUNET_SCHEDULER_TaskContext
584                                    *tc)
585 {
586   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
587   struct Neighbour *n = th->neighbour;
588
589   n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
590   GNUNET_assert (th == n->th);
591   GNUNET_assert (NULL == n->hn);
592   n->th = NULL;
593   th->notify (th->notify_cls, 0, NULL);
594   GNUNET_free (th);
595 }
596
597
598 /**
599  * Transmit message(s) to service.
600  *
601  * @param cls handle to transport
602  * @param size number of bytes available in buf
603  * @param buf where to copy the message
604  * @return number of bytes copied to buf
605  */
606 static size_t
607 transport_notify_ready (void *cls, size_t size, void *buf)
608 {
609   struct GNUNET_TRANSPORT_Handle *h = cls;
610   struct GNUNET_TRANSPORT_TransmitHandle *th;
611   struct Neighbour *n;
612   char *cbuf;
613   struct OutboundMessage obm;
614   size_t ret;
615   size_t nret;
616   size_t mret;
617
618   GNUNET_assert (NULL != h->client);
619   h->cth = NULL;
620   if (NULL == buf)
621   {
622     /* transmission failed */
623     disconnect_and_schedule_reconnect (h);
624     return 0;
625   }
626
627   cbuf = buf;
628   ret = 0;
629   /* first send control messages */
630   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
631   {
632     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
633     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
634 #if DEBUG_TRANSPORT
635     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
636                 "Added %u bytes of control message at %u\n", nret, ret);
637 #endif
638     GNUNET_free (th);
639     ret += nret;
640     size -= nret;
641   }
642
643   /* then, if possible and no control messages pending, send data messages */
644   while ((NULL == h->control_head) &&
645          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
646   {
647     if (GNUNET_YES != n->is_ready)
648     {
649       /* peer not ready, wait for notification! */
650       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
651       n->hn = NULL;
652       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->th->timeout_task);
653       n->th->timeout_task =
654           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
655                                         (n->th->timeout),
656                                         &timeout_request_due_to_congestion,
657                                         n->th);
658       continue;
659     }
660     th = n->th;
661     if (th->notify_size + sizeof (struct OutboundMessage) > size)
662       break;                    /* does not fit */
663     if (GNUNET_BANDWIDTH_tracker_get_delay
664         (&n->out_tracker, th->notify_size).rel_value > 0)
665       break;                    /* too early */
666     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
667     n->hn = NULL;
668     n->th = NULL;
669     n->is_ready = GNUNET_NO;
670     GNUNET_assert (size >= sizeof (struct OutboundMessage));
671     mret =
672         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
673                     &cbuf[ret + sizeof (struct OutboundMessage)]);
674     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
675     if (mret != 0)
676     {
677       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
678                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
679       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
680       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
681       obm.priority = htonl (th->priority);
682       obm.timeout =
683           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
684                                      (th->timeout));
685       obm.peer = n->id;
686       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
687       ret += (mret + sizeof (struct OutboundMessage));
688       size -= (mret + sizeof (struct OutboundMessage));
689       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
690     }
691     GNUNET_free (th);
692   }
693   /* if there are more pending messages, try to schedule those */
694   schedule_transmission (h);
695 #if DEBUG_TRANSPORT
696   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
697               "Transmitting %u bytes to transport service\n", ret);
698 #endif
699   return ret;
700 }
701
702
703 /**
704  * Schedule the task to send one message, either from the control
705  * list or the peer message queues  to the service.
706  *
707  * @param cls transport service to schedule a transmission for
708  * @param tc scheduler context
709  */
710 static void
711 schedule_transmission_task (void *cls,
712                             const struct GNUNET_SCHEDULER_TaskContext *tc)
713 {
714   struct GNUNET_TRANSPORT_Handle *h = cls;
715   size_t size;
716   struct GNUNET_TRANSPORT_TransmitHandle *th;
717   struct Neighbour *n;
718
719   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
720   GNUNET_assert (NULL != h->client);
721   /* destroy all requests that have timed out */
722   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
723          (GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value == 0))
724   {
725     /* notify client that the request could not be satisfied within
726      * the given time constraints */
727     th = n->th;
728     n->th = NULL;
729     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
730     n->hn = NULL;
731 #if DEBUG_TRANSPORT
732     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
733                 "Signalling timeout for transmission to peer %s due to congestion\n",
734                 GNUNET_i2s (&n->id));
735 #endif
736     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
737     GNUNET_free (th);
738   }
739   if (NULL != h->cth)
740     return;
741   if (NULL != h->control_head)
742   {
743     size = h->control_head->notify_size;
744   }
745   else
746   {
747     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
748     if (NULL == n)
749       return;                   /* no pending messages */
750     size = n->th->notify_size + sizeof (struct OutboundMessage);
751   }
752 #if DEBUG_TRANSPORT
753   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Calling notify_transmit_ready\n");
754 #endif
755   h->cth =
756       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
757                                            GNUNET_TIME_UNIT_FOREVER_REL,
758                                            GNUNET_NO, &transport_notify_ready,
759                                            h);
760   GNUNET_assert (NULL != h->cth);
761 }
762
763
764 /**
765  * Schedule the task to send one message, either from the control
766  * list or the peer message queues  to the service.
767  *
768  * @param h transport service to schedule a transmission for
769  */
770 static void
771 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
772 {
773   struct GNUNET_TIME_Relative delay;
774   struct Neighbour *n;
775
776   GNUNET_assert (NULL != h->client);
777   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
778   {
779     GNUNET_SCHEDULER_cancel (h->quota_task);
780     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
781   }
782   if (NULL != h->control_head)
783     delay = GNUNET_TIME_UNIT_ZERO;
784   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
785     delay =
786         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
787                                             n->th->notify_size);
788   else
789     return;                     /* no work to be done */
790   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
791               "Scheduling next transmission to service in %llu ms\n",
792               (unsigned long long) delay.rel_value);
793   h->quota_task =
794       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
795 }
796
797
798 /**
799  * Queue control request for transmission to the transport
800  * service.
801  *
802  * @param h handle to the transport service
803  * @param size number of bytes to be transmitted
804  * @param notify function to call to get the content
805  * @param notify_cls closure for notify
806  */
807 static void
808 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
809                            GNUNET_CONNECTION_TransmitReadyNotify notify,
810                            void *notify_cls)
811 {
812   struct GNUNET_TRANSPORT_TransmitHandle *th;
813
814 #if DEBUG_TRANSPORT
815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
816               "Control transmit of %u bytes requested\n", size);
817 #endif
818   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
819   th->notify = notify;
820   th->notify_cls = notify_cls;
821   th->notify_size = size;
822   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
823   schedule_transmission (h);
824 }
825
826
827 /**
828  * Transmit START message to service.
829  *
830  * @param cls unused
831  * @param size number of bytes available in buf
832  * @param buf where to copy the message
833  * @return number of bytes copied to buf
834  */
835 static size_t
836 send_start (void *cls, size_t size, void *buf)
837 {
838   struct GNUNET_TRANSPORT_Handle *h = cls;
839   struct StartMessage s;
840
841   if (buf == NULL)
842   {
843     /* Can only be shutdown, just give up */
844 #if DEBUG_TRANSPORT
845     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846                 "Shutdown while trying to transmit `%s' request.\n", "START");
847 #endif
848     return 0;
849   }
850 #if DEBUG_TRANSPORT
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "START");
852 #endif
853   GNUNET_assert (size >= sizeof (struct StartMessage));
854   s.header.size = htons (sizeof (struct StartMessage));
855   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
856   s.do_check = htonl (h->check_self);
857   s.self = h->self;
858   memcpy (buf, &s, sizeof (struct StartMessage));
859   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
860                          GNUNET_TIME_UNIT_FOREVER_REL);
861   return sizeof (struct StartMessage);
862 }
863
864
865 /**
866  * Try again to connect to transport service.
867  *
868  * @param cls the handle to the transport service
869  * @param tc scheduler context
870  */
871 static void
872 reconnect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
873 {
874   struct GNUNET_TRANSPORT_Handle *h = cls;
875
876   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
877   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
878   {
879     /* shutdown, just give up */
880     return;
881   }
882 #if DEBUG_TRANSPORT
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to transport service.\n");
884 #endif
885   GNUNET_assert (h->client == NULL);
886   GNUNET_assert (h->control_head == NULL);
887   GNUNET_assert (h->control_tail == NULL);
888   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
889   GNUNET_assert (h->client != NULL);
890   schedule_control_transmit (h, sizeof (struct StartMessage), &send_start, h);
891 }
892
893
894 /**
895  * Function that will schedule the job that will try
896  * to connect us again to the client.
897  *
898  * @param h transport service to reconnect
899  */
900 static void
901 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
902 {
903   struct GNUNET_TRANSPORT_TransmitHandle *th;
904
905   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
906   /* Forget about all neighbours that we used to be connected to */
907   GNUNET_CONTAINER_multihashmap_iterate (h->neighbours, &neighbour_delete, h);
908   if (NULL != h->cth)
909   {
910     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
911     h->cth = NULL;
912   }
913   if (NULL != h->client)
914   {
915     GNUNET_CLIENT_disconnect (h->client, GNUNET_YES);
916     h->client = NULL;
917   }
918   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
919   {
920     GNUNET_SCHEDULER_cancel (h->quota_task);
921     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
922   }
923   while ((NULL != (th = h->control_head)))
924   {
925     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
926     th->notify (th->notify_cls, 0, NULL);
927     GNUNET_free (th);
928   }
929 #if DEBUG_TRANSPORT
930   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
931               "Scheduling task to reconnect to transport service in %llu ms.\n",
932               h->reconnect_delay.rel_value);
933 #endif
934   h->reconnect_task =
935       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
936   if (h->reconnect_delay.rel_value == 0)
937   {
938     h->reconnect_delay = GNUNET_TIME_UNIT_MILLISECONDS;
939   }
940   else
941   {
942     h->reconnect_delay = GNUNET_TIME_relative_multiply (h->reconnect_delay, 2);
943     h->reconnect_delay =
944         GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_SECONDS, h->reconnect_delay);
945   }
946 }
947
948
949 /**
950  * Closure for 'send_set_quota'.
951  */
952 struct SetQuotaContext
953 {
954
955   /**
956    * Identity of the peer impacted by the quota change.
957    */
958   struct GNUNET_PeerIdentity target;
959
960   /**
961    * Quota to transmit.
962    */
963   struct GNUNET_BANDWIDTH_Value32NBO quota_in;
964 };
965
966
967 /**
968  * Send SET_QUOTA message to the service.
969  *
970  * @param cls the 'struct SetQuotaContext'
971  * @param size number of bytes available in buf
972  * @param buf where to copy the message
973  * @return number of bytes copied to buf
974  */
975 static size_t
976 send_set_quota (void *cls, size_t size, void *buf)
977 {
978   struct SetQuotaContext *sqc = cls;
979   struct QuotaSetMessage msg;
980
981   if (buf == NULL)
982   {
983     GNUNET_free (sqc);
984     return 0;
985   }
986 #if DEBUG_TRANSPORT
987   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
988               "Transmitting `%s' request with respect to `%4s'.\n", "SET_QUOTA",
989               GNUNET_i2s (&sqc->target));
990 #endif
991   GNUNET_assert (size >= sizeof (struct QuotaSetMessage));
992   msg.header.size = htons (sizeof (struct QuotaSetMessage));
993   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA);
994   msg.quota = sqc->quota_in;
995   msg.peer = sqc->target;
996   memcpy (buf, &msg, sizeof (msg));
997   GNUNET_free (sqc);
998   return sizeof (struct QuotaSetMessage);
999 }
1000
1001
1002 /**
1003  * Set the share of incoming bandwidth for the given
1004  * peer to the specified amount.
1005  *
1006  * @param handle connection to transport service
1007  * @param target who's bandwidth quota is being changed
1008  * @param quota_in incoming bandwidth quota in bytes per ms
1009  * @param quota_out outgoing bandwidth quota in bytes per ms
1010  */
1011 void
1012 GNUNET_TRANSPORT_set_quota (struct GNUNET_TRANSPORT_Handle *handle,
1013                             const struct GNUNET_PeerIdentity *target,
1014                             struct GNUNET_BANDWIDTH_Value32NBO quota_in,
1015                             struct GNUNET_BANDWIDTH_Value32NBO quota_out)
1016 {
1017   struct Neighbour *n;
1018   struct SetQuotaContext *sqc;
1019
1020   n = neighbour_find (handle, target);
1021   if (NULL == n)
1022   {
1023     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1024                 "Quota changed to %u for peer `%s', but I have no such neighbour!\n",
1025                 (unsigned int) ntohl (quota_out.value__), GNUNET_i2s (target));
1026     return;
1027   }
1028   GNUNET_assert (NULL != handle->client);
1029 #if DEBUG_TRANSPORT
1030   if (ntohl (quota_out.value__) != n->out_tracker.available_bytes_per_s__)
1031     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1032                 "Quota changed from %u to %u for peer `%s'\n",
1033                 (unsigned int) n->out_tracker.available_bytes_per_s__,
1034                 (unsigned int) ntohl (quota_out.value__), GNUNET_i2s (target));
1035   else
1036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Quota remains at %u for peer `%s'\n",
1037                 (unsigned int) n->out_tracker.available_bytes_per_s__,
1038                 GNUNET_i2s (target));
1039 #endif
1040   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, quota_out);
1041   sqc = GNUNET_malloc (sizeof (struct SetQuotaContext));
1042   sqc->target = *target;
1043   sqc->quota_in = quota_in;
1044   schedule_control_transmit (handle, sizeof (struct QuotaSetMessage),
1045                              &send_set_quota, sqc);
1046 }
1047
1048
1049 /**
1050  * Send REQUEST_CONNECT message to the service.
1051  *
1052  * @param cls the 'struct GNUNET_PeerIdentity'
1053  * @param size number of bytes available in buf
1054  * @param buf where to copy the message
1055  * @return number of bytes copied to buf
1056  */
1057 static size_t
1058 send_try_connect (void *cls, size_t size, void *buf)
1059 {
1060   struct GNUNET_PeerIdentity *pid = cls;
1061   struct TransportRequestConnectMessage msg;
1062
1063   if (buf == NULL)
1064   {
1065     GNUNET_free (pid);
1066     return 0;
1067   }
1068 #if DEBUG_TRANSPORT
1069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070               "Transmitting `%s' request with respect to `%4s'.\n",
1071               "REQUEST_CONNECT", GNUNET_i2s (pid));
1072 #endif
1073   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1074   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1075   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1076   msg.reserved = htonl (0);
1077   msg.peer = *pid;
1078   memcpy (buf, &msg, sizeof (msg));
1079   GNUNET_free (pid);
1080   return sizeof (struct TransportRequestConnectMessage);
1081 }
1082
1083
1084 /**
1085  * Ask the transport service to establish a connection to
1086  * the given peer.
1087  *
1088  * @param handle connection to transport service
1089  * @param target who we should try to connect to
1090  */
1091 void
1092 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1093                               const struct GNUNET_PeerIdentity *target)
1094 {
1095   struct GNUNET_PeerIdentity *pid;
1096
1097   if (NULL == handle->client)
1098     return;
1099   pid = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
1100   *pid = *target;
1101   schedule_control_transmit (handle,
1102                              sizeof (struct TransportRequestConnectMessage),
1103                              &send_try_connect, pid);
1104 }
1105
1106
1107 /**
1108  * Send HELLO message to the service.
1109  *
1110  * @param cls the HELLO message to send
1111  * @param size number of bytes available in buf
1112  * @param buf where to copy the message
1113  * @return number of bytes copied to buf
1114  */
1115 static size_t
1116 send_hello (void *cls, size_t size, void *buf)
1117 {
1118   struct GNUNET_MessageHeader *msg = cls;
1119   uint16_t ssize;
1120
1121   if (buf == NULL)
1122   {
1123 #if DEBUG_TRANSPORT_TIMEOUT
1124     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1125                 "Timeout while trying to transmit `%s' request.\n", "HELLO");
1126 #endif
1127     GNUNET_free (msg);
1128     return 0;
1129   }
1130 #if DEBUG_TRANSPORT
1131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' request.\n", "HELLO");
1132 #endif
1133   ssize = ntohs (msg->size);
1134   GNUNET_assert (size >= ssize);
1135   memcpy (buf, msg, ssize);
1136   GNUNET_free (msg);
1137   return ssize;
1138 }
1139
1140
1141 /**
1142  * Offer the transport service the HELLO of another peer.  Note that
1143  * the transport service may just ignore this message if the HELLO is
1144  * malformed or useless due to our local configuration.
1145  *
1146  * @param handle connection to transport service
1147  * @param hello the hello message
1148  * @param cont continuation to call when HELLO has been sent
1149  * @param cls closure for continuation
1150  *
1151  */
1152 void
1153 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1154                               const struct GNUNET_MessageHeader *hello,
1155                               GNUNET_SCHEDULER_Task cont, void *cls)
1156 {
1157   uint16_t size;
1158   struct GNUNET_PeerIdentity peer;
1159   struct GNUNET_MessageHeader *msg;
1160
1161   if (NULL == handle->client)
1162     return;
1163   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1164   size = ntohs (hello->size);
1165   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1166   if (GNUNET_OK !=
1167       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1168   {
1169     GNUNET_break (0);
1170     return;
1171   }
1172   msg = GNUNET_malloc (size);
1173   memcpy (msg, hello, size);
1174 #if DEBUG_TRANSPORT
1175   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1176               "Offering `%s' message of `%4s' to transport for validation.\n",
1177               "HELLO", GNUNET_i2s (&peer));
1178 #endif
1179   schedule_control_transmit (handle, size, &send_hello, msg);
1180 }
1181
1182
1183 /**
1184  * Obtain the HELLO message for this peer.
1185  *
1186  * @param handle connection to transport service
1187  * @param rec function to call with the HELLO, sender will be our peer
1188  *            identity; message and sender will be NULL on timeout
1189  *            (handshake with transport service pending/failed).
1190  *             cost estimate will be 0.
1191  * @param rec_cls closure for rec
1192  */
1193 void
1194 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1195                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1196                             void *rec_cls)
1197 {
1198   struct HelloWaitList *hwl;
1199
1200   hwl = GNUNET_malloc (sizeof (struct HelloWaitList));
1201   hwl->rec = rec;
1202   hwl->rec_cls = rec_cls;
1203   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1204   if (handle->my_hello == NULL)
1205     return;
1206   rec (rec_cls, (const struct GNUNET_MessageHeader *) handle->my_hello);
1207 }
1208
1209
1210 /**
1211  * Stop receiving updates about changes to our HELLO message.
1212  *
1213  * @param handle connection to transport service
1214  * @param rec function previously registered to be called with the HELLOs
1215  * @param rec_cls closure for rec
1216  */
1217 void
1218 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_Handle *handle,
1219                                    GNUNET_TRANSPORT_HelloUpdateCallback rec,
1220                                    void *rec_cls)
1221 {
1222   struct HelloWaitList *pos;
1223
1224   pos = handle->hwl_head;
1225   while (pos != NULL)
1226   {
1227     if ((pos->rec == rec) && (pos->rec_cls == rec_cls))
1228       break;
1229     pos = pos->next;
1230   }
1231   GNUNET_break (pos != NULL);
1232   if (pos == NULL)
1233     return;
1234   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, pos);
1235   GNUNET_free (pos);
1236 }
1237
1238
1239 /**
1240  * Connect to the transport service.  Note that the connection may
1241  * complete (or fail) asynchronously.
1242  *
1243  * @param cfg configuration to use
1244  * @param self our own identity (API should check that it matches
1245  *             the identity found by transport), or NULL (no check)
1246  * @param cls closure for the callbacks
1247  * @param rec receive function to call
1248  * @param nc function to call on connect events
1249  * @param nd function to call on disconnect events
1250  */
1251 struct GNUNET_TRANSPORT_Handle *
1252 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1253                           const struct GNUNET_PeerIdentity *self, void *cls,
1254                           GNUNET_TRANSPORT_ReceiveCallback rec,
1255                           GNUNET_TRANSPORT_NotifyConnect nc,
1256                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1257 {
1258   struct GNUNET_TRANSPORT_Handle *ret;
1259
1260   ret = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_Handle));
1261   if (self != NULL)
1262   {
1263     ret->self = *self;
1264     ret->check_self = GNUNET_YES;
1265   }
1266   ret->cfg = cfg;
1267   ret->cls = cls;
1268   ret->rec = rec;
1269   ret->nc_cb = nc;
1270   ret->nd_cb = nd;
1271   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1272   ret->neighbours =
1273       GNUNET_CONTAINER_multihashmap_create (STARTING_NEIGHBOURS_SIZE);
1274   ret->ready_heap =
1275       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1276   ret->reconnect_task = GNUNET_SCHEDULER_add_now (&reconnect, ret);
1277   return ret;
1278 }
1279
1280
1281 /**
1282  * Disconnect from the transport service.
1283  *
1284  * @param handle handle to the service as returned from GNUNET_TRANSPORT_connect
1285  */
1286 void
1287 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1288 {
1289 #if DEBUG_TRANSPORT
1290   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transport disconnect called!\n");
1291 #endif
1292   /* this disconnects all neighbours... */
1293   if (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1294     disconnect_and_schedule_reconnect (handle);
1295   /* and now we stop trying to connect again... */
1296   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1297   {
1298     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1299     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1300   }
1301   GNUNET_CONTAINER_multihashmap_destroy (handle->neighbours);
1302   handle->neighbours = NULL;
1303   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1304   {
1305     GNUNET_SCHEDULER_cancel (handle->quota_task);
1306     handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1307   }
1308   GNUNET_free_non_null (handle->my_hello);
1309   handle->my_hello = NULL;
1310   GNUNET_assert (handle->hwl_head == NULL);
1311   GNUNET_assert (handle->hwl_tail == NULL);
1312   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1313   handle->ready_heap = NULL;
1314   GNUNET_free (handle);
1315 }
1316
1317
1318 /**
1319  * Check if we could queue a message of the given size for
1320  * transmission.  The transport service will take both its
1321  * internal buffers and bandwidth limits imposed by the
1322  * other peer into consideration when answering this query.
1323  *
1324  * @param handle connection to transport service
1325  * @param target who should receive the message
1326  * @param size how big is the message we want to transmit?
1327  * @param priority how important is the message?
1328  * @param timeout after how long should we give up (and call
1329  *        notify with buf NULL and size 0)?
1330  * @param notify function to call when we are ready to
1331  *        send such a message
1332  * @param notify_cls closure for notify
1333  * @return NULL if someone else is already waiting to be notified
1334  *         non-NULL if the notify callback was queued (can be used to cancel
1335  *         using GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1336  */
1337 struct GNUNET_TRANSPORT_TransmitHandle *
1338 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1339                                         const struct GNUNET_PeerIdentity
1340                                         *target, size_t size, uint32_t priority,
1341                                         struct GNUNET_TIME_Relative timeout,
1342                                         GNUNET_CONNECTION_TransmitReadyNotify
1343                                         notify, void *notify_cls)
1344 {
1345   struct Neighbour *n;
1346   struct GNUNET_TRANSPORT_TransmitHandle *th;
1347   struct GNUNET_TIME_Relative delay;
1348
1349   n = neighbour_find (handle, target);
1350   if (NULL == n)
1351   {
1352     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1353      * once a connection has been established */
1354     GNUNET_assert (0);
1355     return NULL;
1356   }
1357   if (NULL != n->th)
1358   {
1359     /* attempt to send two messages at the same time to the same peer */
1360     GNUNET_assert (0);
1361     return NULL;
1362   }
1363   GNUNET_assert (NULL == n->hn);
1364   th = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_TransmitHandle));
1365   th->neighbour = n;
1366   th->notify = notify;
1367   th->notify_cls = notify_cls;
1368   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1369   th->notify_size = size;
1370   th->priority = priority;
1371   n->th = th;
1372   /* calculate when our transmission should be ready */
1373   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size);
1374   if (delay.rel_value > timeout.rel_value)
1375     delay.rel_value = 0;        /* notify immediately (with failure) */
1376 #if DEBUG_TRANSPORT
1377   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378               "Bandwidth tracker allows next transmission to peer %s in %llu ms\n",
1379               GNUNET_i2s (target), (unsigned long long) delay.rel_value);
1380 #endif
1381   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value);
1382   schedule_transmission (handle);
1383   return th;
1384 }
1385
1386
1387 /**
1388  * Cancel the specified transmission-ready notification.
1389  *
1390  * @param th handle returned from GNUNET_TRANSPORT_notify_transmit_ready
1391  */
1392 void
1393 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct
1394                                                GNUNET_TRANSPORT_TransmitHandle
1395                                                *th)
1396 {
1397   struct Neighbour *n;
1398
1399   GNUNET_assert (NULL == th->next);
1400   GNUNET_assert (NULL == th->prev);
1401   n = th->neighbour;
1402   GNUNET_assert (th == n->th);
1403   n->th = NULL;
1404   if (n->hn != NULL)
1405   {
1406     GNUNET_CONTAINER_heap_remove_node (n->hn);
1407     n->hn = NULL;
1408   }
1409   else
1410   {
1411     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != th->timeout_task);
1412     GNUNET_SCHEDULER_cancel (th->timeout_task);
1413     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1414   }
1415   GNUNET_free (th);
1416 }
1417
1418
1419 /* end of transport_api.c */