More API function tests...
[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     GNUNET_break (0);
630     LOG (GNUNET_ERROR_TYPE_DEBUG,
631          "No handler for incoming channel %X (on port %s, recently closed?)\n",
632          ntohl (ccn.channel_of_client),
633          GNUNET_h2s (port_number));
634     env = GNUNET_MQ_msg (d_msg,
635                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
636     d_msg->ccn = msg->ccn;
637     GNUNET_MQ_send (h->mq,
638                     env);
639     return;
640   }
641
642   ch = create_channel (h,
643                        &ccn);
644   ch->peer = msg->peer;
645   ch->cadet = h;
646   ch->incoming_port = port;
647   ch->options = ntohl (msg->opt);
648   LOG (GNUNET_ERROR_TYPE_DEBUG,
649        "Creating incoming channel %X [%s] %p\n",
650        ntohl (ccn.channel_of_client),
651        GNUNET_h2s (port_number),
652        ch);
653
654   GNUNET_assert (NULL != port->connects);
655   ch->window_changes = port->window_changes;
656   ch->disconnects = port->disconnects;
657   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
658                                           &cadet_mq_destroy_impl,
659                                           &cadet_mq_cancel_impl,
660                                           ch,
661                                           port->handlers,
662                                           &cadet_mq_error_handler,
663                                           ch);
664   ch->ctx = port->connects (port->cls,
665                             ch,
666                             &msg->peer);
667   GNUNET_MQ_set_handlers_closure (ch->mq,
668                                   ch->ctx);
669 }
670
671
672 /**
673  * Process the channel destroy notification and free associated resources
674  *
675  * @param h     The cadet handle
676  * @param msg   A message with the details of the channel being destroyed
677  */
678 static void
679 handle_channel_destroy (void *cls,
680                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
681 {
682   struct GNUNET_CADET_Handle *h = cls;
683   struct GNUNET_CADET_Channel *ch;
684
685   LOG (GNUNET_ERROR_TYPE_DEBUG,
686        "Received channel destroy for channel %X from CADET service\n",
687        ntohl (msg->ccn.channel_of_client));
688   ch = find_channel (h,
689                      msg->ccn);
690   if (NULL == ch)
691   {
692     GNUNET_break (0);
693     return;
694   }
695   destroy_channel (ch);
696 }
697
698
699 /**
700  * Check that message received from CADET service is well-formed.
701  *
702  * @param cls the `struct GNUNET_CADET_Handle`
703  * @param message the message we got
704  * @return #GNUNET_OK if the message is well-formed,
705  *         #GNUNET_SYSERR otherwise
706  */
707 static int
708 check_local_data (void *cls,
709                   const struct GNUNET_CADET_LocalData *message)
710 {
711   struct GNUNET_CADET_Handle *h = cls;
712   struct GNUNET_CADET_Channel *ch;
713   uint16_t size;
714
715   size = ntohs (message->header.size);
716   if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size)
717   {
718     GNUNET_break (0);
719     return GNUNET_SYSERR;
720   }
721
722   ch = find_channel (h,
723                      message->ccn);
724   if (NULL == ch)
725   {
726     GNUNET_break (0);
727     return GNUNET_SYSERR;
728   }
729
730   return GNUNET_OK;
731 }
732
733
734 /**
735  * Process the incoming data packets, call appropriate handlers.
736  *
737  * @param h       The cadet handle
738  * @param message A message encapsulating the data
739  */
740 static void
741 handle_local_data (void *cls,
742                    const struct GNUNET_CADET_LocalData *message)
743 {
744   struct GNUNET_CADET_Handle *h = cls;
745   const struct GNUNET_MessageHeader *payload;
746   struct GNUNET_CADET_Channel *ch;
747   uint16_t type;
748   int fwd;
749
750   ch = find_channel (h,
751                      message->ccn);
752   if (NULL == ch)
753   {
754     GNUNET_break (0);
755     reconnect (h);
756     return;
757   }
758
759   payload = (const struct GNUNET_MessageHeader *) &message[1];
760   type = ntohs (payload->type);
761   fwd = ntohl (ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
762   LOG (GNUNET_ERROR_TYPE_DEBUG,
763        "Got a %s data on channel %s [%X] of type %u\n",
764        fwd ? "FWD" : "BWD",
765        GNUNET_i2s (&ch->peer),
766        ntohl (message->ccn.channel_of_client),
767        type);
768   GNUNET_MQ_inject_message (ch->mq,
769                             payload);
770 }
771
772
773 /**
774  * Process a local ACK message, enabling the client to send
775  * more data to the service.
776  *
777  * @param h Cadet handle.
778  * @param message Message itself.
779  */
780 static void
781 handle_local_ack (void *cls,
782                   const struct GNUNET_CADET_LocalAck *message)
783 {
784   struct GNUNET_CADET_Handle *h = cls;
785   struct GNUNET_CADET_Channel *ch;
786
787   ch = find_channel (h,
788                      message->ccn);
789   if (NULL == ch)
790   {
791     LOG (GNUNET_ERROR_TYPE_DEBUG,
792          "ACK on unknown channel %X\n",
793          ntohl (message->ccn.channel_of_client));
794     return;
795   }
796   ch->allow_send++;
797   if (NULL == ch->pending_env)
798   {
799     LOG (GNUNET_ERROR_TYPE_DEBUG,
800          "Got an ACK on mq channel %X, allow send now %u!\n",
801          ntohl (ch->ccn.channel_of_client),
802          ch->allow_send);
803     notify_window_size (ch);
804     return;
805   }
806   if (NULL != ch->mq_cont)
807     return; /* already working on it! */
808   LOG (GNUNET_ERROR_TYPE_DEBUG,
809        "Got an ACK on mq channel %X, sending pending message!\n",
810        ntohl (ch->ccn.channel_of_client));
811   ch->mq_cont
812     = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
813                                 ch);
814 }
815
816
817 /**
818  * Generic error handler, called with the appropriate error code and
819  * the same closure specified at the creation of the message queue.
820  * Not every message queue implementation supports an error handler.
821  *
822  * @param cls closure, a `struct GNUNET_CORE_Handle *`
823  * @param error error code
824  */
825 static void
826 handle_mq_error (void *cls,
827                  enum GNUNET_MQ_Error error)
828 {
829   struct GNUNET_CADET_Handle *h = cls;
830
831   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832               "MQ ERROR: %u\n",
833               error);
834   GNUNET_MQ_destroy (h->mq);
835   h->mq = NULL;
836   reconnect (h);
837 }
838
839
840 /**
841  * Process a local reply about info on all tunnels, pass info to the user.
842  *
843  * @param cls Closure (Cadet handle).
844  * @param msg Message itself.
845  */
846 static void
847 handle_get_peers (void *cls,
848                   const struct GNUNET_CADET_LocalInfoPeer *msg)
849 {
850   struct GNUNET_CADET_Handle *h = cls;
851
852   if (NULL == h->info_cb.peers_cb)
853     return;
854   h->info_cb.peers_cb (h->info_cls,
855                        &msg->destination,
856                        (int) ntohs (msg->tunnel),
857                        (unsigned int) ntohs (msg->paths),
858                        0);
859 }
860
861
862 /**
863  * Check that message received from CADET service is well-formed.
864  *
865  * @param cls the `struct GNUNET_CADET_Handle`
866  * @param message the message we got
867  * @return #GNUNET_OK if the message is well-formed,
868  *         #GNUNET_SYSERR otherwise
869  */
870 static int
871 check_get_peer (void *cls,
872                 const struct GNUNET_CADET_LocalInfoPeer *message)
873 {
874   size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
875   const struct GNUNET_PeerIdentity *paths_array;
876   size_t esize;
877   unsigned int epaths;
878   unsigned int paths;
879   unsigned int peers;
880
881   esize = ntohs (message->header.size);
882   if (esize < msize)
883   {
884     GNUNET_break (0);
885     return GNUNET_SYSERR;
886   }
887   if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
888   {
889     GNUNET_break (0);
890     return GNUNET_SYSERR;
891   }
892   peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
893   epaths = ntohs (message->paths);
894   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
895   paths = 0;
896   for (unsigned int i = 0; i < peers; i++)
897     if (0 == memcmp (&paths_array[i],
898                      &message->destination,
899                      sizeof (struct GNUNET_PeerIdentity)))
900       paths++;
901   if (paths != epaths)
902   {
903     GNUNET_break (0);
904     return GNUNET_SYSERR;
905   }
906   return GNUNET_OK;
907 }
908
909
910 /**
911  * Process a local peer info reply, pass info to the user.
912  *
913  * @param cls Closure (Cadet handle).
914  * @param message Message itself.
915  */
916 static void
917 handle_get_peer (void *cls,
918                  const struct GNUNET_CADET_LocalInfoPeer *message)
919 {
920   struct GNUNET_CADET_Handle *h = cls;
921   const struct GNUNET_PeerIdentity *paths_array;
922   unsigned int paths;
923   unsigned int path_length;
924   int neighbor;
925   unsigned int peers;
926
927   if (NULL == h->info_cb.peer_cb)
928     return;
929   paths = ntohs (message->paths);
930   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
931   peers = (ntohs (message->header.size) - sizeof (*message))
932           / sizeof (struct GNUNET_PeerIdentity);
933   path_length = 0;
934   neighbor = GNUNET_NO;
935
936   for (unsigned int i = 0; i < peers; i++)
937   {
938     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
939                 " %s\n",
940                 GNUNET_i2s (&paths_array[i]));
941     path_length++;
942     if (0 == memcmp (&paths_array[i], &message->destination,
943                      sizeof (struct GNUNET_PeerIdentity)))
944     {
945       if (1 == path_length)
946         neighbor = GNUNET_YES;
947       path_length = 0;
948     }
949   }
950
951   /* Call Callback with tunnel info. */
952   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
953   h->info_cb.peer_cb (h->info_cls,
954                       &message->destination,
955                       (int) ntohs (message->tunnel),
956                       neighbor,
957                       paths,
958                       paths_array);
959 }
960
961
962 /**
963  * Process a local reply about info on all tunnels, pass info to the user.
964  *
965  * @param cls Closure (Cadet handle).
966  * @param message Message itself.
967  */
968 static void
969 handle_get_tunnels (void *cls,
970                     const struct GNUNET_CADET_LocalInfoTunnel *msg)
971 {
972   struct GNUNET_CADET_Handle *h = cls;
973
974   if (NULL == h->info_cb.tunnels_cb)
975     return;
976   h->info_cb.tunnels_cb (h->info_cls,
977                          &msg->destination,
978                          ntohl (msg->channels),
979                          ntohl (msg->connections),
980                          ntohs (msg->estate),
981                          ntohs (msg->cstate));
982
983 }
984
985
986 /**
987  * Check that message received from CADET service is well-formed.
988  *
989  * @param cls the `struct GNUNET_CADET_Handle`
990  * @param msg the message we got
991  * @return #GNUNET_OK if the message is well-formed,
992  *         #GNUNET_SYSERR otherwise
993  */
994 static int
995 check_get_tunnel (void *cls,
996                   const struct GNUNET_CADET_LocalInfoTunnel *msg)
997 {
998   unsigned int ch_n;
999   unsigned int c_n;
1000   size_t esize;
1001   size_t msize;
1002
1003   /* Verify message sanity */
1004   msize = ntohs (msg->header.size);
1005   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
1006   if (esize > msize)
1007   {
1008     GNUNET_break (0);
1009     return GNUNET_SYSERR;
1010   }
1011   ch_n = ntohl (msg->channels);
1012   c_n = ntohl (msg->connections);
1013   esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
1014   esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
1015   if (msize != esize)
1016   {
1017     GNUNET_break_op (0);
1018     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1019                 "m:%u, e: %u (%u ch, %u conn)\n",
1020                 (unsigned int) msize,
1021                 (unsigned int) esize,
1022                 ch_n,
1023                 c_n);
1024     return GNUNET_SYSERR;
1025   }
1026   return GNUNET_OK;
1027 }
1028
1029
1030 /**
1031  * Process a local tunnel info reply, pass info to the user.
1032  *
1033  * @param cls Closure (Cadet handle).
1034  * @param msg Message itself.
1035  */
1036 static void
1037 handle_get_tunnel (void *cls,
1038                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1039 {
1040   struct GNUNET_CADET_Handle *h = cls;
1041   unsigned int ch_n;
1042   unsigned int c_n;
1043   const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
1044   const struct GNUNET_CADET_ChannelTunnelNumber *chns;
1045
1046   if (NULL == h->info_cb.tunnel_cb)
1047     return;
1048
1049   ch_n = ntohl (msg->channels);
1050   c_n = ntohl (msg->connections);
1051
1052   /* Call Callback with tunnel info. */
1053   conns = (const struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
1054   chns = (const struct GNUNET_CADET_ChannelTunnelNumber *) &conns[c_n];
1055   h->info_cb.tunnel_cb (h->info_cls,
1056                         &msg->destination,
1057                         ch_n,
1058                         c_n,
1059                         chns,
1060                         conns,
1061                         ntohs (msg->estate),
1062                         ntohs (msg->cstate));
1063 }
1064
1065
1066 /**
1067  * Reconnect to the service, retransmit all infomation to try to restore the
1068  * original state.
1069  *
1070  * @param h handle to the cadet
1071  */
1072 static void
1073 reconnect (struct GNUNET_CADET_Handle *h)
1074 {
1075   struct GNUNET_MQ_MessageHandler handlers[] = {
1076     GNUNET_MQ_hd_fixed_size (channel_created,
1077                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1078                              struct GNUNET_CADET_LocalChannelCreateMessage,
1079                              h),
1080     GNUNET_MQ_hd_fixed_size (channel_destroy,
1081                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1082                              struct GNUNET_CADET_LocalChannelDestroyMessage,
1083                              h),
1084     GNUNET_MQ_hd_var_size (local_data,
1085                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1086                            struct GNUNET_CADET_LocalData,
1087                            h),
1088     GNUNET_MQ_hd_fixed_size (local_ack,
1089                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1090                              struct GNUNET_CADET_LocalAck,
1091                              h),
1092     GNUNET_MQ_hd_fixed_size (get_peers,
1093                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1094                              struct GNUNET_CADET_LocalInfoPeer,
1095                              h),
1096     GNUNET_MQ_hd_var_size (get_peer,
1097                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1098                            struct GNUNET_CADET_LocalInfoPeer,
1099                            h),
1100     GNUNET_MQ_hd_fixed_size (get_tunnels,
1101                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1102                              struct GNUNET_CADET_LocalInfoTunnel,
1103                              h),
1104     GNUNET_MQ_hd_var_size (get_tunnel,
1105                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1106                            struct GNUNET_CADET_LocalInfoTunnel,
1107                            h),
1108     GNUNET_MQ_handler_end ()
1109   };
1110
1111   h->mq = GNUNET_CLIENT_connect (h->cfg,
1112                                  "cadet",
1113                                  handlers,
1114                                  &handle_mq_error,
1115                                  h);
1116   if (NULL == h->mq)
1117   {
1118     schedule_reconnect (h);
1119     return;
1120   }
1121   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1122 }
1123
1124
1125 /**
1126  * Function called during #GNUNET_CADET_disconnect() to destroy
1127  * all channels that are still open.
1128  *
1129  * @param cls the `struct GNUNET_CADET_Handle`
1130  * @param cid chanenl ID
1131  * @param value a `struct GNUNET_CADET_Channel` to destroy
1132  * @return #GNUNET_OK (continue to iterate)
1133  */
1134 static int
1135 destroy_channel_cb (void *cls,
1136                     uint32_t cid,
1137                     void *value)
1138 {
1139   /* struct GNUNET_CADET_Handle *handle = cls; */
1140   struct GNUNET_CADET_Channel *ch = value;
1141
1142   if (ntohl (ch->ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1143   {
1144     GNUNET_break (0);
1145     LOG (GNUNET_ERROR_TYPE_DEBUG,
1146          "channel %X not destroyed\n",
1147          ntohl (ch->ccn.channel_of_client));
1148   }
1149   destroy_channel (ch);
1150   return GNUNET_OK;
1151 }
1152
1153
1154 /**
1155  * Function called during #GNUNET_CADET_disconnect() to destroy
1156  * all ports that are still open.
1157  *
1158  * @param cls the `struct GNUNET_CADET_Handle`
1159  * @param id port ID
1160  * @param value a `struct GNUNET_CADET_Channel` to destroy
1161  * @return #GNUNET_OK (continue to iterate)
1162  */
1163 static int
1164 destroy_port_cb (void *cls,
1165                  const struct GNUNET_HashCode *id,
1166                  void *value)
1167 {
1168   /* struct GNUNET_CADET_Handle *handle = cls; */
1169   struct GNUNET_CADET_Port *port = value;
1170
1171   /* This is a warning, the app should have cleanly closed all open ports */
1172   GNUNET_break (0);
1173   GNUNET_CADET_close_port (port);
1174   return GNUNET_OK;
1175 }
1176
1177
1178 /**
1179  * Disconnect from the cadet service. All channels will be destroyed. All channel
1180  * disconnect callbacks will be called on any still connected peers, notifying
1181  * about their disconnection. The registered inbound channel cleaner will be
1182  * called should any inbound channels still exist.
1183  *
1184  * @param handle connection to cadet to disconnect
1185  */
1186 void
1187 GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
1188 {
1189   GNUNET_CONTAINER_multihashmap_iterate (handle->ports,
1190                                          &destroy_port_cb,
1191                                          handle);
1192   GNUNET_CONTAINER_multihashmap_destroy (handle->ports);
1193   handle->ports = NULL;
1194   GNUNET_CONTAINER_multihashmap32_iterate (handle->channels,
1195                                            &destroy_channel_cb,
1196                                            handle);
1197   GNUNET_CONTAINER_multihashmap32_destroy (handle->channels);
1198   handle->channels = NULL;
1199   if (NULL != handle->mq)
1200   {
1201     GNUNET_MQ_destroy (handle->mq);
1202     handle->mq = NULL;
1203   }
1204   if (NULL != handle->reconnect_task)
1205   {
1206     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1207     handle->reconnect_task = NULL;
1208   }
1209   GNUNET_free (handle);
1210 }
1211
1212
1213 /**
1214  * Close a port opened with @a GNUNET_CADET_open_port().
1215  * The @a new_channel callback will no longer be called.
1216  *
1217  * @param p Port handle.
1218  */
1219 void
1220 GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p)
1221 {
1222   struct GNUNET_CADET_PortMessage *msg;
1223   struct GNUNET_MQ_Envelope *env;
1224
1225   env = GNUNET_MQ_msg (msg,
1226                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE);
1227   msg->port = p->id;
1228   GNUNET_MQ_send (p->cadet->mq,
1229                   env);
1230   GNUNET_assert (GNUNET_YES ==
1231                  GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports,
1232                                                        &p->id,
1233                                                        p));
1234   GNUNET_free_non_null (p->handlers);
1235   GNUNET_free (p);
1236 }
1237
1238
1239 /**
1240  * Destroy an existing channel.
1241  *
1242  * The existing end callback for the channel will be called immediately.
1243  * Any pending outgoing messages will be sent but no incoming messages will be
1244  * accepted and no data callbacks will be called.
1245  *
1246  * @param channel Channel handle, becomes invalid after this call.
1247  */
1248 void
1249 GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
1250 {
1251   struct GNUNET_CADET_Handle *h = channel->cadet;
1252   struct GNUNET_CADET_LocalChannelDestroyMessage *msg;
1253   struct GNUNET_MQ_Envelope *env;
1254
1255   if (NULL != h->mq)
1256   {
1257     env = GNUNET_MQ_msg (msg,
1258                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1259     msg->ccn = channel->ccn;
1260     GNUNET_MQ_send (h->mq,
1261                     env);
1262   }
1263   destroy_channel (channel);
1264 }
1265
1266
1267 /**
1268  * Get information about a channel.
1269  *
1270  * @param channel Channel handle.
1271  * @param option Query (GNUNET_CADET_OPTION_*).
1272  * @param ... dependant on option, currently not used
1273  *
1274  * @return Union with an answer to the query.
1275  */
1276 const union GNUNET_CADET_ChannelInfo *
1277 GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
1278                                enum GNUNET_CADET_ChannelOption option,
1279                                ...)
1280 {
1281   static int bool_flag;
1282
1283   switch (option)
1284   {
1285     case GNUNET_CADET_OPTION_NOBUFFER:
1286     case GNUNET_CADET_OPTION_RELIABLE:
1287     case GNUNET_CADET_OPTION_OUT_OF_ORDER:
1288       if (0 != (option & channel->options))
1289         bool_flag = GNUNET_YES;
1290       else
1291         bool_flag = GNUNET_NO;
1292       return (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
1293       break;
1294     case GNUNET_CADET_OPTION_PEER:
1295       return (const union GNUNET_CADET_ChannelInfo *) &channel->peer;
1296       break;
1297     default:
1298       GNUNET_break (0);
1299       return NULL;
1300   }
1301 }
1302
1303
1304 /**
1305  * Send an ack on the channel to confirm the processing of a message.
1306  *
1307  * @param ch Channel on which to send the ACK.
1308  */
1309 void
1310 GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
1311 {
1312   struct GNUNET_CADET_LocalAck *msg;
1313   struct GNUNET_MQ_Envelope *env;
1314
1315   env = GNUNET_MQ_msg (msg,
1316                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
1317   LOG (GNUNET_ERROR_TYPE_DEBUG,
1318        "Sending ACK on channel %X\n",
1319        ntohl (channel->ccn.channel_of_client));
1320   msg->ccn = channel->ccn;
1321   GNUNET_MQ_send (channel->cadet->mq,
1322                   env);
1323 }
1324
1325
1326 /**
1327  * Send message of @a type to CADET service of @a h
1328  *
1329  * @param h handle to CADET service
1330  * @param type message type of trivial information request to send
1331  */
1332 static void
1333 send_info_request (struct GNUNET_CADET_Handle *h,
1334                    uint16_t type)
1335 {
1336   struct GNUNET_MessageHeader *msg;
1337   struct GNUNET_MQ_Envelope *env;
1338
1339   env = GNUNET_MQ_msg (msg,
1340                        type);
1341   GNUNET_MQ_send (h->mq,
1342                   env);
1343 }
1344
1345
1346 /**
1347  * Request a debug dump on the service's STDERR.
1348  *
1349  * WARNING: unstable API, likely to change in the future!
1350  *
1351  * @param h cadet handle
1352  */
1353 void
1354 GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
1355 {
1356   send_info_request (h,
1357                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
1358 }
1359
1360
1361 /**
1362  * Request information about peers known to the running cadet service.
1363  * The callback will be called for every peer known to the service.
1364  * Only one info request (of any kind) can be active at once.
1365  *
1366  * WARNING: unstable API, likely to change in the future!
1367  *
1368  * @param h Handle to the cadet peer.
1369  * @param callback Function to call with the requested data.
1370  * @param callback_cls Closure for @c callback.
1371  * @return #GNUNET_OK / #GNUNET_SYSERR
1372  */
1373 int
1374 GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
1375                        GNUNET_CADET_PeersCB callback,
1376                        void *callback_cls)
1377 {
1378   if (NULL != h->info_cb.peers_cb)
1379   {
1380     GNUNET_break (0);
1381     return GNUNET_SYSERR;
1382   }
1383   send_info_request (h,
1384                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
1385   h->info_cb.peers_cb = callback;
1386   h->info_cls = callback_cls;
1387   return GNUNET_OK;
1388 }
1389
1390
1391 /**
1392  * Cancel a peer info request. The callback will not be called (anymore).
1393  *
1394  * WARNING: unstable API, likely to change in the future!
1395  *
1396  * @param h Cadet handle.
1397  * @return Closure given to GNUNET_CADET_get_peers().
1398  */
1399 void *
1400 GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
1401 {
1402   void *cls = h->info_cls;
1403
1404   h->info_cb.peers_cb = NULL;
1405   h->info_cls = NULL;
1406   return cls;
1407 }
1408
1409
1410 /**
1411  * Request information about a peer known to the running cadet peer.
1412  * The callback will be called for the tunnel once.
1413  * Only one info request (of any kind) can be active at once.
1414  *
1415  * WARNING: unstable API, likely to change in the future!
1416  *
1417  * @param h Handle to the cadet peer.
1418  * @param id Peer whose tunnel to examine.
1419  * @param callback Function to call with the requested data.
1420  * @param callback_cls Closure for @c callback.
1421  * @return #GNUNET_OK / #GNUNET_SYSERR
1422  */
1423 int
1424 GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
1425                        const struct GNUNET_PeerIdentity *id,
1426                        GNUNET_CADET_PeerCB callback,
1427                        void *callback_cls)
1428 {
1429   struct GNUNET_CADET_LocalInfo *msg;
1430   struct GNUNET_MQ_Envelope *env;
1431
1432   if (NULL != h->info_cb.peer_cb)
1433   {
1434     GNUNET_break (0);
1435     return GNUNET_SYSERR;
1436   }
1437   env = GNUNET_MQ_msg (msg,
1438                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
1439   msg->peer = *id;
1440   GNUNET_MQ_send (h->mq,
1441                   env);
1442   h->info_cb.peer_cb = callback;
1443   h->info_cls = callback_cls;
1444   return GNUNET_OK;
1445 }
1446
1447
1448 /**
1449  * Request information about tunnels of the running cadet peer.
1450  * The callback will be called for every tunnel of the service.
1451  * Only one info request (of any kind) can be active at once.
1452  *
1453  * WARNING: unstable API, likely to change in the future!
1454  *
1455  * @param h Handle to the cadet peer.
1456  * @param callback Function to call with the requested data.
1457  * @param callback_cls Closure for @c callback.
1458  * @return #GNUNET_OK / #GNUNET_SYSERR
1459  */
1460 int
1461 GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
1462                          GNUNET_CADET_TunnelsCB callback,
1463                          void *callback_cls)
1464 {
1465   if (NULL != h->info_cb.tunnels_cb)
1466   {
1467     GNUNET_break (0);
1468     return GNUNET_SYSERR;
1469   }
1470   send_info_request (h,
1471                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
1472   h->info_cb.tunnels_cb = callback;
1473   h->info_cls = callback_cls;
1474   return GNUNET_OK;
1475 }
1476
1477
1478 /**
1479  * Cancel a monitor request. The monitor callback will not be called.
1480  *
1481  * @param h Cadet handle.
1482  * @return Closure given to GNUNET_CADET_get_tunnels().
1483  */
1484 void *
1485 GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
1486 {
1487   void *cls = h->info_cls;
1488
1489   h->info_cb.tunnels_cb = NULL;
1490   h->info_cls = NULL;
1491   return cls;
1492 }
1493
1494
1495 /**
1496  * Request information about a tunnel of the running cadet peer.
1497  * The callback will be called for the tunnel once.
1498  * Only one info request (of any kind) can be active at once.
1499  *
1500  * WARNING: unstable API, likely to change in the future!
1501  *
1502  * @param h Handle to the cadet peer.
1503  * @param id Peer whose tunnel to examine.
1504  * @param callback Function to call with the requested data.
1505  * @param callback_cls Closure for @c callback.
1506  * @return #GNUNET_OK / #GNUNET_SYSERR
1507  */
1508 int
1509 GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
1510                         const struct GNUNET_PeerIdentity *id,
1511                         GNUNET_CADET_TunnelCB callback,
1512                         void *callback_cls)
1513 {
1514   struct GNUNET_CADET_LocalInfo *msg;
1515   struct GNUNET_MQ_Envelope *env;
1516
1517   if (NULL != h->info_cb.tunnel_cb)
1518   {
1519     GNUNET_break (0);
1520     return GNUNET_SYSERR;
1521   }
1522   env = GNUNET_MQ_msg (msg,
1523                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1524   msg->peer = *id;
1525   GNUNET_MQ_send (h->mq,
1526                   env);
1527   h->info_cb.tunnel_cb = callback;
1528   h->info_cls = callback_cls;
1529   return GNUNET_OK;
1530 }
1531
1532
1533 /**
1534  * Transitional function to convert an unsigned int port to a hash value.
1535  * WARNING: local static value returned, NOT reentrant!
1536  * WARNING: do not use this function for new code!
1537  *
1538  * @param port Numerical port (unsigned int format).
1539  *
1540  * @return A GNUNET_HashCode usable for the new CADET API.
1541  */
1542 const struct GNUNET_HashCode *
1543 GC_u2h (uint32_t port)
1544 {
1545   static struct GNUNET_HashCode hash;
1546
1547   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1548               "This is a transitional function, use proper crypto hashes as CADET ports\n");
1549   GNUNET_CRYPTO_hash (&port,
1550                       sizeof (port),
1551                       &hash);
1552   return &hash;
1553 }
1554
1555
1556 /**
1557  * Connect to the MQ-based cadet service.
1558  *
1559  * @param cfg Configuration to use.
1560  *
1561  * @return Handle to the cadet service NULL on error.
1562  */
1563 struct GNUNET_CADET_Handle *
1564 GNUNET_CADET_connecT (const struct GNUNET_CONFIGURATION_Handle *cfg)
1565 {
1566   struct GNUNET_CADET_Handle *h;
1567
1568   LOG (GNUNET_ERROR_TYPE_DEBUG,
1569        "GNUNET_CADET_connecT()\n");
1570   h = GNUNET_new (struct GNUNET_CADET_Handle);
1571   h->cfg = cfg;
1572   h->ports = GNUNET_CONTAINER_multihashmap_create (4,
1573                                                    GNUNET_YES);
1574   h->channels = GNUNET_CONTAINER_multihashmap32_create (4);
1575   reconnect (h);
1576   if (NULL == h->mq)
1577   {
1578     GNUNET_break (0);
1579     GNUNET_CADET_disconnect (h);
1580     return NULL;
1581   }
1582   h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1583   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1584   h->reconnect_task = NULL;
1585
1586   return h;
1587 }
1588
1589
1590 /**
1591  * Open a port to receive incomming MQ-based channels.
1592  *
1593  * @param h CADET handle.
1594  * @param port Hash identifying the port.
1595  * @param connects Function called when an incoming channel is connected.
1596  * @param connects_cls Closure for the @a connects handler.
1597  * @param window_changes Function called when the transmit window size changes.
1598  * @param disconnects Function called when a channel is disconnected.
1599  * @param handlers Callbacks for messages we care about, NULL-terminated.
1600  * @return Port handle.
1601  */
1602 struct GNUNET_CADET_Port *
1603 GNUNET_CADET_open_porT (struct GNUNET_CADET_Handle *h,
1604                         const struct GNUNET_HashCode *port,
1605                         GNUNET_CADET_ConnectEventHandler connects,
1606                         void * connects_cls,
1607                         GNUNET_CADET_WindowSizeEventHandler window_changes,
1608                         GNUNET_CADET_DisconnectEventHandler disconnects,
1609                         const struct GNUNET_MQ_MessageHandler *handlers)
1610 {
1611   struct GNUNET_CADET_PortMessage *msg;
1612   struct GNUNET_MQ_Envelope *env;
1613   struct GNUNET_CADET_Port *p;
1614
1615   GNUNET_assert (NULL != connects);
1616   GNUNET_assert (NULL != disconnects);
1617
1618   p = GNUNET_new (struct GNUNET_CADET_Port);
1619   p->cadet = h;
1620   p->id = *port;
1621   p->connects = connects;
1622   p->cls = connects_cls;
1623   p->window_changes = window_changes;
1624   p->disconnects = disconnects;
1625   p->handlers = GNUNET_MQ_copy_handlers (handlers);
1626
1627   GNUNET_assert (GNUNET_OK ==
1628                  GNUNET_CONTAINER_multihashmap_put (h->ports,
1629                                                     &p->id,
1630                                                     p,
1631                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1632
1633   env = GNUNET_MQ_msg (msg,
1634                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN);
1635   msg->port = p->id;
1636   GNUNET_MQ_send (h->mq,
1637                   env);
1638   return p;
1639 }
1640
1641
1642 /**
1643  * Create a new channel towards a remote peer.
1644  *
1645  * If the destination port is not open by any peer or the destination peer
1646  * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
1647  * for this channel.
1648  *
1649  * @param h CADET handle.
1650  * @param channel_cls Closure for the channel. It's given to:
1651  *                    - The disconnect handler @a disconnects
1652  *                    - Each message type callback in @a handlers
1653  * @param destination Peer identity the channel should go to.
1654  * @param port Identification of the destination port.
1655  * @param options CadetOption flag field, with all desired option bits set to 1.
1656  * @param window_changes Function called when the transmit window size changes.
1657  * @param disconnects Function called when the channel is disconnected.
1658  * @param handlers Callbacks for messages we care about, NULL-terminated.
1659  * @return Handle to the channel.
1660  */
1661 struct GNUNET_CADET_Channel *
1662 GNUNET_CADET_channel_creatE (struct GNUNET_CADET_Handle *h,
1663                              void *channel_cls,
1664                              const struct GNUNET_PeerIdentity *destination,
1665                              const struct GNUNET_HashCode *port,
1666                              enum GNUNET_CADET_ChannelOption options,
1667                              GNUNET_CADET_WindowSizeEventHandler window_changes,
1668                              GNUNET_CADET_DisconnectEventHandler disconnects,
1669                              const struct GNUNET_MQ_MessageHandler *handlers)
1670 {
1671   struct GNUNET_CADET_Channel *ch;
1672   struct GNUNET_CADET_LocalChannelCreateMessage *msg;
1673   struct GNUNET_MQ_Envelope *env;
1674
1675   GNUNET_assert (NULL != disconnects);
1676   ch = create_channel (h,
1677                        NULL);
1678   ch->ctx = channel_cls;
1679   ch->peer = *destination;
1680   ch->options = options;
1681   ch->window_changes = window_changes;
1682   ch->disconnects = disconnects;
1683
1684   /* Create MQ for channel */
1685   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
1686                                           &cadet_mq_destroy_impl,
1687                                           &cadet_mq_cancel_impl,
1688                                           ch,
1689                                           handlers,
1690                                           &cadet_mq_error_handler,
1691                                           ch);
1692   GNUNET_MQ_set_handlers_closure (ch->mq, channel_cls);
1693
1694   /* Request channel creation to service */
1695   env = GNUNET_MQ_msg (msg,
1696                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
1697   msg->ccn = ch->ccn;
1698   msg->port = *port;
1699   msg->peer = *destination;
1700   msg->opt = htonl (options);
1701   GNUNET_MQ_send (h->mq,
1702                   env);
1703   return ch;
1704 }
1705
1706
1707 /**
1708  * Obtain the message queue for a connected peer.
1709  *
1710  * @param channel The channel handle from which to get the MQ.
1711  *
1712  * @return NULL if @a channel is not yet connected.
1713  */
1714 struct GNUNET_MQ_Handle *
1715 GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel)
1716 {
1717   return channel->mq;
1718 }
1719
1720 /* end of cadet_api.c */