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