starting re-implementation of CADET service
[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   GCP_id (dest,
275           &msg->peer);
276   GSC_send_to_client (c,
277                       env);
278   return lid;
279 }
280
281
282 /******************************************************************************/
283 /************************      MAIN FUNCTIONS      ****************************/
284 /******************************************************************************/
285
286 /**
287  * Task run during shutdown.
288  *
289  * @param cls unused
290  */
291 static void
292 shutdown_task (void *cls)
293 {
294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
295               "shutting down\n");
296   shutting_down = GNUNET_YES;
297
298   if (NULL != stats)
299   {
300     GNUNET_STATISTICS_destroy (stats,
301                                GNUNET_NO);
302     stats = NULL;
303   }
304   if (NULL != open_ports)
305   {
306     GNUNET_CONTAINER_multihashmap_destroy (open_ports);
307     open_ports = NULL;
308   }
309   if (NULL != loose_channels)
310   {
311     GNUNET_CONTAINER_multihashmap_destroy (loose_channels);
312     loose_channels = NULL;
313   }
314   /* All channels, connections and CORE must be down before this point. */
315   GCP_destroy_all_peers ();
316   if (NULL != peers)
317   {
318     GNUNET_CONTAINER_multipeermap_destroy (peers);
319     peers = NULL;
320   }
321   if (NULL != ats_ch)
322   {
323     GNUNET_ATS_connectivity_done (ats_ch);
324     ats_ch = NULL;
325   }
326   GCD_shutdown ();
327   GCH_shutdown ();
328   GNUNET_free_non_null (my_private_key);
329   my_private_key = NULL;
330 }
331
332
333 /**
334  * We had a remote connection @a value to port @a port before
335  * client @a cls opened port @a port.  Bind them now.
336  *
337  * @param cls the `struct CadetClient`
338  * @param port the port
339  * @param value the `struct CadetChannel`
340  * @return #GNUNET_YES (iterate over all such channels)
341  */
342 static int
343 bind_loose_channel (void *cls,
344                     const struct GNUNET_HashCode *port,
345                     void *value)
346 {
347   struct CadetClient *c = cls;
348   struct CadetChannel *ch = value;
349
350   GCCH_bind (ch,
351              c);
352   GNUNET_assert (GNUNET_YES ==
353                  GNUNET_CONTAINER_multihashmap_remove (loose_channels,
354                                                        port,
355                                                        value));
356   return GNUNET_YES;
357 }
358
359
360 /**
361  * Handler for port open requests.
362  *
363  * @param cls Identification of the client.
364  * @param pmsg The actual message.
365  */
366 static void
367 handle_port_open (void *cls,
368                   const struct GNUNET_CADET_PortMessage *pmsg)
369 {
370   struct CadetClient *c = cls;
371
372   LOG (GNUNET_ERROR_TYPE_DEBUG,
373        "Open port %s requested by client %u\n",
374        GNUNET_h2s (&pmsg->port),
375        c->id);
376   if (NULL == c->ports)
377     c->ports = GNUNET_CONTAINER_multihashmap_create (4,
378                                                      GNUNET_NO);
379   if (GNUNET_OK !=
380       GNUNET_CONTAINER_multihashmap_put (c->ports,
381                                          &pmsg->port,
382                                          c,
383                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
384   {
385     GNUNET_break (0);
386     GNUNET_SERVICE_client_drop (c->client);
387     return;
388   }
389   /* store in global hashmap */
390   /* FIXME only allow one client to have the port open,
391    *       have a backup hashmap with waiting clients */
392   GNUNET_CONTAINER_multihashmap_put (open_ports,
393                                      &pmsg->port,
394                                      c,
395                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
396   GNUNET_CONTAINER_multihashmap_get_multiple (loose_channels,
397                                               &pmsg->port,
398                                               &bind_loose_channel,
399                                               c);
400   GNUNET_SERVICE_client_continue (c->client);
401 }
402
403
404 /**
405  * Handler for port close requests.
406  *
407  * @param cls Identification of the client.
408  * @param pmsg The actual message.
409  */
410 static void
411 handle_port_close (void *cls,
412                    const struct GNUNET_CADET_PortMessage *pmsg)
413 {
414   struct CadetClient *c = cls;
415
416   LOG (GNUNET_ERROR_TYPE_DEBUG,
417        "Open port %s requested by client %u\n",
418        GNUNET_h2s (&pmsg->port),
419        c->id);
420   if (GNUNET_YES !=
421       GNUNET_CONTAINER_multihashmap_remove (c->ports,
422                                             &pmsg->port,
423                                             c))
424   {
425     GNUNET_break (0);
426     GNUNET_SERVICE_client_drop (c->client);
427     return;
428   }
429   GNUNET_assert (GNUNET_YES ==
430                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
431                                                        &pmsg->port,
432                                                        c));
433
434   GNUNET_SERVICE_client_continue (c->client);
435 }
436
437
438 /**
439  * Handler for requests of new channels.
440  *
441  * @param cls Identification of the client.
442  * @param ccm The actual message.
443  */
444 static void
445 handle_channel_create (void *cls,
446                        const struct GNUNET_CADET_ChannelCreateMessage *ccm)
447 {
448   struct CadetClient *c = cls;
449   struct CadetChannel *ch;
450   struct GNUNET_CADET_ClientChannelNumber chid;
451   struct CadetPeer *dst;
452
453   chid = ccm->channel_id;
454   if (ntohl (chid.channel_of_client) < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
455   {
456     /* Channel ID not in allowed range. */
457     GNUNET_break (0);
458     GNUNET_SERVICE_client_drop (c->client);
459     return;
460   }
461   ch = GNUNET_CONTAINER_multihashmap32_get (c->own_channels,
462                                             ntohl (chid.channel_of_client));
463   if (NULL != ch)
464   {
465     /* Channel ID already in use. Not allowed. */
466     GNUNET_break (0);
467     GNUNET_SERVICE_client_drop (c->client);
468     return;
469   }
470
471   dst = GCP_get (&ccm->peer,
472                  GNUNET_YES);
473
474   /* Create channel */
475   ch = GCCH_channel_local_new (c,
476                                chid,
477                                dst,
478                                &ccm->port,
479                                ntohl (ccm->opt));
480   if (NULL == ch)
481   {
482     GNUNET_break (0);
483     GNUNET_SERVICE_client_drop (c->client);
484     return;
485   }
486   GNUNET_assert (GNUNET_YES ==
487                  GNUNET_CONTAINER_multihashmap32_put (c->own_channels,
488                                                       ntohl (chid.channel_of_client),
489                                                       ch,
490                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
491
492   LOG (GNUNET_ERROR_TYPE_DEBUG,
493        "New channel %s to %s at port %s requested by client %u\n",
494        GCCH_2s (ch),
495        GNUNET_i2s (&ccm->peer),
496        GNUNET_h2s (&ccm->port),
497        c->id);
498   GNUNET_SERVICE_client_continue (c->client);
499 }
500
501
502 /**
503  * Return the map which we use for client @a c for a channel ID of @a chid
504  *
505  * @param c client to find map for
506  * @param chid chid to find map for
507  * @return applicable map we use
508  */
509 static struct GNUNET_CONTAINER_MultiHashMap32 *
510 get_map_by_chid (struct CadetClient *c,
511                  struct GNUNET_CADET_ClientChannelNumber chid)
512 {
513   return (ntohl (chid.channel_of_client) >= GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
514     ? c->own_channels
515     : c->incoming_channels;
516 }
517
518
519 /**
520  * Handler for requests of deleting tunnels
521  *
522  * @param cls client identification of the client
523  * @param msg the actual message
524  */
525 static void
526 handle_channel_destroy (void *cls,
527                         const struct GNUNET_CADET_ChannelDestroyMessage *msg)
528 {
529   struct CadetClient *c = cls;
530   struct GNUNET_CADET_ClientChannelNumber chid;
531   struct GNUNET_CONTAINER_MultiHashMap32 *map;
532   struct CadetChannel *ch;
533
534   /* Retrieve tunnel */
535   chid = msg->channel_id;
536   map = get_map_by_chid (c,
537                          chid);
538   ch = GNUNET_CONTAINER_multihashmap32_get (map,
539                                             ntohl (chid.channel_of_client));
540   if (NULL == ch)
541   {
542     /* Client attempted to destroy unknown channel */
543     GNUNET_break (0);
544     GNUNET_SERVICE_client_drop (c->client);
545     return;
546   }
547   LOG (GNUNET_ERROR_TYPE_INFO,
548        "Client %u is destroying channel %s\n",
549        c->id,
550        GCCH_2s (ch));
551   GNUNET_assert (GNUNET_YES ==
552                  GNUNET_CONTAINER_multihashmap32_remove (map,
553                                                          ntohl (chid.channel_of_client),
554                                                          ch));
555   GCCH_channel_local_destroy (ch);
556   GNUNET_SERVICE_client_continue (c->client);
557 }
558
559
560 /**
561  * Check for client traffic data message is well-formed
562  *
563  * @param cls identification of the client
564  * @param msg the actual message
565  * @return #GNUNET_OK if @a msg is OK, #GNUNET_SYSERR if not
566  */
567 static int
568 check_data (void *cls,
569             const struct GNUNET_CADET_LocalData *msg)
570 {
571   const struct GNUNET_MessageHeader *payload;
572   size_t payload_size;
573   size_t payload_claimed_size;
574
575   /* Sanity check for message size */
576   payload_size = ntohs (msg->header.size) - sizeof (*msg);
577   if ( (payload_size < sizeof (struct GNUNET_MessageHeader)) ||
578        (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < payload_size) )
579   {
580     GNUNET_break (0);
581     return GNUNET_SYSERR;
582   }
583   payload = (struct GNUNET_MessageHeader *) &msg[1];
584   payload_claimed_size = ntohs (payload->size);
585   if (payload_size != payload_claimed_size)
586   {
587     GNUNET_break (0);
588     return GNUNET_SYSERR;
589   }
590   return GNUNET_OK;
591 }
592
593
594 /**
595  * Handler for client traffic
596  *
597  * @param cls identification of the client
598  * @param msg the actual message
599  */
600 static void
601 handle_data (void *cls,
602              const struct GNUNET_CADET_LocalData *msg)
603 {
604   struct CadetClient *c = cls;
605   struct GNUNET_CONTAINER_MultiHashMap32 *map;
606   struct GNUNET_CADET_ClientChannelNumber chid;
607   struct CadetChannel *ch;
608   const struct GNUNET_MessageHeader *payload;
609
610   chid = msg->id;
611   map = get_map_by_chid (c,
612                          chid);
613   ch = GNUNET_CONTAINER_multihashmap32_get (map,
614                                             ntohl (chid.channel_of_client));
615   if (NULL == ch)
616   {
617     /* Channel does not exist! */
618     GNUNET_break (0);
619     GNUNET_SERVICE_client_drop (c->client);
620     return;
621   }
622
623   payload = (const struct GNUNET_MessageHeader *) &msg[1];
624   LOG (GNUNET_ERROR_TYPE_DEBUG,
625        "Received %u bytes payload from client %u for channel %s\n",
626        ntohs (payload->size),
627        c->id,
628        GCCH_2s (ch));
629   if (GNUNET_OK !=
630       GCCH_handle_local_data (ch,
631                               payload))
632   {
633     GNUNET_SERVICE_client_drop (c->client);
634     return;
635   }
636   GNUNET_SERVICE_client_continue (c->client);
637 }
638
639
640 /**
641  * Handler for client's ACKs for payload traffic.
642  *
643  * @param cls identification of the client.
644  * @param msg The actual message.
645  */
646 static void
647 handle_ack (void *cls,
648             const struct GNUNET_CADET_LocalAck *msg)
649 {
650   struct CadetClient *c = cls;
651   struct GNUNET_CONTAINER_MultiHashMap32 *map;
652   struct GNUNET_CADET_ClientChannelNumber chid;
653   struct CadetChannel *ch;
654
655   chid = msg->channel_id;
656   map = get_map_by_chid (c,
657                          chid);
658   ch = GNUNET_CONTAINER_multihashmap32_get (map,
659                                             ntohl (chid.channel_of_client));
660   if (NULL == ch)
661   {
662     /* Channel does not exist! */
663     GNUNET_break (0);
664     GNUNET_SERVICE_client_drop (c->client);
665     return;
666   }
667   LOG (GNUNET_ERROR_TYPE_DEBUG,
668        "Got a local ACK from client %u for channel %s\n",
669        c->id,
670        GCCH_2s (ch));
671   GCCH_handle_local_ack (ch);
672   GNUNET_SERVICE_client_continue (c->client);
673 }
674
675
676 /**
677  * Iterator over all peers to send a monitoring client info about each peer.
678  *
679  * @param cls Closure ().
680  * @param peer Peer ID (tunnel remote peer).
681  * @param value Peer info.
682  * @return #GNUNET_YES, to keep iterating.
683  */
684 static int
685 get_all_peers_iterator (void *cls,
686                         const struct GNUNET_PeerIdentity *peer,
687                         void *value)
688 {
689   struct CadetClient *c = cls;
690   struct CadetPeer *p = value;
691   struct GNUNET_MQ_Envelope *env;
692   struct GNUNET_CADET_LocalInfoPeer *msg;
693
694   env = GNUNET_MQ_msg (msg,
695                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
696   msg->destination = *peer;
697   msg->paths = htons (GCP_count_paths (p));
698   msg->tunnel = htons (NULL != GCP_get_tunnel (p,
699                                                GNUNET_NO));
700   GNUNET_MQ_send (c->mq,
701                   env);
702   return GNUNET_YES;
703 }
704
705
706 /**
707  * Handler for client's INFO PEERS request.
708  *
709  * @param cls Identification of the client.
710  * @param message The actual message.
711  */
712 static void
713 handle_get_peers (void *cls,
714                   const struct GNUNET_MessageHeader *message)
715 {
716   struct CadetClient *c = cls;
717   struct GNUNET_MQ_Envelope *env;
718   struct GNUNET_MessageHeader *reply;
719
720   GCP_iterate_all (&get_all_peers_iterator,
721                    c);
722   env = GNUNET_MQ_msg (reply,
723                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
724   GNUNET_MQ_send (c->mq,
725                   env);
726   GNUNET_SERVICE_client_continue (c->client);
727 }
728
729
730 /**
731  * Iterator over all paths of a peer to build an InfoPeer message.
732  * Message contains blocks of peers, first not included.
733  *
734  * @param cls message queue for transmission
735  * @param peer Peer this path is towards.
736  * @param path Path itself
737  * @return #GNUNET_YES if should keep iterating.
738  *         #GNUNET_NO otherwise.
739  */
740 static int
741 path_info_iterator (void *cls,
742                     struct CadetPeer *peer,
743                     struct CadetPeerPath *path)
744 {
745   struct GNUNET_MQ_Handle *mq = cls;
746   struct GNUNET_MQ_Envelope *env;
747   struct GNUNET_MessageHeader *resp;
748   struct GNUNET_PeerIdentity *id;
749   uint16_t path_size;
750   unsigned int i;
751   unsigned int path_length;
752
753   path_length = GCPP_get_length (path);
754   path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
755   if (sizeof (*resp) + path_size > UINT16_MAX)
756   {
757     LOG (GNUNET_ERROR_TYPE_WARNING,
758          "Path of %u entries is too long for info message\n",
759          path_length);
760     return GNUNET_YES;
761   }
762   env = GNUNET_MQ_msg_extra (resp,
763                              path_size,
764                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
765   id = (struct GNUNET_PeerIdentity *) &resp[1];
766
767   /* Don't copy first peer.  First peer is always the local one.  Last
768    * peer is always the destination (leave as 0, EOL).
769    */
770   for (i = 0; i < path_length - 1; i++)
771     GCPP_get_pid_at_offset (path,
772                             i + 1,
773                             &id[i]);
774   GNUNET_MQ_send (mq,
775                   env);
776   return GNUNET_YES;
777 }
778
779
780 /**
781  * Handler for client's SHOW_PEER request.
782  *
783  * @param cls Identification of the client.
784  * @param msg The actual message.
785  */
786 static void
787 handle_show_peer (void *cls,
788                   const struct GNUNET_CADET_LocalInfo *msg)
789 {
790   struct CadetClient *c = cls;
791   struct CadetPeer *p;
792   struct GNUNET_MQ_Envelope *env;
793   struct GNUNET_MessageHeader *resp;
794
795   p = GCP_get (&msg->peer,
796                GNUNET_NO);
797   if (NULL != p)
798     GCP_iterate_paths (p,
799                        &path_info_iterator,
800                        c->mq);
801   /* Send message with 0/0 to indicate the end */
802   env = GNUNET_MQ_msg (resp,
803                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
804   GNUNET_MQ_send (c->mq,
805                   env);
806   GNUNET_SERVICE_client_continue (c->client);
807 }
808
809
810 /**
811  * Iterator over all tunnels to send a monitoring client info about each tunnel.
812  *
813  * @param cls Closure ().
814  * @param peer Peer ID (tunnel remote peer).
815  * @param value a `struct CadetPeer`
816  * @return #GNUNET_YES, to keep iterating.
817  */
818 static int
819 get_all_tunnels_iterator (void *cls,
820                           const struct GNUNET_PeerIdentity *peer,
821                           void *value)
822 {
823   struct CadetClient *c = cls;
824   struct CadetPeer *p = value;
825   struct GNUNET_MQ_Envelope *env;
826   struct GNUNET_CADET_LocalInfoTunnel *msg;
827   struct CadetTunnel *t;
828
829   t = GCP_get_tunnel (p,
830                       GNUNET_NO);
831   if (NULL == t)
832     return GNUNET_YES;
833   env = GNUNET_MQ_msg (msg,
834                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
835   msg->destination = *peer;
836   msg->channels = htonl (GCT_count_channels (t));
837   msg->connections = htonl (GCT_count_any_connections (t));
838   msg->cstate = htons ((uint16_t) GCT_get_cstate (t));
839   msg->estate = htons ((uint16_t) GCT_get_estate (t));
840   GNUNET_MQ_send (c->mq,
841                   env);
842   return GNUNET_YES;
843 }
844
845
846 /**
847  * Handler for client's INFO TUNNELS request.
848  *
849  * @param cls client Identification of the client.
850  * @param message The actual message.
851  */
852 static void
853 handle_get_tunnels (void *cls,
854                     const struct GNUNET_MessageHeader *message)
855 {
856   struct CadetClient *c = cls;
857   struct GNUNET_MQ_Envelope *env;
858   struct GNUNET_MessageHeader *reply;
859
860   GCP_iterate_all (&get_all_tunnels_iterator,
861                    c);
862   env = GNUNET_MQ_msg (reply,
863                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
864   GNUNET_MQ_send (c->mq,
865                   env);
866   GNUNET_SERVICE_client_continue (c->client);
867 }
868
869
870 /**
871  * FIXME.
872  */
873 static void
874 iter_connection (void *cls,
875                  struct CadetConnection *c)
876 {
877   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
878   struct GNUNET_CADET_ConnectionTunnelIdentifier *h;
879
880   h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
881   h[msg->connections++] = *(GCC_get_id (c));
882 }
883
884
885 /**
886  * FIXME.
887  */
888 static void
889 iter_channel (void *cls,
890               struct CadetChannel *ch)
891 {
892   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
893   struct GNUNET_CADET_Hash *h = (struct GNUNET_CADET_Hash *) &msg[1];
894   struct GCT_ChannelTunnelNumber *chn
895     = (struct GCT_ChannelTunnelNumber *) &h[msg->connections];
896
897   chn[msg->channels++] = GCCH_get_id (ch);
898 }
899
900
901 /**
902  * Handler for client's SHOW_TUNNEL request.
903  *
904  * @param cls Identification of the client.
905  * @param msg The actual message.
906  */
907 static void
908 handle_show_tunnel (void *cls,
909                     const struct GNUNET_CADET_LocalInfo *msg)
910 {
911   struct CadetClient *c = cls;
912   struct GNUNET_MQ_Envelope *env;
913   struct GNUNET_CADET_LocalInfoTunnel *resp;
914   struct CadetTunnel *t;
915   struct CadetPeer *p;
916   unsigned int ch_n;
917   unsigned int c_n;
918
919   p = GCP_get (&msg->peer,
920                GNUNET_NO);
921   t = GCP_get_tunnel (p,
922                       GNUNET_NO);
923   if (NULL == t)
924   {
925     /* We don't know the tunnel */
926     struct GNUNET_MQ_Envelope *env;
927     struct GNUNET_CADET_LocalInfoTunnel *warn;
928
929     LOG (GNUNET_ERROR_TYPE_INFO,
930          "Tunnel to %s unknown\n",
931          GNUNET_i2s_full (&msg->peer));
932     env = GNUNET_MQ_msg (warn,
933                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
934     warn->destination = msg->peer;
935     GNUNET_MQ_send (c->mq,
936                     env);
937     GNUNET_SERVICE_client_continue (c->client);
938     return;
939   }
940
941   /* Initialize context */
942   ch_n = GCT_count_channels (t);
943   c_n = GCT_count_any_connections (t);
944   env = GNUNET_MQ_msg_extra (resp,
945                              c_n * sizeof (struct GNUNET_CADET_Hash) +
946                              ch_n * sizeof (struct GCT_ChannelTunnelNumber),
947                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
948   resp->destination = msg->peer;
949   /* Do not reorder! #iter_channel needs counters in HBO! */
950   GCT_iterate_connections (t,
951                            &iter_connection,
952                            resp);
953   GCT_iterate_channels (t,
954                         &iter_channel,
955                         resp);
956   resp->connections = htonl (resp->connections);
957   resp->channels = htonl (resp->channels);
958   resp->cstate = htons (GCT_get_cstate (t));
959   resp->estate = htons (GCT_get_estate (t));
960   GNUNET_MQ_send (c->mq,
961                   env);
962   GNUNET_SERVICE_client_continue (c->client);
963 }
964
965
966 /**
967  * Iterator over all peers to dump info for each peer.
968  *
969  * @param cls Closure (unused).
970  * @param peer Peer ID (tunnel remote peer).
971  * @param value Peer info.
972  *
973  * @return #GNUNET_YES, to keep iterating.
974  */
975 static int
976 show_peer_iterator (void *cls,
977                     const struct GNUNET_PeerIdentity *peer,
978                     void *value)
979 {
980   struct CadetPeer *p = value;
981   struct CadetTunnel *t;
982
983   t = GCP_get_tunnel (p,
984                       GNUNET_NO);
985   if (NULL != t)
986     GCT_debug (t,
987                GNUNET_ERROR_TYPE_ERROR);
988   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
989   return GNUNET_YES;
990 }
991
992
993 /**
994  * Handler for client's INFO_DUMP request.
995  *
996  * @param cls Identification of the client.
997  * @param message The actual message.
998  */
999 static void
1000 handle_info_dump (void *cls,
1001                   const struct GNUNET_MessageHeader *message)
1002 {
1003   struct CadetClient *c = cls;
1004
1005   LOG (GNUNET_ERROR_TYPE_INFO,
1006        "Received dump info request from client %u\n",
1007        c->id);
1008
1009   LOG (GNUNET_ERROR_TYPE_ERROR,
1010        "*************************** DUMP START ***************************\n");
1011   for (struct CadetClient *ci = clients_head; NULL != ci; ci = ci->next)
1012   {
1013     LOG (GNUNET_ERROR_TYPE_ERROR,
1014          "Client %u (%p), handle: %p, ports: %u, own channels: %u, incoming channels: %u\n",
1015          ci->id,
1016          ci,
1017          ci->client,
1018          (NULL != c->ports)
1019          ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
1020          : 0,
1021          GNUNET_CONTAINER_multihashmap32_size (ci->own_channels),
1022          GNUNET_CONTAINER_multihashmap32_size (ci->incoming_channels));
1023   }
1024   LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
1025   GCP_iterate_all (&show_peer_iterator,
1026                    NULL);
1027
1028   LOG (GNUNET_ERROR_TYPE_ERROR,
1029        "**************************** DUMP END ****************************\n");
1030
1031   GNUNET_SERVICE_client_continue (c->client);
1032 }
1033
1034
1035
1036 /**
1037  * Callback called when a client connects to the service.
1038  *
1039  * @param cls closure for the service
1040  * @param client the new client that connected to the service
1041  * @param mq the message queue used to send messages to the client
1042  * @return @a c
1043  */
1044 static void *
1045 client_connect_cb (void *cls,
1046                    struct GNUNET_SERVICE_Client *client,
1047                    struct GNUNET_MQ_Handle *mq)
1048 {
1049   struct CadetClient *c;
1050
1051   c = GNUNET_new (struct CadetClient);
1052   c->client = client;
1053   c->mq = mq;
1054   c->id = next_client_id++; /* overflow not important: just for debug */
1055   c->own_channels
1056     = GNUNET_CONTAINER_multihashmap32_create (32);
1057   c->incoming_channels
1058     = GNUNET_CONTAINER_multihashmap32_create (32);
1059   GNUNET_CONTAINER_DLL_insert (clients_head,
1060                                clients_tail,
1061                                c);
1062   GNUNET_STATISTICS_update (stats,
1063                             "# clients",
1064                             +1,
1065                             GNUNET_NO);
1066   return c;
1067 }
1068
1069
1070 /**
1071  * Iterator for deleting each channel whose client endpoint disconnected.
1072  *
1073  * @param cls Closure (client that has disconnected).
1074  * @param key The local channel id (used to access the hashmap).
1075  * @param value The value stored at the key (channel to destroy).
1076  * @return #GNUNET_OK, keep iterating.
1077  */
1078 static int
1079 own_channel_destroy_iterator (void *cls,
1080                               uint32_t key,
1081                               void *value)
1082 {
1083   struct CadetClient *c = cls;
1084   struct CadetChannel *ch = value;
1085
1086   GNUNET_assert (GNUNET_YES ==
1087                  GNUNET_CONTAINER_multihashmap32_remove (c->own_channels,
1088                                                          key,
1089                                                          ch));
1090   LOG (GNUNET_ERROR_TYPE_DEBUG,
1091        "Destroying own channel %s, due to client %u shutdown.\n",
1092        GCCH_2s (ch),
1093        c->id);
1094   GCCH_channel_local_destroy (ch);
1095   return GNUNET_OK;
1096 }
1097
1098
1099 /**
1100  * Iterator for deleting each channel whose client endpoint disconnected.
1101  *
1102  * @param cls Closure (client that has disconnected).
1103  * @param key The local channel id (used to access the hashmap).
1104  * @param value The value stored at the key (channel to destroy).
1105  * @return #GNUNET_OK, keep iterating.
1106  */
1107 static int
1108 incoming_channel_destroy_iterator (void *cls,
1109                                    uint32_t key,
1110                                    void *value)
1111 {
1112   struct CadetChannel *ch = value;
1113   struct CadetClient *c = cls;
1114
1115   GNUNET_assert (GNUNET_YES ==
1116                  GNUNET_CONTAINER_multihashmap32_remove (c->incoming_channels,
1117                                                          key,
1118                                                          ch));
1119
1120   LOG (GNUNET_ERROR_TYPE_DEBUG,
1121        "Destroying incoming channel %s due to client %u shutdown.\n",
1122        GCCH_2s (ch),
1123        c->id);
1124   GCCH_channel_incoming_destroy (ch);
1125   return GNUNET_OK;
1126 }
1127
1128
1129 /**
1130  * Remove client's ports from the global hashmap on disconnect.
1131  *
1132  * @param cls Closure (unused).
1133  * @param key Port.
1134  * @param value the `struct CadetClient` to remove
1135  * @return #GNUNET_OK, keep iterating.
1136  */
1137 static int
1138 client_release_ports (void *cls,
1139                       const struct GNUNET_HashCode *key,
1140                       void *value)
1141 {
1142   struct CadetClient *c = value;
1143
1144   GNUNET_assert (GNUNET_YES ==
1145                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
1146                                                        key,
1147                                                        value));
1148   GNUNET_assert (GNUNET_YES ==
1149                  GNUNET_CONTAINER_multihashmap_remove (c->ports,
1150                                                        key,
1151                                                        value));
1152   return GNUNET_OK;
1153 }
1154
1155
1156 /**
1157  * Callback called when a client disconnected from the service
1158  *
1159  * @param cls closure for the service
1160  * @param client the client that disconnected
1161  * @param internal_cls should be equal to @a c
1162  */
1163 static void
1164 client_disconnect_cb (void *cls,
1165                       struct GNUNET_SERVICE_Client *client,
1166                       void *internal_cls)
1167 {
1168   struct CadetClient *c = internal_cls;
1169
1170   GNUNET_assert (c->client == client);
1171   c->shutting_down = GNUNET_YES;
1172   if (NULL != c->own_channels)
1173   {
1174     GNUNET_CONTAINER_multihashmap32_iterate (c->own_channels,
1175                                              &own_channel_destroy_iterator,
1176                                              c);
1177     GNUNET_CONTAINER_multihashmap32_destroy (c->own_channels);
1178   }
1179   if (NULL != c->incoming_channels)
1180   {
1181     GNUNET_CONTAINER_multihashmap32_iterate (c->incoming_channels,
1182                                              &incoming_channel_destroy_iterator,
1183                                              c);
1184     GNUNET_CONTAINER_multihashmap32_destroy (c->incoming_channels);
1185   }
1186   if (NULL != c->ports)
1187   {
1188     GNUNET_CONTAINER_multihashmap_iterate (c->ports,
1189                                            &client_release_ports,
1190                                            c);
1191     GNUNET_CONTAINER_multihashmap_destroy (c->ports);
1192   }
1193   GNUNET_CONTAINER_DLL_remove (clients_head,
1194                                clients_tail,
1195                                c);
1196   GNUNET_STATISTICS_update (stats,
1197                             "# clients",
1198                             -1,
1199                             GNUNET_NO);
1200   GNUNET_free (c);
1201 }
1202
1203
1204 /**
1205  * Setup CADET internals.
1206  *
1207  * @param cls closure
1208  * @param server the initialized server
1209  * @param c configuration to use
1210  */
1211 static void
1212 run (void *cls,
1213      const struct GNUNET_CONFIGURATION_Handle *c,
1214      struct GNUNET_SERVICE_Handle *service)
1215 {
1216   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1217   if (NULL == my_private_key)
1218   {
1219     GNUNET_break (0);
1220     GNUNET_SCHEDULER_shutdown ();
1221     return;
1222   }
1223   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1224                                       &my_full_id.public_key);
1225   stats = GNUNET_STATISTICS_create ("cadet",
1226                                     c);
1227   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1228                                  NULL);
1229   ats_ch = GNUNET_ATS_connectivity_init (c);
1230   /* FIXME: optimize code to allow GNUNET_YES here! */
1231   open_ports = GNUNET_CONTAINER_multihashmap_create (16,
1232                                                      GNUNET_NO);
1233   loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
1234                                                          GNUNET_NO);
1235   peers = GNUNET_CONTAINER_multipeermap_create (16,
1236                                                 GNUNET_YES);
1237   GCH_init (c);
1238   GCD_init (c);
1239   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1240               "CADET starting at peer %s\n",
1241               GNUNET_i2s (&my_full_id));
1242
1243 }
1244
1245
1246 /**
1247  * Define "main" method using service macro.
1248  */
1249 GNUNET_SERVICE_MAIN
1250 ("cadet",
1251  GNUNET_SERVICE_OPTION_NONE,
1252  &run,
1253  &client_connect_cb,
1254  &client_disconnect_cb,
1255  NULL,
1256  GNUNET_MQ_hd_fixed_size (port_open,
1257                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
1258                           struct GNUNET_CADET_PortMessage,
1259                           NULL),
1260  GNUNET_MQ_hd_fixed_size (port_close,
1261                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
1262                           struct GNUNET_CADET_PortMessage,
1263                           NULL),
1264  GNUNET_MQ_hd_fixed_size (channel_create,
1265                           GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE,
1266                           struct GNUNET_CADET_ChannelCreateMessage,
1267                           NULL),
1268  GNUNET_MQ_hd_fixed_size (channel_destroy,
1269                           GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY,
1270                           struct GNUNET_CADET_ChannelDestroyMessage,
1271                           NULL),
1272  GNUNET_MQ_hd_var_size (data,
1273                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1274                         struct GNUNET_CADET_LocalData,
1275                         NULL),
1276  GNUNET_MQ_hd_fixed_size (ack,
1277                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1278                           struct GNUNET_CADET_LocalAck,
1279                           NULL),
1280  GNUNET_MQ_hd_fixed_size (get_peers,
1281                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1282                           struct GNUNET_MessageHeader,
1283                           NULL),
1284  GNUNET_MQ_hd_fixed_size (show_peer,
1285                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1286                           struct GNUNET_CADET_LocalInfo,
1287                           NULL),
1288  GNUNET_MQ_hd_fixed_size (get_tunnels,
1289                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1290                           struct GNUNET_MessageHeader,
1291                           NULL),
1292  GNUNET_MQ_hd_fixed_size (show_tunnel,
1293                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1294                           struct GNUNET_CADET_LocalInfo,
1295                           NULL),
1296  GNUNET_MQ_hd_fixed_size (info_dump,
1297                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
1298                           struct GNUNET_MessageHeader,
1299                           NULL),
1300  GNUNET_MQ_handler_end ());
1301
1302 /* end of gnunet-service-cadet-new.c */