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