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