Merge branch 'master' of ssh://gnunet.org/gnunet
[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 peers;
902
903   esize = ntohs (message->header.size);
904   if (esize < msize)
905   {
906     GNUNET_break (0);
907     return GNUNET_SYSERR;
908   }
909   if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
910   {
911     GNUNET_break (0);
912     return GNUNET_SYSERR;
913   }
914   peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
915   epaths = ntohs (message->paths);
916   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
917   
918   return GNUNET_OK;
919 }
920
921
922 /**
923  * Process a local peer info reply, pass info to the user.
924  *
925  * @param cls Closure (Cadet handle).
926  * @param message Message itself.
927  */
928 static void
929 handle_get_peer (void *cls,
930                  const struct GNUNET_CADET_LocalInfoPeer *message)
931 {
932   struct GNUNET_CADET_Handle *h = cls;
933   const struct GNUNET_PeerIdentity *paths_array;
934   unsigned int paths;
935   unsigned int path_length;
936   int neighbor;
937   unsigned int peers;
938
939   if (NULL == h->info_cb.peer_cb)
940     return;
941   
942   LOG (GNUNET_ERROR_TYPE_DEBUG,
943     "number of paths %u\n",
944     ntohs (message->paths));
945   
946   paths = ntohs (message->paths);
947   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
948   peers = (ntohs (message->header.size) - sizeof (*message))
949           / sizeof (struct GNUNET_PeerIdentity);
950   path_length = 0;
951   neighbor = GNUNET_NO;
952
953   for (unsigned int i = 0; i < peers; i++)
954   {
955     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
956                 " %s\n",
957                 GNUNET_i2s (&paths_array[i]));
958     path_length++;
959     if (0 == memcmp (&paths_array[i], &message->destination,
960                      sizeof (struct GNUNET_PeerIdentity)))
961     {
962       if (1 == path_length)
963         neighbor = GNUNET_YES;
964       path_length = 0;
965     }
966   }
967
968   /* Call Callback with tunnel info. */
969   paths_array = (const struct GNUNET_PeerIdentity *) &message[1];
970   h->info_cb.peer_cb (h->info_cls,
971                       &message->destination,
972                       (int) ntohs (message->tunnel),
973                       neighbor,
974                       paths,
975                       paths_array,
976                       (int) ntohs (message->offset),
977                       (int) ntohs (message->finished_with_paths));
978 }
979
980
981 /**
982  * Check that message received from CADET service is well-formed.
983  *
984  * @param cls the `struct GNUNET_CADET_Handle`
985  * @param message the message we got
986  * @return #GNUNET_OK if the message is well-formed,
987  *         #GNUNET_SYSERR otherwise
988  */
989 static int
990 check_get_tunnels (void *cls,
991                    const struct GNUNET_MessageHeader *message)
992 {
993   size_t esize;
994
995   (void) cls;
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   (void) cls;
1056   /* Verify message sanity */
1057   msize = ntohs (msg->header.size);
1058   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
1059   if (esize > msize)
1060   {
1061     GNUNET_break (0);
1062     return GNUNET_SYSERR;
1063   }
1064   ch_n = ntohl (msg->channels);
1065   c_n = ntohl (msg->connections);
1066   esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
1067   esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
1068   if (msize != esize)
1069   {
1070     GNUNET_break_op (0);
1071     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072                 "m:%u, e: %u (%u ch, %u conn)\n",
1073                 (unsigned int) msize,
1074                 (unsigned int) esize,
1075                 ch_n,
1076                 c_n);
1077     return GNUNET_SYSERR;
1078   }
1079   return GNUNET_OK;
1080 }
1081
1082
1083 /**
1084  * Process a local tunnel info reply, pass info to the user.
1085  *
1086  * @param cls Closure (Cadet handle).
1087  * @param msg Message itself.
1088  */
1089 static void
1090 handle_get_tunnel (void *cls,
1091                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1092 {
1093   struct GNUNET_CADET_Handle *h = cls;
1094   unsigned int ch_n;
1095   unsigned int c_n;
1096   const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
1097   const struct GNUNET_CADET_ChannelTunnelNumber *chns;
1098
1099   if (NULL == h->info_cb.tunnel_cb)
1100     return;
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   (void) cls;
1196   (void) cid;
1197   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1198               "Destroying channel due to GNUNET_CADET_disconnect()\n");
1199   destroy_channel (ch);
1200   return GNUNET_OK;
1201 }
1202
1203
1204 /**
1205  * Function called during #GNUNET_CADET_disconnect() to destroy
1206  * all ports that are still open.
1207  *
1208  * @param cls the `struct GNUNET_CADET_Handle`
1209  * @param id port ID
1210  * @param value a `struct GNUNET_CADET_Channel` to destroy
1211  * @return #GNUNET_OK (continue to iterate)
1212  */
1213 static int
1214 destroy_port_cb (void *cls,
1215                  const struct GNUNET_HashCode *id,
1216                  void *value)
1217 {
1218   /* struct GNUNET_CADET_Handle *handle = cls; */
1219   struct GNUNET_CADET_Port *port = value;
1220
1221   (void) cls;
1222   /* This is a warning, the app should have cleanly closed all open ports */
1223   GNUNET_break (0);
1224   GNUNET_CADET_close_port (port);
1225   return GNUNET_OK;
1226 }
1227
1228
1229 /**
1230  * Disconnect from the cadet service. All channels will be destroyed. All channel
1231  * disconnect callbacks will be called on any still connected peers, notifying
1232  * about their disconnection. The registered inbound channel cleaner will be
1233  * called should any inbound channels still exist.
1234  *
1235  * @param handle connection to cadet to disconnect
1236  */
1237 void
1238 GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
1239 {
1240   GNUNET_CONTAINER_multihashmap_iterate (handle->ports,
1241                                          &destroy_port_cb,
1242                                          handle);
1243   GNUNET_CONTAINER_multihashmap_destroy (handle->ports);
1244   handle->ports = NULL;
1245   GNUNET_CONTAINER_multihashmap32_iterate (handle->channels,
1246                                            &destroy_channel_cb,
1247                                            handle);
1248   GNUNET_CONTAINER_multihashmap32_destroy (handle->channels);
1249   handle->channels = NULL;
1250   if (NULL != handle->mq)
1251   {
1252     GNUNET_MQ_destroy (handle->mq);
1253     handle->mq = NULL;
1254   }
1255   if (NULL != handle->reconnect_task)
1256   {
1257     GNUNET_SCHEDULER_cancel (handle->reconnect_task);
1258     handle->reconnect_task = NULL;
1259   }
1260   GNUNET_free (handle);
1261 }
1262
1263
1264 /**
1265  * Close a port opened with @a GNUNET_CADET_open_port().
1266  * The @a new_channel callback will no longer be called.
1267  *
1268  * @param p Port handle.
1269  */
1270 void
1271 GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p)
1272 {
1273   struct GNUNET_CADET_PortMessage *msg;
1274   struct GNUNET_MQ_Envelope *env;
1275
1276   GNUNET_assert (GNUNET_YES ==
1277                  GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports,
1278                                                        &p->id,
1279                                                        p));
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_free_non_null (p->handlers);
1286   GNUNET_free (p);
1287 }
1288
1289
1290 /**
1291  * Destroy an existing channel.
1292  *
1293  * The existing end callback for the channel will be called immediately.
1294  * Any pending outgoing messages will be sent but no incoming messages will be
1295  * accepted and no data callbacks will be called.
1296  *
1297  * @param channel Channel handle, becomes invalid after this call.
1298  */
1299 void
1300 GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
1301 {
1302   struct GNUNET_CADET_Handle *h = channel->cadet;
1303   struct GNUNET_CADET_LocalChannelDestroyMessage *msg;
1304   struct GNUNET_MQ_Envelope *env;
1305
1306   if (NULL != h->mq)
1307   {
1308     env = GNUNET_MQ_msg (msg,
1309                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1310     msg->ccn = channel->ccn;
1311     GNUNET_MQ_send (h->mq,
1312                     env);
1313   }
1314   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1315               "Destroying channel due to GNUNET_CADET_channel_destroy()\n");
1316   destroy_channel (channel);
1317 }
1318
1319
1320 /**
1321  * Get information about a channel.
1322  *
1323  * @param channel Channel handle.
1324  * @param option Query (GNUNET_CADET_OPTION_*).
1325  * @param ... dependant on option, currently not used
1326  *
1327  * @return Union with an answer to the query.
1328  */
1329 const union GNUNET_CADET_ChannelInfo *
1330 GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
1331                                enum GNUNET_CADET_ChannelOption option,
1332                                ...)
1333 {
1334   static int bool_flag;
1335
1336   switch (option)
1337   {
1338     case GNUNET_CADET_OPTION_NOBUFFER:
1339     case GNUNET_CADET_OPTION_RELIABLE:
1340     case GNUNET_CADET_OPTION_OUT_OF_ORDER:
1341       if (0 != (option & channel->options))
1342         bool_flag = GNUNET_YES;
1343       else
1344         bool_flag = GNUNET_NO;
1345       return (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
1346       break;
1347     case GNUNET_CADET_OPTION_PEER:
1348       return (const union GNUNET_CADET_ChannelInfo *) &channel->peer;
1349       break;
1350     default:
1351       GNUNET_break (0);
1352       return NULL;
1353   }
1354 }
1355
1356
1357 /**
1358  * Send an ack on the channel to confirm the processing of a message.
1359  *
1360  * @param ch Channel on which to send the ACK.
1361  */
1362 void
1363 GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
1364 {
1365   struct GNUNET_CADET_LocalAck *msg;
1366   struct GNUNET_MQ_Envelope *env;
1367
1368   env = GNUNET_MQ_msg (msg,
1369                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
1370   LOG (GNUNET_ERROR_TYPE_DEBUG,
1371        "Sending ACK on channel %X\n",
1372        ntohl (channel->ccn.channel_of_client));
1373   msg->ccn = channel->ccn;
1374   GNUNET_MQ_send (channel->cadet->mq,
1375                   env);
1376 }
1377
1378
1379 /**
1380  * Send message of @a type to CADET service of @a h
1381  *
1382  * @param h handle to CADET service
1383  * @param type message type of trivial information request to send
1384  */
1385 static void
1386 send_info_request (struct GNUNET_CADET_Handle *h,
1387                    uint16_t type)
1388 {
1389   struct GNUNET_MessageHeader *msg;
1390   struct GNUNET_MQ_Envelope *env;
1391
1392   env = GNUNET_MQ_msg (msg,
1393                        type);
1394   GNUNET_MQ_send (h->mq,
1395                   env);
1396 }
1397
1398
1399 /**
1400  * Request a debug dump on the service's STDERR.
1401  *
1402  * WARNING: unstable API, likely to change in the future!
1403  *
1404  * @param h cadet handle
1405  */
1406 void
1407 GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
1408 {
1409   send_info_request (h,
1410                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
1411 }
1412
1413
1414 /**
1415  * Request information about peers known to the running cadet service.
1416  * The callback will be called for every peer known to the service.
1417  * Only one info request (of any kind) can be active at once.
1418  *
1419  * WARNING: unstable API, likely to change in the future!
1420  *
1421  * @param h Handle to the cadet peer.
1422  * @param callback Function to call with the requested data.
1423  * @param callback_cls Closure for @c callback.
1424  * @return #GNUNET_OK / #GNUNET_SYSERR
1425  */
1426 int
1427 GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
1428                        GNUNET_CADET_PeersCB callback,
1429                        void *callback_cls)
1430 {
1431   if (NULL != h->info_cb.peers_cb)
1432   {
1433     GNUNET_break (0);
1434     return GNUNET_SYSERR;
1435   }
1436   send_info_request (h,
1437                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
1438   h->info_cb.peers_cb = callback;
1439   h->info_cls = callback_cls;
1440   return GNUNET_OK;
1441 }
1442
1443
1444 /**
1445  * Cancel a peer info request. The callback will not be called (anymore).
1446  *
1447  * WARNING: unstable API, likely to change in the future!
1448  *
1449  * @param h Cadet handle.
1450  * @return Closure given to GNUNET_CADET_get_peers().
1451  */
1452 void *
1453 GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
1454 {
1455   void *cls = h->info_cls;
1456
1457   h->info_cb.peers_cb = NULL;
1458   h->info_cls = NULL;
1459   return cls;
1460 }
1461
1462
1463 /**
1464  * Request information about a peer known to the running cadet peer.
1465  * The callback will be called for the tunnel once.
1466  * Only one info request (of any kind) can be active at once.
1467  *
1468  * WARNING: unstable API, likely to change in the future!
1469  *
1470  * @param h Handle to the cadet peer.
1471  * @param id Peer whose tunnel to examine.
1472  * @param callback Function to call with the requested data.
1473  * @param callback_cls Closure for @c callback.
1474  * @return #GNUNET_OK / #GNUNET_SYSERR
1475  */
1476 int
1477 GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
1478                        const struct GNUNET_PeerIdentity *id,
1479                        GNUNET_CADET_PeerCB callback,
1480                        void *callback_cls)
1481 {
1482   struct GNUNET_CADET_LocalInfo *msg;
1483   struct GNUNET_MQ_Envelope *env;
1484
1485   if (NULL != h->info_cb.peer_cb)
1486   {
1487     GNUNET_break (0);
1488     return GNUNET_SYSERR;
1489   }
1490   env = GNUNET_MQ_msg (msg,
1491                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
1492   msg->peer = *id;
1493   GNUNET_MQ_send (h->mq,
1494                   env);
1495   h->info_cb.peer_cb = callback;
1496   h->info_cls = callback_cls;
1497   return GNUNET_OK;
1498 }
1499
1500
1501 /**
1502  * Request information about tunnels of the running cadet peer.
1503  * The callback will be called for every tunnel of the service.
1504  * Only one info request (of any kind) can be active at once.
1505  *
1506  * WARNING: unstable API, likely to change in the future!
1507  *
1508  * @param h Handle to the cadet peer.
1509  * @param callback Function to call with the requested data.
1510  * @param callback_cls Closure for @c callback.
1511  * @return #GNUNET_OK / #GNUNET_SYSERR
1512  */
1513 int
1514 GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
1515                          GNUNET_CADET_TunnelsCB callback,
1516                          void *callback_cls)
1517 {
1518   if (NULL != h->info_cb.tunnels_cb)
1519   {
1520     GNUNET_break (0);
1521     return GNUNET_SYSERR;
1522   }
1523   send_info_request (h,
1524                      GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
1525   h->info_cb.tunnels_cb = callback;
1526   h->info_cls = callback_cls;
1527   return GNUNET_OK;
1528 }
1529
1530
1531 /**
1532  * Cancel a monitor request. The monitor callback will not be called.
1533  *
1534  * @param h Cadet handle.
1535  * @return Closure given to GNUNET_CADET_get_tunnels().
1536  */
1537 void *
1538 GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
1539 {
1540   void *cls = h->info_cls;
1541
1542   h->info_cb.tunnels_cb = NULL;
1543   h->info_cls = NULL;
1544   return cls;
1545 }
1546
1547
1548 /**
1549  * Request information about a tunnel of the running cadet peer.
1550  * The callback will be called for the tunnel once.
1551  * Only one info request (of any kind) can be active at once.
1552  *
1553  * WARNING: unstable API, likely to change in the future!
1554  *
1555  * @param h Handle to the cadet peer.
1556  * @param id Peer whose tunnel to examine.
1557  * @param callback Function to call with the requested data.
1558  * @param callback_cls Closure for @c callback.
1559  * @return #GNUNET_OK / #GNUNET_SYSERR
1560  */
1561 int
1562 GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
1563                         const struct GNUNET_PeerIdentity *id,
1564                         GNUNET_CADET_TunnelCB callback,
1565                         void *callback_cls)
1566 {
1567   struct GNUNET_CADET_LocalInfo *msg;
1568   struct GNUNET_MQ_Envelope *env;
1569
1570   if (NULL != h->info_cb.tunnel_cb)
1571   {
1572     GNUNET_break (0);
1573     return GNUNET_SYSERR;
1574   }
1575   env = GNUNET_MQ_msg (msg,
1576                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1577   msg->peer = *id;
1578   GNUNET_MQ_send (h->mq,
1579                   env);
1580   h->info_cb.tunnel_cb = callback;
1581   h->info_cls = callback_cls;
1582   return GNUNET_OK;
1583 }
1584
1585
1586 /**
1587  * Transitional function to convert an unsigned int port to a hash value.
1588  * WARNING: local static value returned, NOT reentrant!
1589  * WARNING: do not use this function for new code!
1590  *
1591  * @param port Numerical port (unsigned int format).
1592  *
1593  * @return A GNUNET_HashCode usable for the new CADET API.
1594  */
1595 const struct GNUNET_HashCode *
1596 GC_u2h (uint32_t port)
1597 {
1598   static struct GNUNET_HashCode hash;
1599
1600   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1601               "This is a transitional function, use proper crypto hashes as CADET ports\n");
1602   GNUNET_CRYPTO_hash (&port,
1603                       sizeof (port),
1604                       &hash);
1605   return &hash;
1606 }
1607
1608
1609 /**
1610  * Connect to the MQ-based cadet service.
1611  *
1612  * @param cfg Configuration to use.
1613  *
1614  * @return Handle to the cadet service NULL on error.
1615  */
1616 struct GNUNET_CADET_Handle *
1617 GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
1618 {
1619   struct GNUNET_CADET_Handle *h;
1620
1621   LOG (GNUNET_ERROR_TYPE_DEBUG,
1622        "GNUNET_CADET_connect()\n");
1623   h = GNUNET_new (struct GNUNET_CADET_Handle);
1624   h->cfg = cfg;
1625   h->ports = GNUNET_CONTAINER_multihashmap_create (4,
1626                                                    GNUNET_YES);
1627   h->channels = GNUNET_CONTAINER_multihashmap32_create (4);
1628   reconnect (h);
1629   if (NULL == h->mq)
1630   {
1631     GNUNET_break (0);
1632     GNUNET_CADET_disconnect (h);
1633     return NULL;
1634   }
1635   h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1636   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1637   h->reconnect_task = NULL;
1638
1639   return h;
1640 }
1641
1642
1643 /**
1644  * Open a port to receive incomming MQ-based channels.
1645  *
1646  * @param h CADET handle.
1647  * @param port Hash identifying the port.
1648  * @param connects Function called when an incoming channel is connected.
1649  * @param connects_cls Closure for the @a connects handler.
1650  * @param window_changes Function called when the transmit window size changes.
1651  * @param disconnects Function called when a channel is disconnected.
1652  * @param handlers Callbacks for messages we care about, NULL-terminated.
1653  * @return Port handle, NULL if port is in use
1654  */
1655 struct GNUNET_CADET_Port *
1656 GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h,
1657                         const struct GNUNET_HashCode *port,
1658                         GNUNET_CADET_ConnectEventHandler connects,
1659                         void * connects_cls,
1660                         GNUNET_CADET_WindowSizeEventHandler window_changes,
1661                         GNUNET_CADET_DisconnectEventHandler disconnects,
1662                         const struct GNUNET_MQ_MessageHandler *handlers)
1663 {
1664   struct GNUNET_CADET_PortMessage *msg;
1665   struct GNUNET_MQ_Envelope *env;
1666   struct GNUNET_CADET_Port *p;
1667
1668   GNUNET_assert (NULL != connects);
1669   GNUNET_assert (NULL != disconnects);
1670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1671               "Listening to CADET port %s\n",
1672               GNUNET_h2s (port));
1673
1674   p = GNUNET_new (struct GNUNET_CADET_Port);
1675   p->cadet = h;
1676   p->id = *port;
1677   if (GNUNET_OK !=
1678       GNUNET_CONTAINER_multihashmap_put (h->ports,
1679                                          &p->id,
1680                                          p,
1681                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1682   {
1683     GNUNET_free (p);
1684     return NULL;
1685   }
1686   p->connects = connects;
1687   p->cls = connects_cls;
1688   p->window_changes = window_changes;
1689   p->disconnects = disconnects;
1690   p->handlers = GNUNET_MQ_copy_handlers (handlers);
1691
1692
1693   env = GNUNET_MQ_msg (msg,
1694                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN);
1695   msg->port = p->id;
1696   GNUNET_MQ_send (h->mq,
1697                   env);
1698   return p;
1699 }
1700
1701
1702 /**
1703  * Create a new channel towards a remote peer.
1704  *
1705  * If the destination port is not open by any peer or the destination peer
1706  * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
1707  * for this channel.
1708  *
1709  * @param h CADET handle.
1710  * @param channel_cls Closure for the channel. It's given to:
1711  *                    - The disconnect handler @a disconnects
1712  *                    - Each message type callback in @a handlers
1713  * @param destination Peer identity the channel should go to.
1714  * @param port Identification of the destination port.
1715  * @param options CadetOption flag field, with all desired option bits set to 1.
1716  * @param window_changes Function called when the transmit window size changes.
1717  * @param disconnects Function called when the channel is disconnected.
1718  * @param handlers Callbacks for messages we care about, NULL-terminated.
1719  * @return Handle to the channel.
1720  */
1721 struct GNUNET_CADET_Channel *
1722 GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h,
1723                              void *channel_cls,
1724                              const struct GNUNET_PeerIdentity *destination,
1725                              const struct GNUNET_HashCode *port,
1726                              enum GNUNET_CADET_ChannelOption options,
1727                              GNUNET_CADET_WindowSizeEventHandler window_changes,
1728                              GNUNET_CADET_DisconnectEventHandler disconnects,
1729                              const struct GNUNET_MQ_MessageHandler *handlers)
1730 {
1731   struct GNUNET_CADET_Channel *ch;
1732   struct GNUNET_CADET_LocalChannelCreateMessage *msg;
1733   struct GNUNET_MQ_Envelope *env;
1734
1735   GNUNET_assert (NULL != disconnects);
1736   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1737               "Creating channel to peer %s at port %s\n",
1738               GNUNET_i2s (destination),
1739               GNUNET_h2s (port));
1740   ch = create_channel (h,
1741                        NULL);
1742   ch->ctx = channel_cls;
1743   ch->peer = *destination;
1744   ch->options = options;
1745   ch->window_changes = window_changes;
1746   ch->disconnects = disconnects;
1747
1748   /* Create MQ for channel */
1749   ch->mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
1750                                           &cadet_mq_destroy_impl,
1751                                           &cadet_mq_cancel_impl,
1752                                           ch,
1753                                           handlers,
1754                                           &cadet_mq_error_handler,
1755                                           ch);
1756   GNUNET_MQ_set_handlers_closure (ch->mq, channel_cls);
1757
1758   /* Request channel creation to service */
1759   env = GNUNET_MQ_msg (msg,
1760                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
1761   msg->ccn = ch->ccn;
1762   msg->port = *port;
1763   msg->peer = *destination;
1764   msg->opt = htonl (options);
1765   GNUNET_MQ_send (h->mq,
1766                   env);
1767   return ch;
1768 }
1769
1770
1771 /**
1772  * Obtain the message queue for a connected peer.
1773  *
1774  * @param channel The channel handle from which to get the MQ.
1775  *
1776  * @return NULL if @a channel is not yet connected.
1777  */
1778 struct GNUNET_MQ_Handle *
1779 GNUNET_CADET_get_mq (const struct GNUNET_CADET_Channel *channel)
1780 {
1781   return channel->mq;
1782 }
1783
1784 /* end of cadet_api.c */