74296a27e5b678bff3408cd619f3ad2eb5f33b56
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2013, 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 /**
22  * @file cadet/gnunet-service-cadet-new.c
23  * @brief GNUnet CADET service with encryption
24  * @author Bartlomiej Polot
25  * @author Christian Grothoff
26  *
27  * Dictionary:
28  * - peer: other cadet instance. If there is direct connection it's a neighbor.
29  * - path: series of directly connected peer from one peer to another.
30  * - connection: path which is being used in a tunnel.
31  * - tunnel: encrypted connection to a peer, neighbor or not.
32  * - channel: logical link between two clients, on the same or different peers.
33  *            have properties like reliability.
34  */
35
36 #include "platform.h"
37 #include "gnunet_util_lib.h"
38 #include "cadet.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet-service-cadet-new.h"
41 #include "gnunet-service-cadet-new_channel.h"
42 #include "gnunet-service-cadet-new_connection.h"
43 #include "gnunet-service-cadet-new_dht.h"
44 #include "gnunet-service-cadet-new_hello.h"
45 #include "gnunet-service-cadet-new_tunnels.h"
46 #include "gnunet-service-cadet-new_peer.h"
47 #include "gnunet-service-cadet-new_paths.h"
48
49 #define LOG(level, ...) GNUNET_log (level,__VA_ARGS__)
50
51
52 /**
53  * Struct containing information about a client of the service
54  */
55 struct CadetClient
56 {
57   /**
58    * Linked list next
59    */
60   struct CadetClient *next;
61
62   /**
63    * Linked list prev
64    */
65   struct CadetClient *prev;
66
67   /**
68    * Tunnels that belong to this client, indexed by local id
69    */
70   struct GNUNET_CONTAINER_MultiHashMap32 *own_channels;
71
72   /**
73    * Tunnels this client has accepted, indexed by incoming local id
74    */
75   struct GNUNET_CONTAINER_MultiHashMap32 *incoming_channels;
76
77   /**
78    * Channel ID for the next incoming channel.
79    */
80   struct GNUNET_CADET_ClientChannelNumber next_chid;
81
82   /**
83    * Handle to communicate with the client
84    */
85   struct GNUNET_MQ_Handle *mq;
86
87   /**
88    * Client handle.
89    */
90   struct GNUNET_SERVICE_Client *client;
91
92   /**
93    * Ports that this client has declared interest in.
94    * Indexed by port, contains *Client.
95    */
96   struct GNUNET_CONTAINER_MultiHashMap *ports;
97
98   /**
99    * Whether the client is active or shutting down (don't send confirmations
100    * to a client that is shutting down).
101    */
102   int shutting_down;
103
104   /**
105    * ID of the client, mainly for debug messages
106    */
107   unsigned int id;
108 };
109
110 /******************************************************************************/
111 /***********************      GLOBAL VARIABLES     ****************************/
112 /******************************************************************************/
113
114 /****************************** Global variables ******************************/
115
116 /**
117  * Handle to the statistics service.
118  */
119 struct GNUNET_STATISTICS_Handle *stats;
120
121 /**
122  * Handle to communicate with ATS.
123  */
124 struct GNUNET_ATS_ConnectivityHandle *ats_ch;
125
126 /**
127  * Local peer own ID.
128  */
129 struct GNUNET_PeerIdentity my_full_id;
130
131 /**
132  * Own private key.
133  */
134 struct GNUNET_CRYPTO_EddsaPrivateKey *my_private_key;
135
136 /**
137  * Signal that shutdown is happening: prevent recover measures.
138  */
139 int shutting_down;
140
141 /**
142  * DLL with all the clients, head.
143  */
144 static struct CadetClient *clients_head;
145
146 /**
147  * DLL with all the clients, tail.
148  */
149 static struct CadetClient *clients_tail;
150
151 /**
152  * Next ID to assign to a client.
153  */
154 static unsigned int next_client_id;
155
156 /**
157  * All ports clients of this peer have opened.
158  */
159 struct GNUNET_CONTAINER_MultiHashMap *open_ports;
160
161 /**
162  * Map from ports to channels where the ports were closed at the
163  * time we got the inbound connection.
164  * Indexed by port, contains `struct CadetChannel`.
165  */
166 struct GNUNET_CONTAINER_MultiHashMap *loose_channels;
167
168 /**
169  * Map from PIDs to `struct CadetPeer` entries.
170  */
171 struct GNUNET_CONTAINER_MultiPeerMap *peers;
172
173
174
175 /**
176  * Send a message to a client.
177  *
178  * @param c client to get the message
179  * @param env envelope with the message
180  */
181 void
182 GSC_send_to_client (struct CadetClient *c,
183                     struct GNUNET_MQ_Envelope *env)
184 {
185   GNUNET_MQ_send (c->mq,
186                   env);
187 }
188
189
190 /**
191  * Return identifier for a client as a string.
192  *
193  * @param c client to identify
194  * @return string for debugging
195  */
196 const char *
197 GSC_2s (struct CadetClient *c)
198 {
199   static char buf[32];
200
201   if (NULL == c)
202     return "Client(NULL)";
203   GNUNET_snprintf (buf,
204                    sizeof (buf),
205                    "Client(%u)",
206                    c->id);
207   return buf;
208 }
209
210
211 /**
212  * Obtain the next LID to use for incoming connections to
213  * the given client.
214  *
215  * @param c client handle
216  */
217 static struct GNUNET_CADET_ClientChannelNumber
218 client_get_next_lid (struct CadetClient *c)
219 {
220   struct GNUNET_CADET_ClientChannelNumber ccn = c->next_chid;
221
222   /* increment until we have a free one... */
223   while (NULL !=
224          GNUNET_CONTAINER_multihashmap32_get (c->incoming_channels,
225                                               ntohl (ccn.channel_of_client)))
226   {
227     ccn.channel_of_client
228       = htonl (1 + (ntohl (ccn.channel_of_client)));
229     if (ntohl (ccn.channel_of_client) >=
230         GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
231       ccn.channel_of_client = htonl (0);
232   }
233   c->next_chid.channel_of_client
234     = htonl (1 + (ntohl (ccn.channel_of_client)));
235   return ccn;
236 }
237
238
239 /**
240  * Bind incoming channel to this client, and notify client
241  * about incoming connection.
242  *
243  * @param c client to bind to
244  * @param ch channel to be bound
245  * @param dest peer that establishes the connection
246  * @param port port number
247  * @param options options
248  * @return local channel number assigned to the new client
249  */
250 struct GNUNET_CADET_ClientChannelNumber
251 GSC_bind (struct CadetClient *c,
252           struct CadetChannel *ch,
253           struct CadetPeer *dest,
254           const struct GNUNET_HashCode *port,
255           uint32_t options)
256 {
257   struct GNUNET_MQ_Envelope *env;
258   struct GNUNET_CADET_ChannelCreateMessage *msg;
259   struct GNUNET_CADET_ClientChannelNumber lid;
260
261   lid = client_get_next_lid (c);
262   GNUNET_assert (GNUNET_YES ==
263                  GNUNET_CONTAINER_multihashmap32_put (c->incoming_channels,
264                                                       ntohl (lid.channel_of_client),
265                                                       ch,
266                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
267
268   /* notify local client about incoming connection! */
269   env = GNUNET_MQ_msg (msg,
270                        GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE);
271   msg->channel_id = lid;
272   msg->port = *port;
273   msg->opt = htonl (options);
274   msg->peer = *GCP_get_id (dest);
275   GSC_send_to_client (c,
276                       env);
277   return lid;
278 }
279
280
281 /******************************************************************************/
282 /************************      MAIN FUNCTIONS      ****************************/
283 /******************************************************************************/
284
285 /**
286  * Task run during shutdown.
287  *
288  * @param cls unused
289  */
290 static void
291 shutdown_task (void *cls)
292 {
293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
294               "shutting down\n");
295   shutting_down = GNUNET_YES;
296
297   if (NULL != stats)
298   {
299     GNUNET_STATISTICS_destroy (stats,
300                                GNUNET_NO);
301     stats = NULL;
302   }
303   if (NULL != open_ports)
304   {
305     GNUNET_CONTAINER_multihashmap_destroy (open_ports);
306     open_ports = NULL;
307   }
308   if (NULL != loose_channels)
309   {
310     GNUNET_CONTAINER_multihashmap_destroy (loose_channels);
311     loose_channels = NULL;
312   }
313   /* All channels, connections and CORE must be down before this point. */
314   GCP_destroy_all_peers ();
315   if (NULL != peers)
316   {
317     GNUNET_CONTAINER_multipeermap_destroy (peers);
318     peers = NULL;
319   }
320   if (NULL != ats_ch)
321   {
322     GNUNET_ATS_connectivity_done (ats_ch);
323     ats_ch = NULL;
324   }
325   GCD_shutdown ();
326   GCH_shutdown ();
327   GNUNET_free_non_null (my_private_key);
328   my_private_key = NULL;
329 }
330
331
332 /**
333  * We had a remote connection @a value to port @a port before
334  * client @a cls opened port @a port.  Bind them now.
335  *
336  * @param cls the `struct CadetClient`
337  * @param port the port
338  * @param value the `struct CadetChannel`
339  * @return #GNUNET_YES (iterate over all such channels)
340  */
341 static int
342 bind_loose_channel (void *cls,
343                     const struct GNUNET_HashCode *port,
344                     void *value)
345 {
346   struct CadetClient *c = cls;
347   struct CadetChannel *ch = value;
348
349   GCCH_bind (ch,
350              c);
351   GNUNET_assert (GNUNET_YES ==
352                  GNUNET_CONTAINER_multihashmap_remove (loose_channels,
353                                                        port,
354                                                        value));
355   return GNUNET_YES;
356 }
357
358
359 /**
360  * Handler for port open requests.
361  *
362  * @param cls Identification of the client.
363  * @param pmsg The actual message.
364  */
365 static void
366 handle_port_open (void *cls,
367                   const struct GNUNET_CADET_PortMessage *pmsg)
368 {
369   struct CadetClient *c = cls;
370
371   LOG (GNUNET_ERROR_TYPE_DEBUG,
372        "Open port %s requested by client %u\n",
373        GNUNET_h2s (&pmsg->port),
374        c->id);
375   if (NULL == c->ports)
376     c->ports = GNUNET_CONTAINER_multihashmap_create (4,
377                                                      GNUNET_NO);
378   if (GNUNET_OK !=
379       GNUNET_CONTAINER_multihashmap_put (c->ports,
380                                          &pmsg->port,
381                                          c,
382                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
383   {
384     GNUNET_break (0);
385     GNUNET_SERVICE_client_drop (c->client);
386     return;
387   }
388   /* store in global hashmap */
389   /* FIXME only allow one client to have the port open,
390    *       have a backup hashmap with waiting clients */
391   GNUNET_CONTAINER_multihashmap_put (open_ports,
392                                      &pmsg->port,
393                                      c,
394                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
395   GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels,
396                                               &pmsg->port,
397                                               &bind_loose_channel,
398                                               c);
399   GNUNET_SERVICE_client_continue (c->client);
400 }
401
402
403 /**
404  * Handler for port close requests.
405  *
406  * @param cls Identification of the client.
407  * @param pmsg The actual message.
408  */
409 static void
410 handle_port_close (void *cls,
411                    const struct GNUNET_CADET_PortMessage *pmsg)
412 {
413   struct CadetClient *c = cls;
414
415   LOG (GNUNET_ERROR_TYPE_DEBUG,
416        "Open port %s requested by client %u\n",
417        GNUNET_h2s (&pmsg->port),
418        c->id);
419   if (GNUNET_YES !=
420       GNUNET_CONTAINER_multihashmap_remove (c->ports,
421                                             &pmsg->port,
422                                             c))
423   {
424     GNUNET_break (0);
425     GNUNET_SERVICE_client_drop (c->client);
426     return;
427   }
428   GNUNET_assert (GNUNET_YES ==
429                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
430                                                        &pmsg->port,
431                                                        c));
432
433   GNUNET_SERVICE_client_continue (c->client);
434 }
435
436
437 /**
438  * Handler for requests of new channels.
439  *
440  * @param cls Identification of the client.
441  * @param ccm The actual message.
442  */
443 static void
444 handle_channel_create (void *cls,
445                        const struct GNUNET_CADET_ChannelCreateMessage *ccm)
446 {
447   struct CadetClient *c = cls;
448   struct CadetChannel *ch;
449   struct GNUNET_CADET_ClientChannelNumber chid;
450   struct CadetPeer *dst;
451
452   chid = ccm->channel_id;
453   if (ntohl (chid.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
454   {
455     /* Channel ID not in allowed range. */
456     GNUNET_break (0);
457     GNUNET_SERVICE_client_drop (c->client);
458     return;
459   }
460   ch = GNUNET_CONTAINER_multihashmap32_get (c->own_channels,
461                                             ntohl (chid.channel_of_client));
462   if (NULL != ch)
463   {
464     /* Channel ID already in use. Not allowed. */
465     GNUNET_break (0);
466     GNUNET_SERVICE_client_drop (c->client);
467     return;
468   }
469
470   dst = GCP_get (&ccm->peer,
471                  GNUNET_YES);
472
473   /* Create channel */
474   ch = GCCH_channel_local_new (c,
475                                chid,
476                                dst,
477                                &ccm->port,
478                                ntohl (ccm->opt));
479   if (NULL == ch)
480   {
481     GNUNET_break (0);
482     GNUNET_SERVICE_client_drop (c->client);
483     return;
484   }
485   GNUNET_assert (GNUNET_YES ==
486                  GNUNET_CONTAINER_multihashmap32_put (c->own_channels,
487                                                       ntohl (chid.channel_of_client),
488                                                       ch,
489                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
490
491   LOG (GNUNET_ERROR_TYPE_DEBUG,
492        "New channel %s to %s at port %s requested by client %u\n",
493        GCCH_2s (ch),
494        GNUNET_i2s (&ccm->peer),
495        GNUNET_h2s (&ccm->port),
496        c->id);
497   GNUNET_SERVICE_client_continue (c->client);
498 }
499
500
501 /**
502  * Return the map which we use for client @a c for a channel ID of @a chid
503  *
504  * @param c client to find map for
505  * @param chid chid to find map for
506  * @return applicable map we use
507  */
508 static struct GNUNET_CONTAINER_MultiHashMap32 *
509 get_map_by_chid (struct CadetClient *c,
510                  struct GNUNET_CADET_ClientChannelNumber chid)
511 {
512   return (ntohl (chid.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
513     ? c->own_channels
514     : c->incoming_channels;
515 }
516
517
518 /**
519  * Handler for requests of deleting tunnels
520  *
521  * @param cls client identification of the client
522  * @param msg the actual message
523  */
524 static void
525 handle_channel_destroy (void *cls,
526                         const struct GNUNET_CADET_ChannelDestroyMessage *msg)
527 {
528   struct CadetClient *c = cls;
529   struct GNUNET_CADET_ClientChannelNumber chid;
530   struct GNUNET_CONTAINER_MultiHashMap32 *map;
531   struct CadetChannel *ch;
532
533   /* Retrieve tunnel */
534   chid = msg->channel_id;
535   map = get_map_by_chid (c,
536                          chid);
537   ch = GNUNET_CONTAINER_multihashmap32_get (map,
538                                             ntohl (chid.channel_of_client));
539   if (NULL == ch)
540   {
541     /* Client attempted to destroy unknown channel */
542     GNUNET_break (0);
543     GNUNET_SERVICE_client_drop (c->client);
544     return;
545   }
546   LOG (GNUNET_ERROR_TYPE_INFO,
547        "Client %u is destroying channel %s\n",
548        c->id,
549        GCCH_2s (ch));
550   GNUNET_assert (GNUNET_YES ==
551                  GNUNET_CONTAINER_multihashmap32_remove (map,
552                                                          ntohl (chid.channel_of_client),
553                                                          ch));
554   GCCH_channel_local_destroy (ch);
555   GNUNET_SERVICE_client_continue (c->client);
556 }
557
558
559 /**
560  * Check for client traffic data message is well-formed
561  *
562  * @param cls identification of the client
563  * @param msg the actual message
564  * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not
565  */
566 static int
567 check_data (void *cls,
568             const struct GNUNET_CADET_LocalData *msg)
569 {
570   const struct GNUNET_MessageHeader *payload;
571   size_t payload_size;
572   size_t payload_claimed_size;
573
574   /* Sanity check for message size */
575   payload_size = ntohs (msg->header.size) - sizeof (*msg);
576   if ( (payload_size < sizeof (struct GNUNET_MessageHeader)) ||
577        (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_size) )
578   {
579     GNUNET_break (0);
580     return GNUNET_SYSERR;
581   }
582   payload = (struct GNUNET_MessageHeader *) &msg[1];
583   payload_claimed_size = ntohs (payload->size);
584   if (payload_size != payload_claimed_size)
585   {
586     GNUNET_break (0);
587     return GNUNET_SYSERR;
588   }
589   return GNUNET_OK;
590 }
591
592
593 /**
594  * Handler for client traffic
595  *
596  * @param cls identification of the client
597  * @param msg the actual message
598  */
599 static void
600 handle_data (void *cls,
601              const struct GNUNET_CADET_LocalData *msg)
602 {
603   struct CadetClient *c = cls;
604   struct GNUNET_CONTAINER_MultiHashMap32 *map;
605   struct GNUNET_CADET_ClientChannelNumber chid;
606   struct CadetChannel *ch;
607   const struct GNUNET_MessageHeader *payload;
608
609   chid = msg->id;
610   map = get_map_by_chid (c,
611                          chid);
612   ch = GNUNET_CONTAINER_multihashmap32_get (map,
613                                             ntohl (chid.channel_of_client));
614   if (NULL == ch)
615   {
616     /* Channel does not exist! */
617     GNUNET_break (0);
618     GNUNET_SERVICE_client_drop (c->client);
619     return;
620   }
621
622   payload = (const struct GNUNET_MessageHeader *) &msg[1];
623   LOG (GNUNET_ERROR_TYPE_DEBUG,
624        "Received %u bytes payload from client %u for channel %s\n",
625        ntohs (payload->size),
626        c->id,
627        GCCH_2s (ch));
628   if (GNUNET_OK !=
629       GCCH_handle_local_data (ch,
630                               payload))
631   {
632     GNUNET_SERVICE_client_drop (c->client);
633     return;
634   }
635   GNUNET_SERVICE_client_continue (c->client);
636 }
637
638
639 /**
640  * Handler for client's ACKs for payload traffic.
641  *
642  * @param cls identification of the client.
643  * @param msg The actual message.
644  */
645 static void
646 handle_ack (void *cls,
647             const struct GNUNET_CADET_LocalAck *msg)
648 {
649   struct CadetClient *c = cls;
650   struct GNUNET_CONTAINER_MultiHashMap32 *map;
651   struct GNUNET_CADET_ClientChannelNumber chid;
652   struct CadetChannel *ch;
653
654   chid = msg->channel_id;
655   map = get_map_by_chid (c,
656                          chid);
657   ch = GNUNET_CONTAINER_multihashmap32_get (map,
658                                             ntohl (chid.channel_of_client));
659   if (NULL == ch)
660   {
661     /* Channel does not exist! */
662     GNUNET_break (0);
663     GNUNET_SERVICE_client_drop (c->client);
664     return;
665   }
666   LOG (GNUNET_ERROR_TYPE_DEBUG,
667        "Got a local ACK from client %u for channel %s\n",
668        c->id,
669        GCCH_2s (ch));
670   GCCH_handle_local_ack (ch);
671   GNUNET_SERVICE_client_continue (c->client);
672 }
673
674
675 /**
676  * Iterator over all peers to send a monitoring client info about each peer.
677  *
678  * @param cls Closure ().
679  * @param peer Peer ID (tunnel remote peer).
680  * @param value Peer info.
681  * @return #GNUNET_YES, to keep iterating.
682  */
683 static int
684 get_all_peers_iterator (void *cls,
685                         const struct GNUNET_PeerIdentity *peer,
686                         void *value)
687 {
688   struct CadetClient *c = cls;
689   struct CadetPeer *p = value;
690   struct GNUNET_MQ_Envelope *env;
691   struct GNUNET_CADET_LocalInfoPeer *msg;
692
693   env = GNUNET_MQ_msg (msg,
694                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
695   msg->destination = *peer;
696   msg->paths = htons (GCP_count_paths (p));
697   msg->tunnel = htons (NULL != GCP_get_tunnel (p,
698                                                GNUNET_NO));
699   GNUNET_MQ_send (c->mq,
700                   env);
701   return GNUNET_YES;
702 }
703
704
705 /**
706  * Handler for client's INFO PEERS request.
707  *
708  * @param cls Identification of the client.
709  * @param message The actual message.
710  */
711 static void
712 handle_get_peers (void *cls,
713                   const struct GNUNET_MessageHeader *message)
714 {
715   struct CadetClient *c = cls;
716   struct GNUNET_MQ_Envelope *env;
717   struct GNUNET_MessageHeader *reply;
718
719   GCP_iterate_all (&get_all_peers_iterator,
720                    c);
721   env = GNUNET_MQ_msg (reply,
722                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
723   GNUNET_MQ_send (c->mq,
724                   env);
725   GNUNET_SERVICE_client_continue (c->client);
726 }
727
728
729 /**
730  * Iterator over all paths of a peer to build an InfoPeer message.
731  * Message contains blocks of peers, first not included.
732  *
733  * @param cls message queue for transmission
734  * @param path Path itself
735  * @param off offset of the peer on @a path
736  * @return #GNUNET_YES if should keep iterating.
737  *         #GNUNET_NO otherwise.
738  */
739 static int
740 path_info_iterator (void *cls,
741                     struct CadetPeerPath *path,
742                     unsigned int off)
743 {
744   struct GNUNET_MQ_Handle *mq = cls;
745   struct GNUNET_MQ_Envelope *env;
746   struct GNUNET_MessageHeader *resp;
747   struct GNUNET_PeerIdentity *id;
748   uint16_t path_size;
749   unsigned int i;
750   unsigned int path_length;
751
752   path_length = GCPP_get_length (path);
753   path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
754   if (sizeof (*resp) + path_size > UINT16_MAX)
755   {
756     LOG (GNUNET_ERROR_TYPE_WARNING,
757          "Path of %u entries is too long for info message\n",
758          path_length);
759     return GNUNET_YES;
760   }
761   env = GNUNET_MQ_msg_extra (resp,
762                              path_size,
763                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
764   id = (struct GNUNET_PeerIdentity *) &resp[1];
765
766   /* Don't copy first peer.  First peer is always the local one.  Last
767    * peer is always the destination (leave as 0, EOL).
768    */
769   for (i = 0; i < off; i++)
770     id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path,
771                                                   i + 1));
772   GNUNET_MQ_send (mq,
773                   env);
774   return GNUNET_YES;
775 }
776
777
778 /**
779  * Handler for client's SHOW_PEER request.
780  *
781  * @param cls Identification of the client.
782  * @param msg The actual message.
783  */
784 static void
785 handle_show_peer (void *cls,
786                   const struct GNUNET_CADET_LocalInfo *msg)
787 {
788   struct CadetClient *c = cls;
789   struct CadetPeer *p;
790   struct GNUNET_MQ_Envelope *env;
791   struct GNUNET_MessageHeader *resp;
792
793   p = GCP_get (&msg->peer,
794                GNUNET_NO);
795   if (NULL != p)
796     GCP_iterate_paths (p,
797                        &path_info_iterator,
798                        c->mq);
799   /* Send message with 0/0 to indicate the end */
800   env = GNUNET_MQ_msg (resp,
801                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
802   GNUNET_MQ_send (c->mq,
803                   env);
804   GNUNET_SERVICE_client_continue (c->client);
805 }
806
807
808 /**
809  * Iterator over all tunnels to send a monitoring client info about each tunnel.
810  *
811  * @param cls Closure ().
812  * @param peer Peer ID (tunnel remote peer).
813  * @param value a `struct CadetPeer`
814  * @return #GNUNET_YES, to keep iterating.
815  */
816 static int
817 get_all_tunnels_iterator (void *cls,
818                           const struct GNUNET_PeerIdentity *peer,
819                           void *value)
820 {
821   struct CadetClient *c = cls;
822   struct CadetPeer *p = value;
823   struct GNUNET_MQ_Envelope *env;
824   struct GNUNET_CADET_LocalInfoTunnel *msg;
825   struct CadetTunnel *t;
826
827   t = GCP_get_tunnel (p,
828                       GNUNET_NO);
829   if (NULL == t)
830     return GNUNET_YES;
831   env = GNUNET_MQ_msg (msg,
832                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
833   msg->destination = *peer;
834   msg->channels = htonl (GCT_count_channels (t));
835   msg->connections = htonl (GCT_count_any_connections (t));
836   msg->cstate = htons ((uint16_t) GCT_get_cstate (t));
837   msg->estate = htons ((uint16_t) GCT_get_estate (t));
838   GNUNET_MQ_send (c->mq,
839                   env);
840   return GNUNET_YES;
841 }
842
843
844 /**
845  * Handler for client's INFO TUNNELS request.
846  *
847  * @param cls client Identification of the client.
848  * @param message The actual message.
849  */
850 static void
851 handle_get_tunnels (void *cls,
852                     const struct GNUNET_MessageHeader *message)
853 {
854   struct CadetClient *c = cls;
855   struct GNUNET_MQ_Envelope *env;
856   struct GNUNET_MessageHeader *reply;
857
858   GCP_iterate_all (&get_all_tunnels_iterator,
859                    c);
860   env = GNUNET_MQ_msg (reply,
861                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
862   GNUNET_MQ_send (c->mq,
863                   env);
864   GNUNET_SERVICE_client_continue (c->client);
865 }
866
867
868 /**
869  * FIXME.
870  */
871 static void
872 iter_connection (void *cls,
873                  struct CadetConnection *c)
874 {
875   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
876   struct GNUNET_CADET_ConnectionTunnelIdentifier *h;
877
878   h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
879   h[msg->connections++] = *(GCC_get_id (c));
880 }
881
882
883 /**
884  * FIXME.
885  */
886 static void
887 iter_channel (void *cls,
888               struct CadetChannel *ch)
889 {
890   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
891   struct GNUNET_CADET_Hash *h = (struct GNUNET_CADET_Hash *) &msg[1];
892   struct GCT_ChannelTunnelNumber *chn
893     = (struct GCT_ChannelTunnelNumber *) &h[msg->connections];
894
895   chn[msg->channels++] = GCCH_get_id (ch);
896 }
897
898
899 /**
900  * Handler for client's SHOW_TUNNEL request.
901  *
902  * @param cls Identification of the client.
903  * @param msg The actual message.
904  */
905 static void
906 handle_show_tunnel (void *cls,
907                     const struct GNUNET_CADET_LocalInfo *msg)
908 {
909   struct CadetClient *c = cls;
910   struct GNUNET_MQ_Envelope *env;
911   struct GNUNET_CADET_LocalInfoTunnel *resp;
912   struct CadetTunnel *t;
913   struct CadetPeer *p;
914   unsigned int ch_n;
915   unsigned int c_n;
916
917   p = GCP_get (&msg->peer,
918                GNUNET_NO);
919   t = GCP_get_tunnel (p,
920                       GNUNET_NO);
921   if (NULL == t)
922   {
923     /* We don't know the tunnel */
924     struct GNUNET_MQ_Envelope *env;
925     struct GNUNET_CADET_LocalInfoTunnel *warn;
926
927     LOG (GNUNET_ERROR_TYPE_INFO,
928          "Tunnel to %s unknown\n",
929          GNUNET_i2s_full (&msg->peer));
930     env = GNUNET_MQ_msg (warn,
931                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
932     warn->destination = msg->peer;
933     GNUNET_MQ_send (c->mq,
934                     env);
935     GNUNET_SERVICE_client_continue (c->client);
936     return;
937   }
938
939   /* Initialize context */
940   ch_n = GCT_count_channels (t);
941   c_n = GCT_count_any_connections (t);
942   env = GNUNET_MQ_msg_extra (resp,
943                              c_n * sizeof (struct GNUNET_CADET_Hash) +
944                              ch_n * sizeof (struct GCT_ChannelTunnelNumber),
945                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
946   resp->destination = msg->peer;
947   /* Do not reorder! #iter_channel needs counters in HBO! */
948   GCT_iterate_connections (t,
949                            &iter_connection,
950                            resp);
951   GCT_iterate_channels (t,
952                         &iter_channel,
953                         resp);
954   resp->connections = htonl (resp->connections);
955   resp->channels = htonl (resp->channels);
956   resp->cstate = htons (GCT_get_cstate (t));
957   resp->estate = htons (GCT_get_estate (t));
958   GNUNET_MQ_send (c->mq,
959                   env);
960   GNUNET_SERVICE_client_continue (c->client);
961 }
962
963
964 /**
965  * Iterator over all peers to dump info for each peer.
966  *
967  * @param cls Closure (unused).
968  * @param peer Peer ID (tunnel remote peer).
969  * @param value Peer info.
970  *
971  * @return #GNUNET_YES, to keep iterating.
972  */
973 static int
974 show_peer_iterator (void *cls,
975                     const struct GNUNET_PeerIdentity *peer,
976                     void *value)
977 {
978   struct CadetPeer *p = value;
979   struct CadetTunnel *t;
980
981   t = GCP_get_tunnel (p,
982                       GNUNET_NO);
983   if (NULL != t)
984     GCT_debug (t,
985                GNUNET_ERROR_TYPE_ERROR);
986   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
987   return GNUNET_YES;
988 }
989
990
991 /**
992  * Handler for client's INFO_DUMP request.
993  *
994  * @param cls Identification of the client.
995  * @param message The actual message.
996  */
997 static void
998 handle_info_dump (void *cls,
999                   const struct GNUNET_MessageHeader *message)
1000 {
1001   struct CadetClient *c = cls;
1002
1003   LOG (GNUNET_ERROR_TYPE_INFO,
1004        "Received dump info request from client %u\n",
1005        c->id);
1006
1007   LOG (GNUNET_ERROR_TYPE_ERROR,
1008        "*************************** DUMP START ***************************\n");
1009   for (struct CadetClient *ci = clients_head; NULL != ci; ci = ci->next)
1010   {
1011     LOG (GNUNET_ERROR_TYPE_ERROR,
1012          "Client %u (%p), handle: %p, ports: %u, own channels: %u, incoming channels: %u\n",
1013          ci->id,
1014          ci,
1015          ci->client,
1016          (NULL != c->ports)
1017          ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
1018          : 0,
1019          GNUNET_CONTAINER_multihashmap32_size (ci->own_channels),
1020          GNUNET_CONTAINER_multihashmap32_size (ci->incoming_channels));
1021   }
1022   LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
1023   GCP_iterate_all (&show_peer_iterator,
1024                    NULL);
1025
1026   LOG (GNUNET_ERROR_TYPE_ERROR,
1027        "**************************** DUMP END ****************************\n");
1028
1029   GNUNET_SERVICE_client_continue (c->client);
1030 }
1031
1032
1033
1034 /**
1035  * Callback called when a client connects to the service.
1036  *
1037  * @param cls closure for the service
1038  * @param client the new client that connected to the service
1039  * @param mq the message queue used to send messages to the client
1040  * @return @a c
1041  */
1042 static void *
1043 client_connect_cb (void *cls,
1044                    struct GNUNET_SERVICE_Client *client,
1045                    struct GNUNET_MQ_Handle *mq)
1046 {
1047   struct CadetClient *c;
1048
1049   c = GNUNET_new (struct CadetClient);
1050   c->client = client;
1051   c->mq = mq;
1052   c->id = next_client_id++; /* overflow not important: just for debug */
1053   c->own_channels
1054     = GNUNET_CONTAINER_multihashmap32_create (32);
1055   c->incoming_channels
1056     = GNUNET_CONTAINER_multihashmap32_create (32);
1057   GNUNET_CONTAINER_DLL_insert (clients_head,
1058                                clients_tail,
1059                                c);
1060   GNUNET_STATISTICS_update (stats,
1061                             "# clients",
1062                             +1,
1063                             GNUNET_NO);
1064   return c;
1065 }
1066
1067
1068 /**
1069  * Iterator for deleting each channel whose client endpoint disconnected.
1070  *
1071  * @param cls Closure (client that has disconnected).
1072  * @param key The local channel id (used to access the hashmap).
1073  * @param value The value stored at the key (channel to destroy).
1074  * @return #GNUNET_OK, keep iterating.
1075  */
1076 static int
1077 own_channel_destroy_iterator (void *cls,
1078                               uint32_t key,
1079                               void *value)
1080 {
1081   struct CadetClient *c = cls;
1082   struct CadetChannel *ch = value;
1083
1084   GNUNET_assert (GNUNET_YES ==
1085                  GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1086                                                          key,
1087                                                          ch));
1088   LOG (GNUNET_ERROR_TYPE_DEBUG,
1089        "Destroying own channel %s, due to client %u shutdown.\n",
1090        GCCH_2s (ch),
1091        c->id);
1092   GCCH_channel_local_destroy (ch);
1093   return GNUNET_OK;
1094 }
1095
1096
1097 /**
1098  * Iterator for deleting each channel whose client endpoint disconnected.
1099  *
1100  * @param cls Closure (client that has disconnected).
1101  * @param key The local channel id (used to access the hashmap).
1102  * @param value The value stored at the key (channel to destroy).
1103  * @return #GNUNET_OK, keep iterating.
1104  */
1105 static int
1106 incoming_channel_destroy_iterator (void *cls,
1107                                    uint32_t key,
1108                                    void *value)
1109 {
1110   struct CadetChannel *ch = value;
1111   struct CadetClient *c = cls;
1112
1113   GNUNET_assert (GNUNET_YES ==
1114                  GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1115                                                          key,
1116                                                          ch));
1117
1118   LOG (GNUNET_ERROR_TYPE_DEBUG,
1119        "Destroying incoming channel %s due to client %u shutdown.\n",
1120        GCCH_2s (ch),
1121        c->id);
1122   GCCH_channel_incoming_destroy (ch);
1123   return GNUNET_OK;
1124 }
1125
1126
1127 /**
1128  * Remove client's ports from the global hashmap on disconnect.
1129  *
1130  * @param cls Closure (unused).
1131  * @param key Port.
1132  * @param value the `struct CadetClient` to remove
1133  * @return #GNUNET_OK, keep iterating.
1134  */
1135 static int
1136 client_release_ports (void *cls,
1137                       const struct GNUNET_HashCode *key,
1138                       void *value)
1139 {
1140   struct CadetClient *c = value;
1141
1142   GNUNET_assert (GNUNET_YES ==
1143                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
1144                                                        key,
1145                                                        value));
1146   GNUNET_assert (GNUNET_YES ==
1147                  GNUNET_CONTAINER_multihashmap_remove (c->ports,
1148                                                        key,
1149                                                        value));
1150   return GNUNET_OK;
1151 }
1152
1153
1154 /**
1155  * Callback called when a client disconnected from the service
1156  *
1157  * @param cls closure for the service
1158  * @param client the client that disconnected
1159  * @param internal_cls should be equal to @a c
1160  */
1161 static void
1162 client_disconnect_cb (void *cls,
1163                       struct GNUNET_SERVICE_Client *client,
1164                       void *internal_cls)
1165 {
1166   struct CadetClient *c = internal_cls;
1167
1168   GNUNET_assert (c->client == client);
1169   c->shutting_down = GNUNET_YES;
1170   if (NULL != c->own_channels)
1171   {
1172     GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
1173                                              &own_channel_destroy_iterator,
1174                                              c);
1175     GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
1176   }
1177   if (NULL != c->incoming_channels)
1178   {
1179     GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
1180                                              &incoming_channel_destroy_iterator,
1181                                              c);
1182     GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
1183   }
1184   if (NULL != c->ports)
1185   {
1186     GNUNET_CONTAINER_multihashmap_iterate (c->ports,
1187                                            &client_release_ports,
1188                                            c);
1189     GNUNET_CONTAINER_multihashmap_destroy (c->ports);
1190   }
1191   GNUNET_CONTAINER_DLL_remove (clients_head,
1192                                clients_tail,
1193                                c);
1194   GNUNET_STATISTICS_update (stats,
1195                             "# clients",
1196                             -1,
1197                             GNUNET_NO);
1198   GNUNET_free (c);
1199 }
1200
1201
1202 /**
1203  * Setup CADET internals.
1204  *
1205  * @param cls closure
1206  * @param server the initialized server
1207  * @param c configuration to use
1208  */
1209 static void
1210 run (void *cls,
1211      const struct GNUNET_CONFIGURATION_Handle *c,
1212      struct GNUNET_SERVICE_Handle *service)
1213 {
1214   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1215   if (NULL == my_private_key)
1216   {
1217     GNUNET_break (0);
1218     GNUNET_SCHEDULER_shutdown ();
1219     return;
1220   }
1221   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1222                                       &my_full_id.public_key);
1223   stats = GNUNET_STATISTICS_create ("cadet",
1224                                     c);
1225   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1226                                  NULL);
1227   ats_ch = GNUNET_ATS_connectivity_init (c);
1228   /* FIXME: optimize code to allow GNUNET_YES here! */
1229   open_ports = GNUNET_CONTAINER_multihashmap_create (16,
1230                                                      GNUNET_NO);
1231   loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
1232                                                          GNUNET_NO);
1233   peers = GNUNET_CONTAINER_multipeermap_create (16,
1234                                                 GNUNET_YES);
1235   GCH_init (c);
1236   GCD_init (c);
1237   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1238               "CADET starting at peer %s\n",
1239               GNUNET_i2s (&my_full_id));
1240
1241 }
1242
1243
1244 /**
1245  * Define "main" method using service macro.
1246  */
1247 GNUNET_SERVICE_MAIN
1248 ("cadet",
1249  GNUNET_SERVICE_OPTION_NONE,
1250  &run,
1251  &client_connect_cb,
1252  &client_disconnect_cb,
1253  NULL,
1254  GNUNET_MQ_hd_fixed_size (port_open,
1255                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
1256                           struct GNUNET_CADET_PortMessage,
1257                           NULL),
1258  GNUNET_MQ_hd_fixed_size (port_close,
1259                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
1260                           struct GNUNET_CADET_PortMessage,
1261                           NULL),
1262  GNUNET_MQ_hd_fixed_size (channel_create,
1263                           GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE,
1264                           struct GNUNET_CADET_ChannelCreateMessage,
1265                           NULL),
1266  GNUNET_MQ_hd_fixed_size (channel_destroy,
1267                           GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1268                           struct GNUNET_CADET_ChannelDestroyMessage,
1269                           NULL),
1270  GNUNET_MQ_hd_var_size (data,
1271                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1272                         struct GNUNET_CADET_LocalData,
1273                         NULL),
1274  GNUNET_MQ_hd_fixed_size (ack,
1275                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1276                           struct GNUNET_CADET_LocalAck,
1277                           NULL),
1278  GNUNET_MQ_hd_fixed_size (get_peers,
1279                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1280                           struct GNUNET_MessageHeader,
1281                           NULL),
1282  GNUNET_MQ_hd_fixed_size (show_peer,
1283                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1284                           struct GNUNET_CADET_LocalInfo,
1285                           NULL),
1286  GNUNET_MQ_hd_fixed_size (get_tunnels,
1287                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1288                           struct GNUNET_MessageHeader,
1289                           NULL),
1290  GNUNET_MQ_hd_fixed_size (show_tunnel,
1291                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1292                           struct GNUNET_CADET_LocalInfo,
1293                           NULL),
1294  GNUNET_MQ_hd_fixed_size (info_dump,
1295                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
1296                           struct GNUNET_MessageHeader,
1297                           NULL),
1298  GNUNET_MQ_handler_end ());
1299
1300 /* end of gnunet-service-cadet-new.c */