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