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