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