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