Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / cadet / cadet_api_new.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2011, 2017 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file cadet/cadet_api.c
22  * @brief cadet api: client implementation of cadet service
23  * @author Bartlomiej Polot
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_cadet_service.h"
30 #include "cadet.h"
31 #include "cadet_protocol.h"
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "cadet-api",__VA_ARGS__)
34
35 /**
36  * Ugly legacy hack.
37  */
38 union CadetInfoCB
39 {
40
41   /**
42    * Channel callback.
43    */
44   GNUNET_CADET_ChannelCB channel_cb;
45
46   /**
47    * Monitor callback
48    */
49   GNUNET_CADET_PeersCB peers_cb;
50
51   /**
52    * Monitor callback
53    */
54   GNUNET_CADET_PeerCB peer_cb;
55
56   /**
57    * Monitor callback
58    */
59   GNUNET_CADET_TunnelsCB tunnels_cb;
60
61   /**
62    * Tunnel callback.
63    */
64   GNUNET_CADET_TunnelCB tunnel_cb;
65 };
66
67
68 /**
69  * Opaque handle to the service.
70  */
71 struct GNUNET_CADET_Handle
72 {
73   /**
74    * Message queue.
75    */
76   struct GNUNET_MQ_Handle *mq;
77
78   /**
79    * Ports open.
80    */
81   struct GNUNET_CONTAINER_MultiHashMap *ports;
82
83   /**
84    * Channels open.
85    */
86   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
87
88   /**
89    * child of the next channel to create (to avoid reusing IDs often)
90    */
91   struct GNUNET_CADET_ClientChannelNumber next_ccn;
92
93   /**
94    * Configuration given by the client, in case of reconnection
95    */
96   const struct GNUNET_CONFIGURATION_Handle *cfg;
97
98   /**
99    * Task for trying to reconnect.
100    */
101   struct GNUNET_SCHEDULER_Task *reconnect_task;
102
103   /**
104    * Callback for an info task (only one active at a time).
105    */
106   union CadetInfoCB info_cb;
107
108   /**
109    * Info callback closure for @c info_cb.
110    */
111   void *info_cls;
112
113   /**
114    * Time to the next reconnect in case one reconnect fails
115    */
116   struct GNUNET_TIME_Relative reconnect_time;
117
118 };
119
120
121 /**
122  * Opaque handle to a channel.
123  */
124 struct GNUNET_CADET_Channel
125 {
126
127   /**
128    * Other end of the channel.
129    */
130   struct GNUNET_PeerIdentity peer;
131
132   /**
133    * Handle to the cadet this channel belongs to
134    */
135   struct GNUNET_CADET_Handle *cadet;
136
137   /**
138    * Channel's port, if incoming.
139    */
140   struct GNUNET_CADET_Port *incoming_port;
141
142   /**
143    * Any data the caller wants to put in here, used for the
144    * various callbacks (@e disconnects, @e window_changes, handlers).
145    */
146   void *ctx;
147
148   /**
149    * Message Queue for the channel (which we are implementing).
150    */
151   struct GNUNET_MQ_Handle *mq;
152
153   /**
154    * Task to allow mq to send more traffic.
155    */
156   struct GNUNET_SCHEDULER_Task *mq_cont;
157
158   /**
159    * Pending envelope with a message to be transmitted to the
160    * service as soon as we are allowed to.  Should only be
161    * non-NULL if @e allow_send is 0.
162    */
163   struct GNUNET_MQ_Envelope *pending_env;
164
165   /**
166    * Window change handler.
167    */
168   GNUNET_CADET_WindowSizeEventHandler window_changes;
169
170   /**
171    * Disconnect handler.
172    */
173   GNUNET_CADET_DisconnectEventHandler disconnects;
174
175   /**
176    * Local ID of the channel, #GNUNET_CADET_LOCAL_CHANNEL_ID_CLI bit is set if outbound.
177    */
178   struct GNUNET_CADET_ClientChannelNumber ccn;
179
180   /**
181    * Channel options: reliability, etc.
182    */
183   enum GNUNET_CADET_ChannelOption options;
184
185   /**
186    * How many messages are we allowed to send to the service right now?
187    */
188   unsigned int allow_send;
189
190 };
191
192
193 /**
194  * Opaque handle to a port.
195  */
196 struct GNUNET_CADET_Port
197 {
198
199   /**
200    * Port "number"
201    */
202   struct GNUNET_HashCode id;
203
204   /**
205    * Handle to the CADET session this port belongs to.
206    */
207   struct GNUNET_CADET_Handle *cadet;
208
209   /**
210    * Callback handler for incoming channels on this port.
211    */
212   GNUNET_CADET_InboundChannelNotificationHandler *handler;
213
214   /**
215    * Closure for @a handler.
216    */
217   void *cls;
218
219   /**
220    * Handler for incoming channels on this port
221    */
222   GNUNET_CADET_ConnectEventHandler connects;
223
224   /**
225    * Closure for @ref connects
226    */
227   void *connects_cls;
228
229   /**
230    * Window size change handler.
231    */
232   GNUNET_CADET_WindowSizeEventHandler window_changes;
233
234   /**
235    * Handler called when an incoming channel is destroyed.
236    */
237   GNUNET_CADET_DisconnectEventHandler disconnects;
238
239   /**
240    * Payload handlers for incoming channels.
241    */
242   struct GNUNET_MQ_MessageHandler *handlers;
243 };
244
245
246 /**
247  * Find the Port struct for a hash.
248  *
249  * @param h CADET handle.
250  * @param hash HashCode for the port number.
251  * @return The port handle if known, NULL otherwise.
252  */
253 static struct GNUNET_CADET_Port *
254 find_port (const struct GNUNET_CADET_Handle *h,
255            const struct GNUNET_HashCode *hash)
256 {
257   return GNUNET_CONTAINER_multihashmap_get (h->ports,
258                                             hash);
259 }
260
261
262 /**
263  * Get the channel handler for the channel specified by id from the given handle
264  *
265  * @param h Cadet handle
266  * @param ccn ID of the wanted channel
267  * @return handle to the required channel or NULL if not found
268  */
269 static struct GNUNET_CADET_Channel *
270 find_channel (struct GNUNET_CADET_Handle *h,
271               struct GNUNET_CADET_ClientChannelNumber ccn)
272 {
273   return GNUNET_CONTAINER_multihashmap32_get (h->channels,
274                                               ntohl (ccn.channel_of_client));
275 }
276
277
278 /**
279  * Create a new channel and insert it in the channel list of the cadet handle
280  *
281  * @param h Cadet handle
282  * @param ccnp pointer to desired ccn of the channel, NULL to assign one automatically.
283  * @return Handle to the created channel.
284  */
285 static struct GNUNET_CADET_Channel *
286 create_channel (struct GNUNET_CADET_Handle *h,
287                 const struct GNUNET_CADET_ClientChannelNumber *ccnp)
288 {
289   struct GNUNET_CADET_Channel *ch;
290   struct GNUNET_CADET_ClientChannelNumber ccn;
291
292   ch = GNUNET_new (struct GNUNET_CADET_Channel);
293   ch->cadet = h;
294   if (NULL == ccnp)
295   {
296     while (NULL !=
297            find_channel (h,
298                          h->next_ccn))
299       h->next_ccn.channel_of_client
300         = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI | (1 + ntohl (h->next_ccn.channel_of_client)));
301     ccn = h->next_ccn;
302   }
303   else
304   {
305     ccn = *ccnp;
306   }
307   ch->ccn = ccn;
308   GNUNET_assert (GNUNET_OK ==
309                  GNUNET_CONTAINER_multihashmap32_put (h->channels,
310                                                       ntohl (ch->ccn.channel_of_client),
311                                                       ch,
312                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
313   return ch;
314 }
315
316
317 /**
318  * Destroy the specified channel.
319  * - Destroys all peers, calling the disconnect callback on each if needed
320  * - Cancels all outgoing traffic for that channel, calling respective notifys
321  * - Calls cleaner if channel was inbound
322  * - Frees all memory used
323  *
324  * @param ch Pointer to the channel.
325  * @param call_cleaner Whether to call the cleaner handler.
326  */
327 static void
328 destroy_channel (struct GNUNET_CADET_Channel *ch)
329 {
330   struct GNUNET_CADET_Handle *h = ch->cadet;
331
332   LOG (GNUNET_ERROR_TYPE_DEBUG,
333        "Destroying channel %X of %p\n",
334        ch->ccn,
335        h);
336   GNUNET_assert (GNUNET_YES ==
337                  GNUNET_CONTAINER_multihashmap32_remove (h->channels,
338                                                          ntohl (ch->ccn.channel_of_client),
339                                                          ch));
340   if (NULL != ch->mq_cont)
341   {
342     GNUNET_SCHEDULER_cancel (ch->mq_cont);
343     ch->mq_cont = NULL;
344   }
345   /* signal channel destruction */
346   if (NULL != ch->disconnects)
347     ch->disconnects (ch->ctx,
348                      ch);
349   if (NULL != ch->pending_env)
350     GNUNET_MQ_discard (ch->pending_env);
351   GNUNET_MQ_destroy (ch->mq);
352   GNUNET_free (ch);
353 }
354
355
356 /**
357  * Reconnect to the service, retransmit all infomation to try to restore the
358  * original state.
359  *
360  * @param h handle to the cadet
361  */
362 static void
363 reconnect (struct GNUNET_CADET_Handle *h);
364
365
366 /**
367  * Reconnect callback: tries to reconnect again after a failer previous
368  * reconnecttion
369  *
370  * @param cls closure (cadet handle)
371  */
372 static void
373 reconnect_cbk (void *cls)
374 {
375   struct GNUNET_CADET_Handle *h = cls;
376
377   h->reconnect_task = NULL;
378   reconnect (h);
379 }
380
381
382 /**
383  * Function called during #reconnect() to destroy
384  * all channels that are still open.
385  *
386  * @param cls the `struct GNUNET_CADET_Handle`
387  * @param cid chanenl ID
388  * @param value a `struct GNUNET_CADET_Channel` to destroy
389  * @return #GNUNET_OK (continue to iterate)
390  */
391 static int
392 destroy_channel_on_reconnect_cb (void *cls,
393                                  uint32_t cid,
394                                  void *value)
395 {
396   /* struct GNUNET_CADET_Handle *handle = cls; */
397   struct GNUNET_CADET_Channel *ch = value;
398
399   destroy_channel (ch);
400   return GNUNET_OK;
401 }
402
403
404 /**
405  * Reconnect to the service, retransmit all infomation to try to restore the
406  * original state.
407  *
408  * @param h handle to the cadet
409  *
410  * @return #GNUNET_YES in case of sucess, #GNUNET_NO otherwise (service down...)
411  */
412 static void
413 schedule_reconnect (struct GNUNET_CADET_Handle *h)
414 {
415   if (NULL != h->reconnect_task)
416     return;
417   GNUNET_CONTAINER_multihashmap32_iterate (h->channels,
418                                            &destroy_channel_on_reconnect_cb,
419                                            h);
420   h->reconnect_task
421     = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
422                                     &reconnect_cbk,
423                                     h);
424   h->reconnect_time
425     = GNUNET_TIME_STD_BACKOFF (h->reconnect_time);
426 }
427
428
429 /**
430  * Notify the application about a change in the window size (if needed).
431  *
432  * @param ch Channel to notify about.
433  */
434 static void
435 notify_window_size (struct GNUNET_CADET_Channel *ch)
436 {
437   if (NULL != ch->window_changes)
438     ch->window_changes (ch->ctx,
439                         ch, /* FIXME: remove 'ch'? */
440                         ch->allow_send);
441 }
442
443
444 /**
445  * Transmit the next message from our queue.
446  *
447  * @param cls Closure (channel whose mq to activate).
448  */
449 static void
450 cadet_mq_send_now (void *cls)
451 {
452   struct GNUNET_CADET_Channel *ch = cls;
453   struct GNUNET_MQ_Envelope *env = ch->pending_env;
454
455   ch->mq_cont = NULL;
456   if (0 == ch->allow_send)
457   {
458     /* how did we get here? */
459     GNUNET_break (0);
460     return;
461   }
462   if (NULL == env)
463   {
464     /* how did we get here? */
465     GNUNET_break (0);
466     return;
467   }
468   ch->allow_send--;
469   ch->pending_env = NULL;
470   GNUNET_MQ_send (ch->cadet->mq,
471                   env);
472   GNUNET_MQ_impl_send_continue (ch->mq);
473 }
474
475
476 /**
477  * Implement sending functionality of a message queue for
478  * us sending messages to a peer.
479  *
480  * Encapsulates the payload message in a #GNUNET_CADET_LocalData message
481  * in order to label the message with the channel ID and send the
482  * encapsulated message to the service.
483  *
484  * @param mq the message queue
485  * @param msg the message to send
486  * @param impl_state state of the implementation
487  */
488 static void
489 cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq,
490                     const struct GNUNET_MessageHeader *msg,
491                     void *impl_state)
492 {
493   struct GNUNET_CADET_Channel *ch = impl_state;
494   struct GNUNET_CADET_Handle *h = ch->cadet;
495   uint16_t msize;
496   struct GNUNET_MQ_Envelope *env;
497   struct GNUNET_CADET_LocalData *cadet_msg;
498
499   if (NULL == h->mq)
500   {
501     /* We're currently reconnecting, pretend this worked */
502     GNUNET_MQ_impl_send_continue (mq);
503     return;
504   }
505
506   /* check message size for sanity */
507   msize = ntohs (msg->size);
508   if (msize > GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE)
509   {
510     GNUNET_break (0);
511     GNUNET_MQ_impl_send_continue (mq);
512     return;
513   }
514   env = GNUNET_MQ_msg_nested_mh (cadet_msg,
515                                  GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
516                                  msg);
517   cadet_msg->ccn = ch->ccn;
518   GNUNET_assert (NULL == ch->pending_env);
519   ch->pending_env = env;
520   if (0 < ch->allow_send)
521     ch->mq_cont
522       = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
523                                   ch);
524 }
525
526
527 /**
528  * Handle destruction of a message queue.  Implementations must not
529  * free @a mq, but should take care of @a impl_state.
530  *
531  * @param mq the message queue to destroy
532  * @param impl_state state of the implementation
533  */
534 static void
535 cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
536                        void *impl_state)
537 {
538   struct GNUNET_CADET_Channel *ch = impl_state;
539
540   GNUNET_assert (mq == ch->mq);
541   ch->mq = NULL;
542 }
543
544
545 /**
546  * We had an error processing a message we forwarded from a peer to
547  * the CADET service.  We should just complain about it but otherwise
548  * continue processing.
549  *
550  * @param cls closure with our `struct GNUNET_CADET_Channel`
551  * @param error error code
552  */
553 static void
554 cadet_mq_error_handler (void *cls,
555                         enum GNUNET_MQ_Error error)
556 {
557   struct GNUNET_CADET_Channel *ch = cls;
558
559   GNUNET_break (0);
560   if (GNUNET_MQ_ERROR_NO_MATCH == error)
561   {
562     /* Got a message we did not understand, still try to continue! */
563     GNUNET_CADET_receive_done (ch);
564   }
565   else
566   {
567     schedule_reconnect (ch->cadet);
568   }
569 }
570
571
572 /**
573  * Implementation function that cancels the currently sent message.
574  * Should basically undo whatever #mq_send_impl() did.
575  *
576  * @param mq message queue
577  * @param impl_state state specific to the implementation
578  */
579 static void
580 cadet_mq_cancel_impl (struct GNUNET_MQ_Handle *mq,
581                      void *impl_state)
582 {
583   struct GNUNET_CADET_Channel *ch = impl_state;
584
585   GNUNET_assert (NULL != ch->pending_env);
586   GNUNET_MQ_discard (ch->pending_env);
587   ch->pending_env = NULL;
588   if (NULL != ch->mq_cont)
589   {
590     GNUNET_SCHEDULER_cancel (ch->mq_cont);
591     ch->mq_cont = NULL;
592   }
593 }
594
595
596 /**
597  * Process the new channel notification and add it to the channels in the handle
598  *
599  * @param h     The cadet handle
600  * @param msg   A message with the details of the new incoming channel
601  */
602 static void
603 handle_channel_created (void *cls,
604                         const struct GNUNET_CADET_LocalChannelCreateMessage *msg)
605 {
606   struct GNUNET_CADET_Handle *h = cls;
607   struct GNUNET_CADET_Channel *ch;
608   struct GNUNET_CADET_Port *port;
609   const struct GNUNET_HashCode *port_number;
610   struct GNUNET_CADET_ClientChannelNumber ccn;
611
612   ccn = msg->ccn;
613   port_number = &msg->port;
614   if (ntohl (ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
615   {
616     GNUNET_break (0);
617     return;
618   }
619   port = find_port (h,
620                     port_number);
621   if (NULL == port)
622   {
623     /* We could have closed the port but the service didn't know about it yet
624      * This is not an error.
625      */
626     struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg;
627     struct GNUNET_MQ_Envelope *env;
628
629     LOG (GNUNET_ERROR_TYPE_DEBUG,
630          "No handler for incoming channel %X (on port %s, recently closed?)\n",
631          ntohl (ccn.channel_of_client),
632          GNUNET_h2s (port_number));
633     env = GNUNET_MQ_msg (d_msg,
634                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
635     d_msg->ccn = msg->ccn;
636     GNUNET_MQ_send (h->mq,
637                     env);
638     return;
639   }
640
641   ch = create_channel (h,
642                        &ccn);
643   ch->peer = msg->peer;
644   ch->cadet = h;
645   ch->incoming_port = port;
646   ch->options = ntohl (msg->opt);
647   LOG (GNUNET_ERROR_TYPE_DEBUG,
648        "Creating incoming channel %X [%s] %p\n",
649        ntohl (ccn.channel_of_client),
650        GNUNET_h2s (port_number),
651        ch);
652
653   GNUNET_assert (NULL != port->connects);
654   ch->window_changes = port->window_changes;
655   ch->disconnects = port->disconnects;
656   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
657                                           &cadet_mq_destroy_impl,
658                                           &cadet_mq_cancel_impl,
659                                           ch,
660                                           port->handlers,
661                                           &cadet_mq_error_handler,
662                                           ch);
663   ch->ctx = port->connects (port->cls,
664                             ch,
665                             &msg->peer);
666   GNUNET_MQ_set_handlers_closure (ch->mq,
667                                   ch->ctx);
668 }
669
670
671 /**
672  * Process the channel destroy notification and free associated resources
673  *
674  * @param h     The cadet handle
675  * @param msg   A message with the details of the channel being destroyed
676  */
677 static void
678 handle_channel_destroy (void *cls,
679                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
680 {
681   struct GNUNET_CADET_Handle *h = cls;
682   struct GNUNET_CADET_Channel *ch;
683
684   ch = find_channel (h,
685                      msg->ccn);
686   if (NULL == ch)
687   {
688     LOG (GNUNET_ERROR_TYPE_DEBUG,
689          "Received channel destroy for unknown channel %X from CADET service (recently close?)\n",
690          ntohl (msg->ccn.channel_of_client));
691     return;
692   }
693   LOG (GNUNET_ERROR_TYPE_DEBUG,
694        "Received channel destroy for channel %X from CADET service\n",
695        ntohl (msg->ccn.channel_of_client));
696   destroy_channel (ch);
697 }
698
699
700 /**
701  * Check that message received from CADET service is well-formed.
702  *
703  * @param cls the `struct GNUNET_CADET_Handle`
704  * @param message the message we got
705  * @return #GNUNET_OK if the message is well-formed,
706  *         #GNUNET_SYSERR otherwise
707  */
708 static int
709 check_local_data (void *cls,
710                   const struct GNUNET_CADET_LocalData *message)
711 {
712   uint16_t size;
713
714   size = ntohs (message->header.size);
715   if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size)
716   {
717     GNUNET_break (0);
718     return GNUNET_SYSERR;
719   }
720   return GNUNET_OK;
721 }
722
723
724 /**
725  * Process the incoming data packets, call appropriate handlers.
726  *
727  * @param h       The cadet handle
728  * @param message A message encapsulating the data
729  */
730 static void
731 handle_local_data (void *cls,
732                    const struct GNUNET_CADET_LocalData *message)
733 {
734   struct GNUNET_CADET_Handle *h = cls;
735   const struct GNUNET_MessageHeader *payload;
736   struct GNUNET_CADET_Channel *ch;
737   uint16_t type;
738   int fwd;
739
740   ch = find_channel (h,
741                      message->ccn);
742   if (NULL == ch)
743   {
744     LOG (GNUNET_ERROR_TYPE_DEBUG,
745          "Unknown channel %X for incoming data (recently closed?)\n",
746          ntohl (message->ccn.channel_of_client));
747     return;
748   }
749
750   payload = (const struct GNUNET_MessageHeader *) &message[1];
751   type = ntohs (payload->type);
752   fwd = ntohl (ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
753   LOG (GNUNET_ERROR_TYPE_DEBUG,
754        "Got a %s data on channel %s [%X] of type %u\n",
755        fwd ? "FWD" : "BWD",
756        GNUNET_i2s (&ch->peer),
757        ntohl (message->ccn.channel_of_client),
758        type);
759   GNUNET_MQ_inject_message (ch->mq,
760                             payload);
761 }
762
763
764 /**
765  * Process a local ACK message, enabling the client to send
766  * more data to the service.
767  *
768  * @param h Cadet handle.
769  * @param message Message itself.
770  */
771 static void
772 handle_local_ack (void *cls,
773                   const struct GNUNET_CADET_LocalAck *message)
774 {
775   struct GNUNET_CADET_Handle *h = cls;
776   struct GNUNET_CADET_Channel *ch;
777
778   ch = find_channel (h,
779                      message->ccn);
780   if (NULL == ch)
781   {
782     LOG (GNUNET_ERROR_TYPE_DEBUG,
783          "ACK on unknown channel %X\n",
784          ntohl (message->ccn.channel_of_client));
785     return;
786   }
787   ch->allow_send++;
788   if (NULL == ch->pending_env)
789   {
790     LOG (GNUNET_ERROR_TYPE_DEBUG,
791          "Got an ACK on mq channel %X, allow send now %u!\n",
792          ntohl (ch->ccn.channel_of_client),
793          ch->allow_send);
794     notify_window_size (ch);
795     return;
796   }
797   if (NULL != ch->mq_cont)
798     return; /* already working on it! */
799   LOG (GNUNET_ERROR_TYPE_DEBUG,
800        "Got an ACK on mq channel %X, sending pending message!\n",
801        ntohl (ch->ccn.channel_of_client));
802   ch->mq_cont
803     = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
804                                 ch);
805 }
806
807
808 /**
809  * Generic error handler, called with the appropriate error code and
810  * the same closure specified at the creation of the message queue.
811  * Not every message queue implementation supports an error handler.
812  *
813  * @param cls closure, a `struct GNUNET_CORE_Handle *`
814  * @param error error code
815  */
816 static void
817 handle_mq_error (void *cls,
818                  enum GNUNET_MQ_Error error)
819 {
820   struct GNUNET_CADET_Handle *h = cls;
821
822   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
823               "MQ ERROR: %u\n",
824               error);
825   GNUNET_MQ_destroy (h->mq);
826   h->mq = NULL;
827   reconnect (h);
828 }
829
830
831 /**
832  * Process a local reply about info on all tunnels, pass info to the user.
833  *
834  * @param cls Closure (Cadet handle).
835  * @param msg Message itself.
836  */
837 static void
838 handle_get_peers (void *cls,
839                   const struct GNUNET_CADET_LocalInfoPeer *msg)
840 {
841   struct GNUNET_CADET_Handle *h = cls;
842
843   if (NULL == h->info_cb.peers_cb)
844     return;
845   h->info_cb.peers_cb (h->info_cls,
846                        &msg->destination,
847                        (int) ntohs (msg->tunnel),
848                        (unsigned int) ntohs (msg->paths),
849                        0);
850 }
851
852
853 /**
854  * Check that message received from CADET service is well-formed.
855  *
856  * @param cls the `struct GNUNET_CADET_Handle`
857  * @param message the message we got
858  * @return #GNUNET_OK if the message is well-formed,
859  *         #GNUNET_SYSERR otherwise
860  */
861 static int
862 check_get_peer (void *cls,
863                 const struct GNUNET_CADET_LocalInfoPeer *message)
864 {
865   size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
866   const struct GNUNET_PeerIdentity *paths_array;
867   size_t esize;
868   unsigned int epaths;
869   unsigned int paths;
870   unsigned int peers;
871
872   esize = ntohs (message->header.size);
873   if (esize < msize)
874   {
875     GNUNET_break (0);
876     return GNUNET_SYSERR;
877   }
878   if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
879   {
880     GNUNET_break (0);
881     return GNUNET_SYSERR;
882   }
883   peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
884   epaths = ntohs (message->paths);
885   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
886   paths = 0;
887   for (unsigned int i = 0; i < peers; i++)
888     if (0 == memcmp (&paths_array[i],
889                      &message->destination,
890                      sizeof (struct GNUNET_PeerIdentity)))
891       paths++;
892   if (paths != epaths)
893   {
894     GNUNET_break (0);
895     return GNUNET_SYSERR;
896   }
897   return GNUNET_OK;
898 }
899
900
901 /**
902  * Process a local peer info reply, pass info to the user.
903  *
904  * @param cls Closure (Cadet handle).
905  * @param message Message itself.
906  */
907 static void
908 handle_get_peer (void *cls,
909                  const struct GNUNET_CADET_LocalInfoPeer *message)
910 {
911   struct GNUNET_CADET_Handle *h = cls;
912   const struct GNUNET_PeerIdentity *paths_array;
913   unsigned int paths;
914   unsigned int path_length;
915   int neighbor;
916   unsigned int peers;
917
918   if (NULL == h->info_cb.peer_cb)
919     return;
920   paths = ntohs (message->paths);
921   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
922   peers = (ntohs (message->header.size) - sizeof (*message))
923           / sizeof (struct GNUNET_PeerIdentity);
924   path_length = 0;
925   neighbor = GNUNET_NO;
926
927   for (unsigned int i = 0; i < peers; i++)
928   {
929     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930                 " %s\n",
931                 GNUNET_i2s (&paths_array[i]));
932     path_length++;
933     if (0 == memcmp (&paths_array[i], &message->destination,
934                      sizeof (struct GNUNET_PeerIdentity)))
935     {
936       if (1 == path_length)
937         neighbor = GNUNET_YES;
938       path_length = 0;
939     }
940   }
941
942   /* Call Callback with tunnel info. */
943   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
944   h->info_cb.peer_cb (h->info_cls,
945                       &message->destination,
946                       (int) ntohs (message->tunnel),
947                       neighbor,
948                       paths,
949                       paths_array);
950 }
951
952
953 /**
954  * Process a local reply about info on all tunnels, pass info to the user.
955  *
956  * @param cls Closure (Cadet handle).
957  * @param message Message itself.
958  */
959 static void
960 handle_get_tunnels (void *cls,
961                     const struct GNUNET_CADET_LocalInfoTunnel *msg)
962 {
963   struct GNUNET_CADET_Handle *h = cls;
964
965   if (NULL == h->info_cb.tunnels_cb)
966     return;
967   h->info_cb.tunnels_cb (h->info_cls,
968                          &msg->destination,
969                          ntohl (msg->channels),
970                          ntohl (msg->connections),
971                          ntohs (msg->estate),
972                          ntohs (msg->cstate));
973
974 }
975
976
977 /**
978  * Check that message received from CADET service is well-formed.
979  *
980  * @param cls the `struct GNUNET_CADET_Handle`
981  * @param msg the message we got
982  * @return #GNUNET_OK if the message is well-formed,
983  *         #GNUNET_SYSERR otherwise
984  */
985 static int
986 check_get_tunnel (void *cls,
987                   const struct GNUNET_CADET_LocalInfoTunnel *msg)
988 {
989   unsigned int ch_n;
990   unsigned int c_n;
991   size_t esize;
992   size_t msize;
993
994   /* Verify message sanity */
995   msize = ntohs (msg->header.size);
996   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
997   if (esize > msize)
998   {
999     GNUNET_break (0);
1000     return GNUNET_SYSERR;
1001   }
1002   ch_n = ntohl (msg->channels);
1003   c_n = ntohl (msg->connections);
1004   esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
1005   esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
1006   if (msize != esize)
1007   {
1008     GNUNET_break_op (0);
1009     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1010                 "m:%u, e: %u (%u ch, %u conn)\n",
1011                 (unsigned int) msize,
1012                 (unsigned int) esize,
1013                 ch_n,
1014                 c_n);
1015     return GNUNET_SYSERR;
1016   }
1017   return GNUNET_OK;
1018 }
1019
1020
1021 /**
1022  * Process a local tunnel info reply, pass info to the user.
1023  *
1024  * @param cls Closure (Cadet handle).
1025  * @param msg Message itself.
1026  */
1027 static void
1028 handle_get_tunnel (void *cls,
1029                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1030 {
1031   struct GNUNET_CADET_Handle *h = cls;
1032   unsigned int ch_n;
1033   unsigned int c_n;
1034   const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
1035   const struct GNUNET_CADET_ChannelTunnelNumber *chns;
1036
1037   if (NULL == h->info_cb.tunnel_cb)
1038     return;
1039
1040   ch_n = ntohl (msg->channels);
1041   c_n = ntohl (msg->connections);
1042
1043   /* Call Callback with tunnel info. */
1044   conns = (const struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
1045   chns = (const struct GNUNET_CADET_ChannelTunnelNumber *) &conns[c_n];
1046   h->info_cb.tunnel_cb (h->info_cls,
1047                         &msg->destination,
1048                         ch_n,
1049                         c_n,
1050                         chns,
1051                         conns,
1052                         ntohs (msg->estate),
1053                         ntohs (msg->cstate));
1054 }
1055
1056
1057 /**
1058  * Reconnect to the service, retransmit all infomation to try to restore the
1059  * original state.
1060  *
1061  * @param h handle to the cadet
1062  */
1063 static void
1064 reconnect (struct GNUNET_CADET_Handle *h)
1065 {
1066   struct GNUNET_MQ_MessageHandler handlers[] = {
1067     GNUNET_MQ_hd_fixed_size (channel_created,
1068                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1069                              struct GNUNET_CADET_LocalChannelCreateMessage,
1070                              h),
1071     GNUNET_MQ_hd_fixed_size (channel_destroy,
1072                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1073                              struct GNUNET_CADET_LocalChannelDestroyMessage,
1074                              h),
1075     GNUNET_MQ_hd_var_size (local_data,
1076                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1077                            struct GNUNET_CADET_LocalData,
1078                            h),
1079     GNUNET_MQ_hd_fixed_size (local_ack,
1080                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1081                              struct GNUNET_CADET_LocalAck,
1082                              h),
1083     GNUNET_MQ_hd_fixed_size (get_peers,
1084                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1085                              struct GNUNET_CADET_LocalInfoPeer,
1086                              h),
1087     GNUNET_MQ_hd_var_size (get_peer,
1088                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1089                            struct GNUNET_CADET_LocalInfoPeer,
1090                            h),
1091     GNUNET_MQ_hd_fixed_size (get_tunnels,
1092                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1093                              struct GNUNET_CADET_LocalInfoTunnel,
1094                              h),
1095     GNUNET_MQ_hd_var_size (get_tunnel,
1096                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1097                            struct GNUNET_CADET_LocalInfoTunnel,
1098                            h),
1099     GNUNET_MQ_handler_end ()
1100   };
1101
1102   h->mq = GNUNET_CLIENT_connect (h->cfg,
1103                                  "cadet",
1104                                  handlers,
1105                                  &handle_mq_error,
1106                                  h);
1107   if (NULL == h->mq)
1108   {
1109     schedule_reconnect (h);
1110     return;
1111   }
1112   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1113 }
1114
1115
1116 /**
1117  * Function called during #GNUNET_CADET_disconnect() to destroy
1118  * all channels that are still open.
1119  *
1120  * @param cls the `struct GNUNET_CADET_Handle`
1121  * @param cid chanenl ID
1122  * @param value a `struct GNUNET_CADET_Channel` to destroy
1123  * @return #GNUNET_OK (continue to iterate)
1124  */
1125 static int
1126 destroy_channel_cb (void *cls,
1127                     uint32_t cid,
1128                     void *value)
1129 {
1130   /* struct GNUNET_CADET_Handle *handle = cls; */
1131   struct GNUNET_CADET_Channel *ch = value;
1132
1133   if (ntohl (ch->ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1134   {
1135     GNUNET_break (0);
1136     LOG (GNUNET_ERROR_TYPE_DEBUG,
1137          "channel %X not destroyed\n",
1138          ntohl (ch->ccn.channel_of_client));
1139   }
1140   destroy_channel (ch);
1141   return GNUNET_OK;
1142 }
1143
1144
1145 /**
1146  * Function called during #GNUNET_CADET_disconnect() to destroy
1147  * all ports that are still open.
1148  *
1149  * @param cls the `struct GNUNET_CADET_Handle`
1150  * @param id port ID
1151  * @param value a `struct GNUNET_CADET_Channel` to destroy
1152  * @return #GNUNET_OK (continue to iterate)
1153  */
1154 static int
1155 destroy_port_cb (void *cls,
1156                  const struct GNUNET_HashCode *id,
1157                  void *value)
1158 {
1159   /* struct GNUNET_CADET_Handle *handle = cls; */
1160   struct GNUNET_CADET_Port *port = value;
1161
1162   /* This is a warning, the app should have cleanly closed all open ports */
1163   GNUNET_break (0);
1164   GNUNET_CADET_close_port (port);
1165   return GNUNET_OK;
1166 }
1167
1168
1169 /**
1170  * Disconnect from the cadet service. All channels will be destroyed. All channel
1171  * disconnect callbacks will be called on any still connected peers, notifying
1172  * about their disconnection. The registered inbound channel cleaner will be
1173  * called should any inbound channels still exist.
1174  *
1175  * @param handle connection to cadet to disconnect
1176  */
1177 void
1178 GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
1179 {
1180   GNUNET_CONTAINER_multihashmap_iterate (handle->ports,
1181                                          &destroy_port_cb,
1182                                          handle);
1183   GNUNET_CONTAINER_multihashmap_destroy (handle->ports);
1184   handle->ports = NULL;
1185   GNUNET_CONTAINER_multihashmap32_iterate (handle->channels,
1186                                            &destroy_channel_cb,
1187                                            handle);
1188   GNUNET_CONTAINER_multihashmap32_destroy (handle->channels);
1189   handle->channels = NULL;
1190   if (NULL != handle->mq)
1191   {
1192     GNUNET_MQ_destroy (handle->mq);
1193     handle->mq = NULL;
1194   }
1195   if (NULL != handle->reconnect_task)
1196   {
1197     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1198     handle->reconnect_task = NULL;
1199   }
1200   GNUNET_free (handle);
1201 }
1202
1203
1204 /**
1205  * Close a port opened with @a GNUNET_CADET_open_port().
1206  * The @a new_channel callback will no longer be called.
1207  *
1208  * @param p Port handle.
1209  */
1210 void
1211 GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p)
1212 {
1213   struct GNUNET_CADET_PortMessage *msg;
1214   struct GNUNET_MQ_Envelope *env;
1215
1216   env = GNUNET_MQ_msg (msg,
1217                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE);
1218   msg->port = p->id;
1219   GNUNET_MQ_send (p->cadet->mq,
1220                   env);
1221   GNUNET_assert (GNUNET_YES ==
1222                  GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports,
1223                                                        &p->id,
1224                                                        p));
1225   GNUNET_free_non_null (p->handlers);
1226   GNUNET_free (p);
1227 }
1228
1229
1230 /**
1231  * Destroy an existing channel.
1232  *
1233  * The existing end callback for the channel will be called immediately.
1234  * Any pending outgoing messages will be sent but no incoming messages will be
1235  * accepted and no data callbacks will be called.
1236  *
1237  * @param channel Channel handle, becomes invalid after this call.
1238  */
1239 void
1240 GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
1241 {
1242   struct GNUNET_CADET_Handle *h = channel->cadet;
1243   struct GNUNET_CADET_LocalChannelDestroyMessage *msg;
1244   struct GNUNET_MQ_Envelope *env;
1245
1246   if (NULL != h->mq)
1247   {
1248     env = GNUNET_MQ_msg (msg,
1249                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1250     msg->ccn = channel->ccn;
1251     GNUNET_MQ_send (h->mq,
1252                     env);
1253   }
1254   destroy_channel (channel);
1255 }
1256
1257
1258 /**
1259  * Get information about a channel.
1260  *
1261  * @param channel Channel handle.
1262  * @param option Query (GNUNET_CADET_OPTION_*).
1263  * @param ... dependant on option, currently not used
1264  *
1265  * @return Union with an answer to the query.
1266  */
1267 const union GNUNET_CADET_ChannelInfo *
1268 GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
1269                                enum GNUNET_CADET_ChannelOption option,
1270                                ...)
1271 {
1272   static int bool_flag;
1273
1274   switch (option)
1275   {
1276     case GNUNET_CADET_OPTION_NOBUFFER:
1277     case GNUNET_CADET_OPTION_RELIABLE:
1278     case GNUNET_CADET_OPTION_OUT_OF_ORDER:
1279       if (0 != (option & channel->options))
1280         bool_flag = GNUNET_YES;
1281       else
1282         bool_flag = GNUNET_NO;
1283       return (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
1284       break;
1285     case GNUNET_CADET_OPTION_PEER:
1286       return (const union GNUNET_CADET_ChannelInfo *) &channel->peer;
1287       break;
1288     default:
1289       GNUNET_break (0);
1290       return NULL;
1291   }
1292 }
1293
1294
1295 /**
1296  * Send an ack on the channel to confirm the processing of a message.
1297  *
1298  * @param ch Channel on which to send the ACK.
1299  */
1300 void
1301 GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
1302 {
1303   struct GNUNET_CADET_LocalAck *msg;
1304   struct GNUNET_MQ_Envelope *env;
1305
1306   env = GNUNET_MQ_msg (msg,
1307                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
1308   LOG (GNUNET_ERROR_TYPE_DEBUG,
1309        "Sending ACK on channel %X\n",
1310        ntohl (channel->ccn.channel_of_client));
1311   msg->ccn = channel->ccn;
1312   GNUNET_MQ_send (channel->cadet->mq,
1313                   env);
1314 }
1315
1316
1317 /**
1318  * Send message of @a type to CADET service of @a h
1319  *
1320  * @param h handle to CADET service
1321  * @param type message type of trivial information request to send
1322  */
1323 static void
1324 send_info_request (struct GNUNET_CADET_Handle *h,
1325                    uint16_t type)
1326 {
1327   struct GNUNET_MessageHeader *msg;
1328   struct GNUNET_MQ_Envelope *env;
1329
1330   env = GNUNET_MQ_msg (msg,
1331                        type);
1332   GNUNET_MQ_send (h->mq,
1333                   env);
1334 }
1335
1336
1337 /**
1338  * Request a debug dump on the service's STDERR.
1339  *
1340  * WARNING: unstable API, likely to change in the future!
1341  *
1342  * @param h cadet handle
1343  */
1344 void
1345 GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
1346 {
1347   send_info_request (h,
1348                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
1349 }
1350
1351
1352 /**
1353  * Request information about peers known to the running cadet service.
1354  * The callback will be called for every peer known to the service.
1355  * Only one info request (of any kind) can be active at once.
1356  *
1357  * WARNING: unstable API, likely to change in the future!
1358  *
1359  * @param h Handle to the cadet peer.
1360  * @param callback Function to call with the requested data.
1361  * @param callback_cls Closure for @c callback.
1362  * @return #GNUNET_OK / #GNUNET_SYSERR
1363  */
1364 int
1365 GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
1366                        GNUNET_CADET_PeersCB callback,
1367                        void *callback_cls)
1368 {
1369   if (NULL != h->info_cb.peers_cb)
1370   {
1371     GNUNET_break (0);
1372     return GNUNET_SYSERR;
1373   }
1374   send_info_request (h,
1375                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
1376   h->info_cb.peers_cb = callback;
1377   h->info_cls = callback_cls;
1378   return GNUNET_OK;
1379 }
1380
1381
1382 /**
1383  * Cancel a peer info request. The callback will not be called (anymore).
1384  *
1385  * WARNING: unstable API, likely to change in the future!
1386  *
1387  * @param h Cadet handle.
1388  * @return Closure given to GNUNET_CADET_get_peers().
1389  */
1390 void *
1391 GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
1392 {
1393   void *cls = h->info_cls;
1394
1395   h->info_cb.peers_cb = NULL;
1396   h->info_cls = NULL;
1397   return cls;
1398 }
1399
1400
1401 /**
1402  * Request information about a peer known to the running cadet peer.
1403  * The callback will be called for the tunnel once.
1404  * Only one info request (of any kind) can be active at once.
1405  *
1406  * WARNING: unstable API, likely to change in the future!
1407  *
1408  * @param h Handle to the cadet peer.
1409  * @param id Peer whose tunnel to examine.
1410  * @param callback Function to call with the requested data.
1411  * @param callback_cls Closure for @c callback.
1412  * @return #GNUNET_OK / #GNUNET_SYSERR
1413  */
1414 int
1415 GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
1416                        const struct GNUNET_PeerIdentity *id,
1417                        GNUNET_CADET_PeerCB callback,
1418                        void *callback_cls)
1419 {
1420   struct GNUNET_CADET_LocalInfo *msg;
1421   struct GNUNET_MQ_Envelope *env;
1422
1423   if (NULL != h->info_cb.peer_cb)
1424   {
1425     GNUNET_break (0);
1426     return GNUNET_SYSERR;
1427   }
1428   env = GNUNET_MQ_msg (msg,
1429                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
1430   msg->peer = *id;
1431   GNUNET_MQ_send (h->mq,
1432                   env);
1433   h->info_cb.peer_cb = callback;
1434   h->info_cls = callback_cls;
1435   return GNUNET_OK;
1436 }
1437
1438
1439 /**
1440  * Request information about tunnels of the running cadet peer.
1441  * The callback will be called for every tunnel of the service.
1442  * Only one info request (of any kind) can be active at once.
1443  *
1444  * WARNING: unstable API, likely to change in the future!
1445  *
1446  * @param h Handle to the cadet peer.
1447  * @param callback Function to call with the requested data.
1448  * @param callback_cls Closure for @c callback.
1449  * @return #GNUNET_OK / #GNUNET_SYSERR
1450  */
1451 int
1452 GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
1453                          GNUNET_CADET_TunnelsCB callback,
1454                          void *callback_cls)
1455 {
1456   if (NULL != h->info_cb.tunnels_cb)
1457   {
1458     GNUNET_break (0);
1459     return GNUNET_SYSERR;
1460   }
1461   send_info_request (h,
1462                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
1463   h->info_cb.tunnels_cb = callback;
1464   h->info_cls = callback_cls;
1465   return GNUNET_OK;
1466 }
1467
1468
1469 /**
1470  * Cancel a monitor request. The monitor callback will not be called.
1471  *
1472  * @param h Cadet handle.
1473  * @return Closure given to GNUNET_CADET_get_tunnels().
1474  */
1475 void *
1476 GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
1477 {
1478   void *cls = h->info_cls;
1479
1480   h->info_cb.tunnels_cb = NULL;
1481   h->info_cls = NULL;
1482   return cls;
1483 }
1484
1485
1486 /**
1487  * Request information about a tunnel of the running cadet peer.
1488  * The callback will be called for the tunnel once.
1489  * Only one info request (of any kind) can be active at once.
1490  *
1491  * WARNING: unstable API, likely to change in the future!
1492  *
1493  * @param h Handle to the cadet peer.
1494  * @param id Peer whose tunnel to examine.
1495  * @param callback Function to call with the requested data.
1496  * @param callback_cls Closure for @c callback.
1497  * @return #GNUNET_OK / #GNUNET_SYSERR
1498  */
1499 int
1500 GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
1501                         const struct GNUNET_PeerIdentity *id,
1502                         GNUNET_CADET_TunnelCB callback,
1503                         void *callback_cls)
1504 {
1505   struct GNUNET_CADET_LocalInfo *msg;
1506   struct GNUNET_MQ_Envelope *env;
1507
1508   if (NULL != h->info_cb.tunnel_cb)
1509   {
1510     GNUNET_break (0);
1511     return GNUNET_SYSERR;
1512   }
1513   env = GNUNET_MQ_msg (msg,
1514                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1515   msg->peer = *id;
1516   GNUNET_MQ_send (h->mq,
1517                   env);
1518   h->info_cb.tunnel_cb = callback;
1519   h->info_cls = callback_cls;
1520   return GNUNET_OK;
1521 }
1522
1523
1524 /**
1525  * Transitional function to convert an unsigned int port to a hash value.
1526  * WARNING: local static value returned, NOT reentrant!
1527  * WARNING: do not use this function for new code!
1528  *
1529  * @param port Numerical port (unsigned int format).
1530  *
1531  * @return A GNUNET_HashCode usable for the new CADET API.
1532  */
1533 const struct GNUNET_HashCode *
1534 GC_u2h (uint32_t port)
1535 {
1536   static struct GNUNET_HashCode hash;
1537
1538   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1539               "This is a transitional function, use proper crypto hashes as CADET ports\n");
1540   GNUNET_CRYPTO_hash (&port,
1541                       sizeof (port),
1542                       &hash);
1543   return &hash;
1544 }
1545
1546
1547 /**
1548  * Connect to the MQ-based cadet service.
1549  *
1550  * @param cfg Configuration to use.
1551  *
1552  * @return Handle to the cadet service NULL on error.
1553  */
1554 struct GNUNET_CADET_Handle *
1555 GNUNET_CADET_connecT (const struct GNUNET_CONFIGURATION_Handle *cfg)
1556 {
1557   struct GNUNET_CADET_Handle *h;
1558
1559   LOG (GNUNET_ERROR_TYPE_DEBUG,
1560        "GNUNET_CADET_connecT()\n");
1561   h = GNUNET_new (struct GNUNET_CADET_Handle);
1562   h->cfg = cfg;
1563   h->ports = GNUNET_CONTAINER_multihashmap_create (4,
1564                                                    GNUNET_YES);
1565   h->channels = GNUNET_CONTAINER_multihashmap32_create (4);
1566   reconnect (h);
1567   if (NULL == h->mq)
1568   {
1569     GNUNET_break (0);
1570     GNUNET_CADET_disconnect (h);
1571     return NULL;
1572   }
1573   h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1574   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1575   h->reconnect_task = NULL;
1576
1577   return h;
1578 }
1579
1580
1581 /**
1582  * Open a port to receive incomming MQ-based channels.
1583  *
1584  * @param h CADET handle.
1585  * @param port Hash identifying the port.
1586  * @param connects Function called when an incoming channel is connected.
1587  * @param connects_cls Closure for the @a connects handler.
1588  * @param window_changes Function called when the transmit window size changes.
1589  * @param disconnects Function called when a channel is disconnected.
1590  * @param handlers Callbacks for messages we care about, NULL-terminated.
1591  * @return Port handle.
1592  */
1593 struct GNUNET_CADET_Port *
1594 GNUNET_CADET_open_porT (struct GNUNET_CADET_Handle *h,
1595                         const struct GNUNET_HashCode *port,
1596                         GNUNET_CADET_ConnectEventHandler connects,
1597                         void * connects_cls,
1598                         GNUNET_CADET_WindowSizeEventHandler window_changes,
1599                         GNUNET_CADET_DisconnectEventHandler disconnects,
1600                         const struct GNUNET_MQ_MessageHandler *handlers)
1601 {
1602   struct GNUNET_CADET_PortMessage *msg;
1603   struct GNUNET_MQ_Envelope *env;
1604   struct GNUNET_CADET_Port *p;
1605
1606   GNUNET_assert (NULL != connects);
1607   GNUNET_assert (NULL != disconnects);
1608
1609   p = GNUNET_new (struct GNUNET_CADET_Port);
1610   p->cadet = h;
1611   p->id = *port;
1612   p->connects = connects;
1613   p->cls = connects_cls;
1614   p->window_changes = window_changes;
1615   p->disconnects = disconnects;
1616   p->handlers = GNUNET_MQ_copy_handlers (handlers);
1617
1618   GNUNET_assert (GNUNET_OK ==
1619                  GNUNET_CONTAINER_multihashmap_put (h->ports,
1620                                                     &p->id,
1621                                                     p,
1622                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1623
1624   env = GNUNET_MQ_msg (msg,
1625                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN);
1626   msg->port = p->id;
1627   GNUNET_MQ_send (h->mq,
1628                   env);
1629   return p;
1630 }
1631
1632
1633 /**
1634  * Create a new channel towards a remote peer.
1635  *
1636  * If the destination port is not open by any peer or the destination peer
1637  * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
1638  * for this channel.
1639  *
1640  * @param h CADET handle.
1641  * @param channel_cls Closure for the channel. It's given to:
1642  *                    - The disconnect handler @a disconnects
1643  *                    - Each message type callback in @a handlers
1644  * @param destination Peer identity the channel should go to.
1645  * @param port Identification of the destination port.
1646  * @param options CadetOption flag field, with all desired option bits set to 1.
1647  * @param window_changes Function called when the transmit window size changes.
1648  * @param disconnects Function called when the channel is disconnected.
1649  * @param handlers Callbacks for messages we care about, NULL-terminated.
1650  * @return Handle to the channel.
1651  */
1652 struct GNUNET_CADET_Channel *
1653 GNUNET_CADET_channel_creatE (struct GNUNET_CADET_Handle *h,
1654                              void *channel_cls,
1655                              const struct GNUNET_PeerIdentity *destination,
1656                              const struct GNUNET_HashCode *port,
1657                              enum GNUNET_CADET_ChannelOption options,
1658                              GNUNET_CADET_WindowSizeEventHandler window_changes,
1659                              GNUNET_CADET_DisconnectEventHandler disconnects,
1660                              const struct GNUNET_MQ_MessageHandler *handlers)
1661 {
1662   struct GNUNET_CADET_Channel *ch;
1663   struct GNUNET_CADET_LocalChannelCreateMessage *msg;
1664   struct GNUNET_MQ_Envelope *env;
1665
1666   GNUNET_assert (NULL != disconnects);
1667   ch = create_channel (h,
1668                        NULL);
1669   ch->ctx = channel_cls;
1670   ch->peer = *destination;
1671   ch->options = options;
1672   ch->window_changes = window_changes;
1673   ch->disconnects = disconnects;
1674
1675   /* Create MQ for channel */
1676   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
1677                                           &cadet_mq_destroy_impl,
1678                                           &cadet_mq_cancel_impl,
1679                                           ch,
1680                                           handlers,
1681                                           &cadet_mq_error_handler,
1682                                           ch);
1683   GNUNET_MQ_set_handlers_closure (ch->mq, channel_cls);
1684
1685   /* Request channel creation to service */
1686   env = GNUNET_MQ_msg (msg,
1687                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
1688   msg->ccn = ch->ccn;
1689   msg->port = *port;
1690   msg->peer = *destination;
1691   msg->opt = htonl (options);
1692   GNUNET_MQ_send (h->mq,
1693                   env);
1694   return ch;
1695 }
1696
1697
1698 /**
1699  * Obtain the message queue for a connected peer.
1700  *
1701  * @param channel The channel handle from which to get the MQ.
1702  *
1703  * @return NULL if @a channel is not yet connected.
1704  */
1705 struct GNUNET_MQ_Handle *
1706 GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel)
1707 {
1708   return channel->mq;
1709 }
1710
1711 /* end of cadet_api.c */