guard against 0
[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          (0 == payload_claimed_size) )
649     {
650       GNUNET_break_op (0);
651       return GNUNET_SYSERR;
652     }
653     payload_size -= payload_claimed_size;
654     buf += payload_claimed_size;
655   } while (payload_size >= sizeof (struct GNUNET_MessageHeader));
656   if (0 != payload_size)
657   {
658     GNUNET_break_op (0);
659     return GNUNET_SYSERR;
660   }
661   return GNUNET_OK;
662 }
663
664
665 /**
666  * Handler for client payload traffic to be send on a channel to
667  * another peer.
668  *
669  * @param cls identification of the client
670  * @param msg the actual message
671  */
672 static void
673 handle_data (void *cls,
674              const struct GNUNET_CADET_LocalData *msg)
675 {
676   struct CadetClient *c = cls;
677   struct CadetChannel *ch;
678   size_t payload_size;
679   const char *buf;
680
681   ch = lookup_channel (c,
682                        msg->ccn);
683   if (NULL == ch)
684   {
685     /* Channel does not exist! */
686     GNUNET_break (0);
687     GNUNET_SERVICE_client_drop (c->client);
688     return;
689   }
690   payload_size = ntohs (msg->header.size) - sizeof (*msg);
691   buf = (const char *) &msg[1];
692   LOG (GNUNET_ERROR_TYPE_DEBUG,
693        "Received %u bytes payload from %s for %s\n",
694        (unsigned int) payload_size,
695        GSC_2s (c),
696        GCCH_2s (ch));
697   if (GNUNET_OK !=
698       GCCH_handle_local_data (ch,
699                               buf,
700                               payload_size))
701   {
702     GNUNET_SERVICE_client_drop (c->client);
703     return;
704   }
705   GNUNET_SERVICE_client_continue (c->client);
706 }
707
708
709 /**
710  * Handler for client's ACKs for payload traffic.
711  *
712  * @param cls identification of the client.
713  * @param msg The actual message.
714  */
715 static void
716 handle_ack (void *cls,
717             const struct GNUNET_CADET_LocalAck *msg)
718 {
719   struct CadetClient *c = cls;
720   struct CadetChannel *ch;
721
722   ch = lookup_channel (c,
723                        msg->ccn);
724   if (NULL == ch)
725   {
726     /* Channel does not exist! */
727     GNUNET_break (0);
728     GNUNET_SERVICE_client_drop (c->client);
729     return;
730   }
731   LOG (GNUNET_ERROR_TYPE_DEBUG,
732        "Got a local ACK from %s for %s\n",
733        GSC_2s(c),
734        GCCH_2s (ch));
735   GCCH_handle_local_ack (ch);
736   GNUNET_SERVICE_client_continue (c->client);
737 }
738
739
740 /**
741  * Iterator over all peers to send a monitoring client info about each peer.
742  *
743  * @param cls Closure ().
744  * @param peer Peer ID (tunnel remote peer).
745  * @param value Peer info.
746  * @return #GNUNET_YES, to keep iterating.
747  */
748 static int
749 get_all_peers_iterator (void *cls,
750                         const struct GNUNET_PeerIdentity *peer,
751                         void *value)
752 {
753   struct CadetClient *c = cls;
754   struct CadetPeer *p = value;
755   struct GNUNET_MQ_Envelope *env;
756   struct GNUNET_CADET_LocalInfoPeer *msg;
757
758   env = GNUNET_MQ_msg (msg,
759                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
760   msg->destination = *peer;
761   msg->paths = htons (GCP_count_paths (p));
762   msg->tunnel = htons (NULL != GCP_get_tunnel (p,
763                                                GNUNET_NO));
764   GNUNET_MQ_send (c->mq,
765                   env);
766   return GNUNET_YES;
767 }
768
769
770 /**
771  * Handler for client's INFO PEERS request.
772  *
773  * @param cls Identification of the client.
774  * @param message The actual message.
775  */
776 static void
777 handle_get_peers (void *cls,
778                   const struct GNUNET_MessageHeader *message)
779 {
780   struct CadetClient *c = cls;
781   struct GNUNET_MQ_Envelope *env;
782   struct GNUNET_MessageHeader *reply;
783
784   GCP_iterate_all (&get_all_peers_iterator,
785                    c);
786   env = GNUNET_MQ_msg (reply,
787                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS);
788   GNUNET_MQ_send (c->mq,
789                   env);
790   GNUNET_SERVICE_client_continue (c->client);
791 }
792
793
794 /**
795  * Iterator over all paths of a peer to build an InfoPeer message.
796  * Message contains blocks of peers, first not included.
797  *
798  * @param cls message queue for transmission
799  * @param path Path itself
800  * @param off offset of the peer on @a path
801  * @return #GNUNET_YES if should keep iterating.
802  *         #GNUNET_NO otherwise.
803  */
804 static int
805 path_info_iterator (void *cls,
806                     struct CadetPeerPath *path,
807                     unsigned int off)
808 {
809   struct GNUNET_MQ_Handle *mq = cls;
810   struct GNUNET_MQ_Envelope *env;
811   struct GNUNET_MessageHeader *resp;
812   struct GNUNET_PeerIdentity *id;
813   uint16_t path_size;
814   unsigned int i;
815   unsigned int path_length;
816
817   path_length = GCPP_get_length (path);
818   path_size = sizeof (struct GNUNET_PeerIdentity) * (path_length - 1);
819   if (sizeof (*resp) + path_size > UINT16_MAX)
820   {
821     LOG (GNUNET_ERROR_TYPE_WARNING,
822          "Path of %u entries is too long for info message\n",
823          path_length);
824     return GNUNET_YES;
825   }
826   env = GNUNET_MQ_msg_extra (resp,
827                              path_size,
828                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER);
829   id = (struct GNUNET_PeerIdentity *) &resp[1];
830
831   /* Don't copy first peer.  First peer is always the local one.  Last
832    * peer is always the destination (leave as 0, EOL).
833    */
834   for (i = 0; i < off; i++)
835     id[i] = *GCP_get_id (GCPP_get_peer_at_offset (path,
836                                                   i + 1));
837   GNUNET_MQ_send (mq,
838                   env);
839   return GNUNET_YES;
840 }
841
842
843 /**
844  * Handler for client's SHOW_PEER request.
845  *
846  * @param cls Identification of the client.
847  * @param msg The actual message.
848  */
849 static void
850 handle_show_peer (void *cls,
851                   const struct GNUNET_CADET_LocalInfo *msg)
852 {
853   struct CadetClient *c = cls;
854   struct CadetPeer *p;
855   struct GNUNET_MQ_Envelope *env;
856   struct GNUNET_MessageHeader *resp;
857
858   p = GCP_get (&msg->peer,
859                GNUNET_NO);
860   if (NULL != p)
861     GCP_iterate_paths (p,
862                        &path_info_iterator,
863                        c->mq);
864   /* Send message with 0/0 to indicate the end */
865   env = GNUNET_MQ_msg (resp,
866                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER_END);
867   GNUNET_MQ_send (c->mq,
868                   env);
869   GNUNET_SERVICE_client_continue (c->client);
870 }
871
872
873 /**
874  * Iterator over all tunnels to send a monitoring client info about each tunnel.
875  *
876  * @param cls Closure ().
877  * @param peer Peer ID (tunnel remote peer).
878  * @param value a `struct CadetPeer`
879  * @return #GNUNET_YES, to keep iterating.
880  */
881 static int
882 get_all_tunnels_iterator (void *cls,
883                           const struct GNUNET_PeerIdentity *peer,
884                           void *value)
885 {
886   struct CadetClient *c = cls;
887   struct CadetPeer *p = value;
888   struct GNUNET_MQ_Envelope *env;
889   struct GNUNET_CADET_LocalInfoTunnel *msg;
890   struct CadetTunnel *t;
891
892   t = GCP_get_tunnel (p,
893                       GNUNET_NO);
894   if (NULL == t)
895     return GNUNET_YES;
896   env = GNUNET_MQ_msg (msg,
897                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
898   msg->destination = *peer;
899   msg->channels = htonl (GCT_count_channels (t));
900   msg->connections = htonl (GCT_count_any_connections (t));
901   msg->cstate = htons (0);
902   msg->estate = htons ((uint16_t) GCT_get_estate (t));
903   GNUNET_MQ_send (c->mq,
904                   env);
905   return GNUNET_YES;
906 }
907
908
909 /**
910  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS request.
911  *
912  * @param cls client Identification of the client.
913  * @param message The actual message.
914  */
915 static void
916 handle_info_tunnels (void *cls,
917                      const struct GNUNET_MessageHeader *message)
918 {
919   struct CadetClient *c = cls;
920   struct GNUNET_MQ_Envelope *env;
921   struct GNUNET_MessageHeader *reply;
922
923   GCP_iterate_all (&get_all_tunnels_iterator,
924                    c);
925   env = GNUNET_MQ_msg (reply,
926                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS);
927   GNUNET_MQ_send (c->mq,
928                   env);
929   GNUNET_SERVICE_client_continue (c->client);
930 }
931
932
933 /**
934  * Update the message with information about the connection.
935  *
936  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
937  * @param c a connection about which we should store information in @a cls
938  */
939 static void
940 iter_connection (void *cls,
941                  struct CadetConnection *c)
942 {
943   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
944   struct GNUNET_CADET_ConnectionTunnelIdentifier *h;
945
946   h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
947   h[msg->connections++] = *(GCC_get_id (c));
948 }
949
950
951 /**
952  * Update the message with information about the channel.
953  *
954  * @param cls a `struct GNUNET_CADET_LocalInfoTunnel` message to update
955  * @param ch a channel about which we should store information in @a cls
956  */
957 static void
958 iter_channel (void *cls,
959               struct CadetChannel *ch)
960 {
961   struct GNUNET_CADET_LocalInfoTunnel *msg = cls;
962   struct GNUNET_CADET_ConnectionTunnelIdentifier *h = (struct GNUNET_CADET_ConnectionTunnelIdentifier *) &msg[1];
963   struct GNUNET_CADET_ChannelTunnelNumber *chn
964     = (struct GNUNET_CADET_ChannelTunnelNumber *) &h[msg->connections];
965
966   chn[msg->channels++] = GCCH_get_id (ch);
967 }
968
969
970 /**
971  * Handler for client's #GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL request.
972  *
973  * @param cls Identification of the client.
974  * @param msg The actual message.
975  */
976 static void
977 handle_info_tunnel (void *cls,
978                     const struct GNUNET_CADET_LocalInfo *msg)
979 {
980   struct CadetClient *c = cls;
981   struct GNUNET_MQ_Envelope *env;
982   struct GNUNET_CADET_LocalInfoTunnel *resp;
983   struct CadetTunnel *t;
984   struct CadetPeer *p;
985   unsigned int ch_n;
986   unsigned int c_n;
987
988   p = GCP_get (&msg->peer,
989                GNUNET_NO);
990   t = GCP_get_tunnel (p,
991                       GNUNET_NO);
992   if (NULL == t)
993   {
994     /* We don't know the tunnel */
995     struct GNUNET_MQ_Envelope *env;
996     struct GNUNET_CADET_LocalInfoTunnel *warn;
997
998     LOG (GNUNET_ERROR_TYPE_INFO,
999          "Tunnel to %s unknown\n",
1000          GNUNET_i2s_full (&msg->peer));
1001     env = GNUNET_MQ_msg (warn,
1002                          GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1003     warn->destination = msg->peer;
1004     GNUNET_MQ_send (c->mq,
1005                     env);
1006     GNUNET_SERVICE_client_continue (c->client);
1007     return;
1008   }
1009
1010   /* Initialize context */
1011   ch_n = GCT_count_channels (t);
1012   c_n = GCT_count_any_connections (t);
1013   env = GNUNET_MQ_msg_extra (resp,
1014                              c_n * sizeof (struct GNUNET_CADET_ConnectionTunnelIdentifier) +
1015                              ch_n * sizeof (struct GNUNET_CADET_ChannelTunnelNumber),
1016                              GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL);
1017   resp->destination = msg->peer;
1018   /* Do not reorder! #iter_channel needs counters in HBO! */
1019   GCT_iterate_connections (t,
1020                            &iter_connection,
1021                            resp);
1022   GCT_iterate_channels (t,
1023                         &iter_channel,
1024                         resp);
1025   resp->connections = htonl (resp->connections);
1026   resp->channels = htonl (resp->channels);
1027   resp->cstate = htons (0);
1028   resp->estate = htons (GCT_get_estate (t));
1029   GNUNET_MQ_send (c->mq,
1030                   env);
1031   GNUNET_SERVICE_client_continue (c->client);
1032 }
1033
1034
1035 /**
1036  * Iterator over all peers to dump info for each peer.
1037  *
1038  * @param cls Closure (unused).
1039  * @param peer Peer ID (tunnel remote peer).
1040  * @param value Peer info.
1041  *
1042  * @return #GNUNET_YES, to keep iterating.
1043  */
1044 static int
1045 show_peer_iterator (void *cls,
1046                     const struct GNUNET_PeerIdentity *peer,
1047                     void *value)
1048 {
1049   struct CadetPeer *p = value;
1050   struct CadetTunnel *t;
1051
1052   t = GCP_get_tunnel (p,
1053                       GNUNET_NO);
1054   if (NULL != t)
1055     GCT_debug (t,
1056                GNUNET_ERROR_TYPE_ERROR);
1057   LOG (GNUNET_ERROR_TYPE_ERROR, "\n");
1058   return GNUNET_YES;
1059 }
1060
1061
1062 /**
1063  * Handler for client's INFO_DUMP request.
1064  *
1065  * @param cls Identification of the client.
1066  * @param message The actual message.
1067  */
1068 static void
1069 handle_info_dump (void *cls,
1070                   const struct GNUNET_MessageHeader *message)
1071 {
1072   struct CadetClient *c = cls;
1073
1074   LOG (GNUNET_ERROR_TYPE_INFO,
1075        "Received dump info request from client %u\n",
1076        c->id);
1077
1078   LOG (GNUNET_ERROR_TYPE_ERROR,
1079        "*************************** DUMP START ***************************\n");
1080   for (struct CadetClient *ci = clients_head;
1081        NULL != ci;
1082        ci = ci->next)
1083   {
1084     LOG (GNUNET_ERROR_TYPE_ERROR,
1085          "Client %u (%p), handle: %p, ports: %u, channels: %u\n",
1086          ci->id,
1087          ci,
1088          ci->client,
1089          (NULL != c->ports)
1090          ? GNUNET_CONTAINER_multihashmap_size (ci->ports)
1091          : 0,
1092          GNUNET_CONTAINER_multihashmap32_size (ci->channels));
1093   }
1094   LOG (GNUNET_ERROR_TYPE_ERROR, "***************************\n");
1095   GCP_iterate_all (&show_peer_iterator,
1096                    NULL);
1097
1098   LOG (GNUNET_ERROR_TYPE_ERROR,
1099        "**************************** DUMP END ****************************\n");
1100
1101   GNUNET_SERVICE_client_continue (c->client);
1102 }
1103
1104
1105
1106 /**
1107  * Callback called when a client connects to the service.
1108  *
1109  * @param cls closure for the service
1110  * @param client the new client that connected to the service
1111  * @param mq the message queue used to send messages to the client
1112  * @return @a c
1113  */
1114 static void *
1115 client_connect_cb (void *cls,
1116                    struct GNUNET_SERVICE_Client *client,
1117                    struct GNUNET_MQ_Handle *mq)
1118 {
1119   struct CadetClient *c;
1120
1121   c = GNUNET_new (struct CadetClient);
1122   c->client = client;
1123   c->mq = mq;
1124   c->id = next_client_id++; /* overflow not important: just for debug */
1125   c->channels
1126     = GNUNET_CONTAINER_multihashmap32_create (32);
1127   GNUNET_CONTAINER_DLL_insert (clients_head,
1128                                clients_tail,
1129                                c);
1130   GNUNET_STATISTICS_update (stats,
1131                             "# clients",
1132                             +1,
1133                             GNUNET_NO);
1134   LOG (GNUNET_ERROR_TYPE_DEBUG,
1135        "%s connected\n",
1136        GSC_2s (c));
1137   return c;
1138 }
1139
1140
1141 /**
1142  * A channel was destroyed by the other peer. Tell our client.
1143  *
1144  * @param c client that lost a channel
1145  * @param ccn channel identification number for the client
1146  * @param ch the channel object
1147  */
1148 void
1149 GSC_handle_remote_channel_destroy (struct CadetClient *c,
1150                                    struct GNUNET_CADET_ClientChannelNumber ccn,
1151                                    struct CadetChannel *ch)
1152 {
1153   struct GNUNET_MQ_Envelope *env;
1154   struct GNUNET_CADET_LocalChannelDestroyMessage *tdm;
1155
1156   env = GNUNET_MQ_msg (tdm,
1157                        GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY);
1158   tdm->ccn = ccn;
1159   GSC_send_to_client (c,
1160                       env);
1161   GNUNET_assert (GNUNET_YES ==
1162                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1163                                                          ntohl (ccn.channel_of_client),
1164                                                          ch));
1165 }
1166
1167
1168 /**
1169  * Iterator for deleting each channel whose client endpoint disconnected.
1170  *
1171  * @param cls Closure (client that has disconnected).
1172  * @param key The local channel id in host byte order
1173  * @param value The value stored at the key (channel to destroy).
1174  * @return #GNUNET_OK, keep iterating.
1175  */
1176 static int
1177 channel_destroy_iterator (void *cls,
1178                           uint32_t key,
1179                           void *value)
1180 {
1181   struct CadetClient *c = cls;
1182   struct CadetChannel *ch = value;
1183
1184   LOG (GNUNET_ERROR_TYPE_DEBUG,
1185        "Destroying %s, due to %s disconnecting.\n",
1186        GCCH_2s (ch),
1187        GSC_2s (c));
1188   GNUNET_assert (GNUNET_YES ==
1189                  GNUNET_CONTAINER_multihashmap32_remove (c->channels,
1190                                                          key,
1191                                                          ch));
1192   if (key < GNUNET_CADET_LOCAL_CHANNEL_ID_CLI)
1193     GCCH_channel_local_destroy (ch);
1194   else
1195     GCCH_channel_incoming_destroy (ch);
1196   return GNUNET_OK;
1197 }
1198
1199
1200 /**
1201  * Remove client's ports from the global hashmap on disconnect.
1202  *
1203  * @param cls Closure (unused).
1204  * @param key the port.
1205  * @param value the `struct CadetClient` to remove
1206  * @return #GNUNET_OK, keep iterating.
1207  */
1208 static int
1209 client_release_ports (void *cls,
1210                       const struct GNUNET_HashCode *key,
1211                       void *value)
1212 {
1213   struct CadetClient *c = value;
1214
1215   LOG (GNUNET_ERROR_TYPE_DEBUG,
1216        "Closing port %s due to %s disconnect.\n",
1217        GNUNET_h2s (key),
1218        GSC_2s (c));
1219   GNUNET_assert (GNUNET_YES ==
1220                  GNUNET_CONTAINER_multihashmap_remove (open_ports,
1221                                                        key,
1222                                                        value));
1223   GNUNET_assert (GNUNET_YES ==
1224                  GNUNET_CONTAINER_multihashmap_remove (c->ports,
1225                                                        key,
1226                                                        value));
1227   return GNUNET_OK;
1228 }
1229
1230
1231 /**
1232  * Callback called when a client disconnected from the service
1233  *
1234  * @param cls closure for the service
1235  * @param client the client that disconnected
1236  * @param internal_cls should be equal to @a c
1237  */
1238 static void
1239 client_disconnect_cb (void *cls,
1240                       struct GNUNET_SERVICE_Client *client,
1241                       void *internal_cls)
1242 {
1243   struct CadetClient *c = internal_cls;
1244
1245   GNUNET_assert (c->client == client);
1246   LOG (GNUNET_ERROR_TYPE_DEBUG,
1247        "%s is disconnecting.\n",
1248        GSC_2s (c));
1249   if (NULL != c->channels)
1250   {
1251     GNUNET_CONTAINER_multihashmap32_iterate (c->channels,
1252                                              &channel_destroy_iterator,
1253                                              c);
1254     GNUNET_CONTAINER_multihashmap32_destroy (c->channels);
1255   }
1256   if (NULL != c->ports)
1257   {
1258     GNUNET_CONTAINER_multihashmap_iterate (c->ports,
1259                                            &client_release_ports,
1260                                            c);
1261     GNUNET_CONTAINER_multihashmap_destroy (c->ports);
1262   }
1263   GNUNET_CONTAINER_DLL_remove (clients_head,
1264                                clients_tail,
1265                                c);
1266   GNUNET_STATISTICS_update (stats,
1267                             "# clients",
1268                             -1,
1269                             GNUNET_NO);
1270   GNUNET_free (c);
1271 }
1272
1273
1274 /**
1275  * Setup CADET internals.
1276  *
1277  * @param cls closure
1278  * @param server the initialized server
1279  * @param c configuration to use
1280  */
1281 static void
1282 run (void *cls,
1283      const struct GNUNET_CONFIGURATION_Handle *c,
1284      struct GNUNET_SERVICE_Handle *service)
1285 {
1286   cfg = c;
1287   if (GNUNET_OK !=
1288       GNUNET_CONFIGURATION_get_value_number (c,
1289                                              "CADET",
1290                                              "RATCHET_MESSAGES",
1291                                              &ratchet_messages))
1292   {
1293     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1294                                "CADET",
1295                                "RATCHET_MESSAGES",
1296                                "needs to be a number");
1297     ratchet_messages = 64;
1298   }
1299   if (GNUNET_OK !=
1300       GNUNET_CONFIGURATION_get_value_time (c,
1301                                            "CADET",
1302                                            "RATCHET_TIME",
1303                                            &ratchet_time))
1304   {
1305     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1306                                "CADET",
1307                                "RATCHET_TIME",
1308                                "need delay value");
1309     ratchet_time = GNUNET_TIME_UNIT_HOURS;
1310   }
1311
1312   my_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1313   if (NULL == my_private_key)
1314   {
1315     GNUNET_break (0);
1316     GNUNET_SCHEDULER_shutdown ();
1317     return;
1318   }
1319   GNUNET_CRYPTO_eddsa_key_get_public (my_private_key,
1320                                       &my_full_id.public_key);
1321   stats = GNUNET_STATISTICS_create ("cadet",
1322                                     c);
1323   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1324                                  NULL);
1325   ats_ch = GNUNET_ATS_connectivity_init (c);
1326   /* FIXME: optimize code to allow GNUNET_YES here! */
1327   open_ports = GNUNET_CONTAINER_multihashmap_create (16,
1328                                                      GNUNET_NO);
1329   loose_channels = GNUNET_CONTAINER_multihashmap_create (16,
1330                                                          GNUNET_NO);
1331   peers = GNUNET_CONTAINER_multipeermap_create (16,
1332                                                 GNUNET_YES);
1333   connections = GNUNET_CONTAINER_multishortmap_create (256,
1334                                                        GNUNET_YES);
1335   GCH_init (c);
1336   GCD_init (c);
1337   GCO_init (c);
1338   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1339               "CADET started for peer %s\n",
1340               GNUNET_i2s (&my_full_id));
1341
1342 }
1343
1344
1345 /**
1346  * Define "main" method using service macro.
1347  */
1348 GNUNET_SERVICE_MAIN
1349 ("cadet",
1350  GNUNET_SERVICE_OPTION_NONE,
1351  &run,
1352  &client_connect_cb,
1353  &client_disconnect_cb,
1354  NULL,
1355  GNUNET_MQ_hd_fixed_size (port_open,
1356                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_OPEN,
1357                           struct GNUNET_CADET_PortMessage,
1358                           NULL),
1359  GNUNET_MQ_hd_fixed_size (port_close,
1360                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_PORT_CLOSE,
1361                           struct GNUNET_CADET_PortMessage,
1362                           NULL),
1363  GNUNET_MQ_hd_fixed_size (channel_create,
1364                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_CREATE,
1365                           struct GNUNET_CADET_LocalChannelCreateMessage,
1366                           NULL),
1367  GNUNET_MQ_hd_fixed_size (channel_destroy,
1368                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_CHANNEL_DESTROY,
1369                           struct GNUNET_CADET_LocalChannelDestroyMessage,
1370                           NULL),
1371  GNUNET_MQ_hd_var_size (data,
1372                         GNUNET_MESSAGE_TYPE_CADET_LOCAL_DATA,
1373                         struct GNUNET_CADET_LocalData,
1374                         NULL),
1375  GNUNET_MQ_hd_fixed_size (ack,
1376                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_ACK,
1377                           struct GNUNET_CADET_LocalAck,
1378                           NULL),
1379  GNUNET_MQ_hd_fixed_size (get_peers,
1380                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEERS,
1381                           struct GNUNET_MessageHeader,
1382                           NULL),
1383  GNUNET_MQ_hd_fixed_size (show_peer,
1384                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_PEER,
1385                           struct GNUNET_CADET_LocalInfo,
1386                           NULL),
1387  GNUNET_MQ_hd_fixed_size (info_tunnels,
1388                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNELS,
1389                           struct GNUNET_MessageHeader,
1390                           NULL),
1391  GNUNET_MQ_hd_fixed_size (info_tunnel,
1392                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_TUNNEL,
1393                           struct GNUNET_CADET_LocalInfo,
1394                           NULL),
1395  GNUNET_MQ_hd_fixed_size (info_dump,
1396                           GNUNET_MESSAGE_TYPE_CADET_LOCAL_INFO_DUMP,
1397                           struct GNUNET_MessageHeader,
1398                           NULL),
1399  GNUNET_MQ_handler_end ());
1400
1401 /* end of gnunet-service-cadet-new.c */