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