-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       h->reconnecting = GNUNET_YES;
747       disconnect_and_schedule_reconnect (h);
748       break;
749     }
750     cim = (const struct ConnectInfoMessage *) msg;
751     if (size !=
752         sizeof (struct ConnectInfoMessage))
753     {
754       GNUNET_break (0);
755       h->reconnecting = GNUNET_YES;
756       disconnect_and_schedule_reconnect (h);
757       break;
758     }
759     LOG (GNUNET_ERROR_TYPE_DEBUG,
760          "Receiving CONNECT message for `%s'.\n",
761          GNUNET_i2s (&cim->id));
762     n = neighbour_find (h, &cim->id);
763     if (NULL != n)
764     {
765       GNUNET_break (0);
766       h->reconnecting = GNUNET_YES;
767       disconnect_and_schedule_reconnect (h);
768       break;
769     }
770     n = neighbour_add (h,
771                        &cim->id);
772     LOG (GNUNET_ERROR_TYPE_DEBUG,
773          "Receiving CONNECT message for `%s' with quota %u\n",
774          GNUNET_i2s (&cim->id),
775          ntohl (cim->quota_out.value__));
776     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
777                                            cim->quota_out);
778     if (NULL != h->nc_cb)
779       h->nc_cb (h->cls,
780                 &n->id);
781     break;
782   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
783     if (size != sizeof (struct DisconnectInfoMessage))
784     {
785       GNUNET_break (0);
786       h->reconnecting = GNUNET_YES;
787       disconnect_and_schedule_reconnect (h);
788       break;
789     }
790     dim = (const struct DisconnectInfoMessage *) msg;
791     GNUNET_break (ntohl (dim->reserved) == 0);
792     LOG (GNUNET_ERROR_TYPE_DEBUG,
793          "Receiving DISCONNECT message for `%s'.\n",
794          GNUNET_i2s (&dim->peer));
795     n = neighbour_find (h, &dim->peer);
796     if (NULL == n)
797     {
798       GNUNET_break (0);
799       h->reconnecting = GNUNET_YES;
800       disconnect_and_schedule_reconnect (h);
801       break;
802     }
803     neighbour_delete (h,
804                       &dim->peer,
805                       n);
806     break;
807   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
808     if (size != sizeof (struct SendOkMessage))
809     {
810       GNUNET_break (0);
811       h->reconnecting = GNUNET_YES;
812       disconnect_and_schedule_reconnect (h);
813       break;
814     }
815     okm = (const struct SendOkMessage *) msg;
816     bytes_msg = ntohl (okm->bytes_msg);
817     bytes_physical = ntohl (okm->bytes_physical);
818     LOG (GNUNET_ERROR_TYPE_DEBUG,
819          "Receiving SEND_OK message, transmission %s.\n",
820          ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
821
822     n = neighbour_find (h,
823                         &okm->peer);
824     if (NULL == n)
825     {
826       /* We should never get a 'SEND_OK' for a peer that we are not
827          connected to */
828       GNUNET_break (0);
829       h->reconnecting = GNUNET_YES;
830       disconnect_and_schedule_reconnect (h);
831       break;
832     }
833     if (bytes_physical >= bytes_msg)
834     {
835       LOG (GNUNET_ERROR_TYPE_DEBUG,
836            "Overhead for %u byte message: %u\n",
837            bytes_msg,
838            bytes_physical - bytes_msg);
839       n->traffic_overhead += bytes_physical - bytes_msg;
840     }
841     GNUNET_break (GNUNET_NO == n->is_ready);
842     n->is_ready = GNUNET_YES;
843     if (NULL != n->unready_warn_task)
844     {
845       GNUNET_SCHEDULER_cancel (n->unready_warn_task);
846       n->unready_warn_task = NULL;
847     }
848     if ((NULL != n->th) && (NULL == n->hn))
849     {
850       GNUNET_assert (NULL != n->th->timeout_task);
851       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
852       n->th->timeout_task = NULL;
853       /* we've been waiting for this (congestion, not quota,
854        * caused delayed transmission) */
855       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
856       schedule_transmission (h);
857     }
858     break;
859   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
860     if (size <
861         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
862     {
863       GNUNET_break (0);
864       h->reconnecting = GNUNET_YES;
865       disconnect_and_schedule_reconnect (h);
866       break;
867     }
868     im = (const struct InboundMessage *) msg;
869     imm = (const struct GNUNET_MessageHeader *) &im[1];
870     if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
871     {
872       GNUNET_break (0);
873       h->reconnecting = GNUNET_YES;
874       disconnect_and_schedule_reconnect (h);
875       break;
876     }
877     LOG (GNUNET_ERROR_TYPE_DEBUG,
878          "Received message of type %u from `%s'.\n",
879          ntohs (imm->type), GNUNET_i2s (&im->peer));
880     n = neighbour_find (h, &im->peer);
881     if (NULL == n)
882     {
883       GNUNET_break (0);
884       h->reconnecting = GNUNET_YES;
885       disconnect_and_schedule_reconnect (h);
886       break;
887     }
888     if (NULL != h->rec)
889       h->rec (h->cls,
890               &im->peer,
891               imm);
892     break;
893   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
894     if (size != sizeof (struct QuotaSetMessage))
895     {
896       GNUNET_break (0);
897       h->reconnecting = GNUNET_YES;
898       disconnect_and_schedule_reconnect (h);
899       break;
900     }
901     qm = (const struct QuotaSetMessage *) msg;
902     n = neighbour_find (h, &qm->peer);
903     if (NULL == n)
904     {
905       GNUNET_break (0);
906       h->reconnecting = GNUNET_YES;
907       disconnect_and_schedule_reconnect (h);
908       break;
909     }
910     LOG (GNUNET_ERROR_TYPE_DEBUG,
911          "Receiving SET_QUOTA message for `%s' with quota %u\n",
912          GNUNET_i2s (&qm->peer),
913          ntohl (qm->quota.value__));
914     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
915                                            qm->quota);
916     break;
917   default:
918     LOG (GNUNET_ERROR_TYPE_ERROR,
919          _("Received unexpected message of type %u in %s:%u\n"),
920          ntohs (msg->type),
921          __FILE__,
922          __LINE__);
923     GNUNET_break (0);
924     break;
925   }
926 }
927
928
929 /**
930  * A transmission request could not be satisfied because of
931  * network congestion.  Notify the initiator and clean up.
932  *
933  * @param cls the `struct GNUNET_TRANSPORT_TransmitHandle`
934  * @param tc scheduler context
935  */
936 static void
937 timeout_request_due_to_congestion (void *cls,
938                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
939 {
940   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
941   struct Neighbour *n = th->neighbour;
942   struct GNUNET_TIME_Relative delay;
943
944   n->th->timeout_task = NULL;
945   delay = GNUNET_TIME_absolute_get_duration (th->request_start);
946   LOG (GNUNET_ERROR_TYPE_WARNING,
947        "Discarding %u bytes of payload message after %s delay due to congestion\n",
948        th->notify_size,
949        GNUNET_STRINGS_relative_time_to_string (delay,
950                                                GNUNET_YES));
951   GNUNET_assert (th == n->th);
952   GNUNET_assert (NULL == n->hn);
953   n->th = NULL;
954   th->notify (th->notify_cls,
955               0,
956               NULL);
957   GNUNET_free (th);
958 }
959
960
961 /**
962  * Transmit message(s) to service.
963  *
964  * @param cls handle to transport
965  * @param size number of bytes available in @a buf
966  * @param buf where to copy the message
967  * @return number of bytes copied to @a buf
968  */
969 static size_t
970 transport_notify_ready (void *cls,
971                         size_t size,
972                         void *buf)
973 {
974   struct GNUNET_TRANSPORT_Handle *h = cls;
975   struct GNUNET_TRANSPORT_TransmitHandle *th;
976   struct GNUNET_TIME_Relative delay;
977   struct Neighbour *n;
978   char *cbuf;
979   struct OutboundMessage obm;
980   size_t ret;
981   size_t nret;
982   size_t mret;
983
984   GNUNET_assert (NULL != h->client);
985   h->cth = NULL;
986   if (NULL == buf)
987   {
988     /* transmission failed */
989     disconnect_and_schedule_reconnect (h);
990     return 0;
991   }
992
993   cbuf = buf;
994   ret = 0;
995   /* first send control messages */
996   while ( (NULL != (th = h->control_head)) &&
997           (th->notify_size <= size) )
998   {
999     GNUNET_CONTAINER_DLL_remove (h->control_head,
1000                                  h->control_tail,
1001                                  th);
1002     nret = th->notify (th->notify_cls,
1003                        size,
1004                        &cbuf[ret]);
1005     delay = GNUNET_TIME_absolute_get_duration (th->request_start);
1006     if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
1007       LOG (GNUNET_ERROR_TYPE_WARNING,
1008            "Added %u bytes of control message at %u after %s delay\n",
1009            nret,
1010            ret,
1011            GNUNET_STRINGS_relative_time_to_string (delay,
1012                                                    GNUNET_YES));
1013     else
1014       LOG (GNUNET_ERROR_TYPE_DEBUG,
1015            "Added %u bytes of control message at %u after %s delay\n",
1016            nret,
1017            ret,
1018            GNUNET_STRINGS_relative_time_to_string (delay,
1019                                                    GNUNET_YES));
1020     GNUNET_free (th);
1021     ret += nret;
1022     size -= nret;
1023   }
1024
1025   /* then, if possible and no control messages pending, send data messages */
1026   while ( (NULL == h->control_head) &&
1027           (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) )
1028   {
1029     if (GNUNET_YES != n->is_ready)
1030     {
1031       /* peer not ready, wait for notification! */
1032       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1033       n->hn = NULL;
1034       GNUNET_assert (NULL == n->th->timeout_task);
1035       n->th->timeout_task
1036         = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1037                                         (n->th->timeout),
1038                                         &timeout_request_due_to_congestion,
1039                                         n->th);
1040       continue;
1041     }
1042     th = n->th;
1043     if (th->notify_size + sizeof (struct OutboundMessage) > size)
1044       break;                    /* does not fit */
1045     if (GNUNET_BANDWIDTH_tracker_get_delay
1046         (&n->out_tracker, th->notify_size).rel_value_us > 0)
1047       break;                    /* too early */
1048     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1049     n->hn = NULL;
1050     n->th = NULL;
1051     GNUNET_assert (size >= sizeof (struct OutboundMessage));
1052     mret = th->notify (th->notify_cls,
1053                        size - sizeof (struct OutboundMessage),
1054                        &cbuf[ret + sizeof (struct OutboundMessage)]);
1055     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
1056     if (0 == mret)
1057     {
1058       GNUNET_free (th);
1059       continue;
1060     }
1061     if (NULL != n->unready_warn_task)
1062       n->unready_warn_task
1063         = GNUNET_SCHEDULER_add_delayed (UNREADY_WARN_TIME,
1064                                         &do_warn_unready,
1065                                         n);
1066     n->last_payload = GNUNET_TIME_absolute_get ();
1067     n->is_ready = GNUNET_NO;
1068     GNUNET_assert (mret + sizeof (struct OutboundMessage) <
1069                    GNUNET_SERVER_MAX_MESSAGE_SIZE);
1070     obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
1071     obm.header.size = htons (mret + sizeof (struct OutboundMessage));
1072     obm.reserved = htonl (0);
1073     obm.timeout =
1074       GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
1075                                  (th->timeout));
1076     obm.peer = n->id;
1077     memcpy (&cbuf[ret],
1078             &obm,
1079             sizeof (struct OutboundMessage));
1080     ret += (mret + sizeof (struct OutboundMessage));
1081     size -= (mret + sizeof (struct OutboundMessage));
1082     GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker,
1083                                       mret);
1084     delay = GNUNET_TIME_absolute_get_duration (th->request_start);
1085     if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
1086       LOG (GNUNET_ERROR_TYPE_WARNING,
1087            "Added %u bytes of payload message for %s after %s delay at %u b/s\n",
1088            mret,
1089            GNUNET_i2s (&n->id),
1090            GNUNET_STRINGS_relative_time_to_string (delay,
1091                                                    GNUNET_YES),
1092            (unsigned int) n->out_tracker.available_bytes_per_s__);
1093     else
1094       LOG (GNUNET_ERROR_TYPE_DEBUG,
1095            "Added %u bytes of payload message for %s after %s delay at %u b/s\n",
1096            mret,
1097            GNUNET_i2s (&n->id),
1098            GNUNET_STRINGS_relative_time_to_string (delay,
1099                                                    GNUNET_YES),
1100            (unsigned int) n->out_tracker.available_bytes_per_s__);
1101     GNUNET_free (th);
1102     break;
1103   }
1104   /* if there are more pending messages, try to schedule those */
1105   schedule_transmission (h);
1106   LOG (GNUNET_ERROR_TYPE_DEBUG,
1107        "Transmitting %u bytes to transport service\n",
1108        ret);
1109   return ret;
1110 }
1111
1112
1113 /**
1114  * Schedule the task to send one message, either from the control
1115  * list or the peer message queues  to the service.
1116  *
1117  * @param cls transport service to schedule a transmission for
1118  * @param tc scheduler context
1119  */
1120 static void
1121 schedule_transmission_task (void *cls,
1122                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1123 {
1124   struct GNUNET_TRANSPORT_Handle *h = cls;
1125   size_t size;
1126   struct GNUNET_TRANSPORT_TransmitHandle *th;
1127   struct Neighbour *n;
1128
1129   h->quota_task = NULL;
1130   GNUNET_assert (NULL != h->client);
1131   /* destroy all requests that have timed out */
1132   while ( (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
1133           (0 == GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value_us) )
1134   {
1135     /* notify client that the request could not be satisfied within
1136      * the given time constraints */
1137     th = n->th;
1138     n->th = NULL;
1139     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
1140     n->hn = NULL;
1141     LOG (GNUNET_ERROR_TYPE_DEBUG,
1142          "Signalling timeout for transmission to peer %s due to congestion\n",
1143          GNUNET_i2s (&n->id));
1144     GNUNET_assert (0 == th->notify (th->notify_cls,
1145                                     0,
1146                                     NULL));
1147     GNUNET_free (th);
1148   }
1149   if (NULL != h->cth)
1150     return;
1151   if (NULL != h->control_head)
1152   {
1153     size = h->control_head->notify_size;
1154   }
1155   else
1156   {
1157     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
1158     if (NULL == n)
1159       return;                   /* no pending messages */
1160     size = n->th->notify_size + sizeof (struct OutboundMessage);
1161   }
1162   LOG (GNUNET_ERROR_TYPE_DEBUG,
1163        "Calling notify_transmit_ready\n");
1164   h->cth
1165     = GNUNET_CLIENT_notify_transmit_ready (h->client,
1166                                            size,
1167                                            GNUNET_TIME_UNIT_FOREVER_REL,
1168                                            GNUNET_NO,
1169                                            &transport_notify_ready,
1170                                            h);
1171   GNUNET_assert (NULL != h->cth);
1172 }
1173
1174
1175 /**
1176  * Schedule the task to send one message, either from the control
1177  * list or the peer message queues  to the service.
1178  *
1179  * @param h transport service to schedule a transmission for
1180  */
1181 static void
1182 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
1183 {
1184   struct GNUNET_TIME_Relative delay;
1185   struct Neighbour *n;
1186
1187   GNUNET_assert (NULL != h->client);
1188   if (NULL != h->quota_task)
1189   {
1190     GNUNET_SCHEDULER_cancel (h->quota_task);
1191     h->quota_task = NULL;
1192   }
1193   if (NULL != h->control_head)
1194     delay = GNUNET_TIME_UNIT_ZERO;
1195   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
1196   {
1197     delay =
1198         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
1199                                             n->th->notify_size + n->traffic_overhead);
1200     n->traffic_overhead = 0;
1201   }
1202   else
1203     return;                     /* no work to be done */
1204   LOG (GNUNET_ERROR_TYPE_DEBUG,
1205        "Scheduling next transmission to service in %s\n",
1206        GNUNET_STRINGS_relative_time_to_string (delay,
1207                                                GNUNET_YES));
1208   h->quota_task =
1209       GNUNET_SCHEDULER_add_delayed (delay,
1210                                     &schedule_transmission_task,
1211                                     h);
1212 }
1213
1214
1215 /**
1216  * Queue control request for transmission to the transport
1217  * service.
1218  *
1219  * @param h handle to the transport service
1220  * @param size number of bytes to be transmitted
1221  * @param notify function to call to get the content
1222  * @param notify_cls closure for @a notify
1223  * @return a `struct GNUNET_TRANSPORT_TransmitHandle`
1224  */
1225 static struct GNUNET_TRANSPORT_TransmitHandle *
1226 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h,
1227                            size_t size,
1228                            GNUNET_TRANSPORT_TransmitReadyNotify notify,
1229                            void *notify_cls)
1230 {
1231   struct GNUNET_TRANSPORT_TransmitHandle *th;
1232
1233   LOG (GNUNET_ERROR_TYPE_DEBUG,
1234        "Control transmit of %u bytes requested\n",
1235        size);
1236   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1237   th->notify = notify;
1238   th->notify_cls = notify_cls;
1239   th->notify_size = size;
1240   th->request_start = GNUNET_TIME_absolute_get ();
1241   GNUNET_CONTAINER_DLL_insert_tail (h->control_head,
1242                                     h->control_tail,
1243                                     th);
1244   schedule_transmission (h);
1245   return th;
1246 }
1247
1248
1249 /**
1250  * Transmit START message to service.
1251  *
1252  * @param cls unused
1253  * @param size number of bytes available in @a buf
1254  * @param buf where to copy the message
1255  * @return number of bytes copied to @a buf
1256  */
1257 static size_t
1258 send_start (void *cls,
1259             size_t size,
1260             void *buf)
1261 {
1262   struct GNUNET_TRANSPORT_Handle *h = cls;
1263   struct StartMessage s;
1264   uint32_t options;
1265
1266   if (NULL == buf)
1267   {
1268     /* Can only be shutdown, just give up */
1269     LOG (GNUNET_ERROR_TYPE_DEBUG,
1270          "Shutdown while trying to transmit START request.\n");
1271     return 0;
1272   }
1273   LOG (GNUNET_ERROR_TYPE_DEBUG,
1274        "Transmitting START request.\n");
1275   GNUNET_assert (size >= sizeof (struct StartMessage));
1276   s.header.size = htons (sizeof (struct StartMessage));
1277   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
1278   options = 0;
1279   if (h->check_self)
1280     options |= 1;
1281   if (NULL != h->rec)
1282     options |= 2;
1283   s.options = htonl (options);
1284   s.self = h->self;
1285   memcpy (buf, &s, sizeof (struct StartMessage));
1286   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
1287                          GNUNET_TIME_UNIT_FOREVER_REL);
1288   return sizeof (struct StartMessage);
1289 }
1290
1291
1292 /**
1293  * Try again to connect to transport service.
1294  *
1295  * @param cls the handle to the transport service
1296  * @param tc scheduler context
1297  */
1298 static void
1299 reconnect (void *cls,
1300            const struct GNUNET_SCHEDULER_TaskContext *tc)
1301 {
1302   struct GNUNET_TRANSPORT_Handle *h = cls;
1303
1304   h->reconnect_task = NULL;
1305   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1306   {
1307     /* shutdown, just give up */
1308     return;
1309   }
1310   LOG (GNUNET_ERROR_TYPE_DEBUG,
1311        "Connecting to transport service.\n");
1312   GNUNET_assert (NULL == h->client);
1313   GNUNET_assert (NULL == h->control_head);
1314   GNUNET_assert (NULL == h->control_tail);
1315   h->reconnecting = GNUNET_NO;
1316   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1317
1318   GNUNET_assert (NULL != h->client);
1319   schedule_control_transmit (h, sizeof (struct StartMessage),
1320                              &send_start, h);
1321 }
1322
1323
1324 /**
1325  * Function that will schedule the job that will try
1326  * to connect us again to the client.
1327  *
1328  * @param h transport service to reconnect
1329  */
1330 static void
1331 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1332 {
1333   struct GNUNET_TRANSPORT_TransmitHandle *th;
1334
1335   GNUNET_assert (NULL == h->reconnect_task);
1336   if (NULL != h->cth)
1337   {
1338     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1339     h->cth = NULL;
1340   }
1341   if (NULL != h->client)
1342   {
1343     GNUNET_CLIENT_disconnect (h->client);
1344     h->client = NULL;
1345 /*    LOG (GNUNET_ERROR_TYPE_ERROR,
1346          "Client disconnect done \n");*/
1347   }
1348   /* Forget about all neighbours that we used to be connected to */
1349   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
1350                                          &neighbour_delete,
1351                                          h);
1352   if (NULL != h->quota_task)
1353   {
1354     GNUNET_SCHEDULER_cancel (h->quota_task);
1355     h->quota_task = NULL;
1356   }
1357   while ((NULL != (th = h->control_head)))
1358   {
1359     GNUNET_CONTAINER_DLL_remove (h->control_head,
1360                                  h->control_tail,
1361                                  th);
1362     th->notify (th->notify_cls,
1363                 0,
1364                 NULL);
1365     GNUNET_free (th);
1366   }
1367   LOG (GNUNET_ERROR_TYPE_DEBUG,
1368        "Scheduling task to reconnect to transport service in %s.\n",
1369        GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay,
1370                                                GNUNET_YES));
1371   h->reconnect_task =
1372       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
1373                                     &reconnect,
1374                                     h);
1375   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
1376 }
1377
1378
1379 /**
1380  * Cancel control request for transmission to the transport service.
1381  *
1382  * @param th handle to the transport service
1383  * @param tth transmit handle to cancel
1384  */
1385 static void
1386 cancel_control_transmit (struct GNUNET_TRANSPORT_Handle *th,
1387                          struct GNUNET_TRANSPORT_TransmitHandle *tth)
1388 {
1389   LOG (GNUNET_ERROR_TYPE_DEBUG,
1390        "Canceling transmit of contral transmission requested\n");
1391   GNUNET_CONTAINER_DLL_remove (th->control_head,
1392                                th->control_tail,
1393                                tth);
1394   GNUNET_free (tth);
1395 }
1396
1397
1398 /**
1399  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT message to the
1400  * service.
1401  *
1402  * @param cls the `struct GNUNET_TRANSPORT_TryConnectHandle`
1403  * @param size number of bytes available in @a buf
1404  * @param buf where to copy the message
1405  * @return number of bytes copied to @a buf
1406  */
1407 static size_t
1408 send_try_connect (void *cls,
1409                   size_t size,
1410                   void *buf)
1411 {
1412   struct GNUNET_TRANSPORT_TryConnectHandle *tch = cls;
1413   struct TransportRequestConnectMessage msg;
1414
1415   tch->tth = NULL;
1416   if (NULL == buf)
1417   {
1418     LOG (GNUNET_ERROR_TYPE_DEBUG,
1419          "Discarding  `%s' request to `%s' due to error in transport service connection.\n",
1420          "REQUEST_CONNECT",
1421          GNUNET_i2s (&tch->pid));
1422     if (NULL != tch->cb)
1423       tch->cb (tch->cb_cls,
1424                GNUNET_SYSERR);
1425     GNUNET_TRANSPORT_try_connect_cancel (tch);
1426     return 0;
1427   }
1428   LOG (GNUNET_ERROR_TYPE_DEBUG,
1429        "Transmitting `%s' request with respect to `%s'.\n",
1430        "REQUEST_CONNECT",
1431        GNUNET_i2s (&tch->pid));
1432   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1433   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1434   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1435   msg.reserved = htonl (0);
1436   msg.peer = tch->pid;
1437   memcpy (buf, &msg, sizeof (msg));
1438   if (NULL != tch->cb)
1439     tch->cb (tch->cb_cls, GNUNET_OK);
1440   GNUNET_TRANSPORT_try_connect_cancel (tch);
1441   return sizeof (struct TransportRequestConnectMessage);
1442 }
1443
1444
1445 /**
1446  * Ask the transport service to establish a connection to
1447  * the given peer.
1448  *
1449  * @param handle connection to transport service
1450  * @param target who we should try to connect to
1451  * @param cb callback to be called when request was transmitted to transport
1452  *         service
1453  * @param cb_cls closure for the callback
1454  * @return a `struct GNUNET_TRANSPORT_TryConnectHandle` handle or
1455  *         NULL on failure (cb will not be called)
1456  */
1457 struct GNUNET_TRANSPORT_TryConnectHandle *
1458 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1459                               const struct GNUNET_PeerIdentity *target,
1460                               GNUNET_TRANSPORT_TryConnectCallback cb,
1461                               void *cb_cls)
1462 {
1463   struct GNUNET_TRANSPORT_TryConnectHandle *tch;
1464
1465   if (NULL == handle->client)
1466     return NULL;
1467   tch = GNUNET_new (struct GNUNET_TRANSPORT_TryConnectHandle);
1468   tch->th = handle;
1469   tch->pid = *target;
1470   tch->cb = cb;
1471   tch->cb_cls = cb_cls;
1472   tch->tth = schedule_control_transmit (handle,
1473                                         sizeof (struct TransportRequestConnectMessage),
1474                                         &send_try_connect, tch);
1475   GNUNET_CONTAINER_DLL_insert (handle->tc_head,
1476                                handle->tc_tail,
1477                                tch);
1478   return tch;
1479 }
1480
1481
1482 /**
1483  * Cancel the request to transport to try a connect
1484  * Callback will not be called
1485  *
1486  * @param tch the handle to cancel
1487  */
1488 void
1489 GNUNET_TRANSPORT_try_connect_cancel (struct GNUNET_TRANSPORT_TryConnectHandle *tch)
1490 {
1491   struct GNUNET_TRANSPORT_Handle *th;
1492
1493   th = tch->th;
1494   if (NULL != tch->tth)
1495     cancel_control_transmit (th, tch->tth);
1496   GNUNET_CONTAINER_DLL_remove (th->tc_head,
1497                                th->tc_tail,
1498                                tch);
1499   GNUNET_free (tch);
1500 }
1501
1502
1503 /**
1504  * Send #GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT message to the
1505  * service.
1506  *
1507  * @param cls the `struct GNUNET_TRANSPORT_TryDisconnectHandle`
1508  * @param size number of bytes available in @a buf
1509  * @param buf where to copy the message
1510  * @return number of bytes copied to @a buf
1511  */
1512 static size_t
1513 send_try_disconnect (void *cls,
1514                      size_t size,
1515                      void *buf)
1516 {
1517   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh = cls;
1518   struct TransportRequestConnectMessage msg;
1519
1520   tdh->th = NULL;
1521   if (NULL == buf)
1522   {
1523     LOG (GNUNET_ERROR_TYPE_DEBUG,
1524          "Discarding  `%s' request to `%s' due to error in transport service connection.\n",
1525          "REQUEST_DISCONNECT",
1526          GNUNET_i2s (&tdh->pid));
1527     if (NULL != tdh->cb)
1528       tdh->cb (tdh->cb_cls,
1529                GNUNET_SYSERR);
1530     GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1531     return 0;
1532   }
1533   LOG (GNUNET_ERROR_TYPE_DEBUG,
1534        "Transmitting `%s' request with respect to `%s'.\n",
1535        "REQUEST_DISCONNECT",
1536        GNUNET_i2s (&tdh->pid));
1537   GNUNET_assert (size >= sizeof (struct TransportRequestDisconnectMessage));
1538   msg.header.size = htons (sizeof (struct TransportRequestDisconnectMessage));
1539   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_DISCONNECT);
1540   msg.reserved = htonl (0);
1541   msg.peer = tdh->pid;
1542   memcpy (buf, &msg, sizeof (msg));
1543   if (NULL != tdh->cb)
1544     tdh->cb (tdh->cb_cls, GNUNET_OK);
1545   GNUNET_TRANSPORT_try_disconnect_cancel (tdh);
1546   return sizeof (struct TransportRequestDisconnectMessage);
1547 }
1548
1549
1550 /**
1551  * Ask the transport service to shutdown a connection to
1552  * the given peer.
1553  *
1554  * @param handle connection to transport service
1555  * @param target who we should try to connect to
1556  * @param cb callback to be called when request was transmitted to transport
1557  *         service
1558  * @param cb_cls closure for the callback @a cb
1559  * @return a `struct GNUNET_TRANSPORT_TryDisconnectHandle` handle or
1560  *         NULL on failure (cb will not be called)
1561  */
1562 struct GNUNET_TRANSPORT_TryDisconnectHandle *
1563 GNUNET_TRANSPORT_try_disconnect (struct GNUNET_TRANSPORT_Handle *handle,
1564                                  const struct GNUNET_PeerIdentity *target,
1565                                  GNUNET_TRANSPORT_TryDisconnectCallback cb,
1566                                  void *cb_cls)
1567 {
1568   struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh;
1569
1570   if (NULL == handle->client)
1571     return NULL;
1572   tdh = GNUNET_new (struct GNUNET_TRANSPORT_TryDisconnectHandle);
1573   tdh->th = handle;
1574   tdh->pid = *target;
1575   tdh->cb = cb;
1576   tdh->cb_cls = cb_cls;
1577   tdh->tth = schedule_control_transmit (handle,
1578                                         sizeof (struct TransportRequestDisconnectMessage),
1579                                         &send_try_disconnect, tdh);
1580   GNUNET_CONTAINER_DLL_insert (handle->td_head,
1581                                handle->td_tail,
1582                                tdh);
1583   return tdh;
1584 }
1585
1586
1587 /**
1588  * Cancel the request to transport to try a disconnect
1589  * Callback will not be called
1590  *
1591  * @param tdh the handle to cancel
1592  */
1593 void
1594 GNUNET_TRANSPORT_try_disconnect_cancel (struct GNUNET_TRANSPORT_TryDisconnectHandle *tdh)
1595 {
1596   struct GNUNET_TRANSPORT_Handle *th;
1597
1598   th = tdh->th;
1599   if (NULL != tdh->tth)
1600     cancel_control_transmit (th, tdh->tth);
1601   GNUNET_CONTAINER_DLL_remove (th->td_head,
1602                                th->td_tail,
1603                                tdh);
1604   GNUNET_free (tdh);
1605 }
1606
1607
1608 /**
1609  * Send HELLO message to the service.
1610  *
1611  * @param cls the HELLO message to send
1612  * @param size number of bytes available in @a buf
1613  * @param buf where to copy the message
1614  * @return number of bytes copied to @a buf
1615  */
1616 static size_t
1617 send_hello (void *cls,
1618             size_t size,
1619             void *buf)
1620 {
1621   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh = cls;
1622   struct GNUNET_MessageHeader *msg = ohh->msg;
1623   uint16_t ssize;
1624   struct GNUNET_SCHEDULER_TaskContext tc;
1625
1626   tc.read_ready = NULL;
1627   tc.write_ready = NULL;
1628   tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
1629   if (NULL == buf)
1630   {
1631     LOG (GNUNET_ERROR_TYPE_DEBUG,
1632          "Timeout while trying to transmit `%s' request.\n",
1633          "HELLO");
1634     if (NULL != ohh->cont)
1635       ohh->cont (ohh->cls,
1636                  &tc);
1637     GNUNET_free (msg);
1638     GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head,
1639                                  ohh->th->oh_tail,
1640                                  ohh);
1641     GNUNET_free (ohh);
1642     return 0;
1643   }
1644   LOG (GNUNET_ERROR_TYPE_DEBUG,
1645        "Transmitting `%s' request.\n",
1646        "HELLO");
1647   ssize = ntohs (msg->size);
1648   GNUNET_assert (size >= ssize);
1649   memcpy (buf,
1650           msg,
1651           ssize);
1652   GNUNET_free (msg);
1653   tc.reason = GNUNET_SCHEDULER_REASON_READ_READY;
1654   if (NULL != ohh->cont)
1655     ohh->cont (ohh->cls,
1656                &tc);
1657   GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head,
1658                                ohh->th->oh_tail,
1659                                ohh);
1660   GNUNET_free (ohh);
1661   return ssize;
1662 }
1663
1664
1665 /**
1666  * Send traffic metric message to the service.
1667  *
1668  * @param cls the message to send
1669  * @param size number of bytes available in @a buf
1670  * @param buf where to copy the message
1671  * @return number of bytes copied to @a buf
1672  */
1673 static size_t
1674 send_metric (void *cls,
1675              size_t size,
1676              void *buf)
1677 {
1678   struct TrafficMetricMessage *msg = cls;
1679   uint16_t ssize;
1680
1681   if (NULL == buf)
1682   {
1683     LOG (GNUNET_ERROR_TYPE_DEBUG,
1684          "Timeout while trying to transmit TRAFFIC_METRIC request.\n");
1685     GNUNET_free (msg);
1686     return 0;
1687   }
1688   LOG (GNUNET_ERROR_TYPE_DEBUG,
1689        "Transmitting TRAFFIC_METRIC request.\n");
1690   ssize = ntohs (msg->header.size);
1691   GNUNET_assert (size >= ssize);
1692   memcpy (buf, msg, ssize);
1693   GNUNET_free (msg);
1694   return ssize;
1695 }
1696
1697
1698 /**
1699  * Set transport metrics for a peer and a direction
1700  *
1701  * @param handle transport handle
1702  * @param peer the peer to set the metric for
1703  * @param prop the performance metrics to set
1704  * @param delay_in inbound delay to introduce
1705  * @param delay_out outbound delay to introduce
1706  *
1707  * Note: Delay restrictions in receiving direction will be enforced
1708  * with one message delay.
1709  */
1710 void
1711 GNUNET_TRANSPORT_set_traffic_metric (struct GNUNET_TRANSPORT_Handle *handle,
1712                                      const struct GNUNET_PeerIdentity *peer,
1713                                      const struct GNUNET_ATS_Properties *prop,
1714                                      struct GNUNET_TIME_Relative delay_in,
1715                                      struct GNUNET_TIME_Relative delay_out)
1716 {
1717   struct TrafficMetricMessage *msg;
1718
1719   msg = GNUNET_new (struct TrafficMetricMessage);
1720   msg->header.size = htons (sizeof (struct TrafficMetricMessage));
1721   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC);
1722   msg->reserved = htonl (0);
1723   msg->peer = *peer;
1724   GNUNET_ATS_properties_hton (&msg->properties,
1725                               prop);
1726   msg->delay_in = GNUNET_TIME_relative_hton (delay_in);
1727   msg->delay_out = GNUNET_TIME_relative_hton (delay_out);
1728   schedule_control_transmit (handle,
1729                              sizeof (struct TrafficMetricMessage),
1730                              &send_metric,
1731                              msg);
1732 }
1733
1734
1735 /**
1736  * Offer the transport service the HELLO of another peer.  Note that
1737  * the transport service may just ignore this message if the HELLO is
1738  * malformed or useless due to our local configuration.
1739  *
1740  * @param handle connection to transport service
1741  * @param hello the hello message
1742  * @param cont continuation to call when HELLO has been sent,
1743  *      tc reason #GNUNET_SCHEDULER_REASON_TIMEOUT for fail
1744  *      tc reasong #GNUNET_SCHEDULER_REASON_READ_READY for success
1745  * @param cont_cls closure for @a cont
1746  * @return a `struct GNUNET_TRANSPORT_OfferHelloHandle` handle or NULL on failure,
1747  *      in case of failure @a cont will not be called
1748  *
1749  */
1750 struct GNUNET_TRANSPORT_OfferHelloHandle *
1751 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1752                               const struct GNUNET_MessageHeader *hello,
1753                               GNUNET_SCHEDULER_TaskCallback cont,
1754                               void *cont_cls)
1755 {
1756   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh;
1757   struct GNUNET_MessageHeader *msg;
1758   struct GNUNET_PeerIdentity peer;
1759   uint16_t size;
1760
1761   if (NULL == handle->client)
1762     return NULL;
1763   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1764   size = ntohs (hello->size);
1765   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1766   if (GNUNET_OK !=
1767       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello,
1768                            &peer))
1769   {
1770     GNUNET_break (0);
1771     return NULL;
1772   }
1773
1774   msg = GNUNET_malloc (size);
1775   memcpy (msg, hello, size);
1776   LOG (GNUNET_ERROR_TYPE_DEBUG,
1777        "Offering HELLO message of `%s' to transport for validation.\n",
1778        GNUNET_i2s (&peer));
1779
1780   ohh = GNUNET_new (struct GNUNET_TRANSPORT_OfferHelloHandle);
1781   ohh->th = handle;
1782   ohh->cont = cont;
1783   ohh->cls = cont_cls;
1784   ohh->msg = msg;
1785   ohh->tth = schedule_control_transmit (handle,
1786                                         size,
1787                                         &send_hello,
1788                                         ohh);
1789   GNUNET_CONTAINER_DLL_insert (handle->oh_head,
1790                                handle->oh_tail,
1791                                ohh);
1792   return ohh;
1793 }
1794
1795
1796 /**
1797  * Cancel the request to transport to offer the HELLO message
1798  *
1799  * @param ohh the handle for the operation to cancel
1800  */
1801 void
1802 GNUNET_TRANSPORT_offer_hello_cancel (struct GNUNET_TRANSPORT_OfferHelloHandle *ohh)
1803 {
1804   struct GNUNET_TRANSPORT_Handle *th = ohh->th;
1805
1806   cancel_control_transmit (ohh->th, ohh->tth);
1807   GNUNET_CONTAINER_DLL_remove (th->oh_head,
1808                                th->oh_tail,
1809                                ohh);
1810   GNUNET_free (ohh->msg);
1811   GNUNET_free (ohh);
1812 }
1813
1814
1815 /**
1816  * Checks if a given peer is connected to us
1817  *
1818  * @param handle connection to transport service
1819  * @param peer the peer to check
1820  * @return #GNUNET_YES (connected) or #GNUNET_NO (disconnected)
1821  */
1822 int
1823 GNUNET_TRANSPORT_check_peer_connected (struct GNUNET_TRANSPORT_Handle *handle,
1824                                        const struct GNUNET_PeerIdentity *peer)
1825 {
1826   if (GNUNET_YES ==
1827       GNUNET_CONTAINER_multipeermap_contains (handle->neighbours,
1828                                               peer))
1829     return GNUNET_YES;
1830   return GNUNET_NO;
1831 }
1832
1833
1834 /**
1835  * Task to call the HelloUpdateCallback of the GetHelloHandle
1836  *
1837  * @param cls the `struct GNUNET_TRANSPORT_GetHelloHandle`
1838  * @param tc the scheduler task context
1839  */
1840 static void
1841 call_hello_update_cb_async (void *cls,
1842                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1843 {
1844   struct GNUNET_TRANSPORT_GetHelloHandle *ghh = cls;
1845
1846   GNUNET_assert (NULL != ghh->handle->my_hello);
1847   GNUNET_assert (NULL != ghh->notify_task);
1848   ghh->notify_task = NULL;
1849   ghh->rec (ghh->rec_cls,
1850             ghh->handle->my_hello);
1851 }
1852
1853
1854 /**
1855  * Obtain the HELLO message for this peer.  The callback given in this function
1856  * is never called synchronously.
1857  *
1858  * @param handle connection to transport service
1859  * @param rec function to call with the HELLO, sender will be our peer
1860  *            identity; message and sender will be NULL on timeout
1861  *            (handshake with transport service pending/failed).
1862  *             cost estimate will be 0.
1863  * @param rec_cls closure for @a rec
1864  * @return handle to cancel the operation
1865  */
1866 struct GNUNET_TRANSPORT_GetHelloHandle *
1867 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1868                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1869                             void *rec_cls)
1870 {
1871   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1872
1873   hwl = GNUNET_new (struct GNUNET_TRANSPORT_GetHelloHandle);
1874   hwl->rec = rec;
1875   hwl->rec_cls = rec_cls;
1876   hwl->handle = handle;
1877   GNUNET_CONTAINER_DLL_insert (handle->hwl_head,
1878                                handle->hwl_tail,
1879                                hwl);
1880   if (NULL != handle->my_hello)
1881     hwl->notify_task = GNUNET_SCHEDULER_add_now (&call_hello_update_cb_async,
1882                                                  hwl);
1883   return hwl;
1884 }
1885
1886
1887 /**
1888  * Stop receiving updates about changes to our HELLO message.
1889  *
1890  * @param ghh handle to cancel
1891  */
1892 void
1893 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1894 {
1895   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1896
1897   if (NULL != ghh->notify_task)
1898     GNUNET_SCHEDULER_cancel (ghh->notify_task);
1899   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1900   GNUNET_free (ghh);
1901 }
1902
1903
1904 /**
1905  * Connect to the transport service.  Note that the connection may
1906  * complete (or fail) asynchronously.
1907  *
1908  * @param cfg configuration to use
1909  * @param self our own identity (API should check that it matches
1910  *             the identity found by transport), or NULL (no check)
1911  * @param cls closure for the callbacks
1912  * @param rec receive function to call
1913  * @param nc function to call on connect events
1914  * @param nd function to call on disconnect events
1915  * @return NULL on error
1916  */
1917 struct GNUNET_TRANSPORT_Handle *
1918 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1919                           const struct GNUNET_PeerIdentity *self,
1920                           void *cls,
1921                           GNUNET_TRANSPORT_ReceiveCallback rec,
1922                           GNUNET_TRANSPORT_NotifyConnect nc,
1923                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1924 {
1925   return GNUNET_TRANSPORT_connect2 (cfg,
1926                                     self,
1927                                     cls,
1928                                     rec,
1929                                     nc,
1930                                     nd,
1931                                     NULL);
1932 }
1933
1934
1935 /**
1936  * Connect to the transport service.  Note that the connection may
1937  * complete (or fail) asynchronously.
1938  *
1939  * @param cfg configuration to use
1940  * @param self our own identity (API should check that it matches
1941  *             the identity found by transport), or NULL (no check)
1942  * @param cls closure for the callbacks
1943  * @param rec receive function to call
1944  * @param nc function to call on connect events
1945  * @param nd function to call on disconnect events
1946  * @param neb function to call if we have excess bandwidth to a peer
1947  * @return NULL on error
1948  */
1949 struct GNUNET_TRANSPORT_Handle *
1950 GNUNET_TRANSPORT_connect2 (const struct GNUNET_CONFIGURATION_Handle *cfg,
1951                            const struct GNUNET_PeerIdentity *self,
1952                            void *cls,
1953                            GNUNET_TRANSPORT_ReceiveCallback rec,
1954                            GNUNET_TRANSPORT_NotifyConnect nc,
1955                            GNUNET_TRANSPORT_NotifyDisconnect nd,
1956                            GNUNET_TRANSPORT_NotifyExcessBandwidth neb)
1957 {
1958   struct GNUNET_TRANSPORT_Handle *ret;
1959
1960   ret = GNUNET_new (struct GNUNET_TRANSPORT_Handle);
1961   if (NULL != self)
1962   {
1963     ret->self = *self;
1964     ret->check_self = GNUNET_YES;
1965   }
1966   ret->cfg = cfg;
1967   ret->cls = cls;
1968   ret->rec = rec;
1969   ret->nc_cb = nc;
1970   ret->nd_cb = nd;
1971   ret->neb_cb = neb;
1972   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1973   LOG (GNUNET_ERROR_TYPE_DEBUG,
1974        "Connecting to transport service.\n");
1975   ret->client = GNUNET_CLIENT_connect ("transport",
1976                                        cfg);
1977   if (NULL == ret->client)
1978   {
1979     GNUNET_free (ret);
1980     return NULL;
1981   }
1982   ret->neighbours =
1983     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
1984                                           GNUNET_YES);
1985   ret->ready_heap =
1986       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1987   schedule_control_transmit (ret,
1988                              sizeof (struct StartMessage),
1989                              &send_start,
1990                              ret);
1991   return ret;
1992 }
1993
1994
1995 /**
1996  * Disconnect from the transport service.
1997  *
1998  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_connect()
1999  */
2000 void
2001 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
2002 {
2003   LOG (GNUNET_ERROR_TYPE_DEBUG,
2004        "Transport disconnect called!\n");
2005   /* this disconnects all neighbours... */
2006   if (NULL == handle->reconnect_task)
2007     disconnect_and_schedule_reconnect (handle);
2008   /* and now we stop trying to connect again... */
2009   if (NULL != handle->reconnect_task)
2010   {
2011     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
2012     handle->reconnect_task = NULL;
2013   }
2014   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
2015   handle->neighbours = NULL;
2016   if (NULL != handle->quota_task)
2017   {
2018     GNUNET_SCHEDULER_cancel (handle->quota_task);
2019     handle->quota_task = NULL;
2020   }
2021   GNUNET_free_non_null (handle->my_hello);
2022   handle->my_hello = NULL;
2023   GNUNET_assert (NULL == handle->tc_head);
2024   GNUNET_assert (NULL == handle->tc_tail);
2025   GNUNET_assert (NULL == handle->hwl_head);
2026   GNUNET_assert (NULL == handle->hwl_tail);
2027   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
2028   handle->ready_heap = NULL;
2029   GNUNET_free (handle);
2030 }
2031
2032
2033 /**
2034  * Check if we could queue a message of the given size for
2035  * transmission.  The transport service will take both its
2036  * internal buffers and bandwidth limits imposed by the
2037  * other peer into consideration when answering this query.
2038  *
2039  * @param handle connection to transport service
2040  * @param target who should receive the message
2041  * @param size how big is the message we want to transmit?
2042  * @param timeout after how long should we give up (and call
2043  *        notify with buf NULL and size 0)?
2044  * @param notify function to call when we are ready to
2045  *        send such a message
2046  * @param notify_cls closure for @a notify
2047  * @return NULL if someone else is already waiting to be notified
2048  *         non-NULL if the notify callback was queued (can be used to cancel
2049  *         using #GNUNET_TRANSPORT_notify_transmit_ready_cancel)
2050  */
2051 struct GNUNET_TRANSPORT_TransmitHandle *
2052 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
2053                                         const struct GNUNET_PeerIdentity *target,
2054                                         size_t size,
2055                                         struct GNUNET_TIME_Relative timeout,
2056                                         GNUNET_TRANSPORT_TransmitReadyNotify notify,
2057                                         void *notify_cls)
2058 {
2059   struct Neighbour *n;
2060   struct GNUNET_TRANSPORT_TransmitHandle *th;
2061   struct GNUNET_TIME_Relative delay;
2062
2063   n = neighbour_find (handle, target);
2064   if (NULL == n)
2065   {
2066     /* use GNUNET_TRANSPORT_try_connect first, only use this function
2067      * once a connection has been established */
2068     GNUNET_assert (0);
2069     return NULL;
2070   }
2071   if (NULL != n->th)
2072   {
2073     /* attempt to send two messages at the same time to the same peer */
2074     GNUNET_assert (0);
2075     return NULL;
2076   }
2077   GNUNET_assert (NULL == n->hn);
2078   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
2079   th->neighbour = n;
2080   th->notify = notify;
2081   th->notify_cls = notify_cls;
2082   th->request_start = GNUNET_TIME_absolute_get ();
2083   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2084   th->notify_size = size;
2085   n->th = th;
2086   /* calculate when our transmission should be ready */
2087   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
2088                                               size + n->traffic_overhead);
2089   n->traffic_overhead = 0;
2090   if (delay.rel_value_us > timeout.rel_value_us)
2091     delay.rel_value_us = 0;        /* notify immediately (with failure) */
2092   if (delay.rel_value_us > GNUNET_CONSTANTS_LATENCY_WARN.rel_value_us)
2093     LOG (GNUNET_ERROR_TYPE_WARNING,
2094          "At bandwidth %u byte/s next transmission to %s in %s\n",
2095          (unsigned int) n->out_tracker.available_bytes_per_s__,
2096          GNUNET_i2s (target),
2097          GNUNET_STRINGS_relative_time_to_string (delay,
2098                                                  GNUNET_YES));
2099   else
2100     LOG (GNUNET_ERROR_TYPE_DEBUG,
2101          "At bandwidth %u byte/s next transmission to %s in %s\n",
2102          (unsigned int) n->out_tracker.available_bytes_per_s__,
2103          GNUNET_i2s (target),
2104          GNUNET_STRINGS_relative_time_to_string (delay,
2105                                                  GNUNET_YES));
2106   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap,
2107                                         n,
2108                                         delay.rel_value_us);
2109   schedule_transmission (handle);
2110   return th;
2111 }
2112
2113
2114 /**
2115  * Cancel the specified transmission-ready notification.
2116  *
2117  * @param th handle returned from #GNUNET_TRANSPORT_notify_transmit_ready()
2118  */
2119 void
2120 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct GNUNET_TRANSPORT_TransmitHandle *th)
2121 {
2122   struct Neighbour *n;
2123
2124   GNUNET_assert (NULL == th->next);
2125   GNUNET_assert (NULL == th->prev);
2126   n = th->neighbour;
2127   GNUNET_assert (th == n->th);
2128   n->th = NULL;
2129   if (NULL != n->hn)
2130   {
2131     GNUNET_CONTAINER_heap_remove_node (n->hn);
2132     n->hn = NULL;
2133   }
2134   else
2135   {
2136     GNUNET_assert (NULL != th->timeout_task);
2137     GNUNET_SCHEDULER_cancel (th->timeout_task);
2138     th->timeout_task = NULL;
2139   }
2140   GNUNET_free (th);
2141 }
2142
2143
2144 /* end of transport_api.c */