more work on new CADET
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_tunnels.c
1
2 /*
3      This file is part of GNUnet.
4      Copyright (C) 2013, 2017 GNUnet e.V.
5
6      GNUnet is free software; you can redistribute it and/or modify
7      it under the terms of the GNU General Public License as published
8      by the Free Software Foundation; either version 3, or (at your
9      option) any later version.
10
11      GNUnet is distributed in the hope that it will be useful, but
12      WITHOUT ANY WARRANTY; without even the implied warranty of
13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14      General Public License for more details.
15
16      You should have received a copy of the GNU General Public License
17      along with GNUnet; see the file COPYING.  If not, write to the
18      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19      Boston, MA 02110-1301, USA.
20 */
21
22 /**
23  * @file cadet/gnunet-service-cadet-new_tunnels.c
24  * @brief Information we track per tunnel.
25  * @author Bartlomiej Polot
26  * @author Christian Grothoff
27  *
28  * FIXME:
29  * - when managing connections, distinguish those that
30  *   have (recently) had traffic from those that were
31  *   never ready (or not recently)
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_signatures.h"
36 #include "cadet_protocol.h"
37 #include "cadet_path.h"
38 #include "gnunet-service-cadet-new.h"
39 #include "gnunet-service-cadet-new_channel.h"
40 #include "gnunet-service-cadet-new_connection.h"
41 #include "gnunet-service-cadet-new_tunnels.h"
42 #include "gnunet-service-cadet-new_peer.h"
43 #include "gnunet-service-cadet-new_paths.h"
44
45
46 /**
47  * How long do we wait until tearing down an idle tunnel?
48  */
49 #define IDLE_DESTROY_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
50
51
52 /**
53  * Struct to old keys for skipped messages while advancing the Axolotl ratchet.
54  */
55 struct CadetTunnelSkippedKey
56 {
57   /**
58    * DLL next.
59    */
60   struct CadetTunnelSkippedKey *next;
61
62   /**
63    * DLL prev.
64    */
65   struct CadetTunnelSkippedKey *prev;
66
67   /**
68    * When was this key stored (for timeout).
69    */
70   struct GNUNET_TIME_Absolute timestamp;
71
72   /**
73    * Header key.
74    */
75   struct GNUNET_CRYPTO_SymmetricSessionKey HK;
76
77   /**
78    * Message key.
79    */
80   struct GNUNET_CRYPTO_SymmetricSessionKey MK;
81
82   /**
83    * Key number for a given HK.
84    */
85   unsigned int Kn;
86 };
87
88
89 /**
90  * Axolotl data, according to https://github.com/trevp/axolotl/wiki .
91  */
92 struct CadetTunnelAxolotl
93 {
94   /**
95    * A (double linked) list of stored message keys and associated header keys
96    * for "skipped" messages, i.e. messages that have not been
97    * received despite the reception of more recent messages, (head).
98    */
99   struct CadetTunnelSkippedKey *skipped_head;
100
101   /**
102    * Skipped messages' keys DLL, tail.
103    */
104   struct CadetTunnelSkippedKey *skipped_tail;
105
106   /**
107    * 32-byte root key which gets updated by DH ratchet.
108    */
109   struct GNUNET_CRYPTO_SymmetricSessionKey RK;
110
111   /**
112    * 32-byte header key (send).
113    */
114   struct GNUNET_CRYPTO_SymmetricSessionKey HKs;
115
116   /**
117    * 32-byte header key (recv)
118    */
119   struct GNUNET_CRYPTO_SymmetricSessionKey HKr;
120
121   /**
122    * 32-byte next header key (send).
123    */
124   struct GNUNET_CRYPTO_SymmetricSessionKey NHKs;
125
126   /**
127    * 32-byte next header key (recv).
128    */
129   struct GNUNET_CRYPTO_SymmetricSessionKey NHKr;
130
131   /**
132    * 32-byte chain keys (used for forward-secrecy updating, send).
133    */
134   struct GNUNET_CRYPTO_SymmetricSessionKey CKs;
135
136   /**
137    * 32-byte chain keys (used for forward-secrecy updating, recv).
138    */
139   struct GNUNET_CRYPTO_SymmetricSessionKey CKr;
140
141   /**
142    * ECDH for key exchange (A0 / B0).
143    */
144   struct GNUNET_CRYPTO_EcdhePrivateKey *kx_0;
145
146   /**
147    * ECDH Ratchet key (send).
148    */
149   struct GNUNET_CRYPTO_EcdhePrivateKey *DHRs;
150
151   /**
152    * ECDH Ratchet key (recv).
153    */
154   struct GNUNET_CRYPTO_EcdhePublicKey DHRr;
155
156   /**
157    * When does this ratchet expire and a new one is triggered.
158    */
159   struct GNUNET_TIME_Absolute ratchet_expiration;
160
161   /**
162    * Number of elements in @a skipped_head <-> @a skipped_tail.
163    */
164   unsigned int skipped;
165
166   /**
167    * Message number (reset to 0 with each new ratchet, next message to send).
168    */
169   uint32_t Ns;
170
171   /**
172    * Message number (reset to 0 with each new ratchet, next message to recv).
173    */
174   uint32_t Nr;
175
176   /**
177    * Previous message numbers (# of msgs sent under prev ratchet)
178    */
179   uint32_t PNs;
180
181   /**
182    * True (#GNUNET_YES) if we have to send a new ratchet key in next msg.
183    */
184   int ratchet_flag;
185
186   /**
187    * Number of messages recieved since our last ratchet advance.
188    * - If this counter = 0, we cannot send a new ratchet key in next msg.
189    * - If this counter > 0, we can (but don't yet have to) send a new key.
190    */
191   unsigned int ratchet_allowed;
192
193   /**
194    * Number of messages recieved since our last ratchet advance.
195    * - If this counter = 0, we cannot send a new ratchet key in next msg.
196    * - If this counter > 0, we can (but don't yet have to) send a new key.
197    */
198   unsigned int ratchet_counter;
199
200 };
201
202
203 /**
204  * Entry in list of connections used by tunnel, with metadata.
205  */
206 struct CadetTConnection
207 {
208   /**
209    * Next in DLL.
210    */
211   struct CadetTConnection *next;
212
213   /**
214    * Prev in DLL.
215    */
216   struct CadetTConnection *prev;
217
218   /**
219    * Connection handle.
220    */
221   struct CadetConnection *cc;
222
223   /**
224    * Tunnel this connection belongs to.
225    */
226   struct CadetTunnel *t;
227
228   /**
229    * Creation time, to keep oldest connection alive.
230    */
231   struct GNUNET_TIME_Absolute created;
232
233   /**
234    * Connection throughput, to keep fastest connection alive.
235    */
236   uint32_t throughput;
237 };
238
239
240 /**
241  * Struct used to save messages in a non-ready tunnel to send once connected.
242  */
243 struct CadetTunnelQueueEntry
244 {
245   /**
246    * We are entries in a DLL
247    */
248   struct CadetTunnelQueueEntry *next;
249
250   /**
251    * We are entries in a DLL
252    */
253   struct CadetTunnelQueueEntry *prev;
254
255   /**
256    * Tunnel these messages belong in.
257    */
258   struct CadetTunnel *t;
259
260   /**
261    * Continuation to call once sent (on the channel layer).
262    */
263   GNUNET_SCHEDULER_TaskCallback cont;
264
265   /**
266    * Closure for @c cont.
267    */
268   void *cont_cls;
269
270   /**
271    * Envelope of message to send follows.
272    */
273   struct GNUNET_MQ_Envelope *env;
274 };
275
276
277 /**
278  * Struct containing all information regarding a tunnel to a peer.
279  */
280 struct CadetTunnel
281 {
282   /**
283    * Destination of the tunnel.
284    */
285   struct CadetPeer *destination;
286
287   /**
288    * Peer's ephemeral key, to recreate @c e_key and @c d_key when own
289    * ephemeral key changes.
290    */
291   struct GNUNET_CRYPTO_EcdhePublicKey peers_ephemeral_key;
292
293   /**
294    * Encryption ("our") key. It is only "confirmed" if kx_ctx is NULL.
295    */
296   struct GNUNET_CRYPTO_SymmetricSessionKey e_key;
297
298   /**
299    * Decryption ("their") key. It is only "confirmed" if kx_ctx is NULL.
300    */
301   struct GNUNET_CRYPTO_SymmetricSessionKey d_key;
302
303   /**
304    * Axolotl info.
305    */
306   struct CadetTunnelAxolotl ax;
307
308   /**
309    * State of the tunnel connectivity.
310    */
311   enum CadetTunnelCState cstate;
312
313   /**
314    * State of the tunnel encryption.
315    */
316   enum CadetTunnelEState estate;
317
318   /**
319    * Task to start the rekey process.
320    */
321   struct GNUNET_SCHEDULER_Task *rekey_task;
322
323   /**
324    * DLL of connections that are actively used to reach the destination peer.
325    */
326   struct CadetTConnection *connection_head;
327
328   /**
329    * DLL of connections that are actively used to reach the destination peer.
330    */
331   struct CadetTConnection *connection_tail;
332
333   /**
334    * Channels inside this tunnel. Maps
335    * `struct GCT_ChannelTunnelNumber` to a `struct CadetChannel`.
336    */
337   struct GNUNET_CONTAINER_MultiHashMap32 *channels;
338
339   /**
340    * Channel ID for the next created channel in this tunnel.
341    */
342   struct GCT_ChannelTunnelNumber next_chid;
343
344   /**
345    * Queued messages, to transmit once tunnel gets connected.
346    */
347   struct CadetTunnelQueueEntry *tq_head;
348
349   /**
350    * Queued messages, to transmit once tunnel gets connected.
351    */
352   struct CadetTunnelQueueEntry *tq_tail;
353
354   /**
355    * Task scheduled if there are no more channels using the tunnel.
356    */
357   struct GNUNET_SCHEDULER_Task *destroy_task;
358
359   /**
360    * Task to trim connections if too many are present.
361    */
362   struct GNUNET_SCHEDULER_Task *maintain_connections_task;
363
364   /**
365    * Ephemeral message in the queue (to avoid queueing more than one).
366    */
367   struct CadetConnectionQueue *ephm_hKILL;
368
369   /**
370    * Pong message in the queue.
371    */
372   struct CadetConnectionQueue *pong_hKILL;
373
374   /**
375    * Number of connections in the @e connection_head DLL.
376    */
377   unsigned int num_connections;
378
379   /**
380    * Number of entries in the @e tq_head DLL.
381    */
382   unsigned int tq_len;
383 };
384
385
386 /**
387  * Get the static string for the peer this tunnel is directed.
388  *
389  * @param t Tunnel.
390  *
391  * @return Static string the destination peer's ID.
392  */
393 const char *
394 GCT_2s (const struct CadetTunnel *t)
395 {
396   static char buf[64];
397
398   if (NULL == t)
399     return "T(NULL)";
400
401   GNUNET_snprintf (buf,
402                    sizeof (buf),
403                    "T(%s)",
404                    GCP_2s (t->destination));
405   return buf;
406 }
407
408
409 /**
410  * Return the peer to which this tunnel goes.
411  *
412  * @param t a tunnel
413  * @return the destination of the tunnel
414  */
415 struct CadetPeer *
416 GCT_get_destination (struct CadetTunnel *t)
417 {
418   return t->destination;
419 }
420
421
422 /**
423  * Count channels of a tunnel.
424  *
425  * @param t Tunnel on which to count.
426  *
427  * @return Number of channels.
428  */
429 unsigned int
430 GCT_count_channels (struct CadetTunnel *t)
431 {
432   return GNUNET_CONTAINER_multihashmap32_size (t->channels);
433 }
434
435
436 /**
437  * Count all created connections of a tunnel. Not necessarily ready connections!
438  *
439  * @param t Tunnel on which to count.
440  *
441  * @return Number of connections created, either being established or ready.
442  */
443 unsigned int
444 GCT_count_any_connections (struct CadetTunnel *t)
445 {
446   return t->num_connections;
447 }
448
449
450 /**
451  * Get the connectivity state of a tunnel.
452  *
453  * @param t Tunnel.
454  *
455  * @return Tunnel's connectivity state.
456  */
457 enum CadetTunnelCState
458 GCT_get_cstate (struct CadetTunnel *t)
459 {
460   return t->cstate;
461 }
462
463
464 /**
465  * Get the encryption state of a tunnel.
466  *
467  * @param t Tunnel.
468  *
469  * @return Tunnel's encryption state.
470  */
471 enum CadetTunnelEState
472 GCT_get_estate (struct CadetTunnel *t)
473 {
474   return t->estate;
475 }
476
477
478 /**
479  * Add a channel to a tunnel.
480  *
481  * @param t Tunnel.
482  * @param ch Channel
483  * @return unique number identifying @a ch within @a t
484  */
485 struct GCT_ChannelTunnelNumber
486 GCT_add_channel (struct CadetTunnel *t,
487                  struct CadetChannel *ch)
488 {
489   struct GCT_ChannelTunnelNumber ret;
490   uint32_t chid;
491
492   chid = ntohl (t->next_chid.channel_in_tunnel);
493   while (NULL !=
494          GNUNET_CONTAINER_multihashmap32_get (t->channels,
495                                               chid))
496     chid++;
497   GNUNET_assert (GNUNET_YES ==
498                  GNUNET_CONTAINER_multihashmap32_put (t->channels,
499                                                       chid,
500                                                       ch,
501                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
502   t->next_chid.channel_in_tunnel = htonl (chid + 1);
503   ret.channel_in_tunnel = htonl (chid);
504   return ret;
505 }
506
507
508 /**
509  * This tunnel is no longer used, destroy it.
510  *
511  * @param cls the idle tunnel
512  */
513 static void
514 destroy_tunnel (void *cls)
515 {
516   struct CadetTunnel *t = cls;
517   struct CadetTConnection *ct;
518   struct CadetTunnelQueueEntry *tqe;
519
520   t->destroy_task = NULL;
521   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (t->channels));
522   while (NULL != (ct = t->connection_head))
523   {
524     GNUNET_assert (ct->t == t);
525     GNUNET_CONTAINER_DLL_remove (t->connection_head,
526                                  t->connection_tail,
527                                  ct);
528     GCC_destroy (ct->cc);
529     GNUNET_free (ct);
530   }
531   while (NULL != (tqe = t->tq_head))
532   {
533     GNUNET_CONTAINER_DLL_remove (t->tq_head,
534                                  t->tq_tail,
535                                  tqe);
536     GNUNET_MQ_discard (tqe->env);
537     GNUNET_free (tqe);
538   }
539   GCP_drop_tunnel (t->destination,
540                    t);
541   GNUNET_CONTAINER_multihashmap32_destroy (t->channels);
542   if (NULL != t->maintain_connections_task)
543   {
544     GNUNET_SCHEDULER_cancel (t->maintain_connections_task);
545     t->maintain_connections_task = NULL;
546   }
547   GNUNET_free (t);
548 }
549
550
551 /**
552  * A connection is ready for transmission.  Looks at our message queue
553  * and if there is a message, sends it out via the connection.
554  *
555  * @param cls the `struct CadetTConnection` that is ready
556  */
557 static void
558 connection_ready_cb (void *cls)
559 {
560   struct CadetTConnection *ct = cls;
561   struct CadetTunnel *t = ct->t;
562   struct CadetTunnelQueueEntry *tq = t->tq_head;
563
564   if (NULL == tq)
565     return; /* no messages pending right now */
566
567   /* ready to send message 'tq' on tunnel 'ct' */
568   GNUNET_assert (t == tq->t);
569   GNUNET_CONTAINER_DLL_remove (t->tq_head,
570                                t->tq_tail,
571                                tq);
572   GCC_transmit (ct->cc,
573                 tq->env);
574   tq->cont (tq->cont_cls);
575   GNUNET_free (tq);
576 }
577
578
579 /**
580  * Called when either we have a new connection, or a new message in the
581  * queue, or some existing connection has transmission capacity.  Looks
582  * at our message queue and if there is a message, picks a connection
583  * to send it on.
584  *
585  * @param t tunnel to process messages on
586  */
587 static void
588 trigger_transmissions (struct CadetTunnel *t)
589 {
590   struct CadetTConnection *ct;
591
592   if (NULL == t->tq_head)
593     return; /* no messages pending right now */
594   for (ct = t->connection_head;
595        NULL != ct;
596        ct = ct->next)
597     if (GNUNET_YES == GCC_is_ready (ct->cc))
598       break;
599   if (NULL == ct)
600     return; /* no connections ready */
601   connection_ready_cb (ct);
602 }
603
604
605 /**
606  * Function called to maintain the connections underlying our tunnel.
607  * Tries to maintain (incl. tear down) connections for the tunnel, and
608  * if there is a significant change, may trigger transmissions.
609  *
610  * Basically, needs to check if there are connections that perform
611  * badly, and if so eventually kill them and trigger a replacement.
612  * The strategy is to open one more connection than
613  * #DESIRED_CONNECTIONS_PER_TUNNEL, and then periodically kick out the
614  * least-performing one, and then inquire for new ones.
615  *
616  * @param cls the `struct CadetTunnel`
617  */
618 static void
619 maintain_connections_cb (void *cls)
620 {
621   struct CadetTunnel *t = cls;
622
623   GNUNET_break (0); // FIXME: implement!
624 }
625
626
627 /**
628  * Consider using the path @a p for the tunnel @a t.
629  * The tunnel destination is at offset @a off in path @a p.
630  *
631  * @param cls our tunnel
632  * @param path a path to our destination
633  * @param off offset of the destination on path @a path
634  * @return #GNUNET_YES (should keep iterating)
635  */
636 static int
637 consider_path_cb (void *cls,
638                   struct CadetPeerPath *path,
639                   unsigned int off)
640 {
641   struct CadetTunnel *t = cls;
642   unsigned int min_length = UINT_MAX;
643   GNUNET_CONTAINER_HeapCostType max_desire = 0;
644   struct CadetTConnection *ct;
645
646   /* Check if we care about the new path. */
647   for (ct = t->connection_head;
648        NULL != ct;
649        ct = ct->next)
650   {
651     struct CadetPeerPath *ps;
652
653     ps = GCC_get_path (ct->cc);
654     if (ps == path)
655       return GNUNET_YES; /* duplicate */
656     min_length = GNUNET_MIN (min_length,
657                              GCPP_get_length (ps));
658     max_desire = GNUNET_MAX (max_desire,
659                              GCPP_get_desirability (ps));
660   }
661
662   /* FIXME: not sure we should really just count
663      'num_connections' here, as they may all have
664      consistently failed to connect. */
665
666   /* We iterate by increasing path length; if we have enough paths and
667      this one is more than twice as long than what we are currently
668      using, then ignore all of these super-long ones! */
669   if ( (t->num_connections > DESIRED_CONNECTIONS_PER_TUNNEL) &&
670        (min_length * 2 < off) )
671   {
672     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
673                 "Ignoring paths of length %u, they are way too long.\n",
674                 min_length * 2);
675     return GNUNET_NO;
676   }
677   /* If we have enough paths and this one looks no better, ignore it. */
678   if ( (t->num_connections >= DESIRED_CONNECTIONS_PER_TUNNEL) &&
679        (min_length < GCPP_get_length (path)) &&
680        (max_desire > GCPP_get_desirability (path)) )
681   {
682     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
683                 "Ignoring path (%u/%llu) to %s, got something better already.\n",
684                 GCPP_get_length (path),
685                 (unsigned long long) GCPP_get_desirability (path),
686                 GCP_2s (t->destination));
687     return GNUNET_YES;
688   }
689
690   /* Path is interesting (better by some metric, or we don't have
691      enough paths yet). */
692   ct = GNUNET_new (struct CadetTConnection);
693   ct->created = GNUNET_TIME_absolute_get ();
694   ct->t = t;
695   ct->cc = GCC_create (t->destination,
696                        path,
697                        &connection_ready_cb,
698                        t);
699   /* FIXME: schedule job to kill connection (and path?)  if it takes
700      too long to get ready! (And track performance data on how long
701      other connections took with the tunnel!)
702      => Note: to be done within 'connection'-logic! */
703   GNUNET_CONTAINER_DLL_insert (t->connection_head,
704                                t->connection_tail,
705                                ct);
706   t->num_connections++;
707   return GNUNET_YES;
708 }
709
710
711 /**
712  * Consider using the path @a p for the tunnel @a t.
713  * The tunnel destination is at offset @a off in path @a p.
714  *
715  * @param cls our tunnel
716  * @param path a path to our destination
717  * @param off offset of the destination on path @a path
718  */
719 void
720 GCT_consider_path (struct CadetTunnel *t,
721                    struct CadetPeerPath *p,
722                    unsigned int off)
723 {
724   (void) consider_path_cb (t,
725                            p,
726                            off);
727 }
728
729
730 /**
731  * Create a tunnel to @a destionation.  Must only be called
732  * from within #GCP_get_tunnel().
733  *
734  * @param destination where to create the tunnel to
735  * @return new tunnel to @a destination
736  */
737 struct CadetTunnel *
738 GCT_create_tunnel (struct CadetPeer *destination)
739 {
740   struct CadetTunnel *t;
741
742   t = GNUNET_new (struct CadetTunnel);
743   t->destination = destination;
744   t->channels = GNUNET_CONTAINER_multihashmap32_create (8);
745   (void) GCP_iterate_paths (destination,
746                             &consider_path_cb,
747                             t);
748   t->maintain_connections_task
749     = GNUNET_SCHEDULER_add_now (&maintain_connections_cb,
750                                 t);
751   return t;
752 }
753
754
755 /**
756  * Remove a channel from a tunnel.
757  *
758  * @param t Tunnel.
759  * @param ch Channel
760  * @param gid unique number identifying @a ch within @a t
761  */
762 void
763 GCT_remove_channel (struct CadetTunnel *t,
764                     struct CadetChannel *ch,
765                     struct GCT_ChannelTunnelNumber gid)
766 {
767   GNUNET_assert (GNUNET_YES ==
768                  GNUNET_CONTAINER_multihashmap32_remove (t->channels,
769                                                          ntohl (gid.channel_in_tunnel),
770                                                          ch));
771   if (0 ==
772       GNUNET_CONTAINER_multihashmap32_size (t->channels))
773   {
774     t->destroy_task = GNUNET_SCHEDULER_add_delayed (IDLE_DESTROY_DELAY,
775                                                     &destroy_tunnel,
776                                                     t);
777   }
778 }
779
780
781 /**
782  * Sends an already built message on a tunnel, encrypting it and
783  * choosing the best connection if not provided.
784  *
785  * @param message Message to send. Function modifies it.
786  * @param t Tunnel on which this message is transmitted.
787  * @param cont Continuation to call once message is really sent.
788  * @param cont_cls Closure for @c cont.
789  * @return Handle to cancel message. NULL if @c cont is NULL.
790  */
791 struct CadetTunnelQueueEntry *
792 GCT_send (struct CadetTunnel *t,
793           const struct GNUNET_MessageHeader *message,
794           GNUNET_SCHEDULER_TaskCallback cont,
795           void *cont_cls)
796 {
797   struct CadetTunnelQueueEntry *q;
798   uint16_t payload_size;
799
800   payload_size = ntohs (message->size);
801
802   q = GNUNET_malloc (sizeof (*q) +
803                      payload_size);
804   /* FIXME: encrypt 'message' to end of 'q' */
805   q->t = t;
806   q->cont = cont;
807   q->cont_cls = cont_cls;
808   GNUNET_CONTAINER_DLL_insert_tail (t->tq_head,
809                                     t->tq_tail,
810                                     q);
811   /* FIXME: what about KX being ready? */
812   trigger_transmissions (t);
813   return q;
814 }
815
816
817 /**
818  * Cancel a previously sent message while it's in the queue.
819  *
820  * ONLY can be called before the continuation given to the send
821  * function is called. Once the continuation is called, the message is
822  * no longer in the queue!
823  *
824  * @param q Handle to the queue entry to cancel.
825  */
826 void
827 GCT_send_cancel (struct CadetTunnelQueueEntry *q)
828 {
829   struct CadetTunnel *t = q->t;
830
831   GNUNET_CONTAINER_DLL_remove (t->tq_head,
832                                t->tq_tail,
833                                q);
834   GNUNET_free (q);
835 }
836
837
838 /**
839  * Iterate over all connections of a tunnel.
840  *
841  * @param t Tunnel whose connections to iterate.
842  * @param iter Iterator.
843  * @param iter_cls Closure for @c iter.
844  */
845 void
846 GCT_iterate_connections (struct CadetTunnel *t,
847                          GCT_ConnectionIterator iter,
848                          void *iter_cls)
849 {
850   for (struct CadetTConnection *ct = t->connection_head;
851        NULL != ct;
852        ct = ct->next)
853     iter (iter_cls,
854           ct->cc);
855 }
856
857
858 /**
859  * Closure for #iterate_channels_cb.
860  */
861 struct ChanIterCls
862 {
863   /**
864    * Function to call.
865    */
866   GCT_ChannelIterator iter;
867
868   /**
869    * Closure for @e iter.
870    */
871   void *iter_cls;
872 };
873
874
875 /**
876  * Helper function for #GCT_iterate_channels.
877  *
878  * @param cls the `struct ChanIterCls`
879  * @param key unused
880  * @param value a `struct CadetChannel`
881  * @return #GNUNET_OK
882  */
883 static int
884 iterate_channels_cb (void *cls,
885                      uint32_t key,
886                      void *value)
887 {
888   struct ChanIterCls *ctx = cls;
889   struct CadetChannel *ch = value;
890
891   ctx->iter (ctx->iter_cls,
892              ch);
893   return GNUNET_OK;
894 }
895
896
897 /**
898  * Iterate over all channels of a tunnel.
899  *
900  * @param t Tunnel whose channels to iterate.
901  * @param iter Iterator.
902  * @param iter_cls Closure for @c iter.
903  */
904 void
905 GCT_iterate_channels (struct CadetTunnel *t,
906                       GCT_ChannelIterator iter,
907                       void *iter_cls)
908 {
909   struct ChanIterCls ctx;
910
911   ctx.iter = iter;
912   ctx.iter_cls = iter_cls;
913   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
914                                            &iterate_channels_cb,
915                                            &ctx);
916
917 }
918
919
920 /**
921  * Call #GCCH_debug() on a channel.
922  *
923  * @param cls points to the log level to use
924  * @param key unused
925  * @param value the `struct CadetChannel` to dump
926  * @return #GNUNET_OK (continue iteration)
927  */
928 static int
929 debug_channel (void *cls,
930                uint32_t key,
931                void *value)
932 {
933   const enum GNUNET_ErrorType *level = cls;
934   struct CadetChannel *ch = value;
935
936   GCCH_debug (ch, *level);
937   return GNUNET_OK;
938 }
939
940
941 /**
942  * Get string description for tunnel connectivity state.
943  *
944  * @param cs Tunnel state.
945  *
946  * @return String representation.
947  */
948 static const char *
949 cstate2s (enum CadetTunnelCState cs)
950 {
951   static char buf[32];
952
953   switch (cs)
954   {
955     case CADET_TUNNEL_NEW:
956       return "CADET_TUNNEL_NEW";
957     case CADET_TUNNEL_SEARCHING:
958       return "CADET_TUNNEL_SEARCHING";
959     case CADET_TUNNEL_WAITING:
960       return "CADET_TUNNEL_WAITING";
961     case CADET_TUNNEL_READY:
962       return "CADET_TUNNEL_READY";
963     case CADET_TUNNEL_SHUTDOWN:
964       return "CADET_TUNNEL_SHUTDOWN";
965     default:
966       SPRINTF (buf, "%u (UNKNOWN STATE)", cs);
967       return buf;
968   }
969 }
970
971
972 /**
973  * Get string description for tunnel encryption state.
974  *
975  * @param es Tunnel state.
976  *
977  * @return String representation.
978  */
979 static const char *
980 estate2s (enum CadetTunnelEState es)
981 {
982   static char buf[32];
983
984   switch (es)
985   {
986     case CADET_TUNNEL_KEY_UNINITIALIZED:
987       return "CADET_TUNNEL_KEY_UNINITIALIZED";
988     case CADET_TUNNEL_KEY_SENT:
989       return "CADET_TUNNEL_KEY_SENT";
990     case CADET_TUNNEL_KEY_PING:
991       return "CADET_TUNNEL_KEY_PING";
992     case CADET_TUNNEL_KEY_OK:
993       return "CADET_TUNNEL_KEY_OK";
994     case CADET_TUNNEL_KEY_REKEY:
995       return "CADET_TUNNEL_KEY_REKEY";
996     default:
997       SPRINTF (buf, "%u (UNKNOWN STATE)", es);
998       return buf;
999   }
1000 }
1001
1002
1003 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-tun",__VA_ARGS__)
1004
1005
1006 /**
1007  * Log all possible info about the tunnel state.
1008  *
1009  * @param t Tunnel to debug.
1010  * @param level Debug level to use.
1011  */
1012 void
1013 GCT_debug (const struct CadetTunnel *t,
1014            enum GNUNET_ErrorType level)
1015 {
1016   struct CadetTConnection *iter_c;
1017   int do_log;
1018
1019   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
1020                                        "cadet-tun",
1021                                        __FILE__, __FUNCTION__, __LINE__);
1022   if (0 == do_log)
1023     return;
1024
1025   LOG2 (level,
1026         "TTT TUNNEL TOWARDS %s in cstate %s, estate %s tq_len: %u #cons: %u\n",
1027         GCT_2s (t),
1028         cstate2s (t->cstate),
1029         estate2s (t->estate),
1030         t->tq_len,
1031         t->num_connections);
1032 #if DUMP_KEYS_TO_STDERR
1033   ax_debug (t->ax, level);
1034 #endif
1035   LOG2 (level,
1036         "TTT channels:\n");
1037   GNUNET_CONTAINER_multihashmap32_iterate (t->channels,
1038                                            &debug_channel,
1039                                            &level);
1040   LOG2 (level,
1041         "TTT connections:\n");
1042   for (iter_c = t->connection_head; NULL != iter_c; iter_c = iter_c->next)
1043     GCC_debug (iter_c->cc,
1044                level);
1045
1046   LOG2 (level,
1047         "TTT TUNNEL END\n");
1048 }
1049
1050
1051 /* end of gnunet-service-cadet-new_tunnels.c */