Fixed Uninitialized Variable warning.
[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
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    * Closure for @a handler.
211    */
212   void *cls;
213
214   /**
215    * Handler for incoming channels on this port
216    */
217   GNUNET_CADET_ConnectEventHandler connects;
218
219   /**
220    * Closure for @ref connects
221    */
222   void *connects_cls;
223
224   /**
225    * Window size change handler.
226    */
227   GNUNET_CADET_WindowSizeEventHandler window_changes;
228
229   /**
230    * Handler called when an incoming channel is destroyed.
231    */
232   GNUNET_CADET_DisconnectEventHandler disconnects;
233
234   /**
235    * Payload handlers for incoming channels.
236    */
237   struct GNUNET_MQ_MessageHandler *handlers;
238 };
239
240
241 /**
242  * Find the Port struct for a hash.
243  *
244  * @param h CADET handle.
245  * @param hash HashCode for the port number.
246  * @return The port handle if known, NULL otherwise.
247  */
248 static struct GNUNET_CADET_Port *
249 find_port (const struct GNUNET_CADET_Handle *h,
250            const struct GNUNET_HashCode *hash)
251 {
252   return GNUNET_CONTAINER_multihashmap_get (h->ports,
253                                             hash);
254 }
255
256
257 /**
258  * Get the channel handler for the channel specified by id from the given handle
259  *
260  * @param h Cadet handle
261  * @param ccn ID of the wanted channel
262  * @return handle to the required channel or NULL if not found
263  */
264 static struct GNUNET_CADET_Channel *
265 find_channel (struct GNUNET_CADET_Handle *h,
266               struct GNUNET_CADET_ClientChannelNumber ccn)
267 {
268   return GNUNET_CONTAINER_multihashmap32_get (h->channels,
269                                               ntohl (ccn.channel_of_client));
270 }
271
272
273 /**
274  * Create a new channel and insert it in the channel list of the cadet handle
275  *
276  * @param h Cadet handle
277  * @param ccnp pointer to desired ccn of the channel, NULL to assign one automatically.
278  * @return Handle to the created channel.
279  */
280 static struct GNUNET_CADET_Channel *
281 create_channel (struct GNUNET_CADET_Handle *h,
282                 const struct GNUNET_CADET_ClientChannelNumber *ccnp)
283 {
284   struct GNUNET_CADET_Channel *ch;
285   struct GNUNET_CADET_ClientChannelNumber ccn;
286
287   ch = GNUNET_new (struct GNUNET_CADET_Channel);
288   ch->cadet = h;
289   if (NULL == ccnp)
290   {
291     while (NULL !=
292            find_channel (h,
293                          h->next_ccn))
294       h->next_ccn.channel_of_client
295         = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI | (1 + ntohl (h->next_ccn.channel_of_client)));
296     ccn = h->next_ccn;
297   }
298   else
299   {
300     ccn = *ccnp;
301   }
302   ch->ccn = ccn;
303   GNUNET_assert (GNUNET_OK ==
304                  GNUNET_CONTAINER_multihashmap32_put (h->channels,
305                                                       ntohl (ch->ccn.channel_of_client),
306                                                       ch,
307                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
308   return ch;
309 }
310
311
312 /**
313  * Destroy the specified channel.
314  * - Destroys all peers, calling the disconnect callback on each if needed
315  * - Cancels all outgoing traffic for that channel, calling respective notifys
316  * - Calls cleaner if channel was inbound
317  * - Frees all memory used
318  *
319  * @param ch Pointer to the channel.
320  * @param call_cleaner Whether to call the cleaner handler.
321  */
322 static void
323 destroy_channel (struct GNUNET_CADET_Channel *ch)
324 {
325   struct GNUNET_CADET_Handle *h = ch->cadet;
326
327   LOG (GNUNET_ERROR_TYPE_DEBUG,
328        "Destroying channel %X of %p\n",
329        htonl (ch->ccn.channel_of_client),
330        h);
331   GNUNET_assert (GNUNET_YES ==
332                  GNUNET_CONTAINER_multihashmap32_remove (h->channels,
333                                                          ntohl (ch->ccn.channel_of_client),
334                                                          ch));
335   if (NULL != ch->mq_cont)
336   {
337     GNUNET_SCHEDULER_cancel (ch->mq_cont);
338     ch->mq_cont = NULL;
339   }
340   /* signal channel destruction */
341   if (NULL != ch->disconnects)
342     ch->disconnects (ch->ctx,
343                      ch);
344   if (NULL != ch->pending_env)
345     GNUNET_MQ_discard (ch->pending_env);
346   GNUNET_MQ_destroy (ch->mq);
347   GNUNET_free (ch);
348 }
349
350
351 /**
352  * Reconnect to the service, retransmit all infomation to try to restore the
353  * original state.
354  *
355  * @param h handle to the cadet
356  */
357 static void
358 reconnect (struct GNUNET_CADET_Handle *h);
359
360
361 /**
362  * Reconnect callback: tries to reconnect again after a failer previous
363  * reconnecttion
364  *
365  * @param cls closure (cadet handle)
366  */
367 static void
368 reconnect_cbk (void *cls)
369 {
370   struct GNUNET_CADET_Handle *h = cls;
371
372   h->reconnect_task = NULL;
373   reconnect (h);
374 }
375
376
377 /**
378  * Function called during #reconnect() to destroy
379  * all channels that are still open.
380  *
381  * @param cls the `struct GNUNET_CADET_Handle`
382  * @param cid chanenl ID
383  * @param value a `struct GNUNET_CADET_Channel` to destroy
384  * @return #GNUNET_OK (continue to iterate)
385  */
386 static int
387 destroy_channel_on_reconnect_cb (void *cls,
388                                  uint32_t cid,
389                                  void *value)
390 {
391   /* struct GNUNET_CADET_Handle *handle = cls; */
392   struct GNUNET_CADET_Channel *ch = value;
393
394   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
395               "Destroying channel due to reconnect\n");
396   destroy_channel (ch);
397   return GNUNET_OK;
398 }
399
400
401 /**
402  * Reconnect to the service, retransmit all infomation to try to restore the
403  * original state.
404  *
405  * @param h handle to the cadet
406  *
407  * @return #GNUNET_YES in case of sucess, #GNUNET_NO otherwise (service down...)
408  */
409 static void
410 schedule_reconnect (struct GNUNET_CADET_Handle *h)
411 {
412   if (NULL != h->reconnect_task)
413     return;
414   GNUNET_CONTAINER_multihashmap32_iterate (h->channels,
415                                            &destroy_channel_on_reconnect_cb,
416                                            h);
417   h->reconnect_task
418     = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
419                                     &reconnect_cbk,
420                                     h);
421   h->reconnect_time
422     = GNUNET_TIME_STD_BACKOFF (h->reconnect_time);
423 }
424
425
426 /**
427  * Notify the application about a change in the window size (if needed).
428  *
429  * @param ch Channel to notify about.
430  */
431 static void
432 notify_window_size (struct GNUNET_CADET_Channel *ch)
433 {
434   if (NULL != ch->window_changes)
435     ch->window_changes (ch->ctx,
436                         ch, /* FIXME: remove 'ch'? */
437                         ch->allow_send);
438 }
439
440
441 /**
442  * Transmit the next message from our queue.
443  *
444  * @param cls Closure (channel whose mq to activate).
445  */
446 static void
447 cadet_mq_send_now (void *cls)
448 {
449   struct GNUNET_CADET_Channel *ch = cls;
450   struct GNUNET_MQ_Envelope *env = ch->pending_env;
451
452   ch->mq_cont = NULL;
453   if (0 == ch->allow_send)
454   {
455     /* how did we get here? */
456     GNUNET_break (0);
457     return;
458   }
459   if (NULL == env)
460   {
461     /* how did we get here? */
462     GNUNET_break (0);
463     return;
464   }
465   ch->allow_send--;
466   ch->pending_env = NULL;
467   GNUNET_MQ_send (ch->cadet->mq,
468                   env);
469   GNUNET_MQ_impl_send_continue (ch->mq);
470 }
471
472
473 /**
474  * Implement sending functionality of a message queue for
475  * us sending messages to a peer.
476  *
477  * Encapsulates the payload message in a #GNUNET_CADET_LocalData message
478  * in order to label the message with the channel ID and send the
479  * encapsulated message to the service.
480  *
481  * @param mq the message queue
482  * @param msg the message to send
483  * @param impl_state state of the implementation
484  */
485 static void
486 cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq,
487                     const struct GNUNET_MessageHeader *msg,
488                     void *impl_state)
489 {
490   struct GNUNET_CADET_Channel *ch = impl_state;
491   struct GNUNET_CADET_Handle *h = ch->cadet;
492   uint16_t msize;
493   struct GNUNET_MQ_Envelope *env;
494   struct GNUNET_CADET_LocalData *cadet_msg = NULL;
495
496   if (NULL == h->mq)
497   {
498     /* We're currently reconnecting, pretend this worked */
499     GNUNET_MQ_impl_send_continue (mq);
500     return;
501   }
502
503   /* check message size for sanity */
504   msize = ntohs (msg->size);
505   if (msize > GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE)
506   {
507     GNUNET_break (0);
508     GNUNET_MQ_impl_send_continue (mq);
509     return;
510   }
511   env = GNUNET_MQ_msg_nested_mh (cadet_msg,
512                                  GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
513                                  msg);
514   cadet_msg->ccn = ch->ccn;
515   GNUNET_assert (NULL == ch->pending_env);
516   ch->pending_env = env;
517   if (0 < ch->allow_send)
518     ch->mq_cont
519       = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
520                                   ch);
521 }
522
523
524 /**
525  * Handle destruction of a message queue.  Implementations must not
526  * free @a mq, but should take care of @a impl_state.
527  *
528  * @param mq the message queue to destroy
529  * @param impl_state state of the implementation
530  */
531 static void
532 cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
533                        void *impl_state)
534 {
535   struct GNUNET_CADET_Channel *ch = impl_state;
536
537   GNUNET_assert (mq == ch->mq);
538   ch->mq = NULL;
539 }
540
541
542 /**
543  * We had an error processing a message we forwarded from a peer to
544  * the CADET service.  We should just complain about it but otherwise
545  * continue processing.
546  *
547  * @param cls closure with our `struct GNUNET_CADET_Channel`
548  * @param error error code
549  */
550 static void
551 cadet_mq_error_handler (void *cls,
552                         enum GNUNET_MQ_Error error)
553 {
554   struct GNUNET_CADET_Channel *ch = cls;
555
556   GNUNET_break (0);
557   if (GNUNET_MQ_ERROR_NO_MATCH == error)
558   {
559     /* Got a message we did not understand, still try to continue! */
560     GNUNET_CADET_receive_done (ch);
561   }
562   else
563   {
564     schedule_reconnect (ch->cadet);
565   }
566 }
567
568
569 /**
570  * Implementation function that cancels the currently sent message.
571  * Should basically undo whatever #mq_send_impl() did.
572  *
573  * @param mq message queue
574  * @param impl_state state specific to the implementation
575  */
576 static void
577 cadet_mq_cancel_impl (struct GNUNET_MQ_Handle *mq,
578                      void *impl_state)
579 {
580   struct GNUNET_CADET_Channel *ch = impl_state;
581
582   GNUNET_assert (NULL != ch->pending_env);
583   GNUNET_MQ_discard (ch->pending_env);
584   ch->pending_env = NULL;
585   if (NULL != ch->mq_cont)
586   {
587     GNUNET_SCHEDULER_cancel (ch->mq_cont);
588     ch->mq_cont = NULL;
589   }
590 }
591
592
593 /**
594  * Process the new channel notification and add it to the channels in the handle
595  *
596  * @param h     The cadet handle
597  * @param msg   A message with the details of the new incoming channel
598  */
599 static void
600 handle_channel_created (void *cls,
601                         const struct GNUNET_CADET_LocalChannelCreateMessage *msg)
602 {
603   struct GNUNET_CADET_Handle *h = cls;
604   struct GNUNET_CADET_Channel *ch;
605   struct GNUNET_CADET_Port *port;
606   const struct GNUNET_HashCode *port_number;
607   struct GNUNET_CADET_ClientChannelNumber ccn;
608
609   ccn = msg->ccn;
610   port_number = &msg->port;
611   if (ntohl (ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
612   {
613     GNUNET_break (0);
614     return;
615   }
616   port = find_port (h,
617                     port_number);
618   if (NULL == port)
619   {
620     /* We could have closed the port but the service didn't know about it yet
621      * This is not an error.
622      */
623     struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg;
624     struct GNUNET_MQ_Envelope *env;
625
626     LOG (GNUNET_ERROR_TYPE_DEBUG,
627          "No handler for incoming channel %X (on port %s, recently closed?)\n",
628          ntohl (ccn.channel_of_client),
629          GNUNET_h2s (port_number));
630     env = GNUNET_MQ_msg (d_msg,
631                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
632     d_msg->ccn = msg->ccn;
633     GNUNET_MQ_send (h->mq,
634                     env);
635     return;
636   }
637
638   ch = create_channel (h,
639                        &ccn);
640   ch->peer = msg->peer;
641   ch->cadet = h;
642   ch->incoming_port = port;
643   ch->options = ntohl (msg->opt);
644   LOG (GNUNET_ERROR_TYPE_DEBUG,
645        "Creating incoming channel %X [%s] %p\n",
646        ntohl (ccn.channel_of_client),
647        GNUNET_h2s (port_number),
648        ch);
649
650   GNUNET_assert (NULL != port->connects);
651   ch->window_changes = port->window_changes;
652   ch->disconnects = port->disconnects;
653   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
654                                           &cadet_mq_destroy_impl,
655                                           &cadet_mq_cancel_impl,
656                                           ch,
657                                           port->handlers,
658                                           &cadet_mq_error_handler,
659                                           ch);
660   ch->ctx = port->connects (port->cls,
661                             ch,
662                             &msg->peer);
663   GNUNET_MQ_set_handlers_closure (ch->mq,
664                                   ch->ctx);
665 }
666
667
668 /**
669  * Process the channel destroy notification and free associated resources
670  *
671  * @param h     The cadet handle
672  * @param msg   A message with the details of the channel being destroyed
673  */
674 static void
675 handle_channel_destroy (void *cls,
676                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
677 {
678   struct GNUNET_CADET_Handle *h = cls;
679   struct GNUNET_CADET_Channel *ch;
680
681   ch = find_channel (h,
682                      msg->ccn);
683   if (NULL == ch)
684   {
685     LOG (GNUNET_ERROR_TYPE_DEBUG,
686          "Received channel destroy for unknown channel %X from CADET service (recently close?)\n",
687          ntohl (msg->ccn.channel_of_client));
688     return;
689   }
690   LOG (GNUNET_ERROR_TYPE_DEBUG,
691        "Received channel destroy for channel %X from CADET service\n",
692        ntohl (msg->ccn.channel_of_client));
693   destroy_channel (ch);
694 }
695
696
697 /**
698  * Check that message received from CADET service is well-formed.
699  *
700  * @param cls the `struct GNUNET_CADET_Handle`
701  * @param message the message we got
702  * @return #GNUNET_OK if the message is well-formed,
703  *         #GNUNET_SYSERR otherwise
704  */
705 static int
706 check_local_data (void *cls,
707                   const struct GNUNET_CADET_LocalData *message)
708 {
709   uint16_t size;
710
711   size = ntohs (message->header.size);
712   if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size)
713   {
714     GNUNET_break (0);
715     return GNUNET_SYSERR;
716   }
717   return GNUNET_OK;
718 }
719
720
721 /**
722  * Process the incoming data packets, call appropriate handlers.
723  *
724  * @param h       The cadet handle
725  * @param message A message encapsulating the data
726  */
727 static void
728 handle_local_data (void *cls,
729                    const struct GNUNET_CADET_LocalData *message)
730 {
731   struct GNUNET_CADET_Handle *h = cls;
732   const struct GNUNET_MessageHeader *payload;
733   struct GNUNET_CADET_Channel *ch;
734   uint16_t type;
735   int fwd;
736
737   ch = find_channel (h,
738                      message->ccn);
739   if (NULL == ch)
740   {
741     LOG (GNUNET_ERROR_TYPE_DEBUG,
742          "Unknown channel %X for incoming data (recently closed?)\n",
743          ntohl (message->ccn.channel_of_client));
744     return;
745   }
746
747   payload = (const struct GNUNET_MessageHeader *) &message[1];
748   type = ntohs (payload->type);
749   fwd = ntohl (ch->ccn.channel_of_client) <= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI;
750   LOG (GNUNET_ERROR_TYPE_DEBUG,
751        "Got a %s data on channel %s [%X] of type %u\n",
752        fwd ? "FWD" : "BWD",
753        GNUNET_i2s (&ch->peer),
754        ntohl (message->ccn.channel_of_client),
755        type);
756   GNUNET_MQ_inject_message (ch->mq,
757                             payload);
758 }
759
760
761 /**
762  * Process a local ACK message, enabling the client to send
763  * more data to the service.
764  *
765  * @param h Cadet handle.
766  * @param message Message itself.
767  */
768 static void
769 handle_local_ack (void *cls,
770                   const struct GNUNET_CADET_LocalAck *message)
771 {
772   struct GNUNET_CADET_Handle *h = cls;
773   struct GNUNET_CADET_Channel *ch;
774
775   ch = find_channel (h,
776                      message->ccn);
777   if (NULL == ch)
778   {
779     LOG (GNUNET_ERROR_TYPE_DEBUG,
780          "ACK on unknown channel %X\n",
781          ntohl (message->ccn.channel_of_client));
782     return;
783   }
784   ch->allow_send++;
785   if (NULL == ch->pending_env)
786   {
787     LOG (GNUNET_ERROR_TYPE_DEBUG,
788          "Got an ACK on mq channel %X, allow send now %u!\n",
789          ntohl (ch->ccn.channel_of_client),
790          ch->allow_send);
791     notify_window_size (ch);
792     return;
793   }
794   if (NULL != ch->mq_cont)
795     return; /* already working on it! */
796   LOG (GNUNET_ERROR_TYPE_DEBUG,
797        "Got an ACK on mq channel %X, sending pending message!\n",
798        ntohl (ch->ccn.channel_of_client));
799   ch->mq_cont
800     = GNUNET_SCHEDULER_add_now (&cadet_mq_send_now,
801                                 ch);
802 }
803
804
805 /**
806  * Generic error handler, called with the appropriate error code and
807  * the same closure specified at the creation of the message queue.
808  * Not every message queue implementation supports an error handler.
809  *
810  * @param cls closure, a `struct GNUNET_CORE_Handle *`
811  * @param error error code
812  */
813 static void
814 handle_mq_error (void *cls,
815                  enum GNUNET_MQ_Error error)
816 {
817   struct GNUNET_CADET_Handle *h = cls;
818
819   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
820               "MQ ERROR: %u\n",
821               error);
822   GNUNET_MQ_destroy (h->mq);
823   h->mq = NULL;
824   reconnect (h);
825 }
826
827
828 /**
829  * Check that message received from CADET service is well-formed.
830  *
831  * @param cls the `struct GNUNET_CADET_Handle`
832  * @param message the message we got
833  * @return #GNUNET_OK if the message is well-formed,
834  *         #GNUNET_SYSERR otherwise
835  */
836 static int
837 check_get_peers (void *cls,
838                  const struct GNUNET_MessageHeader *message)
839 {
840   size_t esize;
841
842   esize = ntohs (message->size);
843   if (sizeof (struct GNUNET_CADET_LocalInfoPeer) == esize)
844     return GNUNET_OK;
845   if (sizeof (struct GNUNET_MessageHeader) == esize)
846     return GNUNET_OK;
847   return GNUNET_SYSERR;
848 }
849
850
851 /**
852  * Process a local reply about info on all tunnels, pass info to the user.
853  *
854  * @param cls Closure (Cadet handle).
855  * @param msg Message itself.
856  */
857 static void
858 handle_get_peers (void *cls,
859                   const struct GNUNET_MessageHeader *msg)
860 {
861   struct GNUNET_CADET_Handle *h = cls;
862   const struct GNUNET_CADET_LocalInfoPeer *info =
863     (const struct GNUNET_CADET_LocalInfoPeer *) msg;
864
865   if (NULL == h->info_cb.peers_cb)
866     return;
867   if (sizeof (struct GNUNET_CADET_LocalInfoPeer) == ntohs (msg->size))
868     h->info_cb.peers_cb (h->info_cls,
869                          &info->destination,
870                          (int) ntohs (info->tunnel),
871                          (unsigned int) ntohs (info->paths),
872                          0);
873   else
874     h->info_cb.peers_cb (h->info_cls,
875                          NULL,
876                          0,
877                          0,
878                          0);
879 }
880
881
882 /**
883  * Check that message received from CADET service is well-formed.
884  *
885  * @param cls the `struct GNUNET_CADET_Handle`
886  * @param message the message we got
887  * @return #GNUNET_OK if the message is well-formed,
888  *         #GNUNET_SYSERR otherwise
889  */
890 static int
891 check_get_peer (void *cls,
892                 const struct GNUNET_CADET_LocalInfoPeer *message)
893 {
894   size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
895   const struct GNUNET_PeerIdentity *paths_array;
896   size_t esize;
897   unsigned int epaths;
898   unsigned int paths;
899   unsigned int peers;
900
901   esize = ntohs (message->header.size);
902   if (esize < msize)
903   {
904     GNUNET_break (0);
905     return GNUNET_SYSERR;
906   }
907   if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
908   {
909     GNUNET_break (0);
910     return GNUNET_SYSERR;
911   }
912   peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
913   epaths = ntohs (message->paths);
914   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
915   paths = 0;
916   for (unsigned int i = 0; i < peers; i++)
917     if (0 == memcmp (&paths_array[i],
918                      &message->destination,
919                      sizeof (struct GNUNET_PeerIdentity)))
920       paths++;
921   if (paths != epaths)
922   {
923     GNUNET_break (0);
924     return GNUNET_SYSERR;
925   }
926   return GNUNET_OK;
927 }
928
929
930 /**
931  * Process a local peer info reply, pass info to the user.
932  *
933  * @param cls Closure (Cadet handle).
934  * @param message Message itself.
935  */
936 static void
937 handle_get_peer (void *cls,
938                  const struct GNUNET_CADET_LocalInfoPeer *message)
939 {
940   struct GNUNET_CADET_Handle *h = cls;
941   const struct GNUNET_PeerIdentity *paths_array;
942   unsigned int paths;
943   unsigned int path_length;
944   int neighbor;
945   unsigned int peers;
946
947   if (NULL == h->info_cb.peer_cb)
948     return;
949   paths = ntohs (message->paths);
950   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
951   peers = (ntohs (message->header.size) - sizeof (*message))
952           / sizeof (struct GNUNET_PeerIdentity);
953   path_length = 0;
954   neighbor = GNUNET_NO;
955
956   for (unsigned int i = 0; i < peers; i++)
957   {
958     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
959                 " %s\n",
960                 GNUNET_i2s (&paths_array[i]));
961     path_length++;
962     if (0 == memcmp (&paths_array[i], &message->destination,
963                      sizeof (struct GNUNET_PeerIdentity)))
964     {
965       if (1 == path_length)
966         neighbor = GNUNET_YES;
967       path_length = 0;
968     }
969   }
970
971   /* Call Callback with tunnel info. */
972   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
973   h->info_cb.peer_cb (h->info_cls,
974                       &message->destination,
975                       (int) ntohs (message->tunnel),
976                       neighbor,
977                       paths,
978                       paths_array);
979 }
980
981
982 /**
983  * Check that message received from CADET service is well-formed.
984  *
985  * @param cls the `struct GNUNET_CADET_Handle`
986  * @param message the message we got
987  * @return #GNUNET_OK if the message is well-formed,
988  *         #GNUNET_SYSERR otherwise
989  */
990 static int
991 check_get_tunnels (void *cls,
992                    const struct GNUNET_MessageHeader *message)
993 {
994   size_t esize;
995
996   esize = ntohs (message->size);
997   if (sizeof (struct GNUNET_CADET_LocalInfoTunnel) == esize)
998     return GNUNET_OK;
999   if (sizeof (struct GNUNET_MessageHeader) == esize)
1000     return GNUNET_OK;
1001   return GNUNET_SYSERR;
1002 }
1003
1004
1005 /**
1006  * Process a local reply about info on all tunnels, pass info to the user.
1007  *
1008  * @param cls Closure (Cadet handle).
1009  * @param message Message itself.
1010  */
1011 static void
1012 handle_get_tunnels (void *cls,
1013                     const struct GNUNET_MessageHeader *msg)
1014 {
1015   struct GNUNET_CADET_Handle *h = cls;
1016   const struct GNUNET_CADET_LocalInfoTunnel *info =
1017     (const struct GNUNET_CADET_LocalInfoTunnel *) msg;
1018
1019   if (NULL == h->info_cb.tunnels_cb)
1020     return;
1021   if (sizeof (struct GNUNET_CADET_LocalInfoTunnel) == ntohs (msg->size))
1022     h->info_cb.tunnels_cb (h->info_cls,
1023                            &info->destination,
1024                            ntohl (info->channels),
1025                            ntohl (info->connections),
1026                            ntohs (info->estate),
1027                            ntohs (info->cstate));
1028   else
1029     h->info_cb.tunnels_cb (h->info_cls,
1030                            NULL,
1031                            0,
1032                            0,
1033                            0,
1034                            0);
1035 }
1036
1037
1038 /**
1039  * Check that message received from CADET service is well-formed.
1040  *
1041  * @param cls the `struct GNUNET_CADET_Handle`
1042  * @param msg the message we got
1043  * @return #GNUNET_OK if the message is well-formed,
1044  *         #GNUNET_SYSERR otherwise
1045  */
1046 static int
1047 check_get_tunnel (void *cls,
1048                   const struct GNUNET_CADET_LocalInfoTunnel *msg)
1049 {
1050   unsigned int ch_n;
1051   unsigned int c_n;
1052   size_t esize;
1053   size_t msize;
1054
1055   /* Verify message sanity */
1056   msize = ntohs (msg->header.size);
1057   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
1058   if (esize > msize)
1059   {
1060     GNUNET_break (0);
1061     return GNUNET_SYSERR;
1062   }
1063   ch_n = ntohl (msg->channels);
1064   c_n = ntohl (msg->connections);
1065   esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
1066   esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
1067   if (msize != esize)
1068   {
1069     GNUNET_break_op (0);
1070     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071                 "m:%u, e: %u (%u ch, %u conn)\n",
1072                 (unsigned int) msize,
1073                 (unsigned int) esize,
1074                 ch_n,
1075                 c_n);
1076     return GNUNET_SYSERR;
1077   }
1078   return GNUNET_OK;
1079 }
1080
1081
1082 /**
1083  * Process a local tunnel info reply, pass info to the user.
1084  *
1085  * @param cls Closure (Cadet handle).
1086  * @param msg Message itself.
1087  */
1088 static void
1089 handle_get_tunnel (void *cls,
1090                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1091 {
1092   struct GNUNET_CADET_Handle *h = cls;
1093   unsigned int ch_n;
1094   unsigned int c_n;
1095   const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
1096   const struct GNUNET_CADET_ChannelTunnelNumber *chns;
1097
1098   if (NULL == h->info_cb.tunnel_cb)
1099     return;
1100
1101   ch_n = ntohl (msg->channels);
1102   c_n = ntohl (msg->connections);
1103
1104   /* Call Callback with tunnel info. */
1105   conns = (const struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
1106   chns = (const struct GNUNET_CADET_ChannelTunnelNumber *) &conns[c_n];
1107   h->info_cb.tunnel_cb (h->info_cls,
1108                         &msg->destination,
1109                         ch_n,
1110                         c_n,
1111                         chns,
1112                         conns,
1113                         ntohs (msg->estate),
1114                         ntohs (msg->cstate));
1115 }
1116
1117
1118 /**
1119  * Reconnect to the service, retransmit all infomation to try to restore the
1120  * original state.
1121  *
1122  * @param h handle to the cadet
1123  */
1124 static void
1125 reconnect (struct GNUNET_CADET_Handle *h)
1126 {
1127   struct GNUNET_MQ_MessageHandler handlers[] = {
1128     GNUNET_MQ_hd_fixed_size (channel_created,
1129                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1130                              struct GNUNET_CADET_LocalChannelCreateMessage,
1131                              h),
1132     GNUNET_MQ_hd_fixed_size (channel_destroy,
1133                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1134                              struct GNUNET_CADET_LocalChannelDestroyMessage,
1135                              h),
1136     GNUNET_MQ_hd_var_size (local_data,
1137                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1138                            struct GNUNET_CADET_LocalData,
1139                            h),
1140     GNUNET_MQ_hd_fixed_size (local_ack,
1141                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1142                              struct GNUNET_CADET_LocalAck,
1143                              h),
1144     GNUNET_MQ_hd_var_size (get_peers,
1145                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1146                            struct GNUNET_MessageHeader,
1147                            h),
1148     GNUNET_MQ_hd_var_size (get_peer,
1149                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1150                            struct GNUNET_CADET_LocalInfoPeer,
1151                            h),
1152     GNUNET_MQ_hd_var_size (get_tunnels,
1153                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1154                            struct GNUNET_MessageHeader,
1155                            h),
1156     GNUNET_MQ_hd_var_size (get_tunnel,
1157                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1158                            struct GNUNET_CADET_LocalInfoTunnel,
1159                            h),
1160     GNUNET_MQ_handler_end ()
1161   };
1162
1163   GNUNET_assert (NULL == h->mq);
1164   h->mq = GNUNET_CLIENT_connect (h->cfg,
1165                                  "cadet",
1166                                  handlers,
1167                                  &handle_mq_error,
1168                                  h);
1169   if (NULL == h->mq)
1170   {
1171     schedule_reconnect (h);
1172     return;
1173   }
1174   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1175 }
1176
1177
1178 /**
1179  * Function called during #GNUNET_CADET_disconnect() to destroy
1180  * all channels that are still open.
1181  *
1182  * @param cls the `struct GNUNET_CADET_Handle`
1183  * @param cid chanenl ID
1184  * @param value a `struct GNUNET_CADET_Channel` to destroy
1185  * @return #GNUNET_OK (continue to iterate)
1186  */
1187 static int
1188 destroy_channel_cb (void *cls,
1189                     uint32_t cid,
1190                     void *value)
1191 {
1192   /* struct GNUNET_CADET_Handle *handle = cls; */
1193   struct GNUNET_CADET_Channel *ch = value;
1194
1195   if (ntohl (ch->ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1196   {
1197     GNUNET_break (0);
1198     LOG (GNUNET_ERROR_TYPE_DEBUG,
1199          "channel %X not destroyed\n",
1200          ntohl (ch->ccn.channel_of_client));
1201   }
1202   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1203               "Destroying channel due to GNUNET_CADET_disconnect()\n");
1204   destroy_channel (ch);
1205   return GNUNET_OK;
1206 }
1207
1208
1209 /**
1210  * Function called during #GNUNET_CADET_disconnect() to destroy
1211  * all ports that are still open.
1212  *
1213  * @param cls the `struct GNUNET_CADET_Handle`
1214  * @param id port ID
1215  * @param value a `struct GNUNET_CADET_Channel` to destroy
1216  * @return #GNUNET_OK (continue to iterate)
1217  */
1218 static int
1219 destroy_port_cb (void *cls,
1220                  const struct GNUNET_HashCode *id,
1221                  void *value)
1222 {
1223   /* struct GNUNET_CADET_Handle *handle = cls; */
1224   struct GNUNET_CADET_Port *port = value;
1225
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   env = GNUNET_MQ_msg (msg,
1281                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE);
1282   msg->port = p->id;
1283   GNUNET_MQ_send (p->cadet->mq,
1284                   env);
1285   GNUNET_assert (GNUNET_YES ==
1286                  GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports,
1287                                                        &p->id,
1288                                                        p));
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 */