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