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