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