- fix error messages
[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 static int reconnecting;
481
482 /**
483  * Function we use for handling incoming messages.
484  *
485  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
486  * @param msg message received, NULL on timeout or fatal error
487  */
488 static void
489 demultiplexer (void *cls, const struct GNUNET_MessageHeader *msg)
490 {
491   struct GNUNET_TRANSPORT_Handle *h = cls;
492   const struct DisconnectInfoMessage *dim;
493   const struct ConnectInfoMessage *cim;
494   const struct InboundMessage *im;
495   const struct GNUNET_MessageHeader *imm;
496   const struct SendOkMessage *okm;
497   const struct QuotaSetMessage *qm;
498   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
499   struct GNUNET_TRANSPORT_GetHelloHandle *next_hwl;
500   struct Neighbour *n;
501   struct GNUNET_PeerIdentity me;
502   uint16_t size;
503   uint32_t bytes_msg;
504   uint32_t bytes_physical;
505
506   GNUNET_assert (NULL != h->client);
507   if (GNUNET_YES == reconnecting)
508   {
509     return;
510   }
511   if (NULL == msg)
512   {
513     LOG (GNUNET_ERROR_TYPE_DEBUG,
514          "Error receiving from transport service, disconnecting temporarily.\n");
515     reconnecting = GNUNET_YES;
516     disconnect_and_schedule_reconnect (h);
517     return;
518   }
519   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
520                          GNUNET_TIME_UNIT_FOREVER_REL);
521   size = ntohs (msg->size);
522   switch (ntohs (msg->type))
523   {
524   case GNUNET_MESSAGE_TYPE_HELLO:
525     if (GNUNET_OK !=
526         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg, &me))
527     {
528       GNUNET_break (0);
529       break;
530     }
531     LOG (GNUNET_ERROR_TYPE_DEBUG,
532          "Receiving (my own) `%s' message, I am `%4s'.\n", "HELLO",
533          GNUNET_i2s (&me));
534     GNUNET_free_non_null (h->my_hello);
535     h->my_hello = NULL;
536     if (size < sizeof (struct GNUNET_MessageHeader))
537     {
538       GNUNET_break (0);
539       break;
540     }
541     h->my_hello = GNUNET_malloc (size);
542     memcpy (h->my_hello, msg, size);
543     hwl = h->hwl_head;
544     while (NULL != hwl)
545     {
546       next_hwl = hwl->next;
547       hwl->rec (hwl->rec_cls,
548                 (const struct GNUNET_MessageHeader *) h->my_hello);
549       hwl = next_hwl;
550     }
551     break;
552   case GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT:
553     if (size < sizeof (struct ConnectInfoMessage))
554     {
555       GNUNET_break (0);
556       break;
557     }
558     cim = (const struct ConnectInfoMessage *) msg;
559     if (size !=
560         sizeof (struct ConnectInfoMessage))
561     {
562       GNUNET_break (0);
563       break;
564     }
565     LOG (GNUNET_ERROR_TYPE_DEBUG,
566          "Receiving `%s' message for `%4s'.\n",
567          "CONNECT", GNUNET_i2s (&cim->id));
568     n = neighbour_find (h, &cim->id);
569     if (NULL != n)
570     {
571       GNUNET_break (0);
572       break;
573     }
574     n = neighbour_add (h, &cim->id);
575     LOG (GNUNET_ERROR_TYPE_DEBUG,
576          "Receiving `%s' message for `%4s' with quota %u\n",
577          "CONNECT",
578          GNUNET_i2s (&cim->id),
579          ntohl (cim->quota_out.value__));
580     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, cim->quota_out);
581     if (h->nc_cb != NULL)
582       h->nc_cb (h->cls, &n->id);
583     break;
584   case GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT:
585     if (size != sizeof (struct DisconnectInfoMessage))
586     {
587       GNUNET_break (0);
588       break;
589     }
590     dim = (const struct DisconnectInfoMessage *) msg;
591     GNUNET_break (ntohl (dim->reserved) == 0);
592     LOG (GNUNET_ERROR_TYPE_DEBUG,
593          "Receiving `%s' message for `%4s'.\n",
594          "DISCONNECT", GNUNET_i2s (&dim->peer));
595     n = neighbour_find (h, &dim->peer);
596     if (NULL == n)
597     {
598       GNUNET_break (0);
599       break;
600     }
601     neighbour_delete (h, &dim->peer, n);
602     break;
603   case GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK:
604     if (size != sizeof (struct SendOkMessage))
605     {
606       GNUNET_break (0);
607       break;
608     }
609     okm = (const struct SendOkMessage *) msg;
610     bytes_msg = ntohl (okm->bytes_msg);
611     bytes_physical = ntohl (okm->bytes_physical);
612     LOG (GNUNET_ERROR_TYPE_DEBUG,
613          "Receiving SEND_OK message, transmission %s.\n",
614          ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
615
616     n = neighbour_find (h, &okm->peer);
617     if (NULL == n)
618       break;
619
620     if (bytes_physical >= bytes_msg)
621     {
622         LOG (GNUNET_ERROR_TYPE_DEBUG,
623              "Overhead for %u byte message: %u\n",
624             bytes_msg, bytes_physical - bytes_msg);
625       n->traffic_overhead += bytes_physical - bytes_msg;
626     }
627     GNUNET_break (GNUNET_NO == n->is_ready);
628     n->is_ready = GNUNET_YES;
629     if ((NULL != n->th) && (NULL == n->hn))
630     {
631       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != n->th->timeout_task);
632       GNUNET_SCHEDULER_cancel (n->th->timeout_task);
633       n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
634       /* we've been waiting for this (congestion, not quota,
635        * caused delayed transmission) */
636       n->hn = GNUNET_CONTAINER_heap_insert (h->ready_heap, n, 0);
637       schedule_transmission (h);
638     }
639     break;
640   case GNUNET_MESSAGE_TYPE_TRANSPORT_RECV:
641     LOG (GNUNET_ERROR_TYPE_DEBUG,
642          "Receiving `%s' message.\n",
643          "RECV");
644     if (size <
645         sizeof (struct InboundMessage) + sizeof (struct GNUNET_MessageHeader))
646     {
647       GNUNET_break (0);
648       break;
649     }
650     im = (const struct InboundMessage *) msg;
651     imm = (const struct GNUNET_MessageHeader *) &im[1];
652     if (ntohs (imm->size) + sizeof (struct InboundMessage) != size)
653     {
654       GNUNET_break (0);
655       break;
656     }
657     LOG (GNUNET_ERROR_TYPE_DEBUG,
658          "Received message of type %u from `%4s'.\n",
659          ntohs (imm->type), GNUNET_i2s (&im->peer));
660     n = neighbour_find (h, &im->peer);
661     if (NULL == n)
662     {
663       GNUNET_break (0);
664       break;
665     }
666     if (NULL != h->rec)
667       h->rec (h->cls, &im->peer, imm);
668     break;
669   case GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA:
670     LOG (GNUNET_ERROR_TYPE_DEBUG,
671          "Receiving `%s' message.\n", "SET_QUOTA");
672     if (size != sizeof (struct QuotaSetMessage))
673     {
674       GNUNET_break (0);
675       break;
676     }
677     qm = (const struct QuotaSetMessage *) msg;
678     n = neighbour_find (h, &qm->peer);
679     if (NULL == n)
680       break;
681     LOG (GNUNET_ERROR_TYPE_DEBUG,
682          "Receiving `%s' message for `%4s' with quota %u\n",
683          "SET_QUOTA",
684          GNUNET_i2s (&qm->peer),
685          ntohl (qm->quota.value__));
686     GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker, qm->quota);
687     break;
688   default:
689     LOG (GNUNET_ERROR_TYPE_ERROR,
690          _("Received unexpected message of type %u in %s:%u\n"),
691          ntohs (msg->type), __FILE__, __LINE__);
692     GNUNET_break (0);
693     break;
694   }
695 }
696
697
698 /**
699  * A transmission request could not be satisfied because of
700  * network congestion.  Notify the initiator and clean up.
701  *
702  * @param cls the `struct GNUNET_TRANSPORT_TransmitHandle`
703  * @param tc scheduler context
704  */
705 static void
706 timeout_request_due_to_congestion (void *cls,
707                                    const struct GNUNET_SCHEDULER_TaskContext *tc)
708 {
709   struct GNUNET_TRANSPORT_TransmitHandle *th = cls;
710   struct Neighbour *n = th->neighbour;
711
712   n->th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
713   GNUNET_assert (th == n->th);
714   GNUNET_assert (NULL == n->hn);
715   n->th = NULL;
716   th->notify (th->notify_cls, 0, NULL);
717   GNUNET_free (th);
718 }
719
720
721 /**
722  * Transmit message(s) to service.
723  *
724  * @param cls handle to transport
725  * @param size number of bytes available in @a buf
726  * @param buf where to copy the message
727  * @return number of bytes copied to @a buf
728  */
729 static size_t
730 transport_notify_ready (void *cls, size_t size, void *buf)
731 {
732   struct GNUNET_TRANSPORT_Handle *h = cls;
733   struct GNUNET_TRANSPORT_TransmitHandle *th;
734   struct Neighbour *n;
735   char *cbuf;
736   struct OutboundMessage obm;
737   size_t ret;
738   size_t nret;
739   size_t mret;
740
741   GNUNET_assert (NULL != h->client);
742   h->cth = NULL;
743   if (NULL == buf)
744   {
745     /* transmission failed */
746     disconnect_and_schedule_reconnect (h);
747     return 0;
748   }
749
750   cbuf = buf;
751   ret = 0;
752   /* first send control messages */
753   while ((NULL != (th = h->control_head)) && (th->notify_size <= size))
754   {
755     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
756     nret = th->notify (th->notify_cls, size, &cbuf[ret]);
757     LOG (GNUNET_ERROR_TYPE_DEBUG,
758          "Added %u bytes of control message at %u\n",
759          nret, ret);
760     GNUNET_free (th);
761     ret += nret;
762     size -= nret;
763   }
764
765   /* then, if possible and no control messages pending, send data messages */
766   while ((NULL == h->control_head) &&
767          (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))))
768   {
769     if (GNUNET_YES != n->is_ready)
770     {
771       /* peer not ready, wait for notification! */
772       GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
773       n->hn = NULL;
774       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == n->th->timeout_task);
775       n->th->timeout_task =
776           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
777                                         (n->th->timeout),
778                                         &timeout_request_due_to_congestion,
779                                         n->th);
780       continue;
781     }
782     th = n->th;
783     if (th->notify_size + sizeof (struct OutboundMessage) > size)
784       break;                    /* does not fit */
785     if (GNUNET_BANDWIDTH_tracker_get_delay
786         (&n->out_tracker, th->notify_size).rel_value_us > 0)
787       break;                    /* too early */
788     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
789     n->hn = NULL;
790     n->th = NULL;
791     n->is_ready = GNUNET_NO;
792     GNUNET_assert (size >= sizeof (struct OutboundMessage));
793     mret =
794         th->notify (th->notify_cls, size - sizeof (struct OutboundMessage),
795                     &cbuf[ret + sizeof (struct OutboundMessage)]);
796     GNUNET_assert (mret <= size - sizeof (struct OutboundMessage));
797     if (mret != 0)
798     {
799       GNUNET_assert (mret + sizeof (struct OutboundMessage) <
800                      GNUNET_SERVER_MAX_MESSAGE_SIZE);
801       obm.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_SEND);
802       obm.header.size = htons (mret + sizeof (struct OutboundMessage));
803       obm.priority = htonl (th->priority);
804       obm.timeout =
805           GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining
806                                      (th->timeout));
807       obm.peer = n->id;
808       memcpy (&cbuf[ret], &obm, sizeof (struct OutboundMessage));
809       ret += (mret + sizeof (struct OutboundMessage));
810       size -= (mret + sizeof (struct OutboundMessage));
811       GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker, mret);
812     }
813     GNUNET_free (th);
814   }
815   /* if there are more pending messages, try to schedule those */
816   schedule_transmission (h);
817   LOG (GNUNET_ERROR_TYPE_DEBUG,
818        "Transmitting %u bytes to transport service\n",
819        ret);
820   return ret;
821 }
822
823
824 /**
825  * Schedule the task to send one message, either from the control
826  * list or the peer message queues  to the service.
827  *
828  * @param cls transport service to schedule a transmission for
829  * @param tc scheduler context
830  */
831 static void
832 schedule_transmission_task (void *cls,
833                             const struct GNUNET_SCHEDULER_TaskContext *tc)
834 {
835   struct GNUNET_TRANSPORT_Handle *h = cls;
836   size_t size;
837   struct GNUNET_TRANSPORT_TransmitHandle *th;
838   struct Neighbour *n;
839
840   h->quota_task = GNUNET_SCHEDULER_NO_TASK;
841   GNUNET_assert (NULL != h->client);
842   /* destroy all requests that have timed out */
843   while ((NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap))) &&
844          (0 == GNUNET_TIME_absolute_get_remaining (n->th->timeout).rel_value_us))
845   {
846     /* notify client that the request could not be satisfied within
847      * the given time constraints */
848     th = n->th;
849     n->th = NULL;
850     GNUNET_assert (n == GNUNET_CONTAINER_heap_remove_root (h->ready_heap));
851     n->hn = NULL;
852     LOG (GNUNET_ERROR_TYPE_DEBUG,
853          "Signalling timeout for transmission to peer %s due to congestion\n",
854          GNUNET_i2s (&n->id));
855     GNUNET_assert (0 == th->notify (th->notify_cls, 0, NULL));
856     GNUNET_free (th);
857   }
858   if (NULL != h->cth)
859     return;
860   if (NULL != h->control_head)
861   {
862     size = h->control_head->notify_size;
863   }
864   else
865   {
866     n = GNUNET_CONTAINER_heap_peek (h->ready_heap);
867     if (NULL == n)
868       return;                   /* no pending messages */
869     size = n->th->notify_size + sizeof (struct OutboundMessage);
870   }
871   LOG (GNUNET_ERROR_TYPE_DEBUG, "Calling notify_transmit_ready\n");
872   h->cth =
873       GNUNET_CLIENT_notify_transmit_ready (h->client, size,
874                                            GNUNET_TIME_UNIT_FOREVER_REL,
875                                            GNUNET_NO, &transport_notify_ready,
876                                            h);
877   GNUNET_assert (NULL != h->cth);
878 }
879
880
881 /**
882  * Schedule the task to send one message, either from the control
883  * list or the peer message queues  to the service.
884  *
885  * @param h transport service to schedule a transmission for
886  */
887 static void
888 schedule_transmission (struct GNUNET_TRANSPORT_Handle *h)
889 {
890   struct GNUNET_TIME_Relative delay;
891   struct Neighbour *n;
892
893   GNUNET_assert (NULL != h->client);
894   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
895   {
896     GNUNET_SCHEDULER_cancel (h->quota_task);
897     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
898   }
899   if (NULL != h->control_head)
900     delay = GNUNET_TIME_UNIT_ZERO;
901   else if (NULL != (n = GNUNET_CONTAINER_heap_peek (h->ready_heap)))
902   {
903     delay =
904         GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
905                                             n->th->notify_size + n->traffic_overhead);
906     n->traffic_overhead = 0;
907   }
908   else
909     return;                     /* no work to be done */
910   LOG (GNUNET_ERROR_TYPE_DEBUG,
911        "Scheduling next transmission to service in %s\n",
912        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
913   h->quota_task =
914       GNUNET_SCHEDULER_add_delayed (delay, &schedule_transmission_task, h);
915 }
916
917
918 /**
919  * Queue control request for transmission to the transport
920  * service.
921  *
922  * @param h handle to the transport service
923  * @param size number of bytes to be transmitted
924  * @param notify function to call to get the content
925  * @param notify_cls closure for @a notify
926  * @return a `struct GNUNET_TRANSPORT_TransmitHandle`
927  */
928 static struct GNUNET_TRANSPORT_TransmitHandle *
929 schedule_control_transmit (struct GNUNET_TRANSPORT_Handle *h, size_t size,
930                            GNUNET_CONNECTION_TransmitReadyNotify notify,
931                            void *notify_cls)
932 {
933   struct GNUNET_TRANSPORT_TransmitHandle *th;
934
935   LOG (GNUNET_ERROR_TYPE_DEBUG,
936        "Control transmit of %u bytes requested\n",
937        size);
938   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
939   th->notify = notify;
940   th->notify_cls = notify_cls;
941   th->notify_size = size;
942   GNUNET_CONTAINER_DLL_insert_tail (h->control_head, h->control_tail, th);
943   schedule_transmission (h);
944   return th;
945 }
946
947
948 /**
949  * Transmit START message to service.
950  *
951  * @param cls unused
952  * @param size number of bytes available in @a buf
953  * @param buf where to copy the message
954  * @return number of bytes copied to @a buf
955  */
956 static size_t
957 send_start (void *cls, size_t size, void *buf)
958 {
959   struct GNUNET_TRANSPORT_Handle *h = cls;
960   struct StartMessage s;
961   uint32_t options;
962
963   if (NULL == buf)
964   {
965     /* Can only be shutdown, just give up */
966     LOG (GNUNET_ERROR_TYPE_DEBUG,
967          "Shutdown while trying to transmit `%s' request.\n",
968          "START");
969     return 0;
970   }
971   LOG (GNUNET_ERROR_TYPE_DEBUG,
972        "Transmitting `%s' request.\n",
973        "START");
974   GNUNET_assert (size >= sizeof (struct StartMessage));
975   s.header.size = htons (sizeof (struct StartMessage));
976   s.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_START);
977   options = 0;
978   if (h->check_self)
979     options |= 1;
980   if (h->rec != NULL)
981     options |= 2;
982   s.options = htonl (options);
983   s.self = h->self;
984   memcpy (buf, &s, sizeof (struct StartMessage));
985   GNUNET_CLIENT_receive (h->client, &demultiplexer, h,
986                          GNUNET_TIME_UNIT_FOREVER_REL);
987   return sizeof (struct StartMessage);
988 }
989
990
991 /**
992  * Try again to connect to transport service.
993  *
994  * @param cls the handle to the transport service
995  * @param tc scheduler context
996  */
997 static void
998 reconnect (void *cls,
999            const struct GNUNET_SCHEDULER_TaskContext *tc)
1000 {
1001   struct GNUNET_TRANSPORT_Handle *h = cls;
1002
1003   h->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1004   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1005   {
1006     /* shutdown, just give up */
1007     return;
1008   }
1009   LOG (GNUNET_ERROR_TYPE_DEBUG,
1010        "Connecting to transport service.\n");
1011   GNUNET_assert (NULL == h->client);
1012   GNUNET_assert (NULL == h->control_head);
1013   GNUNET_assert (NULL == h->control_tail);
1014   reconnecting = GNUNET_NO;
1015   h->client = GNUNET_CLIENT_connect ("transport", h->cfg);
1016
1017   GNUNET_assert (NULL != h->client);
1018   schedule_control_transmit (h, sizeof (struct StartMessage), &send_start, h);
1019 }
1020
1021
1022 /**
1023  * Function that will schedule the job that will try
1024  * to connect us again to the client.
1025  *
1026  * @param h transport service to reconnect
1027  */
1028 static void
1029 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_Handle *h)
1030 {
1031   struct GNUNET_TRANSPORT_TransmitHandle *th;
1032
1033   GNUNET_assert (h->reconnect_task == GNUNET_SCHEDULER_NO_TASK);
1034   if (NULL != h->cth)
1035   {
1036     GNUNET_CLIENT_notify_transmit_ready_cancel (h->cth);
1037     h->cth = NULL;
1038   }
1039   if (NULL != h->client)
1040   {
1041     GNUNET_CLIENT_disconnect (h->client);
1042     h->client = NULL;
1043 /*    LOG (GNUNET_ERROR_TYPE_ERROR,
1044          "Client disconnect done \n");*/
1045   }
1046   /* Forget about all neighbours that we used to be connected to */
1047   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
1048                                          &neighbour_delete, h);
1049   if (h->quota_task != GNUNET_SCHEDULER_NO_TASK)
1050   {
1051     GNUNET_SCHEDULER_cancel (h->quota_task);
1052     h->quota_task = GNUNET_SCHEDULER_NO_TASK;
1053   }
1054   while ((NULL != (th = h->control_head)))
1055   {
1056     GNUNET_CONTAINER_DLL_remove (h->control_head, h->control_tail, th);
1057     th->notify (th->notify_cls, 0, NULL);
1058     GNUNET_free (th);
1059   }
1060   LOG (GNUNET_ERROR_TYPE_DEBUG,
1061        "Scheduling task to reconnect to transport service in %s.\n",
1062        GNUNET_STRINGS_relative_time_to_string(h->reconnect_delay, GNUNET_YES));
1063   h->reconnect_task =
1064       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay, &reconnect, h);
1065   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
1066 }
1067
1068
1069 /**
1070  * Cancel control request for transmission to the transport service.
1071  *
1072  * @param th handle to the transport service
1073  * @param tth transmit handle to cancel
1074  */
1075 static void
1076 cancel_control_transmit (struct GNUNET_TRANSPORT_Handle *th,
1077                          struct GNUNET_TRANSPORT_TransmitHandle *tth)
1078 {
1079   LOG (GNUNET_ERROR_TYPE_DEBUG,
1080        "Canceling transmit of contral transmission requested\n");
1081   GNUNET_CONTAINER_DLL_remove (th->control_head, th->control_tail, tth);
1082   GNUNET_free (tth);
1083 }
1084
1085
1086
1087 /**
1088  * Send REQUEST_CONNECT message to the service.
1089  *
1090  * @param cls the `struct GNUNET_PeerIdentity`
1091  * @param size number of bytes available in @a buf
1092  * @param buf where to copy the message
1093  * @return number of bytes copied to @a buf
1094  */
1095 static size_t
1096 send_try_connect (void *cls, size_t size, void *buf)
1097 {
1098   struct GNUNET_TRANSPORT_TryConnectHandle *tch = cls;
1099   struct TransportRequestConnectMessage msg;
1100
1101   if (buf == NULL)
1102   {
1103     if (NULL != tch->cb)
1104       tch->cb (tch->cb_cls, GNUNET_SYSERR);
1105     GNUNET_CONTAINER_DLL_remove (tch->th->tc_head, tch->th->tc_tail, tch);
1106     LOG (GNUNET_ERROR_TYPE_DEBUG,
1107          "Discarding  `%s' request to `%4s' due to error in transport service connection.\n",
1108          "REQUEST_CONNECT",
1109          GNUNET_i2s (&tch->pid));
1110     GNUNET_free (tch);
1111     return 0;
1112   }
1113   LOG (GNUNET_ERROR_TYPE_DEBUG,
1114        "Transmitting `%s' request with respect to `%4s'.\n",
1115        "REQUEST_CONNECT",
1116        GNUNET_i2s (&tch->pid));
1117   GNUNET_assert (size >= sizeof (struct TransportRequestConnectMessage));
1118   msg.header.size = htons (sizeof (struct TransportRequestConnectMessage));
1119   msg.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_REQUEST_CONNECT);
1120   msg.reserved = htonl (0);
1121   msg.peer = tch->pid;
1122   memcpy (buf, &msg, sizeof (msg));
1123   if (NULL != tch->cb)
1124     tch->cb (tch->cb_cls, GNUNET_OK);
1125   GNUNET_CONTAINER_DLL_remove (tch->th->tc_head, tch->th->tc_tail, tch);
1126   GNUNET_free (tch);
1127   return sizeof (struct TransportRequestConnectMessage);
1128 }
1129
1130 /**
1131  * Ask the transport service to establish a connection to
1132  * the given peer.
1133  *
1134  * @param handle connection to transport service
1135  * @param target who we should try to connect to
1136  * @param cb callback to be called when request was transmitted to transport
1137  *         service
1138  * @param cb_cls closure for the callback
1139  * @return a `struct GNUNET_TRANSPORT_TryConnectHandle` handle or
1140  *         NULL on failure (cb will not be called)
1141  */
1142 struct GNUNET_TRANSPORT_TryConnectHandle *
1143 GNUNET_TRANSPORT_try_connect (struct GNUNET_TRANSPORT_Handle *handle,
1144                               const struct GNUNET_PeerIdentity *target,
1145                               GNUNET_TRANSPORT_TryConnectCallback cb,
1146                               void *cb_cls)
1147 {
1148   struct GNUNET_TRANSPORT_TryConnectHandle *tch = NULL;
1149
1150   if (NULL == handle->client)
1151       return NULL;
1152   tch = GNUNET_new (struct GNUNET_TRANSPORT_TryConnectHandle);
1153   tch->th = handle;
1154   tch->pid = *(target);
1155   tch->cb = cb;
1156   tch->cb_cls = cb_cls;
1157   tch->tth = schedule_control_transmit (handle,
1158                                         sizeof (struct TransportRequestConnectMessage),
1159                                         &send_try_connect, tch);
1160   GNUNET_CONTAINER_DLL_insert(handle->tc_head, handle->tc_tail, tch);
1161   return tch;
1162 }
1163
1164
1165 /**
1166  * Cancel the request to transport to try a connect
1167  * Callback will not be called
1168  *
1169  * @param tch the handle to cancel
1170  */
1171 void
1172 GNUNET_TRANSPORT_try_connect_cancel (struct GNUNET_TRANSPORT_TryConnectHandle *tch)
1173 {
1174   struct GNUNET_TRANSPORT_Handle *th;
1175
1176   th = tch->th;
1177   cancel_control_transmit (th, tch->tth);
1178   GNUNET_CONTAINER_DLL_remove (th->tc_head, th->tc_tail, tch);
1179   GNUNET_free (tch);
1180 }
1181
1182 /**
1183  * Send HELLO message to the service.
1184  *
1185  * @param cls the HELLO message to send
1186  * @param size number of bytes available in @a buf
1187  * @param buf where to copy the message
1188  * @return number of bytes copied to @a buf
1189  */
1190 static size_t
1191 send_hello (void *cls, size_t size, void *buf)
1192 {
1193   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh = cls;
1194   struct GNUNET_MessageHeader *msg = ohh->msg;
1195   uint16_t ssize;
1196   struct GNUNET_SCHEDULER_TaskContext tc;
1197
1198   tc.read_ready = NULL;
1199   tc.write_ready = NULL;
1200   tc.reason = GNUNET_SCHEDULER_REASON_TIMEOUT;
1201   if (NULL == buf)
1202   {
1203     LOG (GNUNET_ERROR_TYPE_DEBUG,
1204          "Timeout while trying to transmit `%s' request.\n",
1205          "HELLO");
1206     if (NULL != ohh->cont)
1207       ohh->cont (ohh->cls, &tc);
1208     GNUNET_free (msg);
1209     GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1210     GNUNET_free (ohh);
1211     return 0;
1212   }
1213   LOG (GNUNET_ERROR_TYPE_DEBUG,
1214        "Transmitting `%s' request.\n",
1215        "HELLO");
1216   ssize = ntohs (msg->size);
1217   GNUNET_assert (size >= ssize);
1218   memcpy (buf, msg, ssize);
1219   GNUNET_free (msg);
1220   tc.reason = GNUNET_SCHEDULER_REASON_READ_READY;
1221   if (NULL != ohh->cont)
1222     ohh->cont (ohh->cls, &tc);
1223   GNUNET_CONTAINER_DLL_remove (ohh->th->oh_head, ohh->th->oh_tail, ohh);
1224   GNUNET_free (ohh);
1225   return ssize;
1226 }
1227
1228
1229 /**
1230  * Send traffic metric message to the service.
1231  *
1232  * @param cls the message to send
1233  * @param size number of bytes available in @a buf
1234  * @param buf where to copy the message
1235  * @return number of bytes copied to @a buf
1236  */
1237 static size_t
1238 send_metric (void *cls, size_t size, void *buf)
1239 {
1240   struct TrafficMetricMessage *msg = cls;
1241   uint16_t ssize;
1242
1243   if (NULL == buf)
1244   {
1245     LOG (GNUNET_ERROR_TYPE_DEBUG,
1246          "Timeout while trying to transmit `%s' request.\n",
1247          "TRAFFIC_METRIC");
1248     GNUNET_free (msg);
1249     return 0;
1250   }
1251   LOG (GNUNET_ERROR_TYPE_DEBUG,
1252        "Transmitting `%s' request.\n",
1253        "TRAFFIC_METRIC");
1254   ssize = ntohs (msg->header.size);
1255   GNUNET_assert (size >= ssize);
1256   memcpy (buf, msg, ssize);
1257   GNUNET_free (msg);
1258   return ssize;
1259 }
1260
1261
1262 /**
1263  * Set transport metrics for a peer and a direction
1264  *
1265  * @param handle transport handle
1266  * @param peer the peer to set the metric for
1267  * @param inbound set inbound direction (#GNUNET_YES or #GNUNET_NO)
1268  * @param outbound set outbound direction (#GNUNET_YES or #GNUNET_NO)
1269  * @param ats the metric as ATS information
1270  * @param ats_count the number of metrics
1271  *
1272  * Supported ATS values:
1273  * #GNUNET_ATS_QUALITY_NET_DELAY  (value in ms)
1274  * #GNUNET_ATS_QUALITY_NET_DISTANCE (value in count(hops))
1275  *
1276  * Example:
1277  * To enforce a delay of 10 ms for peer p1 in sending direction use:
1278  * <code>
1279  * struct GNUNET_ATS_Information ats;
1280  * ats.type = ntohl (GNUNET_ATS_QUALITY_NET_DELAY);
1281  * ats.value = ntohl (10);
1282  * GNUNET_TRANSPORT_set_traffic_metric (th, p1, TM_SEND, &ats, 1);
1283  * </code>
1284  * Note:
1285  * Delay restrictions in receiving direction will be enforced with
1286  * 1 message delay.
1287  */
1288 void
1289 GNUNET_TRANSPORT_set_traffic_metric (struct GNUNET_TRANSPORT_Handle *handle,
1290                                      const struct GNUNET_PeerIdentity *peer,
1291                                      int inbound,
1292                                      int outbound,
1293                                      const struct GNUNET_ATS_Information *ats,
1294                                      size_t ats_count)
1295 {
1296   struct TrafficMetricMessage *msg;
1297
1298   GNUNET_assert ((outbound == GNUNET_YES) || (outbound == GNUNET_NO));
1299   GNUNET_assert ((inbound == GNUNET_YES) || (inbound == GNUNET_NO));
1300   if ((GNUNET_NO == inbound) && (GNUNET_NO == outbound))
1301     return;
1302   if (0 == ats_count)
1303     return;
1304
1305   size_t len = sizeof (struct TrafficMetricMessage) +
1306     ats_count * sizeof (struct GNUNET_ATS_Information);
1307
1308   msg = GNUNET_malloc (len);
1309   msg->header.size = htons (len);
1310   msg->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_TRAFFIC_METRIC);
1311   msg->direction = htons (0 + outbound + 2 * inbound);
1312   msg->ats_count = htons (ats_count);
1313   msg->peer = (*peer);
1314   memcpy (&msg[1], ats, ats_count * sizeof (struct GNUNET_ATS_Information));
1315   schedule_control_transmit (handle, len, &send_metric, msg);
1316 }
1317
1318
1319
1320 /**
1321  * Offer the transport service the HELLO of another peer.  Note that
1322  * the transport service may just ignore this message if the HELLO is
1323  * malformed or useless due to our local configuration.
1324  *
1325  * @param handle connection to transport service
1326  * @param hello the hello message
1327  * @param cont continuation to call when HELLO has been sent,
1328  *      tc reason #GNUNET_SCHEDULER_REASON_TIMEOUT for fail
1329  *      tc reasong #GNUNET_SCHEDULER_REASON_READ_READY for success
1330  * @param cls closure for continuation
1331  * @return a `struct GNUNET_TRANSPORT_OfferHelloHandle` handle or NULL on failure,
1332  *      in case of failure cont will not be called
1333  *
1334  */
1335 struct GNUNET_TRANSPORT_OfferHelloHandle *
1336 GNUNET_TRANSPORT_offer_hello (struct GNUNET_TRANSPORT_Handle *handle,
1337                               const struct GNUNET_MessageHeader *hello,
1338                               GNUNET_SCHEDULER_Task cont, void *cls)
1339 {
1340   struct GNUNET_TRANSPORT_OfferHelloHandle *ohh;
1341   struct GNUNET_MessageHeader *msg;
1342   struct GNUNET_PeerIdentity peer;
1343   uint16_t size;
1344
1345   if (NULL == handle->client)
1346     return NULL;
1347   GNUNET_break (ntohs (hello->type) == GNUNET_MESSAGE_TYPE_HELLO);
1348   size = ntohs (hello->size);
1349   GNUNET_break (size >= sizeof (struct GNUNET_MessageHeader));
1350   if (GNUNET_OK !=
1351       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello, &peer))
1352   {
1353     GNUNET_break (0);
1354     return NULL;
1355   }
1356
1357   msg = GNUNET_malloc (size);
1358   memcpy (msg, hello, size);
1359   LOG (GNUNET_ERROR_TYPE_DEBUG,
1360        "Offering `%s' message of `%4s' to transport for validation.\n", "HELLO",
1361        GNUNET_i2s (&peer));
1362
1363   ohh = GNUNET_new (struct GNUNET_TRANSPORT_OfferHelloHandle);
1364   ohh->th = handle;
1365   ohh->cont = cont;
1366   ohh->cls = cls;
1367   ohh->msg = msg;
1368   ohh->tth = schedule_control_transmit (handle, size, &send_hello, ohh);
1369   GNUNET_CONTAINER_DLL_insert (handle->oh_head, handle->oh_tail, ohh);
1370   return ohh;
1371 }
1372
1373
1374 /**
1375  * Cancel the request to transport to offer the HELLO message
1376  *
1377  * @param ohh the GNUNET_TRANSPORT_OfferHelloHandle to cancel
1378  */
1379 void
1380 GNUNET_TRANSPORT_offer_hello_cancel (struct GNUNET_TRANSPORT_OfferHelloHandle *ohh)
1381 {
1382   struct GNUNET_TRANSPORT_Handle *th = ohh->th;
1383
1384   cancel_control_transmit (ohh->th, ohh->tth);
1385   GNUNET_CONTAINER_DLL_remove (th->oh_head, th->oh_tail, ohh);
1386   GNUNET_free (ohh->msg);
1387   GNUNET_free (ohh);
1388 }
1389
1390
1391 /**
1392  * Checks if a given peer is connected to us
1393  *
1394  * @param handle connection to transport service
1395  * @param peer the peer to check
1396  * @return #GNUNET_YES (connected) or #GNUNET_NO (disconnected)
1397  */
1398 int
1399 GNUNET_TRANSPORT_check_peer_connected (struct GNUNET_TRANSPORT_Handle *handle,
1400                                        const struct GNUNET_PeerIdentity *peer)
1401 {
1402   if (GNUNET_YES ==
1403       GNUNET_CONTAINER_multipeermap_contains (handle->neighbours,
1404                                               peer))
1405     return GNUNET_YES;
1406   return GNUNET_NO;
1407 }
1408
1409
1410 /**
1411  * Task to call the HelloUpdateCallback of the GetHelloHandle
1412  *
1413  * @param cls the `struct GNUNET_TRANSPORT_GetHelloHandle`
1414  * @param tc the scheduler task context
1415  */
1416 static void
1417 call_hello_update_cb_async (void *cls,
1418                             const struct GNUNET_SCHEDULER_TaskContext *tc)
1419 {
1420   struct GNUNET_TRANSPORT_GetHelloHandle *ghh = cls;
1421
1422   GNUNET_assert (NULL != ghh->handle->my_hello);
1423   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != ghh->notify_task);
1424   ghh->notify_task = GNUNET_SCHEDULER_NO_TASK;
1425   ghh->rec (ghh->rec_cls,
1426             (const struct GNUNET_MessageHeader *) ghh->handle->my_hello);
1427 }
1428
1429
1430 /**
1431  * Obtain the HELLO message for this peer.  The callback given in this function
1432  * is never called synchronously.
1433  *
1434  * @param handle connection to transport service
1435  * @param rec function to call with the HELLO, sender will be our peer
1436  *            identity; message and sender will be NULL on timeout
1437  *            (handshake with transport service pending/failed).
1438  *             cost estimate will be 0.
1439  * @param rec_cls closure for @a rec
1440  * @return handle to cancel the operation
1441  */
1442 struct GNUNET_TRANSPORT_GetHelloHandle *
1443 GNUNET_TRANSPORT_get_hello (struct GNUNET_TRANSPORT_Handle *handle,
1444                             GNUNET_TRANSPORT_HelloUpdateCallback rec,
1445                             void *rec_cls)
1446 {
1447   struct GNUNET_TRANSPORT_GetHelloHandle *hwl;
1448
1449   hwl = GNUNET_new (struct GNUNET_TRANSPORT_GetHelloHandle);
1450   hwl->rec = rec;
1451   hwl->rec_cls = rec_cls;
1452   hwl->handle = handle;
1453   GNUNET_CONTAINER_DLL_insert (handle->hwl_head, handle->hwl_tail, hwl);
1454   if (handle->my_hello != NULL)
1455     hwl->notify_task = GNUNET_SCHEDULER_add_now (&call_hello_update_cb_async,
1456                                                  hwl);
1457   return hwl;
1458 }
1459
1460
1461 /**
1462  * Stop receiving updates about changes to our HELLO message.
1463  *
1464  * @param ghh handle to cancel
1465  */
1466 void
1467 GNUNET_TRANSPORT_get_hello_cancel (struct GNUNET_TRANSPORT_GetHelloHandle *ghh)
1468 {
1469   struct GNUNET_TRANSPORT_Handle *handle = ghh->handle;
1470
1471   if (GNUNET_SCHEDULER_NO_TASK != ghh->notify_task)
1472     GNUNET_SCHEDULER_cancel (ghh->notify_task);
1473   GNUNET_CONTAINER_DLL_remove (handle->hwl_head, handle->hwl_tail, ghh);
1474   GNUNET_free (ghh);
1475 }
1476
1477
1478 /**
1479  * Connect to the transport service.  Note that the connection may
1480  * complete (or fail) asynchronously.
1481  *
1482  * @param cfg configuration to use
1483  * @param self our own identity (API should check that it matches
1484  *             the identity found by transport), or NULL (no check)
1485  * @param cls closure for the callbacks
1486  * @param rec receive function to call
1487  * @param nc function to call on connect events
1488  * @param nd function to call on disconnect events
1489  */
1490 struct GNUNET_TRANSPORT_Handle *
1491 GNUNET_TRANSPORT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1492                           const struct GNUNET_PeerIdentity *self, void *cls,
1493                           GNUNET_TRANSPORT_ReceiveCallback rec,
1494                           GNUNET_TRANSPORT_NotifyConnect nc,
1495                           GNUNET_TRANSPORT_NotifyDisconnect nd)
1496 {
1497   struct GNUNET_TRANSPORT_Handle *ret;
1498
1499   ret = GNUNET_new (struct GNUNET_TRANSPORT_Handle);
1500   if (NULL != self)
1501   {
1502     ret->self = *self;
1503     ret->check_self = GNUNET_YES;
1504   }
1505   ret->cfg = cfg;
1506   ret->cls = cls;
1507   ret->rec = rec;
1508   ret->nc_cb = nc;
1509   ret->nd_cb = nd;
1510   ret->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
1511   LOG (GNUNET_ERROR_TYPE_DEBUG,
1512        "Connecting to transport service.\n");
1513   ret->client = GNUNET_CLIENT_connect ("transport", cfg);
1514   if (NULL == ret->client)
1515   {
1516     GNUNET_free (ret);
1517     return NULL;
1518   }
1519   ret->neighbours =
1520     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
1521                                           GNUNET_YES);
1522   ret->ready_heap =
1523       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1524  schedule_control_transmit (ret, sizeof (struct StartMessage),
1525                              &send_start, ret);
1526   return ret;
1527 }
1528
1529
1530 /**
1531  * Disconnect from the transport service.
1532  *
1533  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_connect()
1534  */
1535 void
1536 GNUNET_TRANSPORT_disconnect (struct GNUNET_TRANSPORT_Handle *handle)
1537 {
1538   LOG (GNUNET_ERROR_TYPE_DEBUG,
1539        "Transport disconnect called!\n");
1540   /* this disconnects all neighbours... */
1541   if (handle->reconnect_task == GNUNET_SCHEDULER_NO_TASK)
1542     disconnect_and_schedule_reconnect (handle);
1543   /* and now we stop trying to connect again... */
1544   if (handle->reconnect_task != GNUNET_SCHEDULER_NO_TASK)
1545   {
1546     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1547     handle->reconnect_task = GNUNET_SCHEDULER_NO_TASK;
1548   }
1549   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
1550   handle->neighbours = NULL;
1551   if (handle->quota_task != GNUNET_SCHEDULER_NO_TASK)
1552   {
1553     GNUNET_SCHEDULER_cancel (handle->quota_task);
1554     handle->quota_task = GNUNET_SCHEDULER_NO_TASK;
1555   }
1556   GNUNET_free_non_null (handle->my_hello);
1557   handle->my_hello = NULL;
1558   GNUNET_assert (handle->tc_head == NULL);
1559   GNUNET_assert (handle->tc_tail == NULL);
1560   GNUNET_assert (handle->hwl_head == NULL);
1561   GNUNET_assert (handle->hwl_tail == NULL);
1562   GNUNET_CONTAINER_heap_destroy (handle->ready_heap);
1563   handle->ready_heap = NULL;
1564   GNUNET_free (handle);
1565 }
1566
1567
1568 /**
1569  * Check if we could queue a message of the given size for
1570  * transmission.  The transport service will take both its
1571  * internal buffers and bandwidth limits imposed by the
1572  * other peer into consideration when answering this query.
1573  *
1574  * @param handle connection to transport service
1575  * @param target who should receive the message
1576  * @param size how big is the message we want to transmit?
1577  * @param priority how important is the message?
1578  * @param timeout after how long should we give up (and call
1579  *        notify with buf NULL and size 0)?
1580  * @param notify function to call when we are ready to
1581  *        send such a message
1582  * @param notify_cls closure for @a notify
1583  * @return NULL if someone else is already waiting to be notified
1584  *         non-NULL if the notify callback was queued (can be used to cancel
1585  *         using #GNUNET_TRANSPORT_notify_transmit_ready_cancel)
1586  */
1587 struct GNUNET_TRANSPORT_TransmitHandle *
1588 GNUNET_TRANSPORT_notify_transmit_ready (struct GNUNET_TRANSPORT_Handle *handle,
1589                                         const struct GNUNET_PeerIdentity *target,
1590                                         size_t size, uint32_t priority,
1591                                         struct GNUNET_TIME_Relative timeout,
1592                                         GNUNET_CONNECTION_TransmitReadyNotify notify,
1593                                         void *notify_cls)
1594 {
1595   struct Neighbour *n;
1596   struct GNUNET_TRANSPORT_TransmitHandle *th;
1597   struct GNUNET_TIME_Relative delay;
1598
1599   n = neighbour_find (handle, target);
1600   if (NULL == n)
1601   {
1602     /* use GNUNET_TRANSPORT_try_connect first, only use this function
1603      * once a connection has been established */
1604     GNUNET_assert (0);
1605     return NULL;
1606   }
1607   if (NULL != n->th)
1608   {
1609     /* attempt to send two messages at the same time to the same peer */
1610     GNUNET_assert (0);
1611     return NULL;
1612   }
1613   GNUNET_assert (NULL == n->hn);
1614   th = GNUNET_new (struct GNUNET_TRANSPORT_TransmitHandle);
1615   th->neighbour = n;
1616   th->notify = notify;
1617   th->notify_cls = notify_cls;
1618   th->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1619   th->notify_size = size;
1620   th->priority = priority;
1621   n->th = th;
1622   /* calculate when our transmission should be ready */
1623   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker, size + n->traffic_overhead);
1624   n->traffic_overhead = 0;
1625   if (delay.rel_value_us > timeout.rel_value_us)
1626     delay.rel_value_us = 0;        /* notify immediately (with failure) */
1627   LOG (GNUNET_ERROR_TYPE_DEBUG,
1628        "Bandwidth tracker allows next transmission to peer %s in %s\n",
1629        GNUNET_i2s (target),
1630        GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_YES));
1631   n->hn = GNUNET_CONTAINER_heap_insert (handle->ready_heap, n, delay.rel_value_us);
1632   schedule_transmission (handle);
1633   return th;
1634 }
1635
1636
1637 /**
1638  * Cancel the specified transmission-ready notification.
1639  *
1640  * @param th handle returned from #GNUNET_TRANSPORT_notify_transmit_ready()
1641  */
1642 void
1643 GNUNET_TRANSPORT_notify_transmit_ready_cancel (struct GNUNET_TRANSPORT_TransmitHandle *th)
1644 {
1645   struct Neighbour *n;
1646
1647   GNUNET_assert (NULL == th->next);
1648   GNUNET_assert (NULL == th->prev);
1649   n = th->neighbour;
1650   GNUNET_assert (th == n->th);
1651   n->th = NULL;
1652   if (NULL != n->hn)
1653   {
1654     GNUNET_CONTAINER_heap_remove_node (n->hn);
1655     n->hn = NULL;
1656   }
1657   else
1658   {
1659     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != th->timeout_task);
1660     GNUNET_SCHEDULER_cancel (th->timeout_task);
1661     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1662   }
1663   GNUNET_free (th);
1664 }
1665
1666
1667 /* end of transport_api.c */