-fix NPE
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, 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  * - test test test
28  */
29 #include "platform.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_arm_service.h"
33 #include "gnunet_hello_lib.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_transport_service.h"
36 #include "transport.h"
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "transport-api",__VA_ARGS__)
39
40 /**
41  * If we could not send any payload to a peer for this amount of
42  * time, we print a warning.
43  */
44 #define UNREADY_WARN_TIME GNUNET_TIME_UNIT_MINUTES
45
46 /**
47  * How large to start with for the hashmap of neighbours.
48  */
49 #define STARTING_NEIGHBOURS_SIZE 16
50
51 /**
52  * Handle for a message that should be transmitted to the service.
53  * Used for both control messages and normal messages.
54  */
55 struct GNUNET_TRANSPORT_TransmitHandle
56 {
57
58   /**
59    * We keep all requests in a DLL.
60    */
61   struct GNUNET_TRANSPORT_TransmitHandle *next;
62
63   /**
64    * We keep all requests in a DLL.
65    */
66   struct GNUNET_TRANSPORT_TransmitHandle *prev;
67
68   /**
69    * Neighbour for this handle, NULL for control messages.
70    */
71   struct Neighbour *neighbour;
72
73   /**
74    * Function to call when @e notify_size bytes are available
75    * for transmission.
76    */
77   GNUNET_TRANSPORT_TransmitReadyNotify notify;
78
79   /**
80    * Closure for @e notify.
81    */
82   void *notify_cls;
83
84   /**
85    * Time at which this request was originally scheduled.
86    */
87   struct GNUNET_TIME_Absolute request_start;
88
89   /**
90    * Timeout for this request, 0 for control messages.
91    */
92   struct GNUNET_TIME_Absolute timeout;
93
94   /**
95    * Task to trigger request timeout if the request is stalled due to
96    * congestion.
97    */
98   struct GNUNET_SCHEDULER_Task *timeout_task;
99
100   /**
101    * How many bytes is our notify callback waiting for?
102    */
103   size_t notify_size;
104
105 };
106
107
108 /**
109  * Entry in hash table of all of our current (connected) neighbours.
110  */
111 struct Neighbour
112 {
113   /**
114    * Overall transport handle.
115    */
116   struct GNUNET_TRANSPORT_Handle *h;
117
118   /**
119    * Active transmit handle or NULL.
120    */
121   struct GNUNET_TRANSPORT_TransmitHandle *th;
122
123   /**
124    * Identity of this neighbour.
125    */
126   struct GNUNET_PeerIdentity id;
127
128   /**
129    * Outbound bandwidh tracker.
130    */
131   struct GNUNET_BANDWIDTH_Tracker out_tracker;
132
133   /**
134    * Entry in our readyness heap (which is sorted by @e next_ready
135    * value).  NULL if there is no pending transmission request for
136    * this neighbour or if we're waiting for @e is_ready to become
137    * true AFTER the @e out_tracker suggested that this peer's quota
138    * has been satisfied (so once @e is_ready goes to #GNUNET_YES,
139    * we should immediately go back into the heap).
140    */
141   struct GNUNET_CONTAINER_HeapNode *hn;
142
143   /**
144    * Last time when this peer received payload from us.
145    */
146   struct GNUNET_TIME_Absolute last_payload;
147
148   /**
149    * Task to trigger warnings if we do not get SEND_OK after a while.
150    */
151   struct GNUNET_SCHEDULER_Task *unready_warn_task;
152
153   /**
154    * Is this peer currently ready to receive a message?
155    */
156   int is_ready;
157
158   /**
159    * Sending consumed more bytes on wire than payload was announced
160    * This overhead is added to the delay of next sending operation
161    */
162   size_t traffic_overhead;
163 };
164
165
166 /**
167  * Linked list of functions to call whenever our HELLO is updated.
168  */
169 struct GNUNET_TRANSPORT_GetHelloHandle
170 {
171
172   /**
173    * This is a doubly linked list.
174    */
175   struct GNUNET_TRANSPORT_GetHelloHandle *next;
176
177   /**
178    * This is a doubly linked list.
179    */
180   struct GNUNET_TRANSPORT_GetHelloHandle *prev;
181
182   /**
183    * Transport handle.
184    */
185   struct GNUNET_TRANSPORT_Handle *handle;
186
187   /**
188    * Callback to call once we got our HELLO.
189    */
190   GNUNET_TRANSPORT_HelloUpdateCallback rec;
191
192   /**
193    * Task for calling the HelloUpdateCallback when we already have a HELLO
194    */
195   struct GNUNET_SCHEDULER_Task *notify_task;
196
197   /**
198    * Closure for @e rec.
199    */
200   void *rec_cls;
201
202 };
203
204
205 /**
206  * Entry in linked list for a try-connect request.
207  */
208 struct GNUNET_TRANSPORT_TryConnectHandle
209 {
210   /**
211    * For the DLL.
212    */
213   struct GNUNET_TRANSPORT_TryConnectHandle *prev;
214
215   /**
216    * For the DLL.
217    */
218   struct GNUNET_TRANSPORT_TryConnectHandle *next;
219
220   /**
221    * Peer we should try to connect to.
222    */
223   struct GNUNET_PeerIdentity pid;
224
225   /**
226    * Transport service handle this request is part of.
227    */
228   struct GNUNET_TRANSPORT_Handle *th;
229
230   /**
231    * Message transmission request to communicate to service.
232    */
233   struct GNUNET_TRANSPORT_TransmitHandle *tth;
234
235   /**
236    * Function to call upon completion (of request transmission).
237    */
238   GNUNET_TRANSPORT_TryConnectCallback cb;
239
240   /**
241    * Closure for @e cb.
242    */
243   void *cb_cls;
244
245 };
246
247
248 /**
249  * Entry in linked list for all try-disconnect requests
250  */
251 struct GNUNET_TRANSPORT_TryDisconnectHandle
252 {
253   /**
254    * For the DLL.
255    */
256   struct GNUNET_TRANSPORT_TryDisconnectHandle *prev;
257
258   /**
259    * For the DLL.
260    */
261   struct GNUNET_TRANSPORT_TryDisconnectHandle *next;
262
263   /**
264    * Peer we should try to connect to.
265    */
266   struct GNUNET_PeerIdentity pid;
267
268   /**
269    * Transport service handle this request is part of.
270    */
271   struct GNUNET_TRANSPORT_Handle *th;
272
273   /**
274    * Message transmission request to communicate to service.
275    */
276   struct GNUNET_TRANSPORT_TransmitHandle *tth;
277
278   /**
279    * Function to call upon completion (of request transmission).
280    */
281   GNUNET_TRANSPORT_TryDisconnectCallback cb;
282
283   /**
284    * Closure for @e cb.
285    */
286   void *cb_cls;
287
288 };
289
290
291 /**
292  * Entry in linked list for all offer-HELLO requests.
293  */
294 struct GNUNET_TRANSPORT_OfferHelloHandle
295 {
296   /**
297    * For the DLL.
298    */
299   struct GNUNET_TRANSPORT_OfferHelloHandle *prev;
300
301   /**
302    * For the DLL.
303    */
304   struct GNUNET_TRANSPORT_OfferHelloHandle *next;
305
306   /**
307    * Transport service handle we use for transmission.
308    */
309   struct GNUNET_TRANSPORT_Handle *th;
310
311   /**
312    * Transmission handle for this request.
313    */
314   struct GNUNET_TRANSPORT_TransmitHandle *tth;
315
316   /**
317    * Function to call once we are done.
318    */
319   GNUNET_SCHEDULER_TaskCallback cont;
320
321   /**
322    * Closure for @e cont
323    */
324   void *cls;
325
326   /**
327    * The HELLO message to be transmitted.
328    */
329   struct GNUNET_MessageHeader *msg;
330 };
331
332
333 /**
334  * Handle for the transport service (includes all of the
335  * state for the transport service).
336  */
337 struct GNUNET_TRANSPORT_Handle
338 {
339
340   /**
341    * Closure for the callbacks.
342    */
343   void *cls;
344
345   /**
346    * Function to call for received data.
347    */
348   GNUNET_TRANSPORT_ReceiveCallback rec;
349
350   /**
351    * function to call on connect events
352    */
353   GNUNET_TRANSPORT_NotifyConnect nc_cb;
354
355   /**
356    * function to call on disconnect events
357    */
358   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
359
360   /**
361    * function to call on excess bandwidth events
362    */
363   GNUNET_TRANSPORT_NotifyExcessBandwidth neb_cb;
364
365   /**
366    * Head of DLL of control messages.
367    */
368   struct GNUNET_TRANSPORT_TransmitHandle *control_head;
369
370   /**
371    * Tail of DLL of control messages.
372    */
373   struct GNUNET_TRANSPORT_TransmitHandle *control_tail;
374
375   /**
376    * The current HELLO message for this peer.  Updated
377    * whenever transports change their addresses.
378    */
379   struct GNUNET_MessageHeader *my_hello;
380
381   /**
382    * My client connection to the transport service.
383    */
384   struct GNUNET_CLIENT_Connection *client;
385
386   /**
387    * Handle to our registration with the client for notification.
388    */
389   struct GNUNET_CLIENT_TransmitHandle *cth;
390
391   /**
392    * Linked list of pending requests for our HELLO.
393    */
394   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_head;
395
396   /**
397    * Linked list of pending requests for our HELLO.
398    */
399   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_tail;
400
401   /**
402    * Linked list of pending try connect requests head
403    */
404   struct GNUNET_TRANSPORT_TryConnectHandle *tc_head;
405
406   /**
407    * Linked list of pending try connect requests tail
408    */
409   struct GNUNET_TRANSPORT_TryConnectHandle *tc_tail;
410
411   /**
412    * Linked list of pending try disconnect requests head
413    */
414   struct GNUNET_TRANSPORT_TryDisconnectHandle *td_head;
415
416   /**
417    * Linked list of pending try connect requests tail
418    */
419   struct GNUNET_TRANSPORT_TryDisconnectHandle *td_tail;
420
421   /**
422    * Linked list of pending offer HELLO requests head
423    */
424   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_head;
425
426   /**
427    * Linked list of pending offer HELLO requests tail
428    */
429   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_tail;
430
431   /**
432    * My configuration.
433    */
434   const struct GNUNET_CONFIGURATION_Handle *cfg;
435
436   /**
437    * Hash map of the current connected neighbours of this peer.
438    * Maps peer identities to `struct Neighbour` entries.
439    */
440   struct GNUNET_CONTAINER_MultiPeerMap *neighbours;
441
442   /**
443    * Heap sorting peers with pending messages by the timestamps that
444    * specify when we could next send a message to the respective peer.
445    * Excludes control messages (which can always go out immediately).
446    * Maps time stamps to `struct Neighbour` entries.
447    */
448   struct GNUNET_CONTAINER_Heap *ready_heap;
449
450   /**
451    * Peer identity as assumed by this process, or all zeros.
452    */
453   struct GNUNET_PeerIdentity self;
454
455   /**
456    * ID of the task trying to reconnect to the service.
457    */
458   struct GNUNET_SCHEDULER_Task *reconnect_task;
459
460   /**
461    * ID of the task trying to trigger transmission for a peer while
462    * maintaining bandwidth quotas.  In use if there are no control
463    * messages and the smallest entry in the @e ready_heap has a time
464    * stamp in the future.
465    */
466   struct GNUNET_SCHEDULER_Task *quota_task;
467
468   /**
469    * Delay until we try to reconnect.
470    */
471   struct GNUNET_TIME_Relative reconnect_delay;
472
473   /**
474    * Should we check that @e self matches what the service thinks?
475    * (if #GNUNET_NO, then @e self is all zeros!).
476    */
477   int check_self;
478
479   /**
480    * Reconnect in progress
481    */
482   int reconnecting;
483 };
484
485
486 /**
487  * Schedule the task to send one message, either from the control
488  * list or the peer message queues  to the service.
489  *
490  * @param h transport service to schedule a transmission for
491  */
492 static void
493 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
494
495
496 /**
497  * Function that will schedule the job that will try
498  * to connect us again to the client.
499  *
500  * @param h transport service to reconnect
501  */
502 static void
503 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h);
504
505
506 /**
507  * A neighbour has not gotten a SEND_OK in a  while. Print a warning.
508  *
509  * @param cls the `struct Neighbour`
510  * @param tc scheduler context
511  */
512 static void
513 do_warn_unready (void *cls,
514                  const struct GNUNET_SCHEDULER_TaskContext *tc)
515 {
516   struct Neighbour *n = cls;
517   struct GNUNET_TIME_Relative delay;
518
519   delay = GNUNET_TIME_absolute_get_duration (n->last_payload);
520   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
521               "Lacking SEND_OK, no payload could be send to %s for %s\n",
522               GNUNET_i2s (&n->id),
523               GNUNET_STRINGS_relative_time_to_string (delay,
524                                                       GNUNET_YES));
525   n->unready_warn_task
526     = GNUNET_SCHEDULER_add_delayed (UNREADY_WARN_TIME,
527                                     &do_warn_unready,
528                                     n);
529 }
530
531
532 /**
533  * Get the neighbour list entry for the given peer
534  *
535  * @param h our context
536  * @param peer peer to look up
537  * @return NULL if no such peer entry exists
538  */
539 static struct Neighbour *
540 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
541                 const struct GNUNET_PeerIdentity *peer)
542 {
543   return GNUNET_CONTAINER_multipeermap_get (h->neighbours,
544                                             peer);
545 }
546
547
548 /**
549  * The outbound quota has changed in a way that may require
550  * us to reset the timeout.  Update the timeout.
551  *
552  * @param cls the `struct Neighbour` for which the timeout changed
553  */
554 static void
555 outbound_bw_tracker_update (void *cls)
556 {
557   struct Neighbour *n = cls;
558   struct GNUNET_TIME_Relative delay;
559
560   if (NULL == n->hn)
561     return;
562   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
563                                               n->th->notify_size + n->traffic_overhead);
564   LOG (GNUNET_ERROR_TYPE_DEBUG,
565        "New outbound delay %s us\n",
566        GNUNET_STRINGS_relative_time_to_string (delay,
567                                                GNUNET_NO));
568   GNUNET_CONTAINER_heap_update_cost (n->h->ready_heap,
569       n->hn, delay.rel_value_us);
570   schedule_transmission (n->h);
571 }
572
573
574 /**
575  * Function called by the bandwidth tracker if we have excess
576  * bandwidth.
577  *
578  * @param cls the `struct Neighbour` that has excess bandwidth
579  */
580 static void
581 notify_excess_cb (void *cls)
582 {
583   struct Neighbour *n = cls;
584   struct GNUNET_TRANSPORT_Handle *h = n->h;
585
586   if (NULL != h->neb_cb)
587     h->neb_cb (h->cls,
588                &n->id);
589 }
590
591
592 /**
593  * Add neighbour to our list
594  *
595  * @return NULL if this API is currently disconnecting from the service
596  */
597 static struct Neighbour *
598 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
599                const struct GNUNET_PeerIdentity *pid)
600 {
601   struct Neighbour *n;
602
603   LOG (GNUNET_ERROR_TYPE_DEBUG,
604        "Creating entry for neighbour `%s'.\n",
605        GNUNET_i2s (pid));
606   n = GNUNET_new (struct Neighbour);
607   n->id = *pid;
608   n->h = h;
609   n->is_ready = GNUNET_YES;
610   n->traffic_overhead = 0;
611   GNUNET_BANDWIDTH_tracker_init2 (&n->out_tracker,
612                                   &outbound_bw_tracker_update,
613                                   n,
614                                   GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
615                                   MAX_BANDWIDTH_CARRY_S,
616                                   &notify_excess_cb,
617                                   n);
618   GNUNET_assert (GNUNET_OK ==
619                  GNUNET_CONTAINER_multipeermap_put (h->neighbours,
620                                                     &n->id,
621                                                     n,
622                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
623   return n;
624 }
625
626
627 /**
628  * Iterator over hash map entries, for deleting state of a neighbour.
629  *
630  * @param cls the `struct GNUNET_TRANSPORT_Handle *`
631  * @param key peer identity
632  * @param value value in the hash map, the neighbour entry to delete
633  * @return #GNUNET_YES if we should continue to
634  *         iterate,
635  *         #GNUNET_NO if not.
636  */
637 static int
638 neighbour_delete (void *cls,
639                   const struct GNUNET_PeerIdentity *key,
640                   void *value)
641 {
642   struct GNUNET_TRANSPORT_Handle *handle = cls;
643   struct Neighbour *n = value;
644
645   LOG (GNUNET_ERROR_TYPE_DEBUG,
646        "Dropping entry for neighbour `%s'.\n",
647        GNUNET_i2s (key));
648   GNUNET_BANDWIDTH_tracker_notification_stop (&n->out_tracker);
649   if (NULL != handle->nd_cb)
650     handle->nd_cb (handle->cls,
651                    &n->id);
652   if (NULL != n->unready_warn_task)
653   {
654     GNUNET_SCHEDULER_cancel (n->unready_warn_task);
655     n->unready_warn_task = NULL;
656   }
657   GNUNET_assert (NULL == n->th);
658   GNUNET_assert (NULL == n->hn);
659   GNUNET_assert (GNUNET_YES ==
660                  GNUNET_CONTAINER_multipeermap_remove (handle->neighbours,
661                                                        key,
662                                                        n));
663   GNUNET_free (n);
664   return GNUNET_YES;
665 }
666
667
668 /**
669  * Function we use for handling incoming messages.
670  *
671  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
672  * @param msg message received, NULL on timeout or fatal error
673  */
674 static void
675 demultiplexer (void *cls,
676                const struct GNUNET_MessageHeader *msg)
677 {
678   struct GNUNET_TRANSPORT_Handle *h = cls;
679   const struct DisconnectInfoMessage *dim;
680   const struct ConnectInfoMessage *cim;
681   const struct InboundMessage *im;
682   const struct GNUNET_MessageHeader *imm;
683   const struct SendOkMessage *okm;
684   const struct QuotaSetMessage *qm;
685   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
686   struct GNUNET_TRANSPORT_GetHelloHandle *next_hwl;
687   struct Neighbour *n;
688   struct GNUNET_PeerIdentity me;
689   uint16_t size;
690   uint32_t bytes_msg;
691   uint32_t bytes_physical;
692
693   GNUNET_assert (NULL != h->client);
694   if (GNUNET_YES == h->reconnecting)
695   {
696     return;
697   }
698   if (NULL == msg)
699   {
700     LOG (GNUNET_ERROR_TYPE_DEBUG,
701          "Error receiving from transport service, disconnecting temporarily.\n");
702     h->reconnecting = GNUNET_YES;
703     disconnect_and_schedule_reconnect (h);
704     return;
705   }
706   GNUNET_CLIENT_receive (h->client,
707                          &demultiplexer,
708                          h,
709                          GNUNET_TIME_UNIT_FOREVER_REL);
710   size = ntohs (msg->size);
711   switch (ntohs (msg->type))
712   {
713   case GNUNET_MESSAGE_TYPE_HELLO:
714     if (GNUNET_OK !=
715         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
716                              &me))
717     {
718       GNUNET_break (0);
719       break;
720     }
721     LOG (GNUNET_ERROR_TYPE_DEBUG,
722          "Receiving (my own) HELLO message (%u bytes), I am `%s'.\n",
723          (unsigned int) size,
724          GNUNET_i2s (&me));
725     GNUNET_free_non_null (h->my_hello);
726     h->my_hello = NULL;
727     if (size < sizeof (struct GNUNET_MessageHeader))
728     {
729       GNUNET_break (0);
730       break;
731     }
732     h->my_hello = GNUNET_copy_message (msg);
733     hwl = h->hwl_head;
734     while (NULL != hwl)
735     {
736       next_hwl = hwl->next;
737       hwl->rec (hwl->rec_cls,
738                 h->my_hello);
739       hwl = next_hwl;
740     }
741     break;
742   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
743     if (size < sizeof (struct ConnectInfoMessage))
744     {
745       GNUNET_break (0);
746       break;
747     }
748     cim = (const struct ConnectInfoMessage *) msg;
749     if (size !=
750         sizeof (struct ConnectInfoMessage))
751     {
752       GNUNET_break (0);
753       break;
754     }
755     LOG (GNUNET_ERROR_TYPE_DEBUG,
756          "Receiving CONNECT message for `%s'.\n",
757          GNUNET_i2s (&cim->id));
758     n = neighbour_find (h, &cim->id);
759     if (NULL != n)
760     {
761       GNUNET_break (0);
762       break;
763     }
764     n = neighbour_add (h,
765                        &cim->id);
766     LOG (GNUNET_ERROR_TYPE_DEBUG,
767          "Receiving CONNECT message for `%s' with quota %u\n",
768          GNUNET_i2s (&cim->id),
769          ntohl (cim->quota_out.value__));
770     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
771                                            cim->quota_out);
772     if (NULL != h->nc_cb)
773       h->nc_cb (h->cls,
774                 &n->id);
775     break;
776   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
777     if (size != sizeof (struct DisconnectInfoMessage))
778     {
779       GNUNET_break (0);
780       break;
781     }
782     dim = (const struct DisconnectInfoMessage *) msg;
783     GNUNET_break (ntohl (dim->reserved) == 0);
784     LOG (GNUNET_ERROR_TYPE_DEBUG,
785          "Receiving DISCONNECT message for `%s'.\n",
786          GNUNET_i2s (&dim->peer));
787     n = neighbour_find (h, &dim->peer);
788     if (NULL == n)
789     {
790       GNUNET_break (0);
791       break;
792     }
793     neighbour_delete (h,
794                       &dim->peer,
795                       n);
796     break;
797   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
798     if (size != sizeof (struct SendOkMessage))
799     {
800       GNUNET_break (0);
801       break;
802     }
803     okm = (const struct SendOkMessage *) msg;
804     bytes_msg = ntohl (okm->bytes_msg);
805     bytes_physical = ntohl (okm->bytes_physical);
806     LOG (GNUNET_ERROR_TYPE_DEBUG,
807          "Receiving SEND_OK message, transmission %s.\n",
808          ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
809
810     n = neighbour_find (h,
811                         &okm->peer);
812     if (NULL == n)
813     {
814       /* we should never get a 'SEND_OK' for a peer that we are not
815          connected to */
816       GNUNET_break (0);
817       break;
818     }
819     if (bytes_physical >= bytes_msg)
820     {
821       LOG (GNUNET_ERROR_TYPE_DEBUG,
822            "Overhead for %u byte message: %u\n",
823            bytes_msg,
824            bytes_physical - bytes_msg);
825       n->traffic_overhead += bytes_physical - bytes_msg;
826     }
827     GNUNET_break (GNUNET_NO == n->is_ready);
828     n->is_ready = GNUNET_YES;
829     if (NULL != n->unready_warn_task)
830     {
831       GNUNET_SCHEDULER_cancel (n->unready_warn_task);
832       n->unready_warn_task = NULL;
833     }
834     if ((NULL != n->th) && (NULL == n->hn))
835     {
836       GNUNET_assert (NULL != n->th->timeout_task);
837       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
838       n->th->timeout_task = NULL;
839       /* we've been waiting for this (congestion, not quota,
840        * caused delayed transmission) */
841       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
842       schedule_transmission (h);
843     }
844     break;
845   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
846     if (size <
847         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
848     {
849       GNUNET_break (0);
850       break;
851     }
852     im = (const struct InboundMessage *) msg;
853     imm = (const struct GNUNET_MessageHeader *) &im[1];
854     if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
855     {
856       GNUNET_break (0);
857       break;
858     }
859     LOG (GNUNET_ERROR_TYPE_DEBUG,
860          "Received message of type %u from `%s'.\n",
861          ntohs (imm->type), GNUNET_i2s (&im->peer));
862     n = neighbour_find (h, &im->peer);
863     if (NULL == n)
864     {
865       GNUNET_break (0);
866       break;
867     }
868     if (NULL != h->rec)
869       h->rec (h->cls,
870               &im->peer,
871               imm);
872     break;
873   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
874     if (size != sizeof (struct QuotaSetMessage))
875     {
876       GNUNET_break (0);
877       break;
878     }
879     qm = (const struct QuotaSetMessage *) msg;
880     n = neighbour_find (h, &qm->peer);
881     if (NULL == n)
882       break;
883     LOG (GNUNET_ERROR_TYPE_DEBUG,
884          "Receiving SET_QUOTA message for `%s' with quota %u\n",
885          GNUNET_i2s (&qm->peer),
886          ntohl (qm->quota.value__));
887     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
888                                            qm->quota);
889     break;
890   default:
891     LOG (GNUNET_ERROR_TYPE_ERROR,
892          _("Received unexpected message of type %u in %s:%u\n"),
893          ntohs (msg->type),
894          __FILE__,
895          __LINE__);
896     GNUNET_break (0);
897     break;
898   }
899 }
900
901
902 /**
903  * A transmission request could not be satisfied because of
904  * network congestion.  Notify the initiator and clean up.
905  *
906  * @param cls the `struct GNUNET_TRANSPORT_TransmitHandle`
907  * @param tc scheduler context
908  */
909 static void
910 timeout_request_due_to_congestion (void *cls,
911                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
912 {
913   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
914   struct Neighbour *n = th->neighbour;
915   struct GNUNET_TIME_Relative delay;
916
917   n->th->timeout_task = NULL;
918   delay = GNUNET_TIME_absolute_get_duration (th->request_start);
919   LOG (GNUNET_ERROR_TYPE_WARNING,
920        "Discarding %u bytes of payload message after %s delay due to congestion\n",
921        th->notify_size,
922        GNUNET_STRINGS_relative_time_to_string (delay,
923                                                GNUNET_YES));
924   GNUNET_assert (th == n->th);
925   GNUNET_assert (NULL == n->hn);
926   n->th = NULL;
927   th->notify (th->notify_cls,
928               0,
929               NULL);
930   GNUNET_free (th);
931 }
932
933
934 /**
935  * Transmit message(s) to service.
936  *
937  * @param cls handle to transport
938  * @param size number of bytes available in @a buf
939  * @param buf where to copy the message
940  * @return number of bytes copied to @a buf
941  */
942 static size_t
943 transport_notify_ready (void *cls,
944                         size_t size,
945                         void *buf)
946 {
947   struct GNUNET_TRANSPORT_Handle *h = cls;
948   struct GNUNET_TRANSPORT_TransmitHandle *th;
949   struct GNUNET_TIME_Relative delay;
950   struct Neighbour *n;
951   char *cbuf;
952   struct OutboundMessage obm;
953   size_t ret;
954   size_t nret;
955   size_t mret;
956
957   GNUNET_assert (NULL != h->client);
958   h->cth = NULL;
959   if (NULL == buf)
960   {
961     /* transmission failed */
962     disconnect_and_schedule_reconnect (h);
963     return 0;
964   }
965
966   cbuf = buf;
967   ret = 0;
968   /* first send control messages */
969   while ( (NULL != (th = h->control_head)) &&
970           (th->notify_size <= size) )
971   {
972     GNUNET_CONTAINER_DLL_remove (h->control_head,
973                                  h->control_tail,
974                                  th);
975     nret = th->notify (th->notify_cls,
976                        size,
977                        &cbuf[ret]);
978     delay = GNUNET_TIME_absolute_get_duration (th->request_start);
979     if (delay.rel_value_us > 1000 * 1000)
980       LOG (GNUNET_ERROR_TYPE_WARNING,
981            "Added %u bytes of control message at %u after %s delay\n",
982            nret,
983            ret,
984            GNUNET_STRINGS_relative_time_to_string (delay,
985                                                    GNUNET_YES));
986     else
987       LOG (GNUNET_ERROR_TYPE_DEBUG,
988            "Added %u bytes of control message at %u after %s delay\n",
989            nret,
990            ret,
991            GNUNET_STRINGS_relative_time_to_string (delay,
992                                                    GNUNET_YES));
993     GNUNET_free (th);
994     ret += nret;
995     size -= nret;
996   }
997
998   /* then, if possible and no control messages pending, send data messages */
999   while ( (NULL == h->control_head) &&
1000           (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) )
1001   {
1002     if (GNUNET_YES != n->is_ready)
1003     {
1004       /* peer not ready, wait for notification! */
1005       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1006       n->hn = NULL;
1007       GNUNET_assert (NULL == n->th->timeout_task);
1008       n->th->timeout_task
1009         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1010                                         (n->th->timeout),
1011                                         &timeout_request_due_to_congestion,
1012                                         n->th);
1013       continue;
1014     }
1015     th = n->th;
1016     if (th->notify_size + sizeof (struct OutboundMessage) > size)
1017       break;                    /* does not fit */
1018     if (GNUNET_BANDWIDTH_tracker_get_delay
1019         (&n->out_tracker, th->notify_size).rel_value_us > 0)
1020       break;                    /* too early */
1021     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1022     n->hn = NULL;
1023     n->th = NULL;
1024     GNUNET_assert (size >= sizeof (struct OutboundMessage));
1025     mret = th->notify (th->notify_cls,
1026                        size - sizeof (struct OutboundMessage),
1027                        &cbuf[ret + sizeof (struct OutboundMessage)]);
1028     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
1029     if (0 == mret)
1030     {
1031       GNUNET_free (th);
1032       continue;
1033     }
1034     if (NULL != n->unready_warn_task)
1035       n->unready_warn_task
1036         = GNUNET_SCHEDULER_add_delayed (UNREADY_WARN_TIME,
1037                                         &do_warn_unready,
1038                                         n);
1039     n->last_payload = GNUNET_TIME_absolute_get ();
1040     n->is_ready = GNUNET_NO;
1041     GNUNET_assert (mret + sizeof (struct OutboundMessage) <
1042                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
1043     obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
1044     obm.header.size = htons (mret + sizeof (struct OutboundMessage));
1045     obm.reserved = htonl (0);
1046     obm.timeout =
1047       GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1048                                  (th->timeout));
1049     obm.peer = n->id;
1050     memcpy (&cbuf[ret],
1051             &obm,
1052             sizeof (struct OutboundMessage));
1053     ret += (mret + sizeof (struct OutboundMessage));
1054     size -= (mret + sizeof (struct OutboundMessage));
1055     GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker,
1056                                       mret);
1057     delay = GNUNET_TIME_absolute_get_duration (th->request_start);
1058     if (delay.rel_value_us > 1000 * 1000)
1059       LOG (GNUNET_ERROR_TYPE_WARNING,
1060            "Added %u bytes of payload message at %u after %s delay\n",
1061            mret,
1062            ret,
1063            GNUNET_STRINGS_relative_time_to_string (delay,
1064                                                    GNUNET_YES));
1065     else
1066       LOG (GNUNET_ERROR_TYPE_DEBUG,
1067            "Added %u bytes of payload message at %u after %s delay\n",
1068            mret,
1069            ret,
1070            GNUNET_STRINGS_relative_time_to_string (delay,
1071                                                    GNUNET_YES));
1072     GNUNET_free (th);
1073     break;
1074   }
1075   /* if there are more pending messages, try to schedule those */
1076   schedule_transmission (h);
1077   LOG (GNUNET_ERROR_TYPE_DEBUG,
1078        "Transmitting %u bytes to transport service\n",
1079        ret);
1080   return ret;
1081 }
1082
1083
1084 /**
1085  * Schedule the task to send one message, either from the control
1086  * list or the peer message queues  to the service.
1087  *
1088  * @param cls transport service to schedule a transmission for
1089  * @param tc scheduler context
1090  */
1091 static void
1092 schedule_transmission_task (void *cls,
1093                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1094 {
1095   struct GNUNET_TRANSPORT_Handle *h = cls;
1096   size_t size;
1097   struct GNUNET_TRANSPORT_TransmitHandle *th;
1098   struct Neighbour *n;
1099
1100   h->quota_task = NULL;
1101   GNUNET_assert (NULL != h->client);
1102   /* destroy all requests that have timed out */
1103   while ( (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
1104           (0 == GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value_us) )
1105   {
1106     /* notify client that the request could not be satisfied within
1107      * the given time constraints */
1108     th = n->th;
1109     n->th = NULL;
1110     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1111     n->hn = NULL;
1112     LOG (GNUNET_ERROR_TYPE_DEBUG,
1113          "Signalling timeout for transmission to peer %s due to congestion\n",
1114          GNUNET_i2s (&n->id));
1115     GNUNET_assert (0 == th->notify (th->notify_cls,
1116                                     0,
1117                                     NULL));
1118     GNUNET_free (th);
1119   }
1120   if (NULL != h->cth)
1121     return;
1122   if (NULL != h->control_head)
1123   {
1124     size = h->control_head->notify_size;
1125   }
1126   else
1127   {
1128     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
1129     if (NULL == n)
1130       return;                   /* no pending messages */
1131     size = n->th->notify_size + sizeof (struct OutboundMessage);
1132   }
1133   LOG (GNUNET_ERROR_TYPE_DEBUG,
1134        "Calling notify_transmit_ready\n");
1135   h->cth
1136     = GNUNET_CLIENT_notify_transmit_ready (h->client,
1137                                            size,
1138                                            GNUNET_TIME_UNIT_FOREVER_REL,
1139                                            GNUNET_NO,
1140                                            &transport_notify_ready,
1141                                            h);
1142   GNUNET_assert (NULL != h->cth);
1143 }
1144
1145
1146 /**
1147  * Schedule the task to send one message, either from the control
1148  * list or the peer message queues  to the service.
1149  *
1150  * @param h transport service to schedule a transmission for
1151  */
1152 static void
1153 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
1154 {
1155   struct GNUNET_TIME_Relative delay;
1156   struct Neighbour *n;
1157
1158   GNUNET_assert (NULL != h->client);
1159   if (NULL != h->quota_task)
1160   {
1161     GNUNET_SCHEDULER_cancel (h->quota_task);
1162     h->quota_task = NULL;
1163   }
1164   if (NULL != h->control_head)
1165     delay = GNUNET_TIME_UNIT_ZERO;
1166   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
1167   {
1168     delay =
1169         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
1170                                             n->th->notify_size + n->traffic_overhead);
1171     n->traffic_overhead = 0;
1172   }
1173   else
1174     return;                     /* no work to be done */
1175   LOG (GNUNET_ERROR_TYPE_DEBUG,
1176        "Scheduling next transmission to service in %s\n",
1177        GNUNET_STRINGS_relative_time_to_string (delay,
1178                                                GNUNET_YES));
1179   h->quota_task =
1180       GNUNET_SCHEDULER_add_delayed (delay,
1181                                     &schedule_transmission_task,
1182                                     h);
1183 }
1184
1185
1186 /**
1187  * Queue control request for transmission to the transport
1188  * service.
1189  *
1190  * @param h handle to the transport service
1191  * @param size number of bytes to be transmitted
1192  * @param notify function to call to get the content
1193  * @param notify_cls closure for @a notify
1194  * @return a `struct GNUNET_TRANSPORT_TransmitHandle`
1195  */
1196 static struct GNUNET_TRANSPORT_TransmitHandle *
1197 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h,
1198                            size_t size,
1199                            GNUNET_TRANSPORT_TransmitReadyNotify notify,
1200                            void *notify_cls)
1201 {
1202   struct GNUNET_TRANSPORT_TransmitHandle *th;
1203
1204   LOG (GNUNET_ERROR_TYPE_DEBUG,
1205        "Control transmit of %u bytes requested\n",
1206        size);
1207   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1208   th->notify = notify;
1209   th->notify_cls = notify_cls;
1210   th->notify_size = size;
1211   th->request_start = GNUNET_TIME_absolute_get ();
1212   GNUNET_CONTAINER_DLL_insert_tail (h->control_head,
1213                                     h->control_tail,
1214                                     th);
1215   schedule_transmission (h);
1216   return th;
1217 }
1218
1219
1220 /**
1221  * Transmit START message to service.
1222  *
1223  * @param cls unused
1224  * @param size number of bytes available in @a buf
1225  * @param buf where to copy the message
1226  * @return number of bytes copied to @a buf
1227  */
1228 static size_t
1229 send_start (void *cls,
1230             size_t size,
1231             void *buf)
1232 {
1233   struct GNUNET_TRANSPORT_Handle *h = cls;
1234   struct StartMessage s;
1235   uint32_t options;
1236
1237   if (NULL == buf)
1238   {
1239     /* Can only be shutdown, just give up */
1240     LOG (GNUNET_ERROR_TYPE_DEBUG,
1241          "Shutdown while trying to transmit START request.\n");
1242     return 0;
1243   }
1244   LOG (GNUNET_ERROR_TYPE_DEBUG,
1245        "Transmitting START request.\n");
1246   GNUNET_assert (size >= sizeof (struct StartMessage));
1247   s.header.size = htons (sizeof (struct StartMessage));
1248   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1249   options = 0;
1250   if (h->check_self)
1251     options |= 1;
1252   if (NULL != h->rec)
1253     options |= 2;
1254   s.options = htonl (options);
1255   s.self = h->self;
1256   memcpy (buf, &s, sizeof (struct StartMessage));
1257   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
1258                          GNUNET_TIME_UNIT_FOREVER_REL);
1259   return sizeof (struct StartMessage);
1260 }
1261
1262
1263 /**
1264  * Try again to connect to transport service.
1265  *
1266  * @param cls the handle to the transport service
1267  * @param tc scheduler context
1268  */
1269 static void
1270 reconnect (void *cls,
1271            const struct GNUNET_SCHEDULER_TaskContext *tc)
1272 {
1273   struct GNUNET_TRANSPORT_Handle *h = cls;
1274
1275   h->reconnect_task = NULL;
1276   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1277   {
1278     /* shutdown, just give up */
1279     return;
1280   }
1281   LOG (GNUNET_ERROR_TYPE_DEBUG,
1282        "Connecting to transport service.\n");
1283   GNUNET_assert (NULL == h->client);
1284   GNUNET_assert (NULL == h->control_head);
1285   GNUNET_assert (NULL == h->control_tail);
1286   h->reconnecting = GNUNET_NO;
1287   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1288
1289   GNUNET_assert (NULL != h->client);
1290   schedule_control_transmit (h, sizeof (struct StartMessage),
1291                              &send_start, h);
1292 }
1293
1294
1295 /**
1296  * Function that will schedule the job that will try
1297  * to connect us again to the client.
1298  *
1299  * @param h transport service to reconnect
1300  */
1301 static void
1302 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1303 {
1304   struct GNUNET_TRANSPORT_TransmitHandle *th;
1305
1306   GNUNET_assert (h->reconnect_task == NULL);
1307   if (NULL != h->cth)
1308   {
1309     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1310     h->cth = NULL;
1311   }
1312   if (NULL != h->client)
1313   {
1314     GNUNET_CLIENT_disconnect (h->client);
1315     h->client = NULL;
1316 /*    LOG (GNUNET_ERROR_TYPE_ERROR,
1317          "Client disconnect done \n");*/
1318   }
1319   /* Forget about all neighbours that we used to be connected to */
1320   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
1321                                          &neighbour_delete,
1322                                          h);
1323   if (NULL != h->quota_task)
1324   {
1325     GNUNET_SCHEDULER_cancel (h->quota_task);
1326     h->quota_task = NULL;
1327   }
1328   while ((NULL != (th = h->control_head)))
1329   {
1330     GNUNET_CONTAINER_DLL_remove (h->control_head,
1331                                  h->control_tail,
1332                                  th);
1333     th->notify (th->notify_cls,
1334                 0,
1335                 NULL);
1336     GNUNET_free (th);
1337   }
1338   LOG (GNUNET_ERROR_TYPE_DEBUG,
1339        "Scheduling task to reconnect to transport service in %s.\n",
1340        GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay,
1341                                                GNUNET_YES));
1342   h->reconnect_task =
1343       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
1344                                     &reconnect,
1345                                     h);
1346   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
1347 }
1348
1349
1350 /**
1351  * Cancel control request for transmission to the transport service.
1352  *
1353  * @param th handle to the transport service
1354  * @param tth transmit handle to cancel
1355  */
1356 static void
1357 cancel_control_transmit (struct GNUNET_TRANSPORT_Handle *th,
1358                          struct GNUNET_TRANSPORT_TransmitHandle *tth)
1359 {
1360   LOG (GNUNET_ERROR_TYPE_DEBUG,
1361        "Canceling transmit of contral transmission requested\n");
1362   GNUNET_CONTAINER_DLL_remove (th->control_head,
1363                                th->control_tail,
1364                                tth);
1365   GNUNET_free (tth);
1366 }
1367
1368
1369 /**
1370  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT message to the
1371  * service.
1372  *
1373  * @param cls the `struct GNUNET_TRANSPORT_TryConnectHandle`
1374  * @param size number of bytes available in @a buf
1375  * @param buf where to copy the message
1376  * @return number of bytes copied to @a buf
1377  */
1378 static size_t
1379 send_try_connect (void *cls,
1380                   size_t size,
1381                   void *buf)
1382 {
1383   struct GNUNET_TRANSPORT_TryConnectHandle *tch = cls;
1384   struct TransportRequestConnectMessage msg;
1385
1386   tch->tth = NULL;
1387   if (NULL == buf)
1388   {
1389     LOG (GNUNET_ERROR_TYPE_DEBUG,
1390          "Discarding  `%s' request to `%s' due to error in transport service connection.\n",
1391          "REQUEST_CONNECT",
1392          GNUNET_i2s (&tch->pid));
1393     if (NULL != tch->cb)
1394       tch->cb (tch->cb_cls,
1395                GNUNET_SYSERR);
1396     GNUNET_TRANSPORT_try_connect_cancel (tch);
1397     return 0;
1398   }
1399   LOG (GNUNET_ERROR_TYPE_DEBUG,
1400        "Transmitting `%s' request with respect to `%s'.\n",
1401        "REQUEST_CONNECT",
1402        GNUNET_i2s (&tch->pid));
1403   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1404   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1405   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1406   msg.reserved = htonl (0);
1407   msg.peer = tch->pid;
1408   memcpy (buf, &msg, sizeof (msg));
1409   if (NULL != tch->cb)
1410     tch->cb (tch->cb_cls, GNUNET_OK);
1411   GNUNET_TRANSPORT_try_connect_cancel (tch);
1412   return sizeof (struct TransportRequestConnectMessage);
1413 }
1414
1415
1416 /**
1417  * Ask the transport service to establish a connection to
1418  * the given peer.
1419  *
1420  * @param handle connection to transport service
1421  * @param target who we should try to connect to
1422  * @param cb callback to be called when request was transmitted to transport
1423  *         service
1424  * @param cb_cls closure for the callback
1425  * @return a `struct GNUNET_TRANSPORT_TryConnectHandle` handle or
1426  *         NULL on failure (cb will not be called)
1427  */
1428 struct GNUNET_TRANSPORT_TryConnectHandle *
1429 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1430                               const struct GNUNET_PeerIdentity *target,
1431                               GNUNET_TRANSPORT_TryConnectCallback cb,
1432                               void *cb_cls)
1433 {
1434   struct GNUNET_TRANSPORT_TryConnectHandle *tch;
1435
1436   if (NULL == handle->client)
1437     return NULL;
1438   tch = GNUNET_new (struct GNUNET_TRANSPORT_TryConnectHandle);
1439   tch->th = handle;
1440   tch->pid = *target;
1441   tch->cb = cb;
1442   tch->cb_cls = cb_cls;
1443   tch->tth = schedule_control_transmit (handle,
1444                                         sizeof (struct TransportRequestConnectMessage),
1445                                         &send_try_connect, tch);
1446   GNUNET_CONTAINER_DLL_insert (handle->tc_head,
1447                                handle->tc_tail,
1448                                tch);
1449   return tch;
1450 }
1451
1452
1453 /**
1454  * Cancel the request to transport to try a connect
1455  * Callback will not be called
1456  *
1457  * @param tch the handle to cancel
1458  */
1459 void
1460 GNUNET_TRANSPORT_try_connect_cancel (struct GNUNET_TRANSPORT_TryConnectHandle *tch)
1461 {
1462   struct GNUNET_TRANSPORT_Handle *th;
1463
1464   th = tch->th;
1465   if (NULL != tch->tth)
1466     cancel_control_transmit (th, tch->tth);
1467   GNUNET_CONTAINER_DLL_remove (th->tc_head,
1468                                th->tc_tail,
1469                                tch);
1470   GNUNET_free (tch);
1471 }
1472
1473
1474 /**
1475  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT message to the
1476  * service.
1477  *
1478  * @param cls the `struct GNUNET_TRANSPORT_TryDisconnectHandle`
1479  * @param size number of bytes available in @a buf
1480  * @param buf where to copy the message
1481  * @return number of bytes copied to @a buf
1482  */
1483 static size_t
1484 send_try_disconnect (void *cls,
1485                      size_t size,
1486                      void *buf)
1487 {
1488   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh = cls;
1489   struct TransportRequestConnectMessage msg;
1490
1491   tdh->th = NULL;
1492   if (NULL == buf)
1493   {
1494     LOG (GNUNET_ERROR_TYPE_DEBUG,
1495          "Discarding  `%s' request to `%s' due to error in transport service connection.\n",
1496          "REQUEST_DISCONNECT",
1497          GNUNET_i2s (&tdh->pid));
1498     if (NULL != tdh->cb)
1499       tdh->cb (tdh->cb_cls,
1500                GNUNET_SYSERR);
1501     GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1502     return 0;
1503   }
1504   LOG (GNUNET_ERROR_TYPE_DEBUG,
1505        "Transmitting `%s' request with respect to `%s'.\n",
1506        "REQUEST_DISCONNECT",
1507        GNUNET_i2s (&tdh->pid));
1508   GNUNET_assert (size >= sizeof (struct TransportRequestDisconnectMessage));
1509   msg.header.size = htons (sizeof (struct TransportRequestDisconnectMessage));
1510   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT);
1511   msg.reserved = htonl (0);
1512   msg.peer = tdh->pid;
1513   memcpy (buf, &msg, sizeof (msg));
1514   if (NULL != tdh->cb)
1515     tdh->cb (tdh->cb_cls, GNUNET_OK);
1516   GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1517   return sizeof (struct TransportRequestDisconnectMessage);
1518 }
1519
1520
1521 /**
1522  * Ask the transport service to shutdown a connection to
1523  * the given peer.
1524  *
1525  * @param handle connection to transport service
1526  * @param target who we should try to connect to
1527  * @param cb callback to be called when request was transmitted to transport
1528  *         service
1529  * @param cb_cls closure for the callback @a cb
1530  * @return a `struct GNUNET_TRANSPORT_TryDisconnectHandle` handle or
1531  *         NULL on failure (cb will not be called)
1532  */
1533 struct GNUNET_TRANSPORT_TryDisconnectHandle *
1534 GNUNET_TRANSPORT_try_disconnect (struct GNUNET_TRANSPORT_Handle *handle,
1535                                  const struct GNUNET_PeerIdentity *target,
1536                                  GNUNET_TRANSPORT_TryDisconnectCallback cb,
1537                                  void *cb_cls)
1538 {
1539   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh;
1540
1541   if (NULL == handle->client)
1542     return NULL;
1543   tdh = GNUNET_new (struct GNUNET_TRANSPORT_TryDisconnectHandle);
1544   tdh->th = handle;
1545   tdh->pid = *target;
1546   tdh->cb = cb;
1547   tdh->cb_cls = cb_cls;
1548   tdh->tth = schedule_control_transmit (handle,
1549                                         sizeof (struct TransportRequestDisconnectMessage),
1550                                         &send_try_disconnect, tdh);
1551   GNUNET_CONTAINER_DLL_insert (handle->td_head,
1552                                handle->td_tail,
1553                                tdh);
1554   return tdh;
1555 }
1556
1557
1558 /**
1559  * Cancel the request to transport to try a disconnect
1560  * Callback will not be called
1561  *
1562  * @param tdh the handle to cancel
1563  */
1564 void
1565 GNUNET_TRANSPORT_try_disconnect_cancel (struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh)
1566 {
1567   struct GNUNET_TRANSPORT_Handle *th;
1568
1569   th = tdh->th;
1570   if (NULL != tdh->tth)
1571     cancel_control_transmit (th, tdh->tth);
1572   GNUNET_CONTAINER_DLL_remove (th->td_head,
1573                                th->td_tail,
1574                                tdh);
1575   GNUNET_free (tdh);
1576 }
1577
1578
1579 /**
1580  * Send HELLO message to the service.
1581  *
1582  * @param cls the HELLO message to send
1583  * @param size number of bytes available in @a buf
1584  * @param buf where to copy the message
1585  * @return number of bytes copied to @a buf
1586  */
1587 static size_t
1588 send_hello (void *cls,
1589             size_t size,
1590             void *buf)
1591 {
1592   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh = cls;
1593   struct GNUNET_MessageHeader *msg = ohh->msg;
1594   uint16_t ssize;
1595   struct GNUNET_SCHEDULER_TaskContext tc;
1596
1597   tc.read_ready = NULL;
1598   tc.write_ready = NULL;
1599   tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
1600   if (NULL == buf)
1601   {
1602     LOG (GNUNET_ERROR_TYPE_DEBUG,
1603          "Timeout while trying to transmit `%s' request.\n",
1604          "HELLO");
1605     if (NULL != ohh->cont)
1606       ohh->cont (ohh->cls,
1607                  &tc);
1608     GNUNET_free (msg);
1609     GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head,
1610                                  ohh->th->oh_tail,
1611                                  ohh);
1612     GNUNET_free (ohh);
1613     return 0;
1614   }
1615   LOG (GNUNET_ERROR_TYPE_DEBUG,
1616        "Transmitting `%s' request.\n",
1617        "HELLO");
1618   ssize = ntohs (msg->size);
1619   GNUNET_assert (size >= ssize);
1620   memcpy (buf,
1621           msg,
1622           ssize);
1623   GNUNET_free (msg);
1624   tc.reason = GNUNET_SCHEDULER_REASON_READ_READY;
1625   if (NULL != ohh->cont)
1626     ohh->cont (ohh->cls,
1627                &tc);
1628   GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head,
1629                                ohh->th->oh_tail,
1630                                ohh);
1631   GNUNET_free (ohh);
1632   return ssize;
1633 }
1634
1635
1636 /**
1637  * Send traffic metric message to the service.
1638  *
1639  * @param cls the message to send
1640  * @param size number of bytes available in @a buf
1641  * @param buf where to copy the message
1642  * @return number of bytes copied to @a buf
1643  */
1644 static size_t
1645 send_metric (void *cls,
1646              size_t size,
1647              void *buf)
1648 {
1649   struct TrafficMetricMessage *msg = cls;
1650   uint16_t ssize;
1651
1652   if (NULL == buf)
1653   {
1654     LOG (GNUNET_ERROR_TYPE_DEBUG,
1655          "Timeout while trying to transmit TRAFFIC_METRIC request.\n");
1656     GNUNET_free (msg);
1657     return 0;
1658   }
1659   LOG (GNUNET_ERROR_TYPE_DEBUG,
1660        "Transmitting TRAFFIC_METRIC request.\n");
1661   ssize = ntohs (msg->header.size);
1662   GNUNET_assert (size >= ssize);
1663   memcpy (buf, msg, ssize);
1664   GNUNET_free (msg);
1665   return ssize;
1666 }
1667
1668
1669 /**
1670  * Set transport metrics for a peer and a direction
1671  *
1672  * @param handle transport handle
1673  * @param peer the peer to set the metric for
1674  * @param prop the performance metrics to set
1675  * @param delay_in inbound delay to introduce
1676  * @param delay_out outbound delay to introduce
1677  *
1678  * Note: Delay restrictions in receiving direction will be enforced
1679  * with one message delay.
1680  */
1681 void
1682 GNUNET_TRANSPORT_set_traffic_metric (struct GNUNET_TRANSPORT_Handle *handle,
1683                                      const struct GNUNET_PeerIdentity *peer,
1684                                      const struct GNUNET_ATS_Properties *prop,
1685                                      struct GNUNET_TIME_Relative delay_in,
1686                                      struct GNUNET_TIME_Relative delay_out)
1687 {
1688   struct TrafficMetricMessage *msg;
1689
1690   msg = GNUNET_new (struct TrafficMetricMessage);
1691   msg->header.size = htons (sizeof (struct TrafficMetricMessage));
1692   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC);
1693   msg->reserved = htonl (0);
1694   msg->peer = *peer;
1695   GNUNET_ATS_properties_hton (&msg->properties,
1696                               prop);
1697   msg->delay_in = GNUNET_TIME_relative_hton (delay_in);
1698   msg->delay_out = GNUNET_TIME_relative_hton (delay_out);
1699   schedule_control_transmit (handle,
1700                              sizeof (struct TrafficMetricMessage),
1701                              &send_metric,
1702                              msg);
1703 }
1704
1705
1706 /**
1707  * Offer the transport service the HELLO of another peer.  Note that
1708  * the transport service may just ignore this message if the HELLO is
1709  * malformed or useless due to our local configuration.
1710  *
1711  * @param handle connection to transport service
1712  * @param hello the hello message
1713  * @param cont continuation to call when HELLO has been sent,
1714  *      tc reason #GNUNET_SCHEDULER_REASON_TIMEOUT for fail
1715  *      tc reasong #GNUNET_SCHEDULER_REASON_READ_READY for success
1716  * @param cls closure for continuation
1717  * @return a `struct GNUNET_TRANSPORT_OfferHelloHandle` handle or NULL on failure,
1718  *      in case of failure cont will not be called
1719  *
1720  */
1721 struct GNUNET_TRANSPORT_OfferHelloHandle *
1722 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1723                               const struct GNUNET_MessageHeader *hello,
1724                               GNUNET_SCHEDULER_TaskCallback cont,
1725                               void *cls)
1726 {
1727   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh;
1728   struct GNUNET_MessageHeader *msg;
1729   struct GNUNET_PeerIdentity peer;
1730   uint16_t size;
1731
1732   if (NULL == handle->client)
1733     return NULL;
1734   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1735   size = ntohs (hello->size);
1736   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1737   if (GNUNET_OK !=
1738       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello,
1739                            &peer))
1740   {
1741     GNUNET_break (0);
1742     return NULL;
1743   }
1744
1745   msg = GNUNET_malloc (size);
1746   memcpy (msg, hello, size);
1747   LOG (GNUNET_ERROR_TYPE_DEBUG,
1748        "Offering HELLO message of `%s' to transport for validation.\n",
1749        GNUNET_i2s (&peer));
1750
1751   ohh = GNUNET_new (struct GNUNET_TRANSPORT_OfferHelloHandle);
1752   ohh->th = handle;
1753   ohh->cont = cont;
1754   ohh->cls = cls;
1755   ohh->msg = msg;
1756   ohh->tth = schedule_control_transmit (handle, size,
1757                                         &send_hello, ohh);
1758   GNUNET_CONTAINER_DLL_insert (handle->oh_head, handle->oh_tail, ohh);
1759   return ohh;
1760 }
1761
1762
1763 /**
1764  * Cancel the request to transport to offer the HELLO message
1765  *
1766  * @param ohh the handle for the operation to cancel
1767  */
1768 void
1769 GNUNET_TRANSPORT_offer_hello_cancel (struct GNUNET_TRANSPORT_OfferHelloHandle *ohh)
1770 {
1771   struct GNUNET_TRANSPORT_Handle *th = ohh->th;
1772
1773   cancel_control_transmit (ohh->th, ohh->tth);
1774   GNUNET_CONTAINER_DLL_remove (th->oh_head,
1775                                th->oh_tail,
1776                                ohh);
1777   GNUNET_free (ohh->msg);
1778   GNUNET_free (ohh);
1779 }
1780
1781
1782 /**
1783  * Checks if a given peer is connected to us
1784  *
1785  * @param handle connection to transport service
1786  * @param peer the peer to check
1787  * @return #GNUNET_YES (connected) or #GNUNET_NO (disconnected)
1788  */
1789 int
1790 GNUNET_TRANSPORT_check_peer_connected (struct GNUNET_TRANSPORT_Handle *handle,
1791                                        const struct GNUNET_PeerIdentity *peer)
1792 {
1793   if (GNUNET_YES ==
1794       GNUNET_CONTAINER_multipeermap_contains (handle->neighbours,
1795                                               peer))
1796     return GNUNET_YES;
1797   return GNUNET_NO;
1798 }
1799
1800
1801 /**
1802  * Task to call the HelloUpdateCallback of the GetHelloHandle
1803  *
1804  * @param cls the `struct GNUNET_TRANSPORT_GetHelloHandle`
1805  * @param tc the scheduler task context
1806  */
1807 static void
1808 call_hello_update_cb_async (void *cls,
1809                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1810 {
1811   struct GNUNET_TRANSPORT_GetHelloHandle *ghh = cls;
1812
1813   GNUNET_assert (NULL != ghh->handle->my_hello);
1814   GNUNET_assert (NULL != ghh->notify_task);
1815   ghh->notify_task = NULL;
1816   ghh->rec (ghh->rec_cls,
1817             ghh->handle->my_hello);
1818 }
1819
1820
1821 /**
1822  * Obtain the HELLO message for this peer.  The callback given in this function
1823  * is never called synchronously.
1824  *
1825  * @param handle connection to transport service
1826  * @param rec function to call with the HELLO, sender will be our peer
1827  *            identity; message and sender will be NULL on timeout
1828  *            (handshake with transport service pending/failed).
1829  *             cost estimate will be 0.
1830  * @param rec_cls closure for @a rec
1831  * @return handle to cancel the operation
1832  */
1833 struct GNUNET_TRANSPORT_GetHelloHandle *
1834 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1835                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1836                             void *rec_cls)
1837 {
1838   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1839
1840   hwl = GNUNET_new (struct GNUNET_TRANSPORT_GetHelloHandle);
1841   hwl->rec = rec;
1842   hwl->rec_cls = rec_cls;
1843   hwl->handle = handle;
1844   GNUNET_CONTAINER_DLL_insert (handle->hwl_head,
1845                                handle->hwl_tail,
1846                                hwl);
1847   if (NULL != handle->my_hello)
1848     hwl->notify_task = GNUNET_SCHEDULER_add_now (&call_hello_update_cb_async,
1849                                                  hwl);
1850   return hwl;
1851 }
1852
1853
1854 /**
1855  * Stop receiving updates about changes to our HELLO message.
1856  *
1857  * @param ghh handle to cancel
1858  */
1859 void
1860 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1861 {
1862   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1863
1864   if (NULL != ghh->notify_task)
1865     GNUNET_SCHEDULER_cancel (ghh->notify_task);
1866   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1867   GNUNET_free (ghh);
1868 }
1869
1870
1871 /**
1872  * Connect to the transport service.  Note that the connection may
1873  * complete (or fail) asynchronously.
1874  *
1875  * @param cfg configuration to use
1876  * @param self our own identity (API should check that it matches
1877  *             the identity found by transport), or NULL (no check)
1878  * @param cls closure for the callbacks
1879  * @param rec receive function to call
1880  * @param nc function to call on connect events
1881  * @param nd function to call on disconnect events
1882  * @return NULL on error
1883  */
1884 struct GNUNET_TRANSPORT_Handle *
1885 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1886                           const struct GNUNET_PeerIdentity *self,
1887                           void *cls,
1888                           GNUNET_TRANSPORT_ReceiveCallback rec,
1889                           GNUNET_TRANSPORT_NotifyConnect nc,
1890                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1891 {
1892   return GNUNET_TRANSPORT_connect2 (cfg,
1893                                     self,
1894                                     cls,
1895                                     rec,
1896                                     nc,
1897                                     nd,
1898                                     NULL);
1899 }
1900
1901
1902 /**
1903  * Connect to the transport service.  Note that the connection may
1904  * complete (or fail) asynchronously.
1905  *
1906  * @param cfg configuration to use
1907  * @param self our own identity (API should check that it matches
1908  *             the identity found by transport), or NULL (no check)
1909  * @param cls closure for the callbacks
1910  * @param rec receive function to call
1911  * @param nc function to call on connect events
1912  * @param nd function to call on disconnect events
1913  * @param neb function to call if we have excess bandwidth to a peer
1914  * @return NULL on error
1915  */
1916 struct GNUNET_TRANSPORT_Handle *
1917 GNUNET_TRANSPORT_connect2 (const struct GNUNET_CONFIGURATION_Handle *cfg,
1918                            const struct GNUNET_PeerIdentity *self,
1919                            void *cls,
1920                            GNUNET_TRANSPORT_ReceiveCallback rec,
1921                            GNUNET_TRANSPORT_NotifyConnect nc,
1922                            GNUNET_TRANSPORT_NotifyDisconnect nd,
1923                            GNUNET_TRANSPORT_NotifyExcessBandwidth neb)
1924 {
1925   struct GNUNET_TRANSPORT_Handle *ret;
1926
1927   ret = GNUNET_new (struct GNUNET_TRANSPORT_Handle);
1928   if (NULL != self)
1929   {
1930     ret->self = *self;
1931     ret->check_self = GNUNET_YES;
1932   }
1933   ret->cfg = cfg;
1934   ret->cls = cls;
1935   ret->rec = rec;
1936   ret->nc_cb = nc;
1937   ret->nd_cb = nd;
1938   ret->neb_cb = neb;
1939   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1940   LOG (GNUNET_ERROR_TYPE_DEBUG,
1941        "Connecting to transport service.\n");
1942   ret->client = GNUNET_CLIENT_connect ("transport",
1943                                        cfg);
1944   if (NULL == ret->client)
1945   {
1946     GNUNET_free (ret);
1947     return NULL;
1948   }
1949   ret->neighbours =
1950     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
1951                                           GNUNET_YES);
1952   ret->ready_heap =
1953       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1954   schedule_control_transmit (ret,
1955                              sizeof (struct StartMessage),
1956                              &send_start,
1957                              ret);
1958   return ret;
1959 }
1960
1961
1962 /**
1963  * Disconnect from the transport service.
1964  *
1965  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_connect()
1966  */
1967 void
1968 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1969 {
1970   LOG (GNUNET_ERROR_TYPE_DEBUG,
1971        "Transport disconnect called!\n");
1972   /* this disconnects all neighbours... */
1973   if (NULL == handle->reconnect_task)
1974     disconnect_and_schedule_reconnect (handle);
1975   /* and now we stop trying to connect again... */
1976   if (NULL != handle->reconnect_task)
1977   {
1978     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1979     handle->reconnect_task = NULL;
1980   }
1981   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
1982   handle->neighbours = NULL;
1983   if (NULL != handle->quota_task)
1984   {
1985     GNUNET_SCHEDULER_cancel (handle->quota_task);
1986     handle->quota_task = NULL;
1987   }
1988   GNUNET_free_non_null (handle->my_hello);
1989   handle->my_hello = NULL;
1990   GNUNET_assert (NULL == handle->tc_head);
1991   GNUNET_assert (NULL == handle->tc_tail);
1992   GNUNET_assert (NULL == handle->hwl_head);
1993   GNUNET_assert (NULL == handle->hwl_tail);
1994   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1995   handle->ready_heap = NULL;
1996   GNUNET_free (handle);
1997 }
1998
1999
2000 /**
2001  * Check if we could queue a message of the given size for
2002  * transmission.  The transport service will take both its
2003  * internal buffers and bandwidth limits imposed by the
2004  * other peer into consideration when answering this query.
2005  *
2006  * @param handle connection to transport service
2007  * @param target who should receive the message
2008  * @param size how big is the message we want to transmit?
2009  * @param timeout after how long should we give up (and call
2010  *        notify with buf NULL and size 0)?
2011  * @param notify function to call when we are ready to
2012  *        send such a message
2013  * @param notify_cls closure for @a notify
2014  * @return NULL if someone else is already waiting to be notified
2015  *         non-NULL if the notify callback was queued (can be used to cancel
2016  *         using #GNUNET_TRANSPORT_notify_transmit_ready_cancel)
2017  */
2018 struct GNUNET_TRANSPORT_TransmitHandle *
2019 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
2020                                         const struct GNUNET_PeerIdentity *target,
2021                                         size_t size,
2022                                         struct GNUNET_TIME_Relative timeout,
2023                                         GNUNET_TRANSPORT_TransmitReadyNotify notify,
2024                                         void *notify_cls)
2025 {
2026   struct Neighbour *n;
2027   struct GNUNET_TRANSPORT_TransmitHandle *th;
2028   struct GNUNET_TIME_Relative delay;
2029
2030   n = neighbour_find (handle, target);
2031   if (NULL == n)
2032   {
2033     /* use GNUNET_TRANSPORT_try_connect first, only use this function
2034      * once a connection has been established */
2035     GNUNET_assert (0);
2036     return NULL;
2037   }
2038   if (NULL != n->th)
2039   {
2040     /* attempt to send two messages at the same time to the same peer */
2041     GNUNET_assert (0);
2042     return NULL;
2043   }
2044   GNUNET_assert (NULL == n->hn);
2045   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
2046   th->neighbour = n;
2047   th->notify = notify;
2048   th->notify_cls = notify_cls;
2049   th->request_start = GNUNET_TIME_absolute_get ();
2050   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2051   th->notify_size = size;
2052   n->th = th;
2053   /* calculate when our transmission should be ready */
2054   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
2055                                               size + n->traffic_overhead);
2056   n->traffic_overhead = 0;
2057   if (delay.rel_value_us > timeout.rel_value_us)
2058     delay.rel_value_us = 0;        /* notify immediately (with failure) */
2059   if (delay.rel_value_us > GNUNET_TIME_UNIT_SECONDS.rel_value_us)
2060     LOG (GNUNET_ERROR_TYPE_WARNING,
2061          "At bandwidth %u byte/s next transmission to %s in %s\n",
2062          (unsigned int) n->out_tracker.available_bytes_per_s__,
2063          GNUNET_i2s (target),
2064          GNUNET_STRINGS_relative_time_to_string (delay,
2065                                                  GNUNET_YES));
2066   else
2067     LOG (GNUNET_ERROR_TYPE_DEBUG,
2068          "At bandwidth %u byte/s next transmission to %s in %s\n",
2069          (unsigned int) n->out_tracker.available_bytes_per_s__,
2070          GNUNET_i2s (target),
2071          GNUNET_STRINGS_relative_time_to_string (delay,
2072                                                  GNUNET_YES));
2073   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap,
2074                                         n,
2075                                         delay.rel_value_us);
2076   schedule_transmission (handle);
2077   return th;
2078 }
2079
2080
2081 /**
2082  * Cancel the specified transmission-ready notification.
2083  *
2084  * @param th handle returned from #GNUNET_TRANSPORT_notify_transmit_ready()
2085  */
2086 void
2087 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct GNUNET_TRANSPORT_TransmitHandle *th)
2088 {
2089   struct Neighbour *n;
2090
2091   GNUNET_assert (NULL == th->next);
2092   GNUNET_assert (NULL == th->prev);
2093   n = th->neighbour;
2094   GNUNET_assert (th == n->th);
2095   n->th = NULL;
2096   if (NULL != n->hn)
2097   {
2098     GNUNET_CONTAINER_heap_remove_node (n->hn);
2099     n->hn = NULL;
2100   }
2101   else
2102   {
2103     GNUNET_assert (NULL != th->timeout_task);
2104     GNUNET_SCHEDULER_cancel (th->timeout_task);
2105     th->timeout_task = NULL;
2106   }
2107   GNUNET_free (th);
2108 }
2109
2110
2111 /* end of transport_api.c */