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