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