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