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