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