removing depreated 'priority' argument from GNUNET_TRANSPORT_notify_transmit_ready
[oweals/gnunet.git] / src / transport / transport_api.c
1 /*
2      This file is part of GNUnet.
3      (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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/transport_api.c
23  * @brief library to access the low-level P2P IO service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - 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  * How large to start with for the hashmap of neighbours.
42  */
43 #define STARTING_NEIGHBOURS_SIZE 16
44
45 /**
46  * Handle for a message that should be transmitted to the service.
47  * Used for both control messages and normal messages.
48  */
49 struct GNUNET_TRANSPORT_TransmitHandle
50 {
51
52   /**
53    * We keep all requests in a DLL.
54    */
55   struct GNUNET_TRANSPORT_TransmitHandle *next;
56
57   /**
58    * We keep all requests in a DLL.
59    */
60   struct GNUNET_TRANSPORT_TransmitHandle *prev;
61
62   /**
63    * Neighbour for this handle, NULL for control messages.
64    */
65   struct Neighbour *neighbour;
66
67   /**
68    * Function to call when notify_size bytes are available
69    * for transmission.
70    */
71   GNUNET_TRANSPORT_TransmitReadyNotify notify;
72
73   /**
74    * Closure for notify.
75    */
76   void *notify_cls;
77
78   /**
79    * Timeout for this request, 0 for control messages.
80    */
81   struct GNUNET_TIME_Absolute timeout;
82
83   /**
84    * Task to trigger request timeout if the request is stalled due to
85    * congestion.
86    */
87   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
88
89   /**
90    * How many bytes is our notify callback waiting for?
91    */
92   size_t notify_size;
93
94 };
95
96
97 /**
98  * Entry in hash table of all of our current neighbours.
99  */
100 struct Neighbour
101 {
102   /**
103    * Overall transport handle.
104    */
105   struct GNUNET_TRANSPORT_Handle *h;
106
107   /**
108    * Active transmit handle or NULL.
109    */
110   struct GNUNET_TRANSPORT_TransmitHandle *th;
111
112   /**
113    * Identity of this neighbour.
114    */
115   struct GNUNET_PeerIdentity id;
116
117   /**
118    * Outbound bandwidh tracker.
119    */
120   struct GNUNET_BANDWIDTH_Tracker out_tracker;
121
122   /**
123    * Entry in our readyness heap (which is sorted by 'next_ready'
124    * value).  NULL if there is no pending transmission request for
125    * this neighbour or if we're waiting for 'is_ready' to become
126    * true AFTER the 'out_tracker' suggested that this peer's quota
127    * has been satisfied (so once 'is_ready' goes to GNUNET_YES,
128    * we should immediately go back into the heap).
129    */
130   struct GNUNET_CONTAINER_HeapNode *hn;
131
132   /**
133    * Is this peer currently ready to receive a message?
134    */
135   int is_ready;
136
137   /**
138    * Sending consumed more bytes on wire than payload was announced
139    * This overhead is added to the delay of next sending operation
140    */
141   size_t traffic_overhead;
142 };
143
144
145 /**
146  * Linked list of functions to call whenever our HELLO is updated.
147  */
148 struct GNUNET_TRANSPORT_GetHelloHandle
149 {
150
151   /**
152    * This is a doubly linked list.
153    */
154   struct GNUNET_TRANSPORT_GetHelloHandle *next;
155
156   /**
157    * This is a doubly linked list.
158    */
159   struct GNUNET_TRANSPORT_GetHelloHandle *prev;
160
161   /**
162    * Transport handle.
163    */
164   struct GNUNET_TRANSPORT_Handle *handle;
165
166   /**
167    * Callback to call once we got our HELLO.
168    */
169   GNUNET_TRANSPORT_HelloUpdateCallback rec;
170
171   /**
172    * Task for calling the HelloUpdateCallback when we already have a HELLO
173    */
174   GNUNET_SCHEDULER_TaskIdentifier notify_task;
175
176   /**
177    * Closure for @e rec.
178    */
179   void *rec_cls;
180
181 };
182
183 /**
184  * Linked list for all try-connect requests
185  */
186 struct GNUNET_TRANSPORT_TryConnectHandle
187 {
188   /**
189    * For the DLL.
190    */
191   struct GNUNET_TRANSPORT_TryConnectHandle *prev;
192
193   /**
194    * For the DLL.
195    */
196   struct GNUNET_TRANSPORT_TryConnectHandle *next;
197
198   struct GNUNET_PeerIdentity pid;
199
200   struct GNUNET_TRANSPORT_Handle *th;
201
202   struct GNUNET_TRANSPORT_TransmitHandle *tth;
203
204   GNUNET_TRANSPORT_TryConnectCallback cb;
205
206   /**
207    * Closure for @e cb.
208    */
209   void *cb_cls;
210 };
211
212
213 /**
214  * Linked list for all try-connect requests
215  */
216 struct GNUNET_TRANSPORT_OfferHelloHandle
217 {
218   /**
219    * For the DLL.
220    */
221   struct GNUNET_TRANSPORT_OfferHelloHandle *prev;
222
223   /**
224    * For the DLL.
225    */
226   struct GNUNET_TRANSPORT_OfferHelloHandle *next;
227
228   struct GNUNET_TRANSPORT_Handle *th;
229
230   struct GNUNET_TRANSPORT_TransmitHandle *tth;
231
232   GNUNET_SCHEDULER_Task cont;
233
234   /**
235    * Closure for @e cont
236    */
237   void *cls;
238
239   struct GNUNET_MessageHeader *msg;
240 };
241
242
243 /**
244  * Handle for the transport service (includes all of the
245  * state for the transport service).
246  */
247 struct GNUNET_TRANSPORT_Handle
248 {
249
250   /**
251    * Closure for the callbacks.
252    */
253   void *cls;
254
255   /**
256    * Function to call for received data.
257    */
258   GNUNET_TRANSPORT_ReceiveCallback rec;
259
260   /**
261    * function to call on connect events
262    */
263   GNUNET_TRANSPORT_NotifyConnect nc_cb;
264
265   /**
266    * function to call on disconnect events
267    */
268   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
269
270   /**
271    * Head of DLL of control messages.
272    */
273   struct GNUNET_TRANSPORT_TransmitHandle *control_head;
274
275   /**
276    * Tail of DLL of control messages.
277    */
278   struct GNUNET_TRANSPORT_TransmitHandle *control_tail;
279
280   /**
281    * The current HELLO message for this peer.  Updated
282    * whenever transports change their addresses.
283    */
284   struct GNUNET_HELLO_Message *my_hello;
285
286   /**
287    * My client connection to the transport service.
288    */
289   struct GNUNET_CLIENT_Connection *client;
290
291   /**
292    * Handle to our registration with the client for notification.
293    */
294   struct GNUNET_CLIENT_TransmitHandle *cth;
295
296   /**
297    * Linked list of pending requests for our HELLO.
298    */
299   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_head;
300
301   /**
302    * Linked list of pending requests for our HELLO.
303    */
304   struct GNUNET_TRANSPORT_GetHelloHandle *hwl_tail;
305
306   /**
307    * Linked list of pending try connect requests head
308    */
309   struct GNUNET_TRANSPORT_TryConnectHandle *tc_head;
310
311   /**
312    * Linked list of pending try connect requests tail
313    */
314   struct GNUNET_TRANSPORT_TryConnectHandle *tc_tail;
315
316   /**
317    * Linked list of pending offer HELLO requests head
318    */
319   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_head;
320
321   /**
322    * Linked list of pending offer HELLO requests tail
323    */
324   struct GNUNET_TRANSPORT_OfferHelloHandle *oh_tail;
325
326   /**
327    * My configuration.
328    */
329   const struct GNUNET_CONFIGURATION_Handle *cfg;
330
331   /**
332    * Hash map of the current connected neighbours of this peer.
333    * Maps peer identities to 'struct Neighbour' entries.
334    */
335   struct GNUNET_CONTAINER_MultiPeerMap *neighbours;
336
337   /**
338    * Heap sorting peers with pending messages by the timestamps that
339    * specify when we could next send a message to the respective peer.
340    * Excludes control messages (which can always go out immediately).
341    * Maps time stamps to 'struct Neighbour' entries.
342    */
343   struct GNUNET_CONTAINER_Heap *ready_heap;
344
345   /**
346    * Peer identity as assumed by this process, or all zeros.
347    */
348   struct GNUNET_PeerIdentity self;
349
350   /**
351    * ID of the task trying to reconnect to the service.
352    */
353   GNUNET_SCHEDULER_TaskIdentifier reconnect_task;
354
355   /**
356    * ID of the task trying to trigger transmission for a peer while
357    * maintaining bandwidth quotas.  In use if there are no control
358    * messages and the smallest entry in the 'ready_heap' has a time
359    * stamp in the future.
360    */
361   GNUNET_SCHEDULER_TaskIdentifier quota_task;
362
363   /**
364    * Delay until we try to reconnect.
365    */
366   struct GNUNET_TIME_Relative reconnect_delay;
367
368   /**
369    * Should we check that @e self matches what the service thinks?
370    * (if #GNUNET_NO, then @e self is all zeros!).
371    */
372   int check_self;
373
374   /**
375    * Reconnect in progress
376    */
377   int reconnecting;
378 };
379
380
381
382 /**
383  * Schedule the task to send one message, either from the control
384  * list or the peer message queues  to the service.
385  *
386  * @param h transport service to schedule a transmission for
387  */
388 static void
389 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h);
390
391
392 /**
393  * Function that will schedule the job that will try
394  * to connect us again to the client.
395  *
396  * @param h transport service to reconnect
397  */
398 static void
399 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h);
400
401
402 /**
403  * Get the neighbour list entry for the given peer
404  *
405  * @param h our context
406  * @param peer peer to look up
407  * @return NULL if no such peer entry exists
408  */
409 static struct Neighbour *
410 neighbour_find (struct GNUNET_TRANSPORT_Handle *h,
411                 const struct GNUNET_PeerIdentity *peer)
412 {
413   return GNUNET_CONTAINER_multipeermap_get (h->neighbours, peer);
414 }
415
416
417
418 static void
419 outbound_bw_tracker_update (void *cls)
420 {
421   struct Neighbour *n = cls;
422   struct GNUNET_TIME_Relative delay;
423   if (NULL == n->hn)
424     return;
425
426   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
427       n->th->notify_size + n->traffic_overhead);
428   LOG(GNUNET_ERROR_TYPE_DEBUG,
429       "New outbound delay %llu us\n",delay.rel_value_us);
430   GNUNET_CONTAINER_heap_update_cost (n->h->ready_heap,
431       n->hn, delay.rel_value_us);
432   schedule_transmission (n->h);
433 }
434
435
436 /**
437  * Add neighbour to our list
438  *
439  * @return NULL if this API is currently disconnecting from the service
440  */
441 static struct Neighbour *
442 neighbour_add (struct GNUNET_TRANSPORT_Handle *h,
443                const struct GNUNET_PeerIdentity *pid)
444 {
445   struct Neighbour *n;
446
447   LOG (GNUNET_ERROR_TYPE_DEBUG,
448        "Creating entry for neighbour `%4s'.\n",
449        GNUNET_i2s (pid));
450   n = GNUNET_new (struct Neighbour);
451   n->id = *pid;
452   n->h = h;
453   n->is_ready = GNUNET_YES;
454   n->traffic_overhead = 0;
455   GNUNET_BANDWIDTH_tracker_init (&n->out_tracker,
456                                  outbound_bw_tracker_update, n,
457                                  GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
458                                  MAX_BANDWIDTH_CARRY_S);
459   GNUNET_assert (GNUNET_OK ==
460                  GNUNET_CONTAINER_multipeermap_put (h->neighbours,
461                                                     &n->id, n,
462                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
463   return n;
464 }
465
466
467 /**
468  * Iterator over hash map entries, for deleting state of a neighbour.
469  *
470  * @param cls the `struct GNUNET_TRANSPORT_Handle *`
471  * @param key peer identity
472  * @param value value in the hash map, the neighbour entry to delete
473  * @return #GNUNET_YES if we should continue to
474  *         iterate,
475  *         #GNUNET_NO if not.
476  */
477 static int
478 neighbour_delete (void *cls,
479                   const struct GNUNET_PeerIdentity *key, void *value)
480 {
481   struct GNUNET_TRANSPORT_Handle *handle = cls;
482   struct Neighbour *n = value;
483
484   if (NULL != handle->nd_cb)
485     handle->nd_cb (handle->cls, &n->id);
486   GNUNET_assert (NULL == n->th);
487   GNUNET_assert (NULL == n->hn);
488   GNUNET_assert (GNUNET_YES ==
489                  GNUNET_CONTAINER_multipeermap_remove (handle->neighbours, key,
490                                                        n));
491   GNUNET_free (n);
492   return GNUNET_YES;
493 }
494
495 static int reconnecting;
496
497 /**
498  * Function we use for handling incoming messages.
499  *
500  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
501  * @param msg message received, NULL on timeout or fatal error
502  */
503 static void
504 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
505 {
506   struct GNUNET_TRANSPORT_Handle *h = cls;
507   const struct DisconnectInfoMessage *dim;
508   const struct ConnectInfoMessage *cim;
509   const struct InboundMessage *im;
510   const struct GNUNET_MessageHeader *imm;
511   const struct SendOkMessage *okm;
512   const struct QuotaSetMessage *qm;
513   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
514   struct GNUNET_TRANSPORT_GetHelloHandle *next_hwl;
515   struct Neighbour *n;
516   struct GNUNET_PeerIdentity me;
517   uint16_t size;
518   uint32_t bytes_msg;
519   uint32_t bytes_physical;
520
521   GNUNET_assert (NULL != h->client);
522   if (GNUNET_YES == reconnecting)
523   {
524     return;
525   }
526   if (NULL == msg)
527   {
528     LOG (GNUNET_ERROR_TYPE_DEBUG,
529          "Error receiving from transport service, disconnecting temporarily.\n");
530     reconnecting = GNUNET_YES;
531     disconnect_and_schedule_reconnect (h);
532     return;
533   }
534   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
535                          GNUNET_TIME_UNIT_FOREVER_REL);
536   size = ntohs (msg->size);
537   switch (ntohs (msg->type))
538   {
539   case GNUNET_MESSAGE_TYPE_HELLO:
540     if (GNUNET_OK !=
541         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
542     {
543       GNUNET_break (0);
544       break;
545     }
546     LOG (GNUNET_ERROR_TYPE_DEBUG,
547          "Receiving (my own) `%s' message, I am `%4s'.\n", "HELLO",
548          GNUNET_i2s (&me));
549     GNUNET_free_non_null (h->my_hello);
550     h->my_hello = NULL;
551     if (size < sizeof (struct GNUNET_MessageHeader))
552     {
553       GNUNET_break (0);
554       break;
555     }
556     h->my_hello = GNUNET_malloc (size);
557     memcpy (h->my_hello, msg, size);
558     hwl = h->hwl_head;
559     while (NULL != hwl)
560     {
561       next_hwl = hwl->next;
562       hwl->rec (hwl->rec_cls,
563                 (const struct GNUNET_MessageHeader *) h->my_hello);
564       hwl = next_hwl;
565     }
566     break;
567   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
568     if (size < sizeof (struct ConnectInfoMessage))
569     {
570       GNUNET_break (0);
571       break;
572     }
573     cim = (const struct ConnectInfoMessage *) msg;
574     if (size !=
575         sizeof (struct ConnectInfoMessage))
576     {
577       GNUNET_break (0);
578       break;
579     }
580     LOG (GNUNET_ERROR_TYPE_DEBUG,
581          "Receiving `%s' message for `%4s'.\n",
582          "CONNECT", GNUNET_i2s (&cim->id));
583     n = neighbour_find (h, &cim->id);
584     if (NULL != n)
585     {
586       GNUNET_break (0);
587       break;
588     }
589     n = neighbour_add (h, &cim->id);
590     LOG (GNUNET_ERROR_TYPE_DEBUG,
591          "Receiving `%s' message for `%4s' with quota %u\n",
592          "CONNECT",
593          GNUNET_i2s (&cim->id),
594          ntohl (cim->quota_out.value__));
595     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, cim->quota_out);
596     if (h->nc_cb != NULL)
597       h->nc_cb (h->cls, &n->id);
598     break;
599   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
600     if (size != sizeof (struct DisconnectInfoMessage))
601     {
602       GNUNET_break (0);
603       break;
604     }
605     dim = (const struct DisconnectInfoMessage *) msg;
606     GNUNET_break (ntohl (dim->reserved) == 0);
607     LOG (GNUNET_ERROR_TYPE_DEBUG,
608          "Receiving `%s' message for `%4s'.\n",
609          "DISCONNECT", GNUNET_i2s (&dim->peer));
610     n = neighbour_find (h, &dim->peer);
611     if (NULL == n)
612     {
613       GNUNET_break (0);
614       break;
615     }
616     neighbour_delete (h, &dim->peer, n);
617     break;
618   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
619     if (size != sizeof (struct SendOkMessage))
620     {
621       GNUNET_break (0);
622       break;
623     }
624     okm = (const struct SendOkMessage *) msg;
625     bytes_msg = ntohl (okm->bytes_msg);
626     bytes_physical = ntohl (okm->bytes_physical);
627     LOG (GNUNET_ERROR_TYPE_DEBUG,
628          "Receiving SEND_OK message, transmission %s.\n",
629          ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
630
631     n = neighbour_find (h, &okm->peer);
632     if (NULL == n)
633       break;
634
635     if (bytes_physical >= bytes_msg)
636     {
637         LOG (GNUNET_ERROR_TYPE_DEBUG,
638              "Overhead for %u byte message: %u\n",
639             bytes_msg, bytes_physical - bytes_msg);
640       n->traffic_overhead += bytes_physical - bytes_msg;
641     }
642     GNUNET_break (GNUNET_NO == n->is_ready);
643     n->is_ready = GNUNET_YES;
644     if ((NULL != n->th) && (NULL == n->hn))
645     {
646       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->th->timeout_task);
647       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
648       n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
649       /* we've been waiting for this (congestion, not quota,
650        * caused delayed transmission) */
651       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
652       schedule_transmission (h);
653     }
654     break;
655   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
656     LOG (GNUNET_ERROR_TYPE_DEBUG,
657          "Receiving `%s' message.\n",
658          "RECV");
659     if (size <
660         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
661     {
662       GNUNET_break (0);
663       break;
664     }
665     im = (const struct InboundMessage *) msg;
666     imm = (const struct GNUNET_MessageHeader *) &im[1];
667     if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
668     {
669       GNUNET_break (0);
670       break;
671     }
672     LOG (GNUNET_ERROR_TYPE_DEBUG,
673          "Received message of type %u from `%4s'.\n",
674          ntohs (imm->type), GNUNET_i2s (&im->peer));
675     n = neighbour_find (h, &im->peer);
676     if (NULL == n)
677     {
678       GNUNET_break (0);
679       break;
680     }
681     if (NULL != h->rec)
682       h->rec (h->cls, &im->peer, imm);
683     break;
684   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
685     LOG (GNUNET_ERROR_TYPE_DEBUG,
686          "Receiving `%s' message.\n", "SET_QUOTA");
687     if (size != sizeof (struct QuotaSetMessage))
688     {
689       GNUNET_break (0);
690       break;
691     }
692     qm = (const struct QuotaSetMessage *) msg;
693     n = neighbour_find (h, &qm->peer);
694     if (NULL == n)
695       break;
696     LOG (GNUNET_ERROR_TYPE_DEBUG,
697          "Receiving `%s' message for `%4s' with quota %u\n",
698          "SET_QUOTA",
699          GNUNET_i2s (&qm->peer),
700          ntohl (qm->quota.value__));
701     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, qm->quota);
702     break;
703   default:
704     LOG (GNUNET_ERROR_TYPE_ERROR,
705          _("Received unexpected message of type %u in %s:%u\n"),
706          ntohs (msg->type), __FILE__, __LINE__);
707     GNUNET_break (0);
708     break;
709   }
710 }
711
712
713 /**
714  * A transmission request could not be satisfied because of
715  * network congestion.  Notify the initiator and clean up.
716  *
717  * @param cls the `struct GNUNET_TRANSPORT_TransmitHandle`
718  * @param tc scheduler context
719  */
720 static void
721 timeout_request_due_to_congestion (void *cls,
722                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
723 {
724   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
725   struct Neighbour *n = th->neighbour;
726
727   n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
728   GNUNET_assert (th == n->th);
729   GNUNET_assert (NULL == n->hn);
730   n->th = NULL;
731   th->notify (th->notify_cls, 0, NULL);
732   GNUNET_free (th);
733 }
734
735
736 /**
737  * Transmit message(s) to service.
738  *
739  * @param cls handle to transport
740  * @param size number of bytes available in @a buf
741  * @param buf where to copy the message
742  * @return number of bytes copied to @a buf
743  */
744 static size_t
745 transport_notify_ready (void *cls, size_t size, void *buf)
746 {
747   struct GNUNET_TRANSPORT_Handle *h = cls;
748   struct GNUNET_TRANSPORT_TransmitHandle *th;
749   struct Neighbour *n;
750   char *cbuf;
751   struct OutboundMessage obm;
752   size_t ret;
753   size_t nret;
754   size_t mret;
755
756   GNUNET_assert (NULL != h->client);
757   h->cth = NULL;
758   if (NULL == buf)
759   {
760     /* transmission failed */
761     disconnect_and_schedule_reconnect (h);
762     return 0;
763   }
764
765   cbuf = buf;
766   ret = 0;
767   /* first send control messages */
768   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
769   {
770     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
771     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
772     LOG (GNUNET_ERROR_TYPE_DEBUG,
773          "Added %u bytes of control message at %u\n",
774          nret, ret);
775     GNUNET_free (th);
776     ret += nret;
777     size -= nret;
778   }
779
780   /* then, if possible and no control messages pending, send data messages */
781   while ((NULL == h->control_head) &&
782          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
783   {
784     if (GNUNET_YES != n->is_ready)
785     {
786       /* peer not ready, wait for notification! */
787       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
788       n->hn = NULL;
789       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->th->timeout_task);
790       n->th->timeout_task =
791           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
792                                         (n->th->timeout),
793                                         &timeout_request_due_to_congestion,
794                                         n->th);
795       continue;
796     }
797     th = n->th;
798     if (th->notify_size + sizeof (struct OutboundMessage) > size)
799       break;                    /* does not fit */
800     if (GNUNET_BANDWIDTH_tracker_get_delay
801         (&n->out_tracker, th->notify_size).rel_value_us > 0)
802       break;                    /* too early */
803     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
804     n->hn = NULL;
805     n->th = NULL;
806     n->is_ready = GNUNET_NO;
807     GNUNET_assert (size >= sizeof (struct OutboundMessage));
808     mret =
809         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
810                     &cbuf[ret + sizeof (struct OutboundMessage)]);
811     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
812     if (mret != 0)
813     {
814       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
815                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
816       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
817       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
818       obm.reserved = htonl (0);
819       obm.timeout =
820           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
821                                      (th->timeout));
822       obm.peer = n->id;
823       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
824       ret += (mret + sizeof (struct OutboundMessage));
825       size -= (mret + sizeof (struct OutboundMessage));
826       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
827     }
828     GNUNET_free (th);
829   }
830   /* if there are more pending messages, try to schedule those */
831   schedule_transmission (h);
832   LOG (GNUNET_ERROR_TYPE_DEBUG,
833        "Transmitting %u bytes to transport service\n",
834        ret);
835   return ret;
836 }
837
838
839 /**
840  * Schedule the task to send one message, either from the control
841  * list or the peer message queues  to the service.
842  *
843  * @param cls transport service to schedule a transmission for
844  * @param tc scheduler context
845  */
846 static void
847 schedule_transmission_task (void *cls,
848                             const struct GNUNET_SCHEDULER_TaskContext *tc)
849 {
850   struct GNUNET_TRANSPORT_Handle *h = cls;
851   size_t size;
852   struct GNUNET_TRANSPORT_TransmitHandle *th;
853   struct Neighbour *n;
854
855   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
856   GNUNET_assert (NULL != h->client);
857   /* destroy all requests that have timed out */
858   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
859          (0 == GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value_us))
860   {
861     /* notify client that the request could not be satisfied within
862      * the given time constraints */
863     th = n->th;
864     n->th = NULL;
865     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
866     n->hn = NULL;
867     LOG (GNUNET_ERROR_TYPE_DEBUG,
868          "Signalling timeout for transmission to peer %s due to congestion\n",
869          GNUNET_i2s (&n->id));
870     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
871     GNUNET_free (th);
872   }
873   if (NULL != h->cth)
874     return;
875   if (NULL != h->control_head)
876   {
877     size = h->control_head->notify_size;
878   }
879   else
880   {
881     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
882     if (NULL == n)
883       return;                   /* no pending messages */
884     size = n->th->notify_size + sizeof (struct OutboundMessage);
885   }
886   LOG (GNUNET_ERROR_TYPE_DEBUG,
887        "Calling notify_transmit_ready\n");
888   h->cth =
889       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
890                                            GNUNET_TIME_UNIT_FOREVER_REL,
891                                            GNUNET_NO, &transport_notify_ready,
892                                            h);
893   GNUNET_assert (NULL != h->cth);
894 }
895
896
897 /**
898  * Schedule the task to send one message, either from the control
899  * list or the peer message queues  to the service.
900  *
901  * @param h transport service to schedule a transmission for
902  */
903 static void
904 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
905 {
906   struct GNUNET_TIME_Relative delay;
907   struct Neighbour *n;
908
909   GNUNET_assert (NULL != h->client);
910   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
911   {
912     GNUNET_SCHEDULER_cancel (h->quota_task);
913     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
914   }
915   if (NULL != h->control_head)
916     delay = GNUNET_TIME_UNIT_ZERO;
917   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
918   {
919     delay =
920         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
921                                             n->th->notify_size + n->traffic_overhead);
922     n->traffic_overhead = 0;
923   }
924   else
925     return;                     /* no work to be done */
926   LOG (GNUNET_ERROR_TYPE_DEBUG,
927        "Scheduling next transmission to service in %s\n",
928        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
929   h->quota_task =
930       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
931 }
932
933
934 /**
935  * Queue control request for transmission to the transport
936  * service.
937  *
938  * @param h handle to the transport service
939  * @param size number of bytes to be transmitted
940  * @param notify function to call to get the content
941  * @param notify_cls closure for @a notify
942  * @return a `struct GNUNET_TRANSPORT_TransmitHandle`
943  */
944 static struct GNUNET_TRANSPORT_TransmitHandle *
945 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
946                            GNUNET_TRANSPORT_TransmitReadyNotify notify,
947                            void *notify_cls)
948 {
949   struct GNUNET_TRANSPORT_TransmitHandle *th;
950
951   LOG (GNUNET_ERROR_TYPE_DEBUG,
952        "Control transmit of %u bytes requested\n",
953        size);
954   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
955   th->notify = notify;
956   th->notify_cls = notify_cls;
957   th->notify_size = size;
958   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
959   schedule_transmission (h);
960   return th;
961 }
962
963
964 /**
965  * Transmit START message to service.
966  *
967  * @param cls unused
968  * @param size number of bytes available in @a buf
969  * @param buf where to copy the message
970  * @return number of bytes copied to @a buf
971  */
972 static size_t
973 send_start (void *cls, size_t size, void *buf)
974 {
975   struct GNUNET_TRANSPORT_Handle *h = cls;
976   struct StartMessage s;
977   uint32_t options;
978
979   if (NULL == buf)
980   {
981     /* Can only be shutdown, just give up */
982     LOG (GNUNET_ERROR_TYPE_DEBUG,
983          "Shutdown while trying to transmit `%s' request.\n",
984          "START");
985     return 0;
986   }
987   LOG (GNUNET_ERROR_TYPE_DEBUG,
988        "Transmitting `%s' request.\n",
989        "START");
990   GNUNET_assert (size >= sizeof (struct StartMessage));
991   s.header.size = htons (sizeof (struct StartMessage));
992   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
993   options = 0;
994   if (h->check_self)
995     options |= 1;
996   if (h->rec != NULL)
997     options |= 2;
998   s.options = htonl (options);
999   s.self = h->self;
1000   memcpy (buf, &s, sizeof (struct StartMessage));
1001   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
1002                          GNUNET_TIME_UNIT_FOREVER_REL);
1003   return sizeof (struct StartMessage);
1004 }
1005
1006
1007 /**
1008  * Try again to connect to transport service.
1009  *
1010  * @param cls the handle to the transport service
1011  * @param tc scheduler context
1012  */
1013 static void
1014 reconnect (void *cls,
1015            const struct GNUNET_SCHEDULER_TaskContext *tc)
1016 {
1017   struct GNUNET_TRANSPORT_Handle *h = cls;
1018
1019   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1020   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1021   {
1022     /* shutdown, just give up */
1023     return;
1024   }
1025   LOG (GNUNET_ERROR_TYPE_DEBUG,
1026        "Connecting to transport service.\n");
1027   GNUNET_assert (NULL == h->client);
1028   GNUNET_assert (NULL == h->control_head);
1029   GNUNET_assert (NULL == h->control_tail);
1030   reconnecting = GNUNET_NO;
1031   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1032
1033   GNUNET_assert (NULL != h->client);
1034   schedule_control_transmit (h, sizeof (struct StartMessage),
1035                              &send_start, h);
1036 }
1037
1038
1039 /**
1040  * Function that will schedule the job that will try
1041  * to connect us again to the client.
1042  *
1043  * @param h transport service to reconnect
1044  */
1045 static void
1046 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1047 {
1048   struct GNUNET_TRANSPORT_TransmitHandle *th;
1049
1050   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
1051   if (NULL != h->cth)
1052   {
1053     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1054     h->cth = NULL;
1055   }
1056   if (NULL != h->client)
1057   {
1058     GNUNET_CLIENT_disconnect (h->client);
1059     h->client = NULL;
1060 /*    LOG (GNUNET_ERROR_TYPE_ERROR,
1061          "Client disconnect done \n");*/
1062   }
1063   /* Forget about all neighbours that we used to be connected to */
1064   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
1065                                          &neighbour_delete, h);
1066   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
1067   {
1068     GNUNET_SCHEDULER_cancel (h->quota_task);
1069     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
1070   }
1071   while ((NULL != (th = h->control_head)))
1072   {
1073     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
1074     th->notify (th->notify_cls, 0, NULL);
1075     GNUNET_free (th);
1076   }
1077   LOG (GNUNET_ERROR_TYPE_DEBUG,
1078        "Scheduling task to reconnect to transport service in %s.\n",
1079        GNUNET_STRINGS_relative_time_to_string(h->reconnect_delay, GNUNET_YES));
1080   h->reconnect_task =
1081       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
1082   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
1083 }
1084
1085
1086 /**
1087  * Cancel control request for transmission to the transport service.
1088  *
1089  * @param th handle to the transport service
1090  * @param tth transmit handle to cancel
1091  */
1092 static void
1093 cancel_control_transmit (struct GNUNET_TRANSPORT_Handle *th,
1094                          struct GNUNET_TRANSPORT_TransmitHandle *tth)
1095 {
1096   LOG (GNUNET_ERROR_TYPE_DEBUG,
1097        "Canceling transmit of contral transmission requested\n");
1098   GNUNET_CONTAINER_DLL_remove (th->control_head, th->control_tail, tth);
1099   GNUNET_free (tth);
1100 }
1101
1102
1103
1104 /**
1105  * Send REQUEST_CONNECT message to the service.
1106  *
1107  * @param cls the `struct GNUNET_PeerIdentity`
1108  * @param size number of bytes available in @a buf
1109  * @param buf where to copy the message
1110  * @return number of bytes copied to @a buf
1111  */
1112 static size_t
1113 send_try_connect (void *cls, size_t size, void *buf)
1114 {
1115   struct GNUNET_TRANSPORT_TryConnectHandle *tch = cls;
1116   struct TransportRequestConnectMessage msg;
1117
1118   if (buf == NULL)
1119   {
1120     if (NULL != tch->cb)
1121       tch->cb (tch->cb_cls, GNUNET_SYSERR);
1122     GNUNET_CONTAINER_DLL_remove (tch->th->tc_head, tch->th->tc_tail, tch);
1123     LOG (GNUNET_ERROR_TYPE_DEBUG,
1124          "Discarding  `%s' request to `%4s' due to error in transport service connection.\n",
1125          "REQUEST_CONNECT",
1126          GNUNET_i2s (&tch->pid));
1127     GNUNET_free (tch);
1128     return 0;
1129   }
1130   LOG (GNUNET_ERROR_TYPE_DEBUG,
1131        "Transmitting `%s' request with respect to `%4s'.\n",
1132        "REQUEST_CONNECT",
1133        GNUNET_i2s (&tch->pid));
1134   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1135   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1136   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1137   msg.reserved = htonl (0);
1138   msg.peer = tch->pid;
1139   memcpy (buf, &msg, sizeof (msg));
1140   if (NULL != tch->cb)
1141     tch->cb (tch->cb_cls, GNUNET_OK);
1142   GNUNET_CONTAINER_DLL_remove (tch->th->tc_head, tch->th->tc_tail, tch);
1143   GNUNET_free (tch);
1144   return sizeof (struct TransportRequestConnectMessage);
1145 }
1146
1147 /**
1148  * Ask the transport service to establish a connection to
1149  * the given peer.
1150  *
1151  * @param handle connection to transport service
1152  * @param target who we should try to connect to
1153  * @param cb callback to be called when request was transmitted to transport
1154  *         service
1155  * @param cb_cls closure for the callback
1156  * @return a `struct GNUNET_TRANSPORT_TryConnectHandle` handle or
1157  *         NULL on failure (cb will not be called)
1158  */
1159 struct GNUNET_TRANSPORT_TryConnectHandle *
1160 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1161                               const struct GNUNET_PeerIdentity *target,
1162                               GNUNET_TRANSPORT_TryConnectCallback cb,
1163                               void *cb_cls)
1164 {
1165   struct GNUNET_TRANSPORT_TryConnectHandle *tch = NULL;
1166
1167   if (NULL == handle->client)
1168       return NULL;
1169   tch = GNUNET_new (struct GNUNET_TRANSPORT_TryConnectHandle);
1170   tch->th = handle;
1171   tch->pid = *(target);
1172   tch->cb = cb;
1173   tch->cb_cls = cb_cls;
1174   tch->tth = schedule_control_transmit (handle,
1175                                         sizeof (struct TransportRequestConnectMessage),
1176                                         &send_try_connect, tch);
1177   GNUNET_CONTAINER_DLL_insert(handle->tc_head, handle->tc_tail, tch);
1178   return tch;
1179 }
1180
1181
1182 /**
1183  * Cancel the request to transport to try a connect
1184  * Callback will not be called
1185  *
1186  * @param tch the handle to cancel
1187  */
1188 void
1189 GNUNET_TRANSPORT_try_connect_cancel (struct GNUNET_TRANSPORT_TryConnectHandle *tch)
1190 {
1191   struct GNUNET_TRANSPORT_Handle *th;
1192
1193   th = tch->th;
1194   cancel_control_transmit (th, tch->tth);
1195   GNUNET_CONTAINER_DLL_remove (th->tc_head, th->tc_tail, tch);
1196   GNUNET_free (tch);
1197 }
1198
1199 /**
1200  * Send HELLO message to the service.
1201  *
1202  * @param cls the HELLO message to send
1203  * @param size number of bytes available in @a buf
1204  * @param buf where to copy the message
1205  * @return number of bytes copied to @a buf
1206  */
1207 static size_t
1208 send_hello (void *cls, size_t size, void *buf)
1209 {
1210   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh = cls;
1211   struct GNUNET_MessageHeader *msg = ohh->msg;
1212   uint16_t ssize;
1213   struct GNUNET_SCHEDULER_TaskContext tc;
1214
1215   tc.read_ready = NULL;
1216   tc.write_ready = NULL;
1217   tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
1218   if (NULL == buf)
1219   {
1220     LOG (GNUNET_ERROR_TYPE_DEBUG,
1221          "Timeout while trying to transmit `%s' request.\n",
1222          "HELLO");
1223     if (NULL != ohh->cont)
1224       ohh->cont (ohh->cls, &tc);
1225     GNUNET_free (msg);
1226     GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1227     GNUNET_free (ohh);
1228     return 0;
1229   }
1230   LOG (GNUNET_ERROR_TYPE_DEBUG,
1231        "Transmitting `%s' request.\n",
1232        "HELLO");
1233   ssize = ntohs (msg->size);
1234   GNUNET_assert (size >= ssize);
1235   memcpy (buf, msg, ssize);
1236   GNUNET_free (msg);
1237   tc.reason = GNUNET_SCHEDULER_REASON_READ_READY;
1238   if (NULL != ohh->cont)
1239     ohh->cont (ohh->cls, &tc);
1240   GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1241   GNUNET_free (ohh);
1242   return ssize;
1243 }
1244
1245
1246 /**
1247  * Send traffic metric message to the service.
1248  *
1249  * @param cls the message to send
1250  * @param size number of bytes available in @a buf
1251  * @param buf where to copy the message
1252  * @return number of bytes copied to @a buf
1253  */
1254 static size_t
1255 send_metric (void *cls, size_t size, void *buf)
1256 {
1257   struct TrafficMetricMessage *msg = cls;
1258   uint16_t ssize;
1259
1260   if (NULL == buf)
1261   {
1262     LOG (GNUNET_ERROR_TYPE_DEBUG,
1263          "Timeout while trying to transmit `%s' request.\n",
1264          "TRAFFIC_METRIC");
1265     GNUNET_free (msg);
1266     return 0;
1267   }
1268   LOG (GNUNET_ERROR_TYPE_DEBUG,
1269        "Transmitting `%s' request.\n",
1270        "TRAFFIC_METRIC");
1271   ssize = ntohs (msg->header.size);
1272   GNUNET_assert (size >= ssize);
1273   memcpy (buf, msg, ssize);
1274   GNUNET_free (msg);
1275   return ssize;
1276 }
1277
1278
1279 /**
1280  * Set transport metrics for a peer and a direction
1281  *
1282  * @param handle transport handle
1283  * @param peer the peer to set the metric for
1284  * @param inbound set inbound direction (#GNUNET_YES or #GNUNET_NO)
1285  * @param outbound set outbound direction (#GNUNET_YES or #GNUNET_NO)
1286  * @param ats the metric as ATS information
1287  * @param ats_count the number of metrics
1288  *
1289  * Supported ATS values:
1290  * #GNUNET_ATS_QUALITY_NET_DELAY  (value in ms)
1291  * #GNUNET_ATS_QUALITY_NET_DISTANCE (value in count(hops))
1292  *
1293  * Example:
1294  * To enforce a delay of 10 ms for peer p1 in sending direction use:
1295  * <code>
1296  * struct GNUNET_ATS_Information ats;
1297  * ats.type = ntohl (GNUNET_ATS_QUALITY_NET_DELAY);
1298  * ats.value = ntohl (10);
1299  * GNUNET_TRANSPORT_set_traffic_metric (th, p1, TM_SEND, &ats, 1);
1300  * </code>
1301  * Note:
1302  * Delay restrictions in receiving direction will be enforced with
1303  * 1 message delay.
1304  */
1305 void
1306 GNUNET_TRANSPORT_set_traffic_metric (struct GNUNET_TRANSPORT_Handle *handle,
1307                                      const struct GNUNET_PeerIdentity *peer,
1308                                      int inbound,
1309                                      int outbound,
1310                                      const struct GNUNET_ATS_Information *ats,
1311                                      size_t ats_count)
1312 {
1313   struct TrafficMetricMessage *msg;
1314
1315   GNUNET_assert ((outbound == GNUNET_YES) || (outbound == GNUNET_NO));
1316   GNUNET_assert ((inbound == GNUNET_YES) || (inbound == GNUNET_NO));
1317   if ((GNUNET_NO == inbound) && (GNUNET_NO == outbound))
1318     return;
1319   if (0 == ats_count)
1320     return;
1321
1322   size_t len = sizeof (struct TrafficMetricMessage) +
1323     ats_count * sizeof (struct GNUNET_ATS_Information);
1324
1325   msg = GNUNET_malloc (len);
1326   msg->header.size = htons (len);
1327   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC);
1328   msg->direction = htons (0 + outbound + 2 * inbound);
1329   msg->ats_count = htons (ats_count);
1330   msg->peer = (*peer);
1331   memcpy (&msg[1], ats, ats_count * sizeof (struct GNUNET_ATS_Information));
1332   schedule_control_transmit (handle, len,
1333                              &send_metric, msg);
1334 }
1335
1336
1337
1338 /**
1339  * Offer the transport service the HELLO of another peer.  Note that
1340  * the transport service may just ignore this message if the HELLO is
1341  * malformed or useless due to our local configuration.
1342  *
1343  * @param handle connection to transport service
1344  * @param hello the hello message
1345  * @param cont continuation to call when HELLO has been sent,
1346  *      tc reason #GNUNET_SCHEDULER_REASON_TIMEOUT for fail
1347  *      tc reasong #GNUNET_SCHEDULER_REASON_READ_READY for success
1348  * @param cls closure for continuation
1349  * @return a `struct GNUNET_TRANSPORT_OfferHelloHandle` handle or NULL on failure,
1350  *      in case of failure cont will not be called
1351  *
1352  */
1353 struct GNUNET_TRANSPORT_OfferHelloHandle *
1354 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1355                               const struct GNUNET_MessageHeader *hello,
1356                               GNUNET_SCHEDULER_Task cont, void *cls)
1357 {
1358   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh;
1359   struct GNUNET_MessageHeader *msg;
1360   struct GNUNET_PeerIdentity peer;
1361   uint16_t size;
1362
1363   if (NULL == handle->client)
1364     return NULL;
1365   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1366   size = ntohs (hello->size);
1367   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1368   if (GNUNET_OK !=
1369       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1370   {
1371     GNUNET_break (0);
1372     return NULL;
1373   }
1374
1375   msg = GNUNET_malloc (size);
1376   memcpy (msg, hello, size);
1377   LOG (GNUNET_ERROR_TYPE_DEBUG,
1378        "Offering `%s' message of `%4s' to transport for validation.\n", "HELLO",
1379        GNUNET_i2s (&peer));
1380
1381   ohh = GNUNET_new (struct GNUNET_TRANSPORT_OfferHelloHandle);
1382   ohh->th = handle;
1383   ohh->cont = cont;
1384   ohh->cls = cls;
1385   ohh->msg = msg;
1386   ohh->tth = schedule_control_transmit (handle, size,
1387                                         &send_hello, ohh);
1388   GNUNET_CONTAINER_DLL_insert (handle->oh_head, handle->oh_tail, ohh);
1389   return ohh;
1390 }
1391
1392
1393 /**
1394  * Cancel the request to transport to offer the HELLO message
1395  *
1396  * @param ohh the GNUNET_TRANSPORT_OfferHelloHandle to cancel
1397  */
1398 void
1399 GNUNET_TRANSPORT_offer_hello_cancel (struct GNUNET_TRANSPORT_OfferHelloHandle *ohh)
1400 {
1401   struct GNUNET_TRANSPORT_Handle *th = ohh->th;
1402
1403   cancel_control_transmit (ohh->th, ohh->tth);
1404   GNUNET_CONTAINER_DLL_remove (th->oh_head, th->oh_tail, ohh);
1405   GNUNET_free (ohh->msg);
1406   GNUNET_free (ohh);
1407 }
1408
1409
1410 /**
1411  * Checks if a given peer is connected to us
1412  *
1413  * @param handle connection to transport service
1414  * @param peer the peer to check
1415  * @return #GNUNET_YES (connected) or #GNUNET_NO (disconnected)
1416  */
1417 int
1418 GNUNET_TRANSPORT_check_peer_connected (struct GNUNET_TRANSPORT_Handle *handle,
1419                                        const struct GNUNET_PeerIdentity *peer)
1420 {
1421   if (GNUNET_YES ==
1422       GNUNET_CONTAINER_multipeermap_contains (handle->neighbours,
1423                                               peer))
1424     return GNUNET_YES;
1425   return GNUNET_NO;
1426 }
1427
1428
1429 /**
1430  * Task to call the HelloUpdateCallback of the GetHelloHandle
1431  *
1432  * @param cls the `struct GNUNET_TRANSPORT_GetHelloHandle`
1433  * @param tc the scheduler task context
1434  */
1435 static void
1436 call_hello_update_cb_async (void *cls,
1437                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1438 {
1439   struct GNUNET_TRANSPORT_GetHelloHandle *ghh = cls;
1440
1441   GNUNET_assert (NULL != ghh->handle->my_hello);
1442   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != ghh->notify_task);
1443   ghh->notify_task = GNUNET_SCHEDULER_NO_TASK;
1444   ghh->rec (ghh->rec_cls,
1445             (const struct GNUNET_MessageHeader *) ghh->handle->my_hello);
1446 }
1447
1448
1449 /**
1450  * Obtain the HELLO message for this peer.  The callback given in this function
1451  * is never called synchronously.
1452  *
1453  * @param handle connection to transport service
1454  * @param rec function to call with the HELLO, sender will be our peer
1455  *            identity; message and sender will be NULL on timeout
1456  *            (handshake with transport service pending/failed).
1457  *             cost estimate will be 0.
1458  * @param rec_cls closure for @a rec
1459  * @return handle to cancel the operation
1460  */
1461 struct GNUNET_TRANSPORT_GetHelloHandle *
1462 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1463                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1464                             void *rec_cls)
1465 {
1466   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1467
1468   hwl = GNUNET_new (struct GNUNET_TRANSPORT_GetHelloHandle);
1469   hwl->rec = rec;
1470   hwl->rec_cls = rec_cls;
1471   hwl->handle = handle;
1472   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1473   if (handle->my_hello != NULL)
1474     hwl->notify_task = GNUNET_SCHEDULER_add_now (&call_hello_update_cb_async,
1475                                                  hwl);
1476   return hwl;
1477 }
1478
1479
1480 /**
1481  * Stop receiving updates about changes to our HELLO message.
1482  *
1483  * @param ghh handle to cancel
1484  */
1485 void
1486 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1487 {
1488   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1489
1490   if (GNUNET_SCHEDULER_NO_TASK != ghh->notify_task)
1491     GNUNET_SCHEDULER_cancel (ghh->notify_task);
1492   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1493   GNUNET_free (ghh);
1494 }
1495
1496
1497 /**
1498  * Connect to the transport service.  Note that the connection may
1499  * complete (or fail) asynchronously.
1500  *
1501  * @param cfg configuration to use
1502  * @param self our own identity (API should check that it matches
1503  *             the identity found by transport), or NULL (no check)
1504  * @param cls closure for the callbacks
1505  * @param rec receive function to call
1506  * @param nc function to call on connect events
1507  * @param nd function to call on disconnect events
1508  */
1509 struct GNUNET_TRANSPORT_Handle *
1510 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1511                           const struct GNUNET_PeerIdentity *self, void *cls,
1512                           GNUNET_TRANSPORT_ReceiveCallback rec,
1513                           GNUNET_TRANSPORT_NotifyConnect nc,
1514                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1515 {
1516   struct GNUNET_TRANSPORT_Handle *ret;
1517
1518   ret = GNUNET_new (struct GNUNET_TRANSPORT_Handle);
1519   if (NULL != self)
1520   {
1521     ret->self = *self;
1522     ret->check_self = GNUNET_YES;
1523   }
1524   ret->cfg = cfg;
1525   ret->cls = cls;
1526   ret->rec = rec;
1527   ret->nc_cb = nc;
1528   ret->nd_cb = nd;
1529   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1530   LOG (GNUNET_ERROR_TYPE_DEBUG,
1531        "Connecting to transport service.\n");
1532   ret->client = GNUNET_CLIENT_connect ("transport", cfg);
1533   if (NULL == ret->client)
1534   {
1535     GNUNET_free (ret);
1536     return NULL;
1537   }
1538   ret->neighbours =
1539     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
1540                                           GNUNET_YES);
1541   ret->ready_heap =
1542       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1543  schedule_control_transmit (ret, sizeof (struct StartMessage),
1544                             &send_start, ret);
1545   return ret;
1546 }
1547
1548
1549 /**
1550  * Disconnect from the transport service.
1551  *
1552  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_connect()
1553  */
1554 void
1555 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1556 {
1557   LOG (GNUNET_ERROR_TYPE_DEBUG,
1558        "Transport disconnect called!\n");
1559   /* this disconnects all neighbours... */
1560   if (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1561     disconnect_and_schedule_reconnect (handle);
1562   /* and now we stop trying to connect again... */
1563   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1564   {
1565     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1566     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1567   }
1568   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
1569   handle->neighbours = NULL;
1570   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1571   {
1572     GNUNET_SCHEDULER_cancel (handle->quota_task);
1573     handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1574   }
1575   GNUNET_free_non_null (handle->my_hello);
1576   handle->my_hello = NULL;
1577   GNUNET_assert (handle->tc_head == NULL);
1578   GNUNET_assert (handle->tc_tail == NULL);
1579   GNUNET_assert (handle->hwl_head == NULL);
1580   GNUNET_assert (handle->hwl_tail == NULL);
1581   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1582   handle->ready_heap = NULL;
1583   GNUNET_free (handle);
1584 }
1585
1586
1587 /**
1588  * Check if we could queue a message of the given size for
1589  * transmission.  The transport service will take both its
1590  * internal buffers and bandwidth limits imposed by the
1591  * other peer into consideration when answering this query.
1592  *
1593  * @param handle connection to transport service
1594  * @param target who should receive the message
1595  * @param size how big is the message we want to transmit?
1596  * @param timeout after how long should we give up (and call
1597  *        notify with buf NULL and size 0)?
1598  * @param notify function to call when we are ready to
1599  *        send such a message
1600  * @param notify_cls closure for @a notify
1601  * @return NULL if someone else is already waiting to be notified
1602  *         non-NULL if the notify callback was queued (can be used to cancel
1603  *         using #GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1604  */
1605 struct GNUNET_TRANSPORT_TransmitHandle *
1606 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1607                                         const struct GNUNET_PeerIdentity *target,
1608                                         size_t size,
1609                                         struct GNUNET_TIME_Relative timeout,
1610                                         GNUNET_TRANSPORT_TransmitReadyNotify notify,
1611                                         void *notify_cls)
1612 {
1613   struct Neighbour *n;
1614   struct GNUNET_TRANSPORT_TransmitHandle *th;
1615   struct GNUNET_TIME_Relative delay;
1616
1617   n = neighbour_find (handle, target);
1618   if (NULL == n)
1619   {
1620     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1621      * once a connection has been established */
1622     GNUNET_assert (0);
1623     return NULL;
1624   }
1625   if (NULL != n->th)
1626   {
1627     /* attempt to send two messages at the same time to the same peer */
1628     GNUNET_assert (0);
1629     return NULL;
1630   }
1631   GNUNET_assert (NULL == n->hn);
1632   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1633   th->neighbour = n;
1634   th->notify = notify;
1635   th->notify_cls = notify_cls;
1636   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1637   th->notify_size = size;
1638   n->th = th;
1639   /* calculate when our transmission should be ready */
1640   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size + n->traffic_overhead);
1641   n->traffic_overhead = 0;
1642   if (delay.rel_value_us > timeout.rel_value_us)
1643     delay.rel_value_us = 0;        /* notify immediately (with failure) */
1644   LOG (GNUNET_ERROR_TYPE_DEBUG,
1645        "Bandwidth tracker allows next transmission to peer %s in %s\n",
1646        GNUNET_i2s (target),
1647        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1648   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value_us);
1649   schedule_transmission (handle);
1650   return th;
1651 }
1652
1653
1654 /**
1655  * Cancel the specified transmission-ready notification.
1656  *
1657  * @param th handle returned from #GNUNET_TRANSPORT_notify_transmit_ready()
1658  */
1659 void
1660 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct GNUNET_TRANSPORT_TransmitHandle *th)
1661 {
1662   struct Neighbour *n;
1663
1664   GNUNET_assert (NULL == th->next);
1665   GNUNET_assert (NULL == th->prev);
1666   n = th->neighbour;
1667   GNUNET_assert (th == n->th);
1668   n->th = NULL;
1669   if (NULL != n->hn)
1670   {
1671     GNUNET_CONTAINER_heap_remove_node (n->hn);
1672     n->hn = NULL;
1673   }
1674   else
1675   {
1676     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != th->timeout_task);
1677     GNUNET_SCHEDULER_cancel (th->timeout_task);
1678     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1679   }
1680   GNUNET_free (th);
1681 }
1682
1683
1684 /* end of transport_api.c */