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