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