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