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