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