fix ftbfs
[oweals/gnunet.git] / src / transport / transport_api_core.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2013, 2016 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18      SPDX-License-Identifier: AGPL3.0-or-later
19 */
20
21 /**
22  * @file transport/transport_api_core.c
23  * @brief library to access the transport service for message exchange
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_arm_service.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_transport_core_service.h"
33 #include "gnunet_transport_service.h"
34 #include "transport.h"
35
36 #define LOG(kind,...) GNUNET_log_from (kind, "transport-api-core",__VA_ARGS__)
37
38 /**
39  * If we could not send any payload to a peer for this amount of
40  * time, we print a warning.
41  */
42 #define UNREADY_WARN_TIME GNUNET_TIME_UNIT_MINUTES
43
44 /**
45  * How large to start with for the hashmap of neighbours.
46  */
47 #define STARTING_NEIGHBOURS_SIZE 16
48
49
50 /**
51  * Entry in hash table of all of our current (connected) neighbours.
52  */
53 struct Neighbour
54 {
55   /**
56    * Overall transport handle.
57    */
58   struct GNUNET_TRANSPORT_CoreHandle *h;
59
60   /**
61    * Active message queue for the peer.
62    */
63   struct GNUNET_MQ_Handle *mq;
64
65   /**
66    * Envelope with the message we are currently transmitting (or NULL).
67    */
68   struct GNUNET_MQ_Envelope *env;
69
70   /**
71    * Closure for @e mq handlers.
72    */
73   void *handlers_cls;
74
75   /**
76    * Identity of this neighbour.
77    */
78   struct GNUNET_PeerIdentity id;
79
80   /**
81    * Outbound bandwidh tracker.
82    */
83   struct GNUNET_BANDWIDTH_Tracker out_tracker;
84
85   /**
86    * Entry in our readyness heap (which is sorted by @e next_ready
87    * value).  NULL if there is no pending transmission request for
88    * this neighbour or if we're waiting for @e is_ready to become
89    * true AFTER the @e out_tracker suggested that this peer's quota
90    * has been satisfied (so once @e is_ready goes to #GNUNET_YES,
91    * we should immediately go back into the heap).
92    */
93   struct GNUNET_CONTAINER_HeapNode *hn;
94
95   /**
96    * Task to trigger MQ when we have enough bandwidth for the
97    * next transmission.
98    */
99   struct GNUNET_SCHEDULER_Task *timeout_task;
100
101   /**
102    * Sending consumed more bytes on wire than payload was announced
103    * This overhead is added to the delay of next sending operation
104    */
105   unsigned long long traffic_overhead;
106
107   /**
108    * Is this peer currently ready to receive a message?
109    */
110   int is_ready;
111
112   /**
113    * Size of the message in @e env.
114    */
115   uint16_t env_size;
116
117 };
118
119
120
121 /**
122  * Handle for the transport service (includes all of the
123  * state for the transport service).
124  */
125 struct GNUNET_TRANSPORT_CoreHandle
126 {
127
128   /**
129    * Closure for the callbacks.
130    */
131   void *cls;
132
133   /**
134    * Functions to call for received data (template for
135    * new message queues).
136    */
137   struct GNUNET_MQ_MessageHandler *handlers;
138
139   /**
140    * function to call on connect events
141    */
142   GNUNET_TRANSPORT_NotifyConnect nc_cb;
143
144   /**
145    * function to call on disconnect events
146    */
147   GNUNET_TRANSPORT_NotifyDisconnect nd_cb;
148
149   /**
150    * function to call on excess bandwidth events
151    */
152   GNUNET_TRANSPORT_NotifyExcessBandwidth neb_cb;
153
154   /**
155    * My client connection to the transport service.
156    */
157   struct GNUNET_MQ_Handle *mq;
158
159   /**
160    * My configuration.
161    */
162   const struct GNUNET_CONFIGURATION_Handle *cfg;
163
164   /**
165    * Hash map of the current connected neighbours of this peer.
166    * Maps peer identities to `struct Neighbour` entries.
167    */
168   struct GNUNET_CONTAINER_MultiPeerMap *neighbours;
169
170   /**
171    * Peer identity as assumed by this process, or all zeros.
172    */
173   struct GNUNET_PeerIdentity self;
174
175   /**
176    * ID of the task trying to reconnect to the service.
177    */
178   struct GNUNET_SCHEDULER_Task *reconnect_task;
179
180   /**
181    * Delay until we try to reconnect.
182    */
183   struct GNUNET_TIME_Relative reconnect_delay;
184
185   /**
186    * Should we check that @e self matches what the service thinks?
187    * (if #GNUNET_NO, then @e self is all zeros!).
188    */
189   int check_self;
190
191 };
192
193
194 /**
195  * Function that will schedule the job that will try
196  * to connect us again to the client.
197  *
198  * @param h transport service to reconnect
199  */
200 static void
201 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_CoreHandle *h);
202
203
204 /**
205  * Get the neighbour list entry for the given peer
206  *
207  * @param h our context
208  * @param peer peer to look up
209  * @return NULL if no such peer entry exists
210  */
211 static struct Neighbour *
212 neighbour_find (struct GNUNET_TRANSPORT_CoreHandle *h,
213                 const struct GNUNET_PeerIdentity *peer)
214 {
215   return GNUNET_CONTAINER_multipeermap_get (h->neighbours,
216                                             peer);
217 }
218
219
220 /**
221  * Function called by the bandwidth tracker if we have excess
222  * bandwidth.
223  *
224  * @param cls the `struct Neighbour` that has excess bandwidth
225  */
226 static void
227 notify_excess_cb (void *cls)
228 {
229   struct Neighbour *n = cls;
230   struct GNUNET_TRANSPORT_CoreHandle *h = n->h;
231
232   LOG (GNUNET_ERROR_TYPE_DEBUG,
233        "Notifying CORE that more bandwidth is available for %s\n",
234        GNUNET_i2s (&n->id));
235
236   if (NULL != h->neb_cb)
237     h->neb_cb (h->cls,
238                &n->id,
239                n->handlers_cls);
240 }
241
242
243 /**
244  * Iterator over hash map entries, for deleting state of a neighbour.
245  *
246  * @param cls the `struct GNUNET_TRANSPORT_CoreHandle *`
247  * @param key peer identity
248  * @param value value in the hash map, the neighbour entry to delete
249  * @return #GNUNET_YES if we should continue to
250  *         iterate,
251  *         #GNUNET_NO if not.
252  */
253 static int
254 neighbour_delete (void *cls,
255                   const struct GNUNET_PeerIdentity *key,
256                   void *value)
257 {
258   struct GNUNET_TRANSPORT_CoreHandle *handle = cls;
259   struct Neighbour *n = value;
260
261   LOG (GNUNET_ERROR_TYPE_DEBUG,
262        "Dropping entry for neighbour `%s'.\n",
263        GNUNET_i2s (key));
264   GNUNET_BANDWIDTH_tracker_notification_stop (&n->out_tracker);
265   if (NULL != handle->nd_cb)
266     handle->nd_cb (handle->cls,
267                    &n->id,
268                    n->handlers_cls);
269   if (NULL != n->timeout_task)
270   {
271     GNUNET_SCHEDULER_cancel (n->timeout_task);
272     n->timeout_task = NULL;
273   }
274   if (NULL != n->env)
275   {
276     GNUNET_MQ_send_cancel (n->env);
277     n->env = NULL;
278   }
279   GNUNET_MQ_destroy (n->mq);
280   GNUNET_assert (NULL == n->mq);
281   GNUNET_assert (GNUNET_YES ==
282                  GNUNET_CONTAINER_multipeermap_remove (handle->neighbours,
283                                                        key,
284                                                        n));
285   GNUNET_free (n);
286   return GNUNET_YES;
287 }
288
289
290 /**
291  * Generic error handler, called with the appropriate
292  * error code and the same closure specified at the creation of
293  * the message queue.
294  * Not every message queue implementation supports an error handler.
295  *
296  * @param cls closure with the `struct GNUNET_TRANSPORT_CoreHandle *`
297  * @param error error code
298  */
299 static void
300 mq_error_handler (void *cls,
301                   enum GNUNET_MQ_Error error)
302 {
303   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
304
305   LOG (GNUNET_ERROR_TYPE_ERROR,
306        "Error receiving from transport service (%d), disconnecting temporarily.\n",
307        error);
308   disconnect_and_schedule_reconnect (h);
309 }
310
311
312 /**
313  * Function we use for checking incoming HELLO messages.
314  *
315  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
316  * @param msg message received
317  * @return #GNUNET_OK if message is well-formed
318  */
319 static int
320 check_hello (void *cls,
321              const struct GNUNET_MessageHeader *msg)
322 {
323   struct GNUNET_PeerIdentity me;
324
325   if (GNUNET_OK !=
326       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
327                            &me))
328   {
329     GNUNET_break (0);
330     return GNUNET_SYSERR;
331   }
332   return GNUNET_OK;
333 }
334
335
336 /**
337  * Function we use for handling incoming HELLO messages.
338  *
339  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
340  * @param msg message received
341  */
342 static void
343 handle_hello (void *cls,
344               const struct GNUNET_MessageHeader *msg)
345 {
346   /* we do not care => FIXME: signal in options to NEVER send HELLOs! */
347 }
348
349
350 /**
351  * A message from the handler's message queue to a neighbour was
352  * transmitted.  Now trigger (possibly delayed) notification of the
353  * neighbour's message queue that we are done and thus ready for
354  * the next message.
355  *
356  * @param cls the `struct Neighbour` where the message was sent
357  */
358 static void
359 notify_send_done_fin (void *cls)
360 {
361   struct Neighbour *n = cls;
362
363   n->timeout_task = NULL;
364   n->is_ready = GNUNET_YES;
365   GNUNET_MQ_impl_send_continue (n->mq);
366 }
367
368
369 /**
370  * A message from the handler's message queue to a neighbour was
371  * transmitted.  Now trigger (possibly delayed) notification of the
372  * neighbour's message queue that we are done and thus ready for
373  * the next message.
374  *
375  * @param cls the `struct Neighbour` where the message was sent
376  */
377 static void
378 notify_send_done (void *cls)
379 {
380   struct Neighbour *n = cls;
381   struct GNUNET_TIME_Relative delay;
382
383   n->timeout_task = NULL;
384   if (NULL != n->env)
385   {
386     GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker,
387                                       n->env_size + n->traffic_overhead);
388     n->env = NULL;
389     n->traffic_overhead = 0;
390   }
391   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
392                                               128);
393   if (0 == delay.rel_value_us)
394   {
395     n->is_ready = GNUNET_YES;
396     GNUNET_MQ_impl_send_continue (n->mq);
397     return;
398   }
399   GNUNET_MQ_impl_send_in_flight (n->mq);
400   /* cannot send even a small message without violating
401      quota, wait a before allowing MQ to send next message */
402   n->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
403                                                   &notify_send_done_fin,
404                                                   n);
405 }
406
407
408 /**
409  * Implement sending functionality of a message queue.
410  * Called one message at a time. Should send the @a msg
411  * to the transport service and then notify the queue
412  * once we are ready for the next one.
413  *
414  * @param mq the message queue
415  * @param msg the message to send
416  * @param impl_state state of the implementation
417  */
418 static void
419 mq_send_impl (struct GNUNET_MQ_Handle *mq,
420               const struct GNUNET_MessageHeader *msg,
421               void *impl_state)
422 {
423   struct Neighbour *n = impl_state;
424   struct GNUNET_TRANSPORT_CoreHandle *h = n->h;
425   struct OutboundMessage *obm;
426   uint16_t msize;
427
428   GNUNET_assert (GNUNET_YES == n->is_ready);
429   msize = ntohs (msg->size);
430   if (msize >= GNUNET_MAX_MESSAGE_SIZE - sizeof (*obm))
431   {
432     GNUNET_break (0);
433     GNUNET_MQ_impl_send_continue (mq);
434     return;
435   }
436   GNUNET_assert (NULL == n->env);
437   n->env = GNUNET_MQ_msg_nested_mh (obm,
438                                     GNUNET_MESSAGE_TYPE_TRANSPORT_SEND,
439                                     msg);
440   obm->reserved = htonl (0);
441   obm->timeout = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_MINUTES); /* FIXME: to be removed */
442   obm->peer = n->id;
443   GNUNET_assert (NULL == n->timeout_task);
444   n->is_ready = GNUNET_NO;
445   n->env_size = ntohs (msg->size);
446   GNUNET_MQ_notify_sent (n->env,
447                          &notify_send_done,
448                          n);
449   GNUNET_MQ_send (h->mq,
450                   n->env);
451   LOG (GNUNET_ERROR_TYPE_DEBUG,
452        "Queued message of type %u for neighbour `%s'.\n",
453        ntohs (msg->type),
454        GNUNET_i2s (&n->id));
455 }
456
457
458 /**
459  * Handle destruction of a message queue.  Implementations must not
460  * free @a mq, but should take care of @a impl_state.
461  *
462  * @param mq the message queue to destroy
463  * @param impl_state state of the implementation
464  */
465 static void
466 mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
467                  void *impl_state)
468 {
469   struct Neighbour *n = impl_state;
470
471   GNUNET_assert (mq == n->mq);
472   n->mq = NULL;
473 }
474
475
476 /**
477  * Implementation function that cancels the currently sent message.
478  * Should basically undo whatever #mq_send_impl() did.
479  *
480  * @param mq message queue
481  * @param impl_state state specific to the implementation
482  */
483 static void
484 mq_cancel_impl (struct GNUNET_MQ_Handle *mq,
485                 void *impl_state)
486 {
487   struct Neighbour *n = impl_state;
488
489   GNUNET_assert (GNUNET_NO == n->is_ready);
490   if (NULL != n->env)
491   {
492     GNUNET_MQ_send_cancel (n->env);
493     n->env = NULL;
494   }
495
496   n->is_ready = GNUNET_YES;
497 }
498
499
500 /**
501  * We had an error processing a message we forwarded from a peer to
502  * the CORE service.  We should just complain about it but otherwise
503  * continue processing.
504  *
505  * @param cls closure
506  * @param error error code
507  */
508 static void
509 peer_mq_error_handler (void *cls,
510                        enum GNUNET_MQ_Error error)
511 {
512   /* struct Neighbour *n = cls; */
513
514   GNUNET_break_op (0);
515 }
516
517
518 /**
519  * The outbound quota has changed in a way that may require
520  * us to reset the timeout.  Update the timeout.
521  *
522  * @param cls the `struct Neighbour` for which the timeout changed
523  */
524 static void
525 outbound_bw_tracker_update (void *cls)
526 {
527   struct Neighbour *n = cls;
528   struct GNUNET_TIME_Relative delay;
529
530   if (NULL == n->timeout_task)
531     return;
532   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
533                                               128);
534   GNUNET_SCHEDULER_cancel (n->timeout_task);
535   n->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
536                                                   &notify_send_done,
537                                                   n);
538 }
539
540
541 /**
542  * Function we use for handling incoming connect messages.
543  *
544  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
545  * @param cim message received
546  */
547 static void
548 handle_connect (void *cls,
549                 const struct ConnectInfoMessage *cim)
550 {
551   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
552   struct Neighbour *n;
553
554   LOG (GNUNET_ERROR_TYPE_DEBUG,
555        "Receiving CONNECT message for `%s' with quota %u\n",
556        GNUNET_i2s (&cim->id),
557        ntohl (cim->quota_out.value__));
558   n = neighbour_find (h,
559                       &cim->id);
560   if (NULL != n)
561   {
562     GNUNET_break (0); /* FIXME: this assertion seems to fail sometimes!? */
563     disconnect_and_schedule_reconnect (h);
564     return;
565   }
566   n = GNUNET_new (struct Neighbour);
567   n->id = cim->id;
568   n->h = h;
569   n->is_ready = GNUNET_YES;
570   n->traffic_overhead = 0;
571   GNUNET_BANDWIDTH_tracker_init2 (&n->out_tracker,
572                                   &outbound_bw_tracker_update,
573                                   n,
574                                   GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
575                                   MAX_BANDWIDTH_CARRY_S,
576                                   &notify_excess_cb,
577                                   n);
578   GNUNET_assert (GNUNET_OK ==
579                  GNUNET_CONTAINER_multipeermap_put (h->neighbours,
580                                                     &n->id,
581                                                     n,
582                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
583
584   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
585                                          cim->quota_out);
586   n->mq = GNUNET_MQ_queue_for_callbacks (&mq_send_impl,
587                                          &mq_destroy_impl,
588                                          &mq_cancel_impl,
589                                          n,
590                                          h->handlers,
591                                          &peer_mq_error_handler,
592                                          n);
593   if (NULL != h->nc_cb)
594   {
595     n->handlers_cls = h->nc_cb (h->cls,
596                                 &n->id,
597                                 n->mq);
598     GNUNET_MQ_set_handlers_closure (n->mq,
599                                     n->handlers_cls);
600   }
601 }
602
603
604 /**
605  * Function we use for handling incoming disconnect messages.
606  *
607  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
608  * @param dim message received
609  */
610 static void
611 handle_disconnect (void *cls,
612                    const struct DisconnectInfoMessage *dim)
613 {
614   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
615   struct Neighbour *n;
616
617   GNUNET_break (ntohl (dim->reserved) == 0);
618   LOG (GNUNET_ERROR_TYPE_DEBUG,
619        "Receiving DISCONNECT message for `%s'.\n",
620        GNUNET_i2s (&dim->peer));
621   n = neighbour_find (h, &dim->peer);
622   if (NULL == n)
623   {
624     GNUNET_break (0);
625     disconnect_and_schedule_reconnect (h);
626     return;
627   }
628   GNUNET_assert (GNUNET_YES ==
629                  neighbour_delete (h,
630                                    &dim->peer,
631                                    n));
632 }
633
634
635 /**
636  * Function we use for handling incoming send-ok messages.
637  *
638  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
639  * @param okm message received
640  */
641 static void
642 handle_send_ok (void *cls,
643                 const struct SendOkMessage *okm)
644 {
645   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
646   struct Neighbour *n;
647   uint32_t bytes_msg;
648   uint32_t bytes_physical;
649
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 to %s %s.\n",
654        GNUNET_i2s (&okm->peer),
655        ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
656   n = neighbour_find (h,
657                       &okm->peer);
658   if (NULL == n)
659   {
660     /* We should never get a 'SEND_OK' for a peer that we are not
661        connected to */
662     GNUNET_break (0);
663     disconnect_and_schedule_reconnect (h);
664     return;
665   }
666   if (bytes_physical > bytes_msg)
667   {
668     LOG (GNUNET_ERROR_TYPE_DEBUG,
669          "Overhead for %u byte message was %u\n",
670          bytes_msg,
671          bytes_physical - bytes_msg);
672     n->traffic_overhead += bytes_physical - bytes_msg;
673   }
674 }
675
676
677 /**
678  * Function we use for checking incoming "inbound" messages.
679  *
680  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
681  * @param im message received
682  */
683 static int
684 check_recv (void *cls,
685              const struct InboundMessage *im)
686 {
687   const struct GNUNET_MessageHeader *imm;
688   uint16_t size;
689
690   size = ntohs (im->header.size) - sizeof (*im);
691   if (size < sizeof (struct GNUNET_MessageHeader))
692   {
693     GNUNET_break (0);
694     return GNUNET_SYSERR;
695   }
696   imm = (const struct GNUNET_MessageHeader *) &im[1];
697   if (ntohs (imm->size) != size)
698   {
699     GNUNET_break (0);
700     return GNUNET_SYSERR;
701   }
702   return GNUNET_OK;
703 }
704
705
706 /**
707  * Function we use for handling incoming messages.
708  *
709  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
710  * @param im message received
711  */
712 static void
713 handle_recv (void *cls,
714              const struct InboundMessage *im)
715 {
716   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
717   const struct GNUNET_MessageHeader *imm
718     = (const struct GNUNET_MessageHeader *) &im[1];
719   struct Neighbour *n;
720
721   LOG (GNUNET_ERROR_TYPE_DEBUG,
722        "Received message of type %u with %u bytes from `%s'.\n",
723        (unsigned int) ntohs (imm->type),
724        (unsigned int) ntohs (imm->size),
725        GNUNET_i2s (&im->peer));
726   n = neighbour_find (h, &im->peer);
727   if (NULL == n)
728   {
729     GNUNET_break (0);
730     disconnect_and_schedule_reconnect (h);
731     return;
732   }
733   GNUNET_MQ_inject_message (n->mq,
734                             imm);
735 }
736
737
738 /**
739  * Function we use for handling incoming set quota messages.
740  *
741  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
742  * @param msg message received
743  */
744 static void
745 handle_set_quota (void *cls,
746                   const struct QuotaSetMessage *qm)
747 {
748   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
749   struct Neighbour *n;
750
751   LOG (GNUNET_ERROR_TYPE_DEBUG,
752        "Receiving SET_QUOTA message for `%s' with quota %u\n",
753        GNUNET_i2s (&qm->peer),
754        ntohl (qm->quota.value__));
755   n = neighbour_find (h,
756                       &qm->peer);
757   if (NULL == n)
758   {
759     GNUNET_break (0); /* FIXME: julius reports this assertion fails sometimes? */
760     disconnect_and_schedule_reconnect (h);
761     return;
762   }
763   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
764                                          qm->quota);
765 }
766
767
768 /**
769  * Try again to connect to transport service.
770  *
771  * @param cls the handle to the transport service
772  */
773 static void
774 reconnect (void *cls)
775 {
776   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
777   struct GNUNET_MQ_MessageHandler handlers[] = {
778     GNUNET_MQ_hd_var_size (hello,
779                            GNUNET_MESSAGE_TYPE_HELLO,
780                            struct GNUNET_MessageHeader,
781                            h),
782     GNUNET_MQ_hd_fixed_size (connect,
783                              GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT,
784                              struct ConnectInfoMessage,
785                              h),
786     GNUNET_MQ_hd_fixed_size (disconnect,
787                              GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT,
788                              struct DisconnectInfoMessage,
789                              h),
790     GNUNET_MQ_hd_fixed_size (send_ok,
791                              GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK,
792                              struct SendOkMessage,
793                              h),
794     GNUNET_MQ_hd_var_size (recv,
795                            GNUNET_MESSAGE_TYPE_TRANSPORT_RECV,
796                            struct InboundMessage,
797                            h),
798     GNUNET_MQ_hd_fixed_size (set_quota,
799                              GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA,
800                              struct QuotaSetMessage,
801                              h),
802     GNUNET_MQ_handler_end ()
803   };
804   struct GNUNET_MQ_Envelope *env;
805   struct StartMessage *s;
806   uint32_t options;
807
808   h->reconnect_task = NULL;
809   LOG (GNUNET_ERROR_TYPE_DEBUG,
810        "Connecting to transport service.\n");
811   GNUNET_assert (NULL == h->mq);
812   h->mq = GNUNET_CLIENT_connect (h->cfg,
813                                  "transport",
814                                  handlers,
815                                  &mq_error_handler,
816                                  h);
817   if (NULL == h->mq)
818     return;
819   env = GNUNET_MQ_msg (s,
820                        GNUNET_MESSAGE_TYPE_TRANSPORT_START);
821   options = 0;
822   if (h->check_self)
823     options |= 1;
824   if (NULL != h->handlers)
825     options |= 2;
826   s->options = htonl (options);
827   s->self = h->self;
828   GNUNET_MQ_send (h->mq,
829                   env);
830 }
831
832
833 /**
834  * Function that will schedule the job that will try
835  * to connect us again to the client.
836  *
837  * @param h transport service to reconnect
838  */
839 static void
840 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_CoreHandle *h)
841 {
842   GNUNET_assert (NULL == h->reconnect_task);
843   /* Forget about all neighbours that we used to be connected to */
844   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
845                                          &neighbour_delete,
846                                          h);
847   if (NULL != h->mq)
848   {
849     GNUNET_MQ_destroy (h->mq);
850     h->mq = NULL;
851   }
852   LOG (GNUNET_ERROR_TYPE_DEBUG,
853        "Scheduling task to reconnect to transport service in %s.\n",
854        GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay,
855                                                GNUNET_YES));
856   h->reconnect_task =
857       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
858                                     &reconnect,
859                                     h);
860   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
861 }
862
863
864 /**
865  * Checks if a given peer is connected to us and get the message queue.
866  *
867  * @param handle connection to transport service
868  * @param peer the peer to check
869  * @return NULL if disconnected, otherwise message queue for @a peer
870  */
871 struct GNUNET_MQ_Handle *
872 GNUNET_TRANSPORT_core_get_mq (struct GNUNET_TRANSPORT_CoreHandle *handle,
873                               const struct GNUNET_PeerIdentity *peer)
874 {
875   struct Neighbour *n;
876
877   n = neighbour_find (handle,
878                       peer);
879   if (NULL == n)
880     return NULL;
881   return n->mq;
882 }
883
884
885 /**
886  * Connect to the transport service.  Note that the connection may
887  * complete (or fail) asynchronously.
888  *
889  * @param cfg configuration to use
890  * @param self our own identity (API should check that it matches
891  *             the identity found by transport), or NULL (no check)
892  * @param cls closure for the callbacks
893  * @param rec receive function to call
894  * @param nc function to call on connect events
895  * @param nd function to call on disconnect events
896  * @param neb function to call if we have excess bandwidth to a peer
897  * @return NULL on error
898  */
899 struct GNUNET_TRANSPORT_CoreHandle *
900 GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
901                                const struct GNUNET_PeerIdentity *self,
902                                const struct GNUNET_MQ_MessageHandler *handlers,
903                                void *cls,
904                                GNUNET_TRANSPORT_NotifyConnect nc,
905                                GNUNET_TRANSPORT_NotifyDisconnect nd,
906                                GNUNET_TRANSPORT_NotifyExcessBandwidth neb)
907 {
908   struct GNUNET_TRANSPORT_CoreHandle *h;
909   unsigned int i;
910
911   h = GNUNET_new (struct GNUNET_TRANSPORT_CoreHandle);
912   if (NULL != self)
913   {
914     h->self = *self;
915     h->check_self = GNUNET_YES;
916   }
917   h->cfg = cfg;
918   h->cls = cls;
919   h->nc_cb = nc;
920   h->nd_cb = nd;
921   h->neb_cb = neb;
922   h->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
923   if (NULL != handlers)
924   {
925     for (i=0;NULL != handlers[i].cb; i++) ;
926     h->handlers = GNUNET_new_array (i + 1,
927                                     struct GNUNET_MQ_MessageHandler);
928     GNUNET_memcpy (h->handlers,
929                    handlers,
930                    i * sizeof (struct GNUNET_MQ_MessageHandler));
931   }
932   LOG (GNUNET_ERROR_TYPE_DEBUG,
933        "Connecting to transport service\n");
934   reconnect (h);
935   if (NULL == h->mq)
936   {
937     GNUNET_free_non_null (h->handlers);
938     GNUNET_free (h);
939     return NULL;
940   }
941   h->neighbours =
942     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
943                                           GNUNET_YES);
944   return h;
945 }
946
947
948 /**
949  * Disconnect from the transport service.
950  *
951  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_core_connect()
952  */
953 void
954 GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle)
955 {
956   LOG (GNUNET_ERROR_TYPE_DEBUG,
957        "Transport disconnect called!\n");
958   /* this disconnects all neighbours... */
959   if (NULL == handle->reconnect_task)
960     disconnect_and_schedule_reconnect (handle);
961   /* and now we stop trying to connect again... */
962   if (NULL != handle->reconnect_task)
963   {
964     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
965     handle->reconnect_task = NULL;
966   }
967   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
968   handle->neighbours = NULL;
969   GNUNET_free_non_null (handle->handlers);
970   handle->handlers = NULL;
971   GNUNET_free (handle);
972 }
973
974
975 /* end of transport_api_core.c */