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