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