style fixes during debugging
[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_DEBUG,
306        "Error receiving from transport service, disconnecting temporarily.\n");
307   disconnect_and_schedule_reconnect (h);
308 }
309
310
311 /**
312  * Function we use for checking incoming HELLO messages.
313  *
314  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
315  * @param msg message received
316  * @return #GNUNET_OK if message is well-formed
317  */
318 static int
319 check_hello (void *cls,
320              const struct GNUNET_MessageHeader *msg)
321 {
322   struct GNUNET_PeerIdentity me;
323
324   if (GNUNET_OK !=
325       GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) msg,
326                            &me))
327   {
328     GNUNET_break (0);
329     return GNUNET_SYSERR;
330   }
331   return GNUNET_OK;
332 }
333
334
335 /**
336  * Function we use for handling incoming HELLO messages.
337  *
338  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
339  * @param msg message received
340  */
341 static void
342 handle_hello (void *cls,
343               const struct GNUNET_MessageHeader *msg)
344 {
345   /* we do not care => FIXME: signal in options to NEVER send HELLOs! */
346 }
347
348
349 /**
350  * A message from the handler's message queue to a neighbour was
351  * transmitted.  Now trigger (possibly delayed) notification of the
352  * neighbour's message queue that we are done and thus ready for
353  * the next message.
354  *
355  * @param cls the `struct Neighbour` where the message was sent
356  */
357 static void
358 notify_send_done_fin (void *cls)
359 {
360   struct Neighbour *n = cls;
361
362   n->timeout_task = NULL;
363   n->is_ready = GNUNET_YES;
364   GNUNET_MQ_impl_send_continue (n->mq);
365 }
366
367
368 /**
369  * A message from the handler's message queue to a neighbour was
370  * transmitted.  Now trigger (possibly delayed) notification of the
371  * neighbour's message queue that we are done and thus ready for
372  * the next message.
373  *
374  * @param cls the `struct Neighbour` where the message was sent
375  */
376 static void
377 notify_send_done (void *cls)
378 {
379   struct Neighbour *n = cls;
380   struct GNUNET_TIME_Relative delay;
381
382   n->timeout_task = NULL;
383   if (NULL != n->env)
384   {
385     GNUNET_BANDWIDTH_tracker_consume (&n->out_tracker,
386                                       n->env_size + n->traffic_overhead);
387     n->env = NULL;
388     n->traffic_overhead = 0;
389   }
390   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
391                                               128);
392   if (0 == delay.rel_value_us)
393   {
394     n->is_ready = GNUNET_YES;
395     GNUNET_MQ_impl_send_continue (n->mq);
396     return;
397   }
398   GNUNET_MQ_impl_send_in_flight (n->mq);
399   /* cannot send even a small message without violating
400      quota, wait a before allowing MQ to send next message */
401   n->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
402                                                   &notify_send_done_fin,
403                                                   n);
404 }
405
406
407 /**
408  * Implement sending functionality of a message queue.
409  * Called one message at a time. Should send the @a msg
410  * to the transport service and then notify the queue
411  * once we are ready for the next one.
412  *
413  * @param mq the message queue
414  * @param msg the message to send
415  * @param impl_state state of the implementation
416  */
417 static void
418 mq_send_impl (struct GNUNET_MQ_Handle *mq,
419               const struct GNUNET_MessageHeader *msg,
420               void *impl_state)
421 {
422   struct Neighbour *n = impl_state;
423   struct GNUNET_TRANSPORT_CoreHandle *h = n->h;
424   struct OutboundMessage *obm;
425   uint16_t msize;
426
427   GNUNET_assert (GNUNET_YES == n->is_ready);
428   msize = ntohs (msg->size);
429   if (msize >= GNUNET_MAX_MESSAGE_SIZE - sizeof (*obm))
430   {
431     GNUNET_break (0);
432     GNUNET_MQ_impl_send_continue (mq);
433     return;
434   }
435   GNUNET_assert (NULL == n->env);
436   n->env = GNUNET_MQ_msg_nested_mh (obm,
437                                     GNUNET_MESSAGE_TYPE_TRANSPORT_SEND,
438                                     msg);
439   obm->reserved = htonl (0);
440   obm->timeout = GNUNET_TIME_relative_hton (GNUNET_TIME_UNIT_MINUTES); /* FIXME: to be removed */
441   obm->peer = n->id;
442   GNUNET_assert (NULL == n->timeout_task);
443   n->is_ready = GNUNET_NO;
444   n->env_size = ntohs (msg->size);
445   GNUNET_MQ_notify_sent (n->env,
446                          &notify_send_done,
447                          n);
448   GNUNET_MQ_send (h->mq,
449                   n->env);
450   LOG (GNUNET_ERROR_TYPE_DEBUG,
451        "Queued message of type %u for neighbour `%s'.\n",
452        ntohs (msg->type),
453        GNUNET_i2s (&n->id));
454 }
455
456
457 /**
458  * Handle destruction of a message queue.  Implementations must not
459  * free @a mq, but should take care of @a impl_state.
460  *
461  * @param mq the message queue to destroy
462  * @param impl_state state of the implementation
463  */
464 static void
465 mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
466                  void *impl_state)
467 {
468   struct Neighbour *n = impl_state;
469
470   GNUNET_assert (mq == n->mq);
471   n->mq = NULL;
472 }
473
474
475 /**
476  * Implementation function that cancels the currently sent message.
477  * Should basically undo whatever #mq_send_impl() did.
478  *
479  * @param mq message queue
480  * @param impl_state state specific to the implementation
481  */
482 static void
483 mq_cancel_impl (struct GNUNET_MQ_Handle *mq,
484                 void *impl_state)
485 {
486   struct Neighbour *n = impl_state;
487
488   GNUNET_assert (GNUNET_NO == n->is_ready);
489   if (NULL != n->env)
490   {
491     GNUNET_MQ_send_cancel (n->env);
492     n->env = NULL;
493   }
494
495   n->is_ready = GNUNET_YES;
496 }
497
498
499 /**
500  * We had an error processing a message we forwarded from a peer to
501  * the CORE service.  We should just complain about it but otherwise
502  * continue processing.
503  *
504  * @param cls closure
505  * @param error error code
506  */
507 static void
508 peer_mq_error_handler (void *cls,
509                        enum GNUNET_MQ_Error error)
510 {
511   /* struct Neighbour *n = cls; */
512
513   GNUNET_break_op (0);
514 }
515
516
517 /**
518  * The outbound quota has changed in a way that may require
519  * us to reset the timeout.  Update the timeout.
520  *
521  * @param cls the `struct Neighbour` for which the timeout changed
522  */
523 static void
524 outbound_bw_tracker_update (void *cls)
525 {
526   struct Neighbour *n = cls;
527   struct GNUNET_TIME_Relative delay;
528
529   if (NULL == n->timeout_task)
530     return;
531   delay = GNUNET_BANDWIDTH_tracker_get_delay (&n->out_tracker,
532                                               128);
533   GNUNET_SCHEDULER_cancel (n->timeout_task);
534   n->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
535                                                   &notify_send_done,
536                                                   n);
537 }
538
539
540 /**
541  * Function we use for handling incoming connect messages.
542  *
543  * @param cls closure, a `struct GNUNET_TRANSPORT_Handle *`
544  * @param cim message received
545  */
546 static void
547 handle_connect (void *cls,
548                 const struct ConnectInfoMessage *cim)
549 {
550   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
551   struct Neighbour *n;
552
553   LOG (GNUNET_ERROR_TYPE_DEBUG,
554        "Receiving CONNECT message for `%s' with quota %u\n",
555        GNUNET_i2s (&cim->id),
556        ntohl (cim->quota_out.value__));
557   n = neighbour_find (h,
558                       &cim->id);
559   if (NULL != n)
560   {
561     GNUNET_break (0); /* FIXME: this assertion seems to fail sometimes!? */
562     disconnect_and_schedule_reconnect (h);
563     return;
564   }
565   n = GNUNET_new (struct Neighbour);
566   n->id = cim->id;
567   n->h = h;
568   n->is_ready = GNUNET_YES;
569   n->traffic_overhead = 0;
570   GNUNET_BANDWIDTH_tracker_init2 (&n->out_tracker,
571                                   &outbound_bw_tracker_update,
572                                   n,
573                                   GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT,
574                                   MAX_BANDWIDTH_CARRY_S,
575                                   &notify_excess_cb,
576                                   n);
577   GNUNET_assert (GNUNET_OK ==
578                  GNUNET_CONTAINER_multipeermap_put (h->neighbours,
579                                                     &n->id,
580                                                     n,
581                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
582
583   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
584                                          cim->quota_out);
585   n->mq = GNUNET_MQ_queue_for_callbacks (&mq_send_impl,
586                                          &mq_destroy_impl,
587                                          &mq_cancel_impl,
588                                          n,
589                                          h->handlers,
590                                          &peer_mq_error_handler,
591                                          n);
592   if (NULL != h->nc_cb)
593   {
594     n->handlers_cls = h->nc_cb (h->cls,
595                                 &n->id,
596                                 n->mq);
597     GNUNET_MQ_set_handlers_closure (n->mq,
598                                     n->handlers_cls);
599   }
600 }
601
602
603 /**
604  * Function we use for handling incoming disconnect messages.
605  *
606  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
607  * @param dim message received
608  */
609 static void
610 handle_disconnect (void *cls,
611                    const struct DisconnectInfoMessage *dim)
612 {
613   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
614   struct Neighbour *n;
615
616   GNUNET_break (ntohl (dim->reserved) == 0);
617   LOG (GNUNET_ERROR_TYPE_DEBUG,
618        "Receiving DISCONNECT message for `%s'.\n",
619        GNUNET_i2s (&dim->peer));
620   n = neighbour_find (h, &dim->peer);
621   if (NULL == n)
622   {
623     GNUNET_break (0);
624     disconnect_and_schedule_reconnect (h);
625     return;
626   }
627   GNUNET_assert (GNUNET_YES ==
628                  neighbour_delete (h,
629                                    &dim->peer,
630                                    n));
631 }
632
633
634 /**
635  * Function we use for handling incoming send-ok messages.
636  *
637  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
638  * @param okm message received
639  */
640 static void
641 handle_send_ok (void *cls,
642                 const struct SendOkMessage *okm)
643 {
644   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
645   struct Neighbour *n;
646   uint32_t bytes_msg;
647   uint32_t bytes_physical;
648
649   bytes_msg = ntohl (okm->bytes_msg);
650   bytes_physical = ntohl (okm->bytes_physical);
651   LOG (GNUNET_ERROR_TYPE_DEBUG,
652        "Receiving SEND_OK message, transmission to %s %s.\n",
653        GNUNET_i2s (&okm->peer),
654        ntohl (okm->success) == GNUNET_OK ? "succeeded" : "failed");
655   n = neighbour_find (h,
656                       &okm->peer);
657   if (NULL == n)
658   {
659     /* We should never get a 'SEND_OK' for a peer that we are not
660        connected to */
661     GNUNET_break (0);
662     disconnect_and_schedule_reconnect (h);
663     return;
664   }
665   if (bytes_physical > bytes_msg)
666   {
667     LOG (GNUNET_ERROR_TYPE_DEBUG,
668          "Overhead for %u byte message was %u\n",
669          bytes_msg,
670          bytes_physical - bytes_msg);
671     n->traffic_overhead += bytes_physical - bytes_msg;
672   }
673 }
674
675
676 /**
677  * Function we use for checking incoming "inbound" messages.
678  *
679  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
680  * @param im message received
681  */
682 static int
683 check_recv (void *cls,
684              const struct InboundMessage *im)
685 {
686   const struct GNUNET_MessageHeader *imm;
687   uint16_t size;
688
689   size = ntohs (im->header.size) - sizeof (*im);
690   if (size < sizeof (struct GNUNET_MessageHeader))
691   {
692     GNUNET_break (0);
693     return GNUNET_SYSERR;
694   }
695   imm = (const struct GNUNET_MessageHeader *) &im[1];
696   if (ntohs (imm->size) != size)
697   {
698     GNUNET_break (0);
699     return GNUNET_SYSERR;
700   }
701   return GNUNET_OK;
702 }
703
704
705 /**
706  * Function we use for handling incoming messages.
707  *
708  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
709  * @param im message received
710  */
711 static void
712 handle_recv (void *cls,
713              const struct InboundMessage *im)
714 {
715   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
716   const struct GNUNET_MessageHeader *imm
717     = (const struct GNUNET_MessageHeader *) &im[1];
718   struct Neighbour *n;
719
720   LOG (GNUNET_ERROR_TYPE_DEBUG,
721        "Received message of type %u with %u bytes from `%s'.\n",
722        (unsigned int) ntohs (imm->type),
723        (unsigned int) ntohs (imm->size),
724        GNUNET_i2s (&im->peer));
725   n = neighbour_find (h, &im->peer);
726   if (NULL == n)
727   {
728     GNUNET_break (0);
729     disconnect_and_schedule_reconnect (h);
730     return;
731   }
732   GNUNET_MQ_inject_message (n->mq,
733                             imm);
734 }
735
736
737 /**
738  * Function we use for handling incoming set quota messages.
739  *
740  * @param cls closure, a `struct GNUNET_TRANSPORT_CoreHandle *`
741  * @param msg message received
742  */
743 static void
744 handle_set_quota (void *cls,
745                   const struct QuotaSetMessage *qm)
746 {
747   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
748   struct Neighbour *n;
749
750   LOG (GNUNET_ERROR_TYPE_DEBUG,
751        "Receiving SET_QUOTA message for `%s' with quota %u\n",
752        GNUNET_i2s (&qm->peer),
753        ntohl (qm->quota.value__));
754   n = neighbour_find (h,
755                       &qm->peer);
756   if (NULL == n)
757   {
758     GNUNET_break (0); /* FIXME: julius reports this assertion fails sometimes? */
759     disconnect_and_schedule_reconnect (h);
760     return;
761   }
762   GNUNET_BANDWIDTH_tracker_update_quota (&n->out_tracker,
763                                          qm->quota);
764 }
765
766
767 /**
768  * Try again to connect to transport service.
769  *
770  * @param cls the handle to the transport service
771  */
772 static void
773 reconnect (void *cls)
774 {
775   struct GNUNET_TRANSPORT_CoreHandle *h = cls;
776   struct GNUNET_MQ_MessageHandler handlers[] = {
777     GNUNET_MQ_hd_var_size (hello,
778                            GNUNET_MESSAGE_TYPE_HELLO,
779                            struct GNUNET_MessageHeader,
780                            h),
781     GNUNET_MQ_hd_fixed_size (connect,
782                              GNUNET_MESSAGE_TYPE_TRANSPORT_CONNECT,
783                              struct ConnectInfoMessage,
784                              h),
785     GNUNET_MQ_hd_fixed_size (disconnect,
786                              GNUNET_MESSAGE_TYPE_TRANSPORT_DISCONNECT,
787                              struct DisconnectInfoMessage,
788                              h),
789     GNUNET_MQ_hd_fixed_size (send_ok,
790                              GNUNET_MESSAGE_TYPE_TRANSPORT_SEND_OK,
791                              struct SendOkMessage,
792                              h),
793     GNUNET_MQ_hd_var_size (recv,
794                            GNUNET_MESSAGE_TYPE_TRANSPORT_RECV,
795                            struct InboundMessage,
796                            h),
797     GNUNET_MQ_hd_fixed_size (set_quota,
798                              GNUNET_MESSAGE_TYPE_TRANSPORT_SET_QUOTA,
799                              struct QuotaSetMessage,
800                              h),
801     GNUNET_MQ_handler_end ()
802   };
803   struct GNUNET_MQ_Envelope *env;
804   struct StartMessage *s;
805   uint32_t options;
806
807   h->reconnect_task = NULL;
808   LOG (GNUNET_ERROR_TYPE_DEBUG,
809        "Connecting to transport service.\n");
810   GNUNET_assert (NULL == h->mq);
811   h->mq = GNUNET_CLIENT_connect (h->cfg,
812                                  "transport",
813                                  handlers,
814                                  &mq_error_handler,
815                                  h);
816   if (NULL == h->mq)
817     return;
818   env = GNUNET_MQ_msg (s,
819                        GNUNET_MESSAGE_TYPE_TRANSPORT_START);
820   options = 0;
821   if (h->check_self)
822     options |= 1;
823   if (NULL != h->handlers)
824     options |= 2;
825   s->options = htonl (options);
826   s->self = h->self;
827   GNUNET_MQ_send (h->mq,
828                   env);
829 }
830
831
832 /**
833  * Function that will schedule the job that will try
834  * to connect us again to the client.
835  *
836  * @param h transport service to reconnect
837  */
838 static void
839 disconnect_and_schedule_reconnect (struct GNUNET_TRANSPORT_CoreHandle *h)
840 {
841   GNUNET_assert (NULL == h->reconnect_task);
842   /* Forget about all neighbours that we used to be connected to */
843   GNUNET_CONTAINER_multipeermap_iterate (h->neighbours,
844                                          &neighbour_delete,
845                                          h);
846   if (NULL != h->mq)
847   {
848     GNUNET_MQ_destroy (h->mq);
849     h->mq = NULL;
850   }
851   LOG (GNUNET_ERROR_TYPE_DEBUG,
852        "Scheduling task to reconnect to transport service in %s.\n",
853        GNUNET_STRINGS_relative_time_to_string (h->reconnect_delay,
854                                                GNUNET_YES));
855   h->reconnect_task =
856       GNUNET_SCHEDULER_add_delayed (h->reconnect_delay,
857                                     &reconnect,
858                                     h);
859   h->reconnect_delay = GNUNET_TIME_STD_BACKOFF (h->reconnect_delay);
860 }
861
862
863 /**
864  * Checks if a given peer is connected to us and get the message queue.
865  *
866  * @param handle connection to transport service
867  * @param peer the peer to check
868  * @return NULL if disconnected, otherwise message queue for @a peer
869  */
870 struct GNUNET_MQ_Handle *
871 GNUNET_TRANSPORT_core_get_mq (struct GNUNET_TRANSPORT_CoreHandle *handle,
872                               const struct GNUNET_PeerIdentity *peer)
873 {
874   struct Neighbour *n;
875
876   n = neighbour_find (handle,
877                       peer);
878   if (NULL == n)
879     return NULL;
880   return n->mq;
881 }
882
883
884 /**
885  * Connect to the transport service.  Note that the connection may
886  * complete (or fail) asynchronously.
887  *
888  * @param cfg configuration to use
889  * @param self our own identity (API should check that it matches
890  *             the identity found by transport), or NULL (no check)
891  * @param cls closure for the callbacks
892  * @param rec receive function to call
893  * @param nc function to call on connect events
894  * @param nd function to call on disconnect events
895  * @param neb function to call if we have excess bandwidth to a peer
896  * @return NULL on error
897  */
898 struct GNUNET_TRANSPORT_CoreHandle *
899 GNUNET_TRANSPORT_core_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
900                                const struct GNUNET_PeerIdentity *self,
901                                const struct GNUNET_MQ_MessageHandler *handlers,
902                                void *cls,
903                                GNUNET_TRANSPORT_NotifyConnect nc,
904                                GNUNET_TRANSPORT_NotifyDisconnect nd,
905                                GNUNET_TRANSPORT_NotifyExcessBandwidth neb)
906 {
907   struct GNUNET_TRANSPORT_CoreHandle *h;
908   unsigned int i;
909
910   h = GNUNET_new (struct GNUNET_TRANSPORT_CoreHandle);
911   if (NULL != self)
912   {
913     h->self = *self;
914     h->check_self = GNUNET_YES;
915   }
916   h->cfg = cfg;
917   h->cls = cls;
918   h->nc_cb = nc;
919   h->nd_cb = nd;
920   h->neb_cb = neb;
921   h->reconnect_delay = GNUNET_TIME_UNIT_ZERO;
922   if (NULL != handlers)
923   {
924     for (i=0;NULL != handlers[i].cb; i++) ;
925     h->handlers = GNUNET_new_array (i + 1,
926                                     struct GNUNET_MQ_MessageHandler);
927     GNUNET_memcpy (h->handlers,
928                    handlers,
929                    i * sizeof (struct GNUNET_MQ_MessageHandler));
930   }
931   LOG (GNUNET_ERROR_TYPE_DEBUG,
932        "Connecting to transport service\n");
933   reconnect (h);
934   if (NULL == h->mq)
935   {
936     GNUNET_free_non_null (h->handlers);
937     GNUNET_free (h);
938     return NULL;
939   }
940   h->neighbours =
941     GNUNET_CONTAINER_multipeermap_create (STARTING_NEIGHBOURS_SIZE,
942                                           GNUNET_YES);
943   return h;
944 }
945
946
947 /**
948  * Disconnect from the transport service.
949  *
950  * @param handle handle to the service as returned from #GNUNET_TRANSPORT_core_connect()
951  */
952 void
953 GNUNET_TRANSPORT_core_disconnect (struct GNUNET_TRANSPORT_CoreHandle *handle)
954 {
955   LOG (GNUNET_ERROR_TYPE_DEBUG,
956        "Transport disconnect called!\n");
957   /* this disconnects all neighbours... */
958   if (NULL == handle->reconnect_task)
959     disconnect_and_schedule_reconnect (handle);
960   /* and now we stop trying to connect again... */
961   if (NULL != handle->reconnect_task)
962   {
963     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
964     handle->reconnect_task = NULL;
965   }
966   GNUNET_CONTAINER_multipeermap_destroy (handle->neighbours);
967   handle->neighbours = NULL;
968   GNUNET_free_non_null (handle->handlers);
969   handle->handlers = NULL;
970   GNUNET_free (handle);
971 }
972
973
974 /* end of transport_api_core.c */