a3b23d9138f5bc2f9b048978b3054fc5ee61d03d
[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  */
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 /************************      DATA STRUCTURES     ****************************/
37 /******************************************************************************/
38
39 /**
40  * Transmission queue to the service
41  */
42 struct GNUNET_CADET_TransmitHandle
43 {
44   /**
45    * Double Linked list
46    */
47   struct GNUNET_CADET_TransmitHandle *next;
48
49   /**
50    * Double Linked list
51    */
52   struct GNUNET_CADET_TransmitHandle *prev;
53
54   /**
55    * Channel this message is sent on / for (may be NULL for control messages).
56    */
57   struct GNUNET_CADET_Channel *channel;
58
59   /**
60    * Request data task.
61    */
62   struct GNUNET_SCHEDULER_Task *request_data_task;
63
64   /**
65    * Callback to obtain the message to transmit, or NULL if we
66    * got the message in 'data'.  Notice that messages built
67    * by 'notify' need to be encapsulated with information about
68    * the 'target'.
69    */
70   GNUNET_CONNECTION_TransmitReadyNotify notify;
71
72   /**
73    * Closure for 'notify'
74    */
75   void *notify_cls;
76
77   /**
78    * Size of the payload.
79    */
80   size_t size;
81 };
82
83
84 union CadetInfoCB
85 {
86
87   /**
88    * Channel callback.
89    */
90   GNUNET_CADET_ChannelCB channel_cb;
91
92   /**
93    * Monitor callback
94    */
95   GNUNET_CADET_PeersCB peers_cb;
96
97   /**
98    * Monitor callback
99    */
100   GNUNET_CADET_PeerCB peer_cb;
101
102   /**
103    * Monitor callback
104    */
105   GNUNET_CADET_TunnelsCB tunnels_cb;
106
107   /**
108    * Tunnel callback.
109    */
110   GNUNET_CADET_TunnelCB tunnel_cb;
111 };
112
113
114 /**
115  * Opaque handle to the service.
116  */
117 struct GNUNET_CADET_Handle
118 {
119   /**
120    * Message queue (if available).
121    */
122   struct GNUNET_MQ_Handle *mq;
123
124   /**
125    * Set of handlers used for processing incoming messages in the channels
126    */
127   const struct GNUNET_CADET_MessageHandler *message_handlers;
128
129   /**
130    * Number of handlers in the handlers array.
131    */
132   unsigned int n_handlers;
133
134   /**
135    * Ports open.
136    */
137   struct GNUNET_CONTAINER_MultiHashMap *ports;
138
139   /**
140    * Double linked list of the channels this client is connected to, head.
141    */
142   struct GNUNET_CADET_Channel *channels_head;
143
144   /**
145    * Double linked list of the channels this client is connected to, tail.
146    */
147   struct GNUNET_CADET_Channel *channels_tail;
148
149   /**
150    * Callback for inbound channel disconnection
151    */
152   GNUNET_CADET_ChannelEndHandler *cleaner;
153
154   /**
155    * Closure for all the handlers given by the client
156    */
157   void *cls;
158
159   /**
160    * Messages to send to the service, head.
161    */
162   struct GNUNET_CADET_TransmitHandle *th_head;
163
164   /**
165    * Messages to send to the service, tail.
166    */
167   struct GNUNET_CADET_TransmitHandle *th_tail;
168
169   /**
170    * child of the next channel to create (to avoid reusing IDs often)
171    */
172   struct GNUNET_CADET_ClientChannelNumber next_ccn;
173
174   /**
175    * Configuration given by the client, in case of reconnection
176    */
177   const struct GNUNET_CONFIGURATION_Handle *cfg;
178
179   /**
180    * Time to the next reconnect in case one reconnect fails
181    */
182   struct GNUNET_TIME_Relative reconnect_time;
183
184   /**
185    * Task for trying to reconnect.
186    */
187   struct GNUNET_SCHEDULER_Task * reconnect_task;
188
189   /**
190    * Callback for an info task (only one active at a time).
191    */
192   union CadetInfoCB info_cb;
193
194   /**
195    * Info callback closure for @c info_cb.
196    */
197   void *info_cls;
198 };
199
200
201 /**
202  * Description of a peer
203  */
204 struct GNUNET_CADET_Peer
205 {
206   /**
207    * ID of the peer in short form
208    */
209   GNUNET_PEER_Id id;
210
211   /**
212    * Channel this peer belongs to
213    */
214   struct GNUNET_CADET_Channel *t;
215 };
216
217
218 /**
219  * Opaque handle to a channel.
220  */
221 struct GNUNET_CADET_Channel
222 {
223   /**
224    * DLL next
225    */
226   struct GNUNET_CADET_Channel *next;
227
228   /**
229    * DLL prev
230    */
231   struct GNUNET_CADET_Channel *prev;
232
233   /**
234    * Handle to the cadet this channel belongs to
235    */
236   struct GNUNET_CADET_Handle *cadet;
237
238   /**
239    * Local ID of the channel
240    */
241   struct GNUNET_CADET_ClientChannelNumber ccn;
242
243   /**
244    * Channel's port, if any.
245    */
246   struct GNUNET_CADET_Port *port;
247
248   /**
249    * Other end of the channel.
250    */
251   GNUNET_PEER_Id peer;
252
253   /**
254    * Any data the caller wants to put in here
255    */
256   void *ctx;
257
258   /**
259    * Channel options: reliability, etc.
260    */
261   enum GNUNET_CADET_ChannelOption options;
262
263   /**
264    * Are we allowed to send to the service?
265    */
266   unsigned int allow_send;
267
268 };
269
270
271 /**
272  * Opaque handle to a port.
273  */
274 struct GNUNET_CADET_Port
275 {
276   /**
277    * Handle to the CADET session this port belongs to.
278    */
279   struct GNUNET_CADET_Handle *cadet;
280
281   /**
282    * Port ID.
283    */
284   struct GNUNET_HashCode *hash;
285
286   /**
287    * Callback handler for incoming channels on this port.
288    */
289   GNUNET_CADET_InboundChannelNotificationHandler *handler;
290
291   /**
292    * Closure for @a handler.
293    */
294   void *cls;
295 };
296
297
298 /**
299  * Implementation state for cadet's message queue.
300  */
301 struct CadetMQState
302 {
303   /**
304    * The current transmit handle, or NULL
305    * if no transmit is active.
306    */
307   struct GNUNET_CADET_TransmitHandle *th;
308
309   /**
310    * Channel to send the data over.
311    */
312   struct GNUNET_CADET_Channel *channel;
313 };
314
315
316 /******************************************************************************/
317 /***********************     AUXILIARY FUNCTIONS      *************************/
318 /******************************************************************************/
319
320 /**
321  * Check if transmission is a payload packet.
322  *
323  * @param th Transmission handle.
324  *
325  * @return #GNUNET_YES if it is a payload packet,
326  *         #GNUNET_NO if it is a cadet management packet.
327  */
328 static int
329 th_is_payload (struct GNUNET_CADET_TransmitHandle *th)
330 {
331   return (th->notify != NULL) ? GNUNET_YES : GNUNET_NO;
332 }
333
334
335 /**
336  * Find the Port struct for a hash.
337  *
338  * @param h CADET handle.
339  * @param hash HashCode for the port number.
340  *
341  * @return The port handle if known, NULL otherwise.
342  */
343 static struct GNUNET_CADET_Port *
344 find_port (const struct GNUNET_CADET_Handle *h,
345            const struct GNUNET_HashCode *hash)
346 {
347   struct GNUNET_CADET_Port *p;
348
349   p = GNUNET_CONTAINER_multihashmap_get (h->ports, hash);
350
351   return p;
352 }
353
354
355 /**
356  * Get the channel handler for the channel specified by id from the given handle
357  *
358  * @param h Cadet handle
359  * @param ccn ID of the wanted channel
360  * @return handle to the required channel or NULL if not found
361  */
362 static struct GNUNET_CADET_Channel *
363 retrieve_channel (struct GNUNET_CADET_Handle *h,
364                   struct GNUNET_CADET_ClientChannelNumber ccn)
365 {
366   struct GNUNET_CADET_Channel *ch;
367
368   for (ch = h->channels_head; NULL != ch; ch = ch->next)
369     if (ch->ccn.channel_of_client == ccn.channel_of_client)
370       return ch;
371   return NULL;
372 }
373
374
375 /**
376  * Create a new channel and insert it in the channel list of the cadet handle
377  *
378  * @param h Cadet handle
379  * @param ccn Desired ccn of the channel, 0 to assign one automatically.
380  *
381  * @return Handle to the created channel.
382  */
383 static struct GNUNET_CADET_Channel *
384 create_channel (struct GNUNET_CADET_Handle *h,
385                 struct GNUNET_CADET_ClientChannelNumber ccn)
386 {
387   struct GNUNET_CADET_Channel *ch;
388
389   ch = GNUNET_new (struct GNUNET_CADET_Channel);
390   GNUNET_CONTAINER_DLL_insert (h->channels_head,
391                                h->channels_tail,
392                                ch);
393   ch->cadet = h;
394   if (0 == ccn.channel_of_client)
395   {
396     ch->ccn = h->next_ccn;
397     while (NULL != retrieve_channel (h,
398                                      h->next_ccn))
399     {
400       h->next_ccn.channel_of_client
401         = htonl (1 + ntohl (h->next_ccn.channel_of_client));
402       if (0 == ntohl (h->next_ccn.channel_of_client))
403         h->next_ccn.channel_of_client
404           = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
405     }
406   }
407   else
408   {
409     ch->ccn = ccn;
410   }
411   return ch;
412 }
413
414
415 /**
416  * Destroy the specified channel.
417  * - Destroys all peers, calling the disconnect callback on each if needed
418  * - Cancels all outgoing traffic for that channel, calling respective notifys
419  * - Calls cleaner if channel was inbound
420  * - Frees all memory used
421  *
422  * @param ch Pointer to the channel.
423  * @param call_cleaner Whether to call the cleaner handler.
424  *
425  * @return Handle to the required channel or NULL if not found.
426  */
427 // FIXME: simplify: call_cleaner is always #GNUNET_YES!!!
428 static void
429 destroy_channel (struct GNUNET_CADET_Channel *ch,
430                  int call_cleaner)
431 {
432   struct GNUNET_CADET_Handle *h;
433   struct GNUNET_CADET_TransmitHandle *th;
434   struct GNUNET_CADET_TransmitHandle *next;
435
436   if (NULL == ch)
437   {
438     GNUNET_break (0);
439     return;
440   }
441   h = ch->cadet;
442   LOG (GNUNET_ERROR_TYPE_DEBUG,
443        " destroy_channel %X of %p\n",
444        ch->ccn,
445        h);
446
447   GNUNET_CONTAINER_DLL_remove (h->channels_head,
448                                h->channels_tail,
449                                ch);
450
451   /* signal channel destruction */
452   if ( (NULL != h->cleaner) &&
453        (0 != ch->peer) &&
454        (GNUNET_YES == call_cleaner) )
455   {
456     LOG (GNUNET_ERROR_TYPE_DEBUG,
457          " calling cleaner\n");
458     h->cleaner (h->cls, ch, ch->ctx);
459   }
460
461   /* check that clients did not leave messages behind in the queue */
462   for (th = h->th_head; NULL != th; th = next)
463   {
464     next = th->next;
465     if (th->channel != ch)
466       continue;
467     /* Clients should have aborted their requests already.
468      * Management traffic should be ok, as clients can't cancel that.
469      * If the service crashed and we are reconnecting, it's ok.
470      */
471     GNUNET_break (GNUNET_NO == th_is_payload (th));
472     GNUNET_CADET_notify_transmit_ready_cancel (th);
473   }
474
475   if (0 != ch->peer)
476     GNUNET_PEER_change_rc (ch->peer, -1);
477   GNUNET_free (ch);
478 }
479
480
481 /**
482  * Add a transmit handle to the transmission queue and set the
483  * timeout if needed.
484  *
485  * @param h cadet handle with the queue head and tail
486  * @param th handle to the packet to be transmitted
487  */
488 static void
489 add_to_queue (struct GNUNET_CADET_Handle *h,
490               struct GNUNET_CADET_TransmitHandle *th)
491 {
492   GNUNET_CONTAINER_DLL_insert_tail (h->th_head, h->th_tail, th);
493 }
494
495
496 /**
497  * Remove a transmit handle from the transmission queue, if present.
498  *
499  * Safe to call even if not queued.
500  *
501  * @param th handle to the packet to be unqueued.
502  */
503 static void
504 remove_from_queue (struct GNUNET_CADET_TransmitHandle *th)
505 {
506   struct GNUNET_CADET_Handle *h = th->channel->cadet;
507
508   /* It might or might not have been queued (rarely not), but check anyway. */
509   if (NULL != th->next || h->th_tail == th)
510   {
511     GNUNET_CONTAINER_DLL_remove (h->th_head, h->th_tail, th);
512   }
513 }
514
515
516
517 /******************************************************************************/
518 /***********************      RECEIVE HANDLERS     ****************************/
519 /******************************************************************************/
520
521
522 /**
523  * Call the @a notify callback given to #GNUNET_CADET_notify_transmit_ready to
524  * request the data to send over MQ. Since MQ manages the queue, this function
525  * is scheduled immediatly after a transmit ready notification.
526  *
527  * @param cls Closure (transmit handle).
528  */
529 static void
530 request_data (void *cls)
531 {
532   struct GNUNET_CADET_TransmitHandle *th = cls;
533   struct GNUNET_CADET_LocalData *msg;
534   struct GNUNET_MQ_Envelope *env;
535   size_t osize;
536
537   LOG (GNUNET_ERROR_TYPE_DEBUG,
538        "Requesting Data: %u bytes (allow send is %u)\n",
539        th->size,
540        th->channel->allow_send);
541
542   GNUNET_assert (0 < th->channel->allow_send);
543   th->channel->allow_send--;
544   /* NOTE: we may be allowed to send another packet immediately,
545      albeit the current logic waits for the ACK. */
546   th->request_data_task = NULL;
547   remove_from_queue (th);
548
549   env = GNUNET_MQ_msg_extra (msg,
550                              th->size,
551                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA);
552   msg->ccn = th->channel->ccn;
553   osize = th->notify (th->notify_cls,
554                       th->size,
555                       &msg[1]);
556   GNUNET_assert (osize == th->size);
557   GNUNET_MQ_send (th->channel->cadet->mq,
558                   env);
559   GNUNET_free (th);
560 }
561
562
563 /**
564  * Process the new channel notification and add it to the channels in the handle
565  *
566  * @param h     The cadet handle
567  * @param msg   A message with the details of the new incoming channel
568  */
569 static void
570 handle_channel_created (void *cls,
571                         const struct GNUNET_CADET_LocalChannelCreateMessage *msg)
572 {
573   struct GNUNET_CADET_Handle *h = cls;
574   struct GNUNET_CADET_Channel *ch;
575   struct GNUNET_CADET_Port *port;
576   const struct GNUNET_HashCode *port_number;
577   struct GNUNET_CADET_ClientChannelNumber ccn;
578
579   ccn = msg->ccn;
580   port_number = &msg->port;
581   if (ntohl (ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
582   {
583     GNUNET_break (0);
584     return;
585   }
586   port = find_port (h, port_number);
587   if (NULL == port)
588   {
589     struct GNUNET_CADET_LocalChannelDestroyMessage *d_msg;
590     struct GNUNET_MQ_Envelope *env;
591
592     GNUNET_break (0);
593     LOG (GNUNET_ERROR_TYPE_DEBUG,
594          "No handler for incoming channel %X [%s]\n",
595          ntohl (ccn.channel_of_client),
596          GNUNET_h2s (port_number));
597     /* FIXME: should disconnect instead, this is a serious error! */
598     env = GNUNET_MQ_msg (d_msg,
599                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
600     d_msg->ccn = msg->ccn;
601     GNUNET_MQ_send (h->mq,
602                     env);
603     return;
604   }
605
606   ch = create_channel (h,
607                        ccn);
608   ch->peer = GNUNET_PEER_intern (&msg->peer);
609   ch->cadet = h;
610   ch->ccn = ccn;
611   ch->port = port;
612   ch->options = ntohl (msg->opt);
613
614   LOG (GNUNET_ERROR_TYPE_DEBUG,
615        "Creating incoming channel %X [%s] %p\n",
616        ntohl (ccn.channel_of_client),
617        GNUNET_h2s (port_number),
618        ch);
619   ch->ctx = port->handler (port->cls,
620                            ch,
621                            &msg->peer,
622                            port->hash,
623                            ch->options);
624 }
625
626
627 /**
628  * Process the channel destroy notification and free associated resources
629  *
630  * @param h     The cadet handle
631  * @param msg   A message with the details of the channel being destroyed
632  */
633 static void
634 handle_channel_destroy (void *cls,
635                         const struct GNUNET_CADET_LocalChannelDestroyMessage *msg)
636 {
637   struct GNUNET_CADET_Handle *h = cls;
638   struct GNUNET_CADET_Channel *ch;
639   struct GNUNET_CADET_ClientChannelNumber ccn;
640
641   ccn = msg->ccn;
642   LOG (GNUNET_ERROR_TYPE_DEBUG,
643        "Channel %X Destroy from service\n",
644        ntohl (ccn.channel_of_client));
645   ch = retrieve_channel (h,
646                          ccn);
647
648   if (NULL == ch)
649   {
650     LOG (GNUNET_ERROR_TYPE_DEBUG,
651          "channel %X unknown\n",
652          ntohl (ccn.channel_of_client));
653     return;
654   }
655   destroy_channel (ch,
656                    GNUNET_YES);
657 }
658
659
660 /**
661  * Check that message received from CADET service is well-formed.
662  *
663  * @param cls the `struct GNUNET_CADET_Handle`
664  * @param message the message we got
665  * @return #GNUNET_OK if the message is well-formed,
666  *         #GNUNET_SYSERR otherwise
667  */
668 static int
669 check_local_data (void *cls,
670                   const struct GNUNET_CADET_LocalData *message)
671 {
672   struct GNUNET_CADET_Handle *h = cls;
673   struct GNUNET_CADET_Channel *ch;
674   uint16_t size;
675
676   size = ntohs (message->header.size);
677   if (sizeof (*message) + sizeof (struct GNUNET_MessageHeader) > size)
678   {
679     GNUNET_break_op (0);
680     return GNUNET_SYSERR;
681   }
682
683   ch = retrieve_channel (h,
684                          message->ccn);
685   if (NULL == ch)
686   {
687     GNUNET_break_op (0);
688     return GNUNET_SYSERR;
689   }
690
691   return GNUNET_OK;
692 }
693
694
695 /**
696  * Process the incoming data packets, call appropriate handlers.
697  *
698  * @param h       The cadet handle
699  * @param message A message encapsulating the data
700  */
701 static void
702 handle_local_data (void *cls,
703                    const struct GNUNET_CADET_LocalData *message)
704 {
705   struct GNUNET_CADET_Handle *h = cls;
706   const struct GNUNET_MessageHeader *payload;
707   const struct GNUNET_CADET_MessageHandler *handler;
708   struct GNUNET_CADET_Channel *ch;
709   unsigned int i;
710   uint16_t type;
711
712   ch = retrieve_channel (h,
713                          message->ccn);
714   GNUNET_assert (NULL != ch);
715
716   payload = (struct GNUNET_MessageHeader *) &message[1];
717   type = ntohs (payload->type);
718   LOG (GNUNET_ERROR_TYPE_DEBUG,
719        "Got a %s data on channel %s [%X] of type %s (%u)\n",
720        GC_f2s (ntohl (ch->ccn.channel_of_client) >=
721                GNUNET_CADET_LOCAL_CHANNEL_ID_CLI),
722        GNUNET_i2s (GNUNET_PEER_resolve2 (ch->peer)),
723        ntohl (message->ccn.channel_of_client),
724        GC_m2s (type),
725        type);
726
727   for (i = 0; i < h->n_handlers; i++)
728   {
729     handler = &h->message_handlers[i];
730     if (handler->type == type)
731     {
732       if (GNUNET_OK !=
733           handler->callback (h->cls,
734                              ch,
735                              &ch->ctx,
736                              payload))
737       {
738         LOG (GNUNET_ERROR_TYPE_DEBUG,
739              "callback caused disconnection\n");
740         GNUNET_CADET_channel_destroy (ch);
741         break;
742       }
743       break;
744     }
745   }
746 }
747
748
749 /**
750  * Process a local ACK message, enabling the client to send
751  * more data to the service.
752  *
753  * @param h Cadet handle.
754  * @param message Message itself.
755  */
756 static void
757 handle_local_ack (void *cls,
758                   const struct GNUNET_CADET_LocalAck *message)
759 {
760   struct GNUNET_CADET_Handle *h = cls;
761   struct GNUNET_CADET_Channel *ch;
762   struct GNUNET_CADET_ClientChannelNumber ccn;
763   struct GNUNET_CADET_TransmitHandle *th;
764
765   ccn = message->ccn;
766   ch = retrieve_channel (h, ccn);
767   if (NULL == ch)
768   {
769     LOG (GNUNET_ERROR_TYPE_DEBUG,
770          "ACK on unknown channel %X\n",
771          ntohl (ccn.channel_of_client));
772     return;
773   }
774   ch->allow_send++;
775   LOG (GNUNET_ERROR_TYPE_DEBUG,
776        "Got an ACK on channel %X, allow send now %u!\n",
777        ntohl (ch->ccn.channel_of_client),
778        ch->allow_send);
779   for (th = h->th_head; NULL != th; th = th->next)
780   {
781     if ( (th->channel == ch) &&
782          (NULL == th->request_data_task) )
783     {
784       th->request_data_task
785         = GNUNET_SCHEDULER_add_now (&request_data,
786                                     th);
787       break;
788     }
789   }
790 }
791
792 /**
793  * Reconnect to the service, retransmit all infomation to try to restore the
794  * original state.
795  *
796  * @param h handle to the cadet
797  *
798  * @return #GNUNET_YES in case of sucess, #GNUNET_NO otherwise (service down...)
799  */
800 static void
801 reconnect (struct GNUNET_CADET_Handle *h);
802
803
804 /**
805  * Reconnect callback: tries to reconnect again after a failer previous
806  * reconnection.
807  *
808  * @param cls closure (cadet handle)
809  */
810 static void
811 reconnect_cbk (void *cls);
812
813
814 /**
815  * Generic error handler, called with the appropriate error code and
816  * the same closure specified at the creation of the message queue.
817  * Not every message queue implementation supports an error handler.
818  *
819  * @param cls closure, a `struct GNUNET_CORE_Handle *`
820  * @param error error code
821  */
822 static void
823 handle_mq_error (void *cls,
824                  enum GNUNET_MQ_Error error)
825 {
826   struct GNUNET_CADET_Handle *h = cls;
827
828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MQ ERROR: %u\n", error);
829   GNUNET_MQ_destroy (h->mq);
830   h->mq = NULL;
831   reconnect (h);
832 }
833
834
835 /*
836  * Process a local reply about info on all channels, pass info to the user.
837  *
838  * @param h Cadet handle.
839  * @param message Message itself.
840  */
841 // static void
842 // process_get_channels (struct GNUNET_CADET_Handle *h,
843 //                      const struct GNUNET_MessageHeader *message)
844 // {
845 //   struct GNUNET_CADET_LocalInfo *msg;
846 //
847 //   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Get Channels messasge received\n");
848 //
849 //   if (NULL == h->channels_cb)
850 //   {
851 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
852 //     return;
853 //   }
854 //
855 //   msg = (struct GNUNET_CADET_LocalInfo *) message;
856 //   if (ntohs (message->size) !=
857 //       (sizeof (struct GNUNET_CADET_LocalInfo) +
858 //        sizeof (struct GNUNET_PeerIdentity)))
859 //   {
860 //     GNUNET_break_op (0);
861 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
862 //                 "Get channels message: size %hu - expected %u\n",
863 //                 ntohs (message->size),
864 //                 sizeof (struct GNUNET_CADET_LocalInfo));
865 //     return;
866 //   }
867 //   h->channels_cb (h->channels_cls,
868 //                   ntohl (msg->channel_id),
869 //                   &msg->owner,
870 //                   &msg->destination);
871 // }
872
873
874
875 /*
876  * Process a local monitor_channel reply, pass info to the user.
877  *
878  * @param h Cadet handle.
879  * @param message Message itself.
880  */
881 // static void
882 // process_show_channel (struct GNUNET_CADET_Handle *h,
883 //                      const struct GNUNET_MessageHeader *message)
884 // {
885 //   struct GNUNET_CADET_LocalInfo *msg;
886 //   size_t esize;
887 //
888 //   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Show Channel messasge received\n");
889 //
890 //   if (NULL == h->channel_cb)
891 //   {
892 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "  ignored\n");
893 //     return;
894 //   }
895 //
896 //   /* Verify message sanity */
897 //   msg = (struct GNUNET_CADET_LocalInfo *) message;
898 //   esize = sizeof (struct GNUNET_CADET_LocalInfo);
899 //   if (ntohs (message->size) != esize)
900 //   {
901 //     GNUNET_break_op (0);
902 //     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
903 //                 "Show channel message: size %hu - expected %u\n",
904 //                 ntohs (message->size),
905 //                 esize);
906 //
907 //     h->channel_cb (h->channel_cls, NULL, NULL);
908 //     h->channel_cb = NULL;
909 //     h->channel_cls = NULL;
910 //
911 //     return;
912 //   }
913 //
914 //   h->channel_cb (h->channel_cls,
915 //                  &msg->destination,
916 //                  &msg->owner);
917 // }
918
919
920
921 /**
922  * Check that message received from CADET service is well-formed.
923  *
924  * @param cls the `struct GNUNET_CADET_Handle`
925  * @param message the message we got
926  * @return #GNUNET_OK if the message is well-formed,
927  *         #GNUNET_SYSERR otherwise
928  */
929 static int
930 check_get_peers (void *cls,
931                  const struct GNUNET_CADET_LocalInfoPeer *message)
932 {
933   struct GNUNET_CADET_Handle *h = cls;
934   uint16_t size;
935
936   if (NULL == h->info_cb.peers_cb)
937   {
938     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
939                 "  no handler for peesr monitor message!\n");
940     return GNUNET_SYSERR;
941   }
942
943   size = ntohs (message->header.size);
944   if (sizeof (struct GNUNET_CADET_LocalInfoPeer) > size)
945   {
946     h->info_cb.peers_cb (h->info_cls, NULL, -1, 0, 0);
947     h->info_cb.peers_cb = NULL;
948     h->info_cls = NULL;
949     return GNUNET_SYSERR;
950   }
951
952   return GNUNET_OK;
953 }
954
955
956 /**
957  * Process a local reply about info on all tunnels, pass info to the user.
958  *
959  * @param cls Closure (Cadet handle).
960  * @param msg Message itself.
961  */
962 static void
963 handle_get_peers (void *cls,
964                   const struct GNUNET_CADET_LocalInfoPeer *msg)
965 {
966   struct GNUNET_CADET_Handle *h = cls;
967   h->info_cb.peers_cb (h->info_cls, &msg->destination,
968                        (int) ntohs (msg->tunnel),
969                        (unsigned int ) ntohs (msg->paths),
970                        0);
971 }
972
973
974 /**
975  * Check that message received from CADET service is well-formed.
976  *
977  * @param cls the `struct GNUNET_CADET_Handle`
978  * @param message the message we got
979  * @return #GNUNET_OK if the message is well-formed,
980  *         #GNUNET_SYSERR otherwise
981  */
982 static int
983 check_get_peer (void *cls,
984                 const struct GNUNET_CADET_LocalInfoPeer *message)
985 {
986   struct GNUNET_CADET_Handle *h = cls;
987   const size_t msize = sizeof (struct GNUNET_CADET_LocalInfoPeer);
988   struct GNUNET_PeerIdentity *paths_array;
989   size_t esize;
990   unsigned int epaths;
991   unsigned int paths;
992   unsigned int peers;
993
994   if (NULL == h->info_cb.peer_cb)
995   {
996     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
997                 "  no handler for peer monitor message!\n");
998     goto clean_cls;
999   }
1000
1001   /* Verify message sanity */
1002   esize = ntohs (message->header.size);
1003   if (esize < msize)
1004   {
1005     GNUNET_break_op (0);
1006     h->info_cb.peer_cb (h->info_cls, NULL, 0, 0, 0, NULL);
1007     goto clean_cls;
1008   }
1009   if (0 != ((esize - msize) % sizeof (struct GNUNET_PeerIdentity)))
1010   {
1011     GNUNET_break_op (0);
1012     h->info_cb.peer_cb (h->info_cls, NULL, 0, 0, 0, NULL);
1013     goto clean_cls;
1014
1015   }
1016   peers = (esize - msize) / sizeof (struct GNUNET_PeerIdentity);
1017   epaths = (unsigned int) ntohs (message->paths);
1018   paths_array = (struct GNUNET_PeerIdentity *) &message[1];
1019   paths = 0;
1020   for (int i = 0; i < peers; i++)
1021   {
1022     if (0 == memcmp (&paths_array[i], &message->destination,
1023                      sizeof (struct GNUNET_PeerIdentity)))
1024     {
1025       paths++;
1026     }
1027   }
1028   if (paths != epaths)
1029   {
1030     GNUNET_break_op (0);
1031     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "p:%u, e: %u\n", paths, epaths);
1032     h->info_cb.peer_cb (h->info_cls, NULL, 0, 0, 0, NULL);
1033     goto clean_cls;
1034   }
1035
1036   return GNUNET_OK;
1037
1038 clean_cls:
1039   h->info_cb.peer_cb = NULL;
1040   h->info_cls = NULL;
1041   return GNUNET_SYSERR;
1042 }
1043
1044
1045 /**
1046  * Process a local peer info reply, pass info to the user.
1047  *
1048  * @param cls Closure (Cadet handle).
1049  * @param message Message itself.
1050  */
1051 static void
1052 handle_get_peer (void *cls,
1053                  const struct GNUNET_CADET_LocalInfoPeer *message)
1054 {
1055   struct GNUNET_CADET_Handle *h = cls;
1056   struct GNUNET_PeerIdentity *paths_array;
1057   unsigned int paths;
1058   unsigned int path_length;
1059   int neighbor;
1060   unsigned int peers;
1061
1062   paths = (unsigned int) ntohs (message->paths);
1063   paths_array = (struct GNUNET_PeerIdentity *) &message[1];
1064   peers = (ntohs (message->header.size) - sizeof (*message))
1065           / sizeof (struct GNUNET_PeerIdentity);
1066   path_length = 0;
1067   neighbor = GNUNET_NO;
1068
1069   for (int i = 0; i < peers; i++)
1070   {
1071     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " %s\n", GNUNET_i2s (&paths_array[i]));
1072     path_length++;
1073     if (0 == memcmp (&paths_array[i], &message->destination,
1074                      sizeof (struct GNUNET_PeerIdentity)))
1075     {
1076       if (1 == path_length)
1077         neighbor = GNUNET_YES;
1078       path_length = 0;
1079     }
1080   }
1081
1082   /* Call Callback with tunnel info. */
1083   paths_array = (struct GNUNET_PeerIdentity *) &message[1];
1084   h->info_cb.peer_cb (h->info_cls,
1085                       &message->destination,
1086                       (int) ntohs (message->tunnel),
1087                       neighbor,
1088                       paths,
1089                       paths_array);
1090 }
1091
1092
1093 /**
1094  * Check that message received from CADET service is well-formed.
1095  *
1096  * @param cls the `struct GNUNET_CADET_Handle`
1097  * @param msg the message we got
1098  * @return #GNUNET_OK if the message is well-formed,
1099  *         #GNUNET_SYSERR otherwise
1100  */
1101 static int
1102 check_get_tunnels (void *cls,
1103                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1104 {
1105   struct GNUNET_CADET_Handle *h = cls;
1106   uint16_t size;
1107
1108   if (NULL == h->info_cb.tunnels_cb)
1109   {
1110     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1111                 "  no handler for tunnels monitor message!\n");
1112     return GNUNET_SYSERR;
1113   }
1114
1115   size = ntohs (msg->header.size);
1116   if (sizeof (struct GNUNET_CADET_LocalInfoTunnel) > size)
1117   {
1118     h->info_cb.tunnels_cb (h->info_cls, NULL, 0, 0, 0, 0);
1119     h->info_cb.tunnels_cb = NULL;
1120     h->info_cls = NULL;
1121     return GNUNET_SYSERR;
1122   }
1123   return GNUNET_OK;
1124 }
1125
1126
1127 /**
1128  * Process a local reply about info on all tunnels, pass info to the user.
1129  *
1130  * @param cls Closure (Cadet handle).
1131  * @param message Message itself.
1132  */
1133 static void
1134 handle_get_tunnels (void *cls,
1135                     const struct GNUNET_CADET_LocalInfoTunnel *msg)
1136 {
1137   struct GNUNET_CADET_Handle *h = cls;
1138
1139   h->info_cb.tunnels_cb (h->info_cls,
1140                          &msg->destination,
1141                          ntohl (msg->channels),
1142                          ntohl (msg->connections),
1143                          ntohs (msg->estate),
1144                          ntohs (msg->cstate));
1145
1146 }
1147
1148
1149 /**
1150  * Check that message received from CADET service is well-formed.
1151  *
1152  * @param cls the `struct GNUNET_CADET_Handle`
1153  * @param msg the message we got
1154  * @return #GNUNET_OK if the message is well-formed,
1155  *         #GNUNET_SYSERR otherwise
1156  */
1157 static int
1158 check_get_tunnel (void *cls,
1159                   const struct GNUNET_CADET_LocalInfoTunnel *msg)
1160 {
1161   struct GNUNET_CADET_Handle *h = cls;
1162   unsigned int ch_n;
1163   unsigned int c_n;
1164   size_t esize;
1165   size_t msize;
1166
1167   if (NULL == h->info_cb.tunnel_cb)
1168   {
1169     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1170                 "  no handler for tunnel monitor message!\n");
1171     goto clean_cls;
1172   }
1173
1174   /* Verify message sanity */
1175   msize = ntohs (msg->header.size);
1176   esize = sizeof (struct GNUNET_CADET_LocalInfoTunnel);
1177   if (esize > msize)
1178   {
1179     GNUNET_break_op (0);
1180     h->info_cb.tunnel_cb (h->info_cls,
1181                           NULL, 0, 0, NULL, NULL, 0, 0);
1182     goto clean_cls;
1183   }
1184   ch_n = ntohl (msg->channels);
1185   c_n = ntohl (msg->connections);
1186   esize += ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber);
1187   esize += c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier);
1188   if (msize != esize)
1189   {
1190     GNUNET_break_op (0);
1191     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192                 "m:%u, e: %u (%u ch, %u conn)\n",
1193                 (unsigned int) msize,
1194                 (unsigned int) esize,
1195                 ch_n,
1196                 c_n);
1197     h->info_cb.tunnel_cb (h->info_cls,
1198                           NULL, 0, 0, NULL, NULL, 0, 0);
1199     goto clean_cls;
1200   }
1201
1202   return GNUNET_OK;
1203
1204 clean_cls:
1205   h->info_cb.tunnel_cb = NULL;
1206   h->info_cls = NULL;
1207   return GNUNET_SYSERR;
1208 }
1209
1210
1211 /**
1212  * Process a local tunnel info reply, pass info to the user.
1213  *
1214  * @param cls Closure (Cadet handle).
1215  * @param msg Message itself.
1216  */
1217 static void
1218 handle_get_tunnel (void *cls,
1219                    const struct GNUNET_CADET_LocalInfoTunnel *msg)
1220 {
1221   struct GNUNET_CADET_Handle *h = cls;
1222   unsigned int ch_n;
1223   unsigned int c_n;
1224   const struct GNUNET_CADET_ConnectionTunnelIdentifier *conns;
1225   const struct GNUNET_CADET_ChannelTunnelNumber *chns;
1226
1227   ch_n = ntohl (msg->channels);
1228   c_n = ntohl (msg->connections);
1229
1230   /* Call Callback with tunnel info. */
1231   conns = (const struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
1232   chns = (const struct GNUNET_CADET_ChannelTunnelNumber *) &conns[c_n];
1233   h->info_cb.tunnel_cb (h->info_cls,
1234                         &msg->destination,
1235                         ch_n,
1236                         c_n,
1237                         chns,
1238                         conns,
1239                         ntohs (msg->estate),
1240                         ntohs (msg->cstate));
1241 }
1242
1243
1244
1245 /**
1246  * Reconnect to the service, retransmit all infomation to try to restore the
1247  * original state.
1248  *
1249  * @param h handle to the cadet
1250  * @return #GNUNET_YES in case of success, #GNUNET_NO otherwise (service down...)
1251  */
1252 static int
1253 do_reconnect (struct GNUNET_CADET_Handle *h)
1254 {
1255   struct GNUNET_MQ_MessageHandler handlers[] = {
1256     GNUNET_MQ_hd_fixed_size (channel_created,
1257                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1258                              struct GNUNET_CADET_LocalChannelCreateMessage,
1259                              h),
1260     GNUNET_MQ_hd_fixed_size (channel_destroy,
1261                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1262                              struct GNUNET_CADET_LocalChannelDestroyMessage,
1263                              h),
1264     GNUNET_MQ_hd_var_size (local_data,
1265                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1266                            struct GNUNET_CADET_LocalData,
1267                            h),
1268     GNUNET_MQ_hd_fixed_size (local_ack,
1269                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1270                              struct GNUNET_CADET_LocalAck,
1271                              h),
1272     GNUNET_MQ_hd_var_size (get_peers,
1273                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1274                            struct GNUNET_CADET_LocalInfoPeer,
1275                            h),
1276     GNUNET_MQ_hd_var_size (get_peer,
1277                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1278                            struct GNUNET_CADET_LocalInfoPeer,
1279                            h),
1280     GNUNET_MQ_hd_var_size (get_tunnels,
1281                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1282                            struct GNUNET_CADET_LocalInfoTunnel,
1283                            h),
1284     GNUNET_MQ_hd_var_size (get_tunnel,
1285                            GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1286                            struct GNUNET_CADET_LocalInfoTunnel,
1287                            h),
1288   // FIXME
1289 //   GNUNET_MQ_hd_fixed_Y       size (channel_destroyed,
1290 //                            GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN_NACK_DEPRECATED,
1291 //                            struct GNUNET_CADET_ChannelDestroyMessage);
1292     GNUNET_MQ_handler_end ()
1293   };
1294
1295   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connecting to CADET\n");
1296
1297   GNUNET_assert (NULL == h->mq);
1298   h->mq = GNUNET_CLIENT_connect (h->cfg,
1299                                  "cadet",
1300                                  handlers,
1301                                  &handle_mq_error,
1302                                  h);
1303   if (NULL == h->mq)
1304   {
1305     reconnect (h);
1306     return GNUNET_NO;
1307   }
1308   else
1309   {
1310     h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1311   }
1312   return GNUNET_YES;
1313 }
1314
1315 /**
1316  * Reconnect callback: tries to reconnect again after a failer previous
1317  * reconnecttion
1318  *
1319  * @param cls closure (cadet handle)
1320  */
1321 static void
1322 reconnect_cbk (void *cls)
1323 {
1324   struct GNUNET_CADET_Handle *h = cls;
1325
1326   h->reconnect_task = NULL;
1327   do_reconnect (h);
1328 }
1329
1330
1331 /**
1332  * Reconnect to the service, retransmit all infomation to try to restore the
1333  * original state.
1334  *
1335  * @param h handle to the cadet
1336  *
1337  * @return #GNUNET_YES in case of sucess, #GNUNET_NO otherwise (service down...)
1338  */
1339 static void
1340 reconnect (struct GNUNET_CADET_Handle *h)
1341 {
1342   struct GNUNET_CADET_Channel *ch;
1343
1344   LOG (GNUNET_ERROR_TYPE_DEBUG,
1345        "Requested RECONNECT, destroying all channels\n");
1346   while (NULL != (ch = h->channels_head))
1347     destroy_channel (ch, GNUNET_YES);
1348   if (NULL == h->reconnect_task)
1349     h->reconnect_task = GNUNET_SCHEDULER_add_delayed (h->reconnect_time,
1350                                                       &reconnect_cbk, h);
1351 }
1352
1353
1354 /******************************************************************************/
1355 /**********************      API CALL DEFINITIONS     *************************/
1356 /******************************************************************************/
1357
1358 struct GNUNET_CADET_Handle *
1359 GNUNET_CADET_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
1360                       void *cls,
1361                       GNUNET_CADET_ChannelEndHandler cleaner,
1362                       const struct GNUNET_CADET_MessageHandler *handlers)
1363 {
1364   struct GNUNET_CADET_Handle *h;
1365
1366   h = GNUNET_new (struct GNUNET_CADET_Handle);
1367   LOG (GNUNET_ERROR_TYPE_DEBUG,
1368        "GNUNET_CADET_connect() %p\n",
1369        h);
1370   h->cfg = cfg;
1371   h->cleaner = cleaner;
1372   h->ports = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_YES);
1373   do_reconnect (h);
1374   if (h->mq == NULL)
1375   {
1376     GNUNET_break (0);
1377     GNUNET_CADET_disconnect (h);
1378     return NULL;
1379   }
1380   h->cls = cls;
1381   h->message_handlers = handlers;
1382   h->next_ccn.channel_of_client = htonl (GNUNET_CADET_LOCAL_CHANNEL_ID_CLI);
1383   h->reconnect_time = GNUNET_TIME_UNIT_MILLISECONDS;
1384   h->reconnect_task = NULL;
1385
1386   /* count handlers */
1387   for (h->n_handlers = 0;
1388        handlers && handlers[h->n_handlers].type;
1389        h->n_handlers++) ;
1390   return h;
1391 }
1392
1393
1394 /**
1395  * Disconnect from the cadet service. All channels will be destroyed. All channel
1396  * disconnect callbacks will be called on any still connected peers, notifying
1397  * about their disconnection. The registered inbound channel cleaner will be
1398  * called should any inbound channels still exist.
1399  *
1400  * @param handle connection to cadet to disconnect
1401  */
1402 void
1403 GNUNET_CADET_disconnect (struct GNUNET_CADET_Handle *handle)
1404 {
1405   struct GNUNET_CADET_Channel *ch;
1406   struct GNUNET_CADET_Channel *aux;
1407   struct GNUNET_CADET_TransmitHandle *th;
1408
1409   LOG (GNUNET_ERROR_TYPE_DEBUG,
1410        "CADET DISCONNECT\n");
1411   ch = handle->channels_head;
1412   while (NULL != ch)
1413   {
1414     aux = ch->next;
1415     if (ntohl (ch->ccn.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1416     {
1417       GNUNET_break (0);
1418       LOG (GNUNET_ERROR_TYPE_DEBUG,
1419            "channel %X not destroyed\n",
1420            ntohl (ch->ccn.channel_of_client));
1421     }
1422     destroy_channel (ch,
1423                      GNUNET_YES);
1424     ch = aux;
1425   }
1426   while (NULL != (th = handle->th_head))
1427   {
1428     struct GNUNET_MessageHeader *msg;
1429
1430     /* Make sure it is an allowed packet (everything else should have been
1431      * already canceled).
1432      */
1433     GNUNET_break (GNUNET_NO == th_is_payload (th));
1434     msg = (struct GNUNET_MessageHeader *) &th[1];
1435     switch (ntohs(msg->type))
1436     {
1437       case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_OPEN:
1438       case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1439       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN:
1440       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE:
1441       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNELS:
1442       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL:
1443       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER:
1444       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS:
1445       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL:
1446       case GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS:
1447         break;
1448       default:
1449         GNUNET_break (0);
1450         LOG (GNUNET_ERROR_TYPE_ERROR, "unexpected unsent msg %s\n",
1451              GC_m2s (ntohs(msg->type)));
1452     }
1453
1454     GNUNET_CADET_notify_transmit_ready_cancel (th);
1455   }
1456
1457   if (NULL != handle->mq)
1458   {
1459     GNUNET_MQ_destroy (handle->mq);
1460     handle->mq = NULL;
1461   }
1462   if (NULL != handle->reconnect_task)
1463   {
1464     GNUNET_SCHEDULER_cancel(handle->reconnect_task);
1465     handle->reconnect_task = NULL;
1466   }
1467
1468   GNUNET_CONTAINER_multihashmap_destroy (handle->ports);
1469   handle->ports = NULL;
1470   GNUNET_free (handle);
1471 }
1472
1473
1474 /**
1475  * Open a port to receive incomming channels.
1476  *
1477  * @param h CADET handle.
1478  * @param port Hash representing the port number.
1479  * @param new_channel Function called when an channel is received.
1480  * @param new_channel_cls Closure for @a new_channel.
1481  * @return Port handle.
1482  */
1483 struct GNUNET_CADET_Port *
1484 GNUNET_CADET_open_port (struct GNUNET_CADET_Handle *h,
1485                         const struct GNUNET_HashCode *port,
1486                         GNUNET_CADET_InboundChannelNotificationHandler
1487                             new_channel,
1488                         void *new_channel_cls)
1489 {
1490   struct GNUNET_CADET_PortMessage *msg;
1491   struct GNUNET_MQ_Envelope *env;
1492   struct GNUNET_CADET_Port *p;
1493
1494   GNUNET_assert (NULL != new_channel);
1495   p = GNUNET_new (struct GNUNET_CADET_Port);
1496   p->cadet = h;
1497   p->hash = GNUNET_new (struct GNUNET_HashCode);
1498   *p->hash = *port;
1499   p->handler = new_channel;
1500   p->cls = new_channel_cls;
1501   GNUNET_assert (GNUNET_OK ==
1502                  GNUNET_CONTAINER_multihashmap_put (h->ports,
1503                                                     p->hash,
1504                                                     p,
1505                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1506
1507   env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN);
1508   msg->port = *p->hash;
1509   GNUNET_MQ_send (h->mq, env);
1510
1511   return p;
1512 }
1513
1514 /**
1515  * Close a port opened with @a GNUNET_CADET_open_port.
1516  * The @a new_channel callback will no longer be called.
1517  *
1518  * @param p Port handle.
1519  */
1520 void
1521 GNUNET_CADET_close_port (struct GNUNET_CADET_Port *p)
1522 {
1523   struct GNUNET_CADET_PortMessage *msg;
1524   struct GNUNET_MQ_Envelope *env;
1525
1526   env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE);
1527
1528   msg->port = *p->hash;
1529   GNUNET_MQ_send (p->cadet->mq, env);
1530   GNUNET_CONTAINER_multihashmap_remove (p->cadet->ports, p->hash, p);
1531   GNUNET_free (p->hash);
1532   GNUNET_free (p);
1533 }
1534
1535
1536 /**
1537  * Create a new channel towards a remote peer.
1538  *
1539  * If the destination port is not open by any peer or the destination peer
1540  * does not accept the channel, #GNUNET_CADET_ChannelEndHandler will be called
1541  * for this channel.
1542  *
1543  * @param h cadet handle
1544  * @param channel_ctx client's channel context to associate with the channel
1545  * @param peer peer identity the channel should go to
1546  * @param port Port hash (port number).
1547  * @param options CadetOption flag field, with all desired option bits set to 1.
1548  * @return handle to the channel
1549  */
1550 struct GNUNET_CADET_Channel *
1551 GNUNET_CADET_channel_create (struct GNUNET_CADET_Handle *h,
1552                             void *channel_ctx,
1553                             const struct GNUNET_PeerIdentity *peer,
1554                             const struct GNUNET_HashCode *port,
1555                             enum GNUNET_CADET_ChannelOption options)
1556 {
1557   struct GNUNET_CADET_LocalChannelCreateMessage *msg;
1558   struct GNUNET_MQ_Envelope *env;
1559   struct GNUNET_CADET_Channel *ch;
1560   struct GNUNET_CADET_ClientChannelNumber ccn;
1561
1562   ccn.channel_of_client = htonl (0);
1563   ch = create_channel (h, ccn);
1564   ch->ctx = channel_ctx;
1565   ch->peer = GNUNET_PEER_intern (peer);
1566
1567   LOG (GNUNET_ERROR_TYPE_DEBUG,
1568        "Creating new channel to %s:%u at %p number %X\n",
1569        GNUNET_i2s (peer),
1570        port,
1571        ch,
1572        ntohl (ch->ccn.channel_of_client));
1573   env = GNUNET_MQ_msg (msg,
1574                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE);
1575   msg->ccn = ch->ccn;
1576   msg->port = *port;
1577   msg->peer = *peer;
1578   msg->opt = htonl (options);
1579   GNUNET_MQ_send (h->mq,
1580                   env);
1581   return ch;
1582 }
1583
1584
1585 void
1586 GNUNET_CADET_channel_destroy (struct GNUNET_CADET_Channel *channel)
1587 {
1588   struct GNUNET_CADET_Handle *h;
1589   struct GNUNET_CADET_LocalChannelDestroyMessage *msg;
1590   struct GNUNET_MQ_Envelope *env;
1591   struct GNUNET_CADET_TransmitHandle *th;
1592   struct GNUNET_CADET_TransmitHandle *next;
1593
1594   LOG (GNUNET_ERROR_TYPE_DEBUG,
1595        "Destroying channel\n");
1596   h = channel->cadet;
1597   for  (th = h->th_head; th != NULL; th = next)
1598   {
1599     next = th->next;
1600     if (th->channel == channel)
1601     {
1602       GNUNET_break (0);
1603       if (GNUNET_YES == th_is_payload (th))
1604       {
1605         /* applications should cancel before destroying channel */
1606         LOG (GNUNET_ERROR_TYPE_WARNING,
1607              "Channel destroyed without cancelling transmission requests\n");
1608         th->notify (th->notify_cls, 0, NULL);
1609       }
1610       else
1611       {
1612         LOG (GNUNET_ERROR_TYPE_WARNING,
1613              "no meta-traffic should be queued\n");
1614       }
1615       GNUNET_CONTAINER_DLL_remove (h->th_head,
1616                                    h->th_tail,
1617                                    th);
1618       GNUNET_CADET_notify_transmit_ready_cancel (th);
1619     }
1620   }
1621
1622   env = GNUNET_MQ_msg (msg,
1623                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1624   msg->ccn = channel->ccn;
1625   GNUNET_MQ_send (h->mq,
1626                   env);
1627
1628   destroy_channel (channel,
1629                    GNUNET_YES);
1630 }
1631
1632
1633 /**
1634  * Get information about a channel.
1635  *
1636  * @param channel Channel handle.
1637  * @param option Query (GNUNET_CADET_OPTION_*).
1638  * @param ... dependant on option, currently not used
1639  *
1640  * @return Union with an answer to the query.
1641  */
1642 const union GNUNET_CADET_ChannelInfo *
1643 GNUNET_CADET_channel_get_info (struct GNUNET_CADET_Channel *channel,
1644                               enum GNUNET_CADET_ChannelOption option, ...)
1645 {
1646   static int bool_flag;
1647   const union GNUNET_CADET_ChannelInfo *ret;
1648
1649   switch (option)
1650   {
1651     case GNUNET_CADET_OPTION_NOBUFFER:
1652     case GNUNET_CADET_OPTION_RELIABLE:
1653     case GNUNET_CADET_OPTION_OUT_OF_ORDER:
1654       if (0 != (option & channel->options))
1655         bool_flag = GNUNET_YES;
1656       else
1657         bool_flag = GNUNET_NO;
1658       ret = (const union GNUNET_CADET_ChannelInfo *) &bool_flag;
1659       break;
1660     case GNUNET_CADET_OPTION_PEER:
1661       ret = (const union GNUNET_CADET_ChannelInfo *) GNUNET_PEER_resolve2 (channel->peer);
1662       break;
1663     default:
1664       GNUNET_break (0);
1665       return NULL;
1666   }
1667
1668   return ret;
1669 }
1670
1671
1672 struct GNUNET_CADET_TransmitHandle *
1673 GNUNET_CADET_notify_transmit_ready (struct GNUNET_CADET_Channel *channel,
1674                                     int cork,
1675                                     struct GNUNET_TIME_Relative maxdelay,
1676                                     size_t notify_size,
1677                                     GNUNET_CONNECTION_TransmitReadyNotify notify,
1678                                     void *notify_cls)
1679 {
1680   struct GNUNET_CADET_TransmitHandle *th;
1681
1682   GNUNET_assert (NULL != channel);
1683   GNUNET_assert (NULL != notify);
1684   GNUNET_assert (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE >= notify_size);
1685   LOG (GNUNET_ERROR_TYPE_DEBUG,
1686        "CADET NOTIFY TRANSMIT READY on channel %X allow_send is %u to %s with %u bytes\n",
1687        channel->ccn,
1688        channel->allow_send,
1689        (ntohl (channel->ccn.channel_of_client) >=
1690         GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1691        ? "origin"
1692        : "destination",
1693        (unsigned int) notify_size);
1694   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us != maxdelay.rel_value_us)
1695   {
1696     LOG (GNUNET_ERROR_TYPE_WARNING,
1697          "CADET transmit ready timeout is deprected (has no effect)\n");
1698   }
1699
1700   th = GNUNET_new (struct GNUNET_CADET_TransmitHandle);
1701   th->channel = channel;
1702   th->size = notify_size;
1703   th->notify = notify;
1704   th->notify_cls = notify_cls;
1705   if (0 != channel->allow_send)
1706     th->request_data_task
1707       = GNUNET_SCHEDULER_add_now (&request_data,
1708                                   th);
1709   else
1710     add_to_queue (channel->cadet,
1711                   th);
1712   return th;
1713 }
1714
1715
1716 void
1717 GNUNET_CADET_notify_transmit_ready_cancel (struct GNUNET_CADET_TransmitHandle *th)
1718 {
1719   if (NULL != th->request_data_task)
1720   {
1721     GNUNET_SCHEDULER_cancel (th->request_data_task);
1722     th->request_data_task = NULL;
1723   }
1724   remove_from_queue (th);
1725   GNUNET_free (th);
1726 }
1727
1728
1729 /**
1730  * Send an ack on the channel to confirm the processing of a message.
1731  *
1732  * @param ch Channel on which to send the ACK.
1733  */
1734 void
1735 GNUNET_CADET_receive_done (struct GNUNET_CADET_Channel *channel)
1736 {
1737   struct GNUNET_CADET_LocalAck *msg;
1738   struct GNUNET_MQ_Envelope *env;
1739
1740   env = GNUNET_MQ_msg (msg,
1741                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK);
1742   LOG (GNUNET_ERROR_TYPE_DEBUG,
1743        "Sending ACK on channel %X\n",
1744        channel->ccn.channel_of_client);
1745   msg->ccn = channel->ccn;
1746   GNUNET_MQ_send (channel->cadet->mq,
1747                   env);
1748 }
1749
1750
1751 static void
1752 send_info_request (struct GNUNET_CADET_Handle *h, uint16_t type)
1753 {
1754   struct GNUNET_MessageHeader *msg;
1755   struct GNUNET_MQ_Envelope *env;
1756
1757   LOG (GNUNET_ERROR_TYPE_DEBUG,
1758        " Sending %s monitor message to service\n",
1759        GC_m2s(type));
1760
1761   env = GNUNET_MQ_msg (msg, type);
1762   GNUNET_MQ_send (h->mq, env);
1763 }
1764
1765
1766 /**
1767  * Request a debug dump on the service's STDERR.
1768  *
1769  * WARNING: unstable API, likely to change in the future!
1770  *
1771  * @param h cadet handle
1772  */
1773 void
1774 GNUNET_CADET_request_dump (struct GNUNET_CADET_Handle *h)
1775 {
1776   LOG (GNUNET_ERROR_TYPE_DEBUG, "requesting dump\n");
1777   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP);
1778 }
1779
1780
1781 /**
1782  * Request information about peers known to the running cadet service.
1783  * The callback will be called for every peer known to the service.
1784  * Only one info request (of any kind) can be active at once.
1785  *
1786  *
1787  * WARNING: unstable API, likely to change in the future!
1788  *
1789  * @param h Handle to the cadet peer.
1790  * @param callback Function to call with the requested data.
1791  * @param callback_cls Closure for @c callback.
1792  *
1793  * @return #GNUNET_OK / #GNUNET_SYSERR
1794  */
1795 int
1796 GNUNET_CADET_get_peers (struct GNUNET_CADET_Handle *h,
1797                        GNUNET_CADET_PeersCB callback,
1798                        void *callback_cls)
1799 {
1800   if (NULL != h->info_cb.peers_cb)
1801   {
1802     GNUNET_break (0);
1803     return GNUNET_SYSERR;
1804   }
1805   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
1806   h->info_cb.peers_cb = callback;
1807   h->info_cls = callback_cls;
1808   return GNUNET_OK;
1809 }
1810
1811
1812 /**
1813  * Cancel a peer info request. The callback will not be called (anymore).
1814  *
1815  * WARNING: unstable API, likely to change in the future!
1816  *
1817  * @param h Cadet handle.
1818  *
1819  * @return Closure given to GNUNET_CADET_get_peers.
1820  */
1821 void *
1822 GNUNET_CADET_get_peers_cancel (struct GNUNET_CADET_Handle *h)
1823 {
1824   void *cls;
1825
1826   cls = h->info_cls;
1827   h->info_cb.peers_cb = NULL;
1828   h->info_cls = NULL;
1829   return cls;
1830 }
1831
1832
1833 /**
1834  * Request information about a peer known to the running cadet peer.
1835  * The callback will be called for the tunnel once.
1836  * Only one info request (of any kind) can be active at once.
1837  *
1838  * WARNING: unstable API, likely to change in the future!
1839  *
1840  * @param h Handle to the cadet peer.
1841  * @param id Peer whose tunnel to examine.
1842  * @param callback Function to call with the requested data.
1843  * @param callback_cls Closure for @c callback.
1844  *
1845  * @return #GNUNET_OK / #GNUNET_SYSERR
1846  */
1847 int
1848 GNUNET_CADET_get_peer (struct GNUNET_CADET_Handle *h,
1849                        const struct GNUNET_PeerIdentity *id,
1850                        GNUNET_CADET_PeerCB callback,
1851                        void *callback_cls)
1852 {
1853   struct GNUNET_CADET_LocalInfo *msg;
1854   struct GNUNET_MQ_Envelope *env;
1855
1856   if (NULL != h->info_cb.peer_cb)
1857   {
1858     GNUNET_break (0);
1859     return GNUNET_SYSERR;
1860   }
1861
1862   env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
1863   msg->peer = *id;
1864   GNUNET_MQ_send (h->mq, env);
1865
1866   h->info_cb.peer_cb = callback;
1867   h->info_cls = callback_cls;
1868   return GNUNET_OK;
1869 }
1870
1871
1872 /**
1873  * Request information about tunnels of the running cadet peer.
1874  * The callback will be called for every tunnel of the service.
1875  * Only one info request (of any kind) can be active at once.
1876  *
1877  * WARNING: unstable API, likely to change in the future!
1878  *
1879  * @param h Handle to the cadet peer.
1880  * @param callback Function to call with the requested data.
1881  * @param callback_cls Closure for @c callback.
1882  *
1883  * @return #GNUNET_OK / #GNUNET_SYSERR
1884  */
1885 int
1886 GNUNET_CADET_get_tunnels (struct GNUNET_CADET_Handle *h,
1887                          GNUNET_CADET_TunnelsCB callback,
1888                          void *callback_cls)
1889 {
1890   if (NULL != h->info_cb.tunnels_cb)
1891   {
1892     GNUNET_break (0);
1893     return GNUNET_SYSERR;
1894   }
1895   send_info_request (h, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
1896   h->info_cb.tunnels_cb = callback;
1897   h->info_cls = callback_cls;
1898   return GNUNET_OK;
1899 }
1900
1901
1902 /**
1903  * Cancel a monitor request. The monitor callback will not be called.
1904  *
1905  * @param h Cadet handle.
1906  *
1907  * @return Closure given to GNUNET_CADET_get_tunnels.
1908  */
1909 void *
1910 GNUNET_CADET_get_tunnels_cancel (struct GNUNET_CADET_Handle *h)
1911 {
1912   void *cls;
1913
1914   h->info_cb.tunnels_cb = NULL;
1915   cls = h->info_cls;
1916   h->info_cls = NULL;
1917
1918   return cls;
1919 }
1920
1921
1922
1923 /**
1924  * Request information about a tunnel of the running cadet peer.
1925  * The callback will be called for the tunnel once.
1926  * Only one info request (of any kind) can be active at once.
1927  *
1928  * WARNING: unstable API, likely to change in the future!
1929  *
1930  * @param h Handle to the cadet peer.
1931  * @param id Peer whose tunnel to examine.
1932  * @param callback Function to call with the requested data.
1933  * @param callback_cls Closure for @c callback.
1934  *
1935  * @return #GNUNET_OK / #GNUNET_SYSERR
1936  */
1937 int
1938 GNUNET_CADET_get_tunnel (struct GNUNET_CADET_Handle *h,
1939                         const struct GNUNET_PeerIdentity *id,
1940                         GNUNET_CADET_TunnelCB callback,
1941                         void *callback_cls)
1942 {
1943   struct GNUNET_CADET_LocalInfo *msg;
1944   struct GNUNET_MQ_Envelope *env;
1945
1946   if (NULL != h->info_cb.tunnel_cb)
1947   {
1948     GNUNET_break (0);
1949     return GNUNET_SYSERR;
1950   }
1951
1952   env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1953   msg->peer = *id;
1954   GNUNET_MQ_send (h->mq, env);
1955
1956   h->info_cb.tunnel_cb = callback;
1957   h->info_cls = callback_cls;
1958   return GNUNET_OK;
1959 }
1960
1961
1962 /**
1963  * Request information about a specific channel of the running cadet peer.
1964  *
1965  * WARNING: unstable API, likely to change in the future!
1966  * FIXME Add destination option.
1967  *
1968  * @param h Handle to the cadet peer.
1969  * @param initiator ID of the owner of the channel.
1970  * @param channel_number Channel number.
1971  * @param callback Function to call with the requested data.
1972  * @param callback_cls Closure for @c callback.
1973  *
1974  * @return #GNUNET_OK / #GNUNET_SYSERR
1975  */
1976 int
1977 GNUNET_CADET_show_channel (struct GNUNET_CADET_Handle *h,
1978                            struct GNUNET_PeerIdentity *initiator,
1979                            unsigned int channel_number,
1980                            GNUNET_CADET_ChannelCB callback,
1981                            void *callback_cls)
1982 {
1983   struct GNUNET_CADET_LocalInfo *msg;
1984   struct GNUNET_MQ_Envelope *env;
1985
1986   if (NULL != h->info_cb.channel_cb)
1987   {
1988     GNUNET_break (0);
1989     return GNUNET_SYSERR;
1990   }
1991
1992   env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_CHANNEL);
1993   msg->peer = *initiator;
1994   msg->ccn.channel_of_client = htonl (channel_number);
1995   GNUNET_MQ_send (h->mq, env);
1996
1997   h->info_cb.channel_cb = callback;
1998   h->info_cls = callback_cls;
1999   return GNUNET_OK;
2000 }
2001
2002
2003 /**
2004  * Function called to notify a client about the connection
2005  * begin ready to queue more data.  "buf" will be
2006  * NULL and "size" zero if the connection was closed for
2007  * writing in the meantime.
2008  *
2009  * @param cls closure
2010  * @param size number of bytes available in buf
2011  * @param buf where the callee should write the message
2012  * @return number of bytes written to buf
2013  */
2014 static size_t
2015 cadet_mq_ntr (void *cls, size_t size,
2016              void *buf)
2017 {
2018   struct GNUNET_MQ_Handle *mq = cls;
2019   struct CadetMQState *state = GNUNET_MQ_impl_state (mq);
2020   const struct GNUNET_MessageHeader *msg = GNUNET_MQ_impl_current (mq);
2021   uint16_t msize;
2022
2023   state->th = NULL;
2024   if (NULL == buf)
2025   {
2026     GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_WRITE);
2027     return 0;
2028   }
2029   msize = ntohs (msg->size);
2030   GNUNET_assert (msize <= size);
2031   GNUNET_memcpy (buf, msg, msize);
2032   GNUNET_MQ_impl_send_continue (mq);
2033   return msize;
2034 }
2035
2036
2037 /**
2038  * Signature of functions implementing the
2039  * sending functionality of a message queue.
2040  *
2041  * @param mq the message queue
2042  * @param msg the message to send
2043  * @param impl_state state of the implementation
2044  */
2045 static void
2046 cadet_mq_send_impl (struct GNUNET_MQ_Handle *mq,
2047                     const struct GNUNET_MessageHeader *msg,
2048                     void *impl_state)
2049 {
2050   struct CadetMQState *state = impl_state;
2051
2052   GNUNET_assert (NULL == state->th);
2053   state->th =
2054       GNUNET_CADET_notify_transmit_ready (state->channel,
2055                                          /* FIXME: add option for corking */
2056                                          GNUNET_NO,
2057                                          GNUNET_TIME_UNIT_FOREVER_REL,
2058                                          ntohs (msg->size),
2059                                          &cadet_mq_ntr, mq);
2060
2061 }
2062
2063
2064 /**
2065  * Signature of functions implementing the
2066  * destruction of a message queue.
2067  * Implementations must not free 'mq', but should
2068  * take care of 'impl_state'.
2069  *
2070  * @param mq the message queue to destroy
2071  * @param impl_state state of the implementation
2072  */
2073 static void
2074 cadet_mq_destroy_impl (struct GNUNET_MQ_Handle *mq,
2075                        void *impl_state)
2076 {
2077   struct CadetMQState *state = impl_state;
2078
2079   if (NULL != state->th)
2080     GNUNET_CADET_notify_transmit_ready_cancel (state->th);
2081
2082   GNUNET_free (state);
2083 }
2084
2085
2086 /**
2087  * Create a message queue for a cadet channel.
2088  * The message queue can only be used to transmit messages,
2089  * not to receive them.
2090  *
2091  * @param channel the channel to create the message qeue for
2092  * @return a message queue to messages over the channel
2093  */
2094 struct GNUNET_MQ_Handle *
2095 GNUNET_CADET_mq_create (struct GNUNET_CADET_Channel *channel)
2096 {
2097   struct GNUNET_MQ_Handle *mq;
2098   struct CadetMQState *state;
2099
2100   state = GNUNET_new (struct CadetMQState);
2101   state->channel = channel;
2102
2103   mq = GNUNET_MQ_queue_for_callbacks (&cadet_mq_send_impl,
2104                                       &cadet_mq_destroy_impl,
2105                                       NULL, /* FIXME: cancel impl. */
2106                                       state,
2107                                       NULL, /* no msg handlers */
2108                                       NULL, /* no err handlers */
2109                                       NULL); /* no handler cls */
2110   return mq;
2111 }
2112
2113
2114 /**
2115  * Transitional function to convert an unsigned int port to a hash value.
2116  * WARNING: local static value returned, NOT reentrant!
2117  * WARNING: do not use this function for new code!
2118  *
2119  * @param port Numerical port (unsigned int format).
2120  *
2121  * @return A GNUNET_HashCode usable for the new CADET API.
2122  */
2123 const struct GNUNET_HashCode *
2124 GC_u2h (uint32_t port)
2125 {
2126   static struct GNUNET_HashCode hash;
2127
2128   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2129               "This is a transitional function, "
2130               "use proper crypto hashes as CADET ports\n");
2131   GNUNET_CRYPTO_hash (&port, sizeof (port), &hash);
2132
2133   return &hash;
2134 }