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