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