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