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