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