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