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