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