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