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