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