complete new KX implementation, including KX_AUTH defense against KX-injection based...
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet-new_connection.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-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_connection.c
23  * @brief management of CORE-level end-to-end connections; establishes
24  *        end-to-end routes and transmits messages along the route
25  * @author Bartlomiej Polot
26  * @author Christian Grothoff
27  *
28  * TODO:
29  * - Optimization: keep per-connection performance metrics (?)
30  */
31 #include "platform.h"
32 #include "gnunet-service-cadet-new.h"
33 #include "gnunet-service-cadet-new_channel.h"
34 #include "gnunet-service-cadet-new_connection.h"
35 #include "gnunet-service-cadet-new_paths.h"
36 #include "gnunet-service-cadet-new_peer.h"
37 #include "gnunet-service-cadet-new_tunnels.h"
38 #include "gnunet_cadet_service.h"
39 #include "gnunet_statistics_service.h"
40 #include "cadet_protocol.h"
41
42
43 #define LOG(level, ...) GNUNET_log_from(level,"cadet-con",__VA_ARGS__)
44
45
46 /**
47  * All the states a connection can be in.
48  */
49 enum CadetConnectionState
50 {
51   /**
52    * Uninitialized status, we have not yet even gotten the message queue.
53    */
54   CADET_CONNECTION_NEW,
55
56   /**
57    * Connection create message in queue, awaiting transmission by CORE.
58    */
59   CADET_CONNECTION_SENDING_CREATE,
60
61   /**
62    * Connection create message sent, waiting for ACK.
63    */
64   CADET_CONNECTION_SENT,
65
66   /**
67    * We are an inbound connection, and received a CREATE. Need to
68    * send an CREATE_ACK back.
69    */
70   CADET_CONNECTION_CREATE_RECEIVED,
71
72   /**
73    * Connection confirmed, ready to carry traffic.
74    */
75   CADET_CONNECTION_READY
76
77 };
78
79
80 /**
81  * Low-level connection to a destination.
82  */
83 struct CadetConnection
84 {
85
86   /**
87    * ID of the connection.
88    */
89   struct GNUNET_CADET_ConnectionTunnelIdentifier cid;
90
91   /**
92    * To which peer does this connection go?
93    */
94   struct CadetPeer *destination;
95
96   /**
97    * Which tunnel is using this connection?
98    */
99   struct CadetTConnection *ct;
100
101   /**
102    * Path we are using to our destination.
103    */
104   struct CadetPeerPath *path;
105
106   /**
107    * Pending message, NULL if we are ready to transmit.
108    */
109   struct GNUNET_MQ_Envelope *env;
110
111   /**
112    * Handle for calling #GCP_request_mq_cancel() once we are finished.
113    */
114   struct GCP_MessageQueueManager *mq_man;
115
116   /**
117    * Task for connection maintenance.
118    */
119   struct GNUNET_SCHEDULER_Task *task;
120
121   /**
122    * Queue entry for keepalive messages.
123    */
124   struct CadetTunnelQueueEntry *keepalive_qe;
125
126   /**
127    * Function to call once we are ready to transmit.
128    */
129   GCC_ReadyCallback ready_cb;
130
131   /**
132    * Closure for @e ready_cb.
133    */
134   void *ready_cb_cls;
135
136   /**
137    * How long do we wait before we try again with a CREATE message?
138    */
139   struct GNUNET_TIME_Relative retry_delay;
140
141   /**
142    * State of the connection.
143    */
144   enum CadetConnectionState state;
145
146   /**
147    * Offset of our @e destination in @e path.
148    */
149   unsigned int off;
150
151   /**
152    * Are we ready to transmit via @e mq_man right now?
153    */
154   int mqm_ready;
155
156 };
157
158
159 /**
160  * Destroy a connection, part of the internal implementation.  Called
161  * only from #GCC_destroy_from_core() or #GCC_destroy_from_tunnel().
162  *
163  * @param cc connection to destroy
164  */
165 static void
166 GCC_destroy (struct CadetConnection *cc)
167 {
168   LOG (GNUNET_ERROR_TYPE_DEBUG,
169        "Destroying %s\n",
170        GCC_2s (cc));
171   if (NULL != cc->mq_man)
172   {
173     GCP_request_mq_cancel (cc->mq_man,
174                            NULL);
175     cc->mq_man = NULL;
176   }
177   if (NULL != cc->task)
178   {
179     GNUNET_SCHEDULER_cancel (cc->task);
180     cc->task = NULL;
181   }
182   if (NULL != cc->keepalive_qe)
183   {
184     GCT_send_cancel (cc->keepalive_qe);
185     cc->keepalive_qe = NULL;
186   }
187   GCPP_del_connection (cc->path,
188                        cc->off,
189                        cc);
190   GNUNET_assert (GNUNET_YES ==
191                  GNUNET_CONTAINER_multishortmap_remove (connections,
192                                                         &GCC_get_id (cc)->connection_of_tunnel,
193                                                         cc));
194   GNUNET_free (cc);
195 }
196
197
198
199 /**
200  * Destroy a connection, called when the CORE layer is already done
201  * (i.e. has received a BROKEN message), but if we still have to
202  * communicate the destruction of the connection to the tunnel (if one
203  * exists).
204  *
205  * @param cc connection to destroy
206  */
207 void
208 GCC_destroy_without_core (struct CadetConnection *cc)
209 {
210   if (NULL != cc->ct)
211   {
212     GCT_connection_lost (cc->ct);
213     cc->ct = NULL;
214   }
215   GCC_destroy (cc);
216 }
217
218
219 /**
220  * Destroy a connection, called if the tunnel association with the
221  * connection was already broken, but we still need to notify the CORE
222  * layer about the breakage.
223  *
224  * @param cc connection to destroy
225  */
226 void
227 GCC_destroy_without_tunnel (struct CadetConnection *cc)
228 {
229   cc->ct = NULL;
230   if ( (CADET_CONNECTION_SENDING_CREATE != cc->state) &&
231        (NULL != cc->mq_man) )
232   {
233     struct GNUNET_MQ_Envelope *env;
234     struct GNUNET_CADET_ConnectionDestroyMessage *destroy_msg;
235
236     /* Need to notify next hop that we are down. */
237     env = GNUNET_MQ_msg (destroy_msg,
238                          GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY);
239     destroy_msg->cid = cc->cid;
240     GCP_request_mq_cancel (cc->mq_man,
241                            env);
242     cc->mq_man = NULL;
243   }
244   GCC_destroy (cc);
245 }
246
247
248 /**
249  * Return the tunnel associated with this connection.
250  *
251  * @param cc connection to query
252  * @return corresponding entry in the tunnel's connection list
253  */
254 struct CadetTConnection *
255 GCC_get_ct (struct CadetConnection *cc)
256 {
257   return cc->ct;
258 }
259
260
261 /**
262  * Send a #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE through the
263  * tunnel to prevent it from timing out.
264  *
265  * @param cls the `struct CadetConnection` to keep alive.
266  */
267 static void
268 send_keepalive (void *cls);
269
270
271 /**
272  * Keepalive was transmitted.  Remember this, and possibly
273  * schedule the next one.
274  *
275  * @param cls the `struct CadetConnection` to keep alive.
276  */
277 static void
278 keepalive_done (void *cls)
279 {
280   struct CadetConnection *cc = cls;
281
282   cc->keepalive_qe = NULL;
283   if ( (GNUNET_YES == cc->mqm_ready) &&
284        (NULL == cc->task) )
285     cc->task = GNUNET_SCHEDULER_add_delayed (keepalive_period,
286                                              &send_keepalive,
287                                              cc);
288 }
289
290
291 /**
292  * Send a #GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE through the
293  * tunnel to prevent it from timing out.
294  *
295  * @param cls the `struct CadetConnection` to keep alive.
296  */
297 static void
298 send_keepalive (void *cls)
299 {
300   struct CadetConnection *cc = cls;
301   struct GNUNET_MessageHeader msg;
302
303   cc->task = NULL;
304   if (CADET_TUNNEL_KEY_OK != GCT_get_estate (cc->ct->t))
305   {
306     /* Tunnel not yet ready, wait with keepalives... */
307     cc->task = GNUNET_SCHEDULER_add_delayed (keepalive_period,
308                                              &send_keepalive,
309                                              cc);
310     return;
311   }
312   GNUNET_assert (NULL != cc->ct);
313   GNUNET_assert (GNUNET_YES == cc->mqm_ready);
314   GNUNET_assert (NULL == cc->keepalive_qe);
315   LOG (GNUNET_ERROR_TYPE_INFO,
316        "Sending KEEPALIVE on behalf of %s via %s\n",
317        GCC_2s (cc),
318        GCT_2s (cc->ct->t));
319   GNUNET_STATISTICS_update (stats,
320                             "# keepalives sent",
321                             1,
322                             GNUNET_NO);
323   msg.size = htons (sizeof (msg));
324   msg.type = htons (GNUNET_MESSAGE_TYPE_CADET_CHANNEL_KEEPALIVE);
325
326   cc->keepalive_qe
327     = GCT_send (cc->ct->t,
328                 &msg,
329                 &keepalive_done,
330                 cc);
331 }
332
333
334 /**
335  * A #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK was received for this connection, implying
336  * that the end-to-end connection is up.  Process it.
337  *
338  * @param cc the connection that got the ACK.
339  */
340 void
341 GCC_handle_connection_create_ack (struct CadetConnection *cc)
342 {
343   LOG (GNUNET_ERROR_TYPE_DEBUG,
344        "Received CADET_CONNECTION_CREATE_ACK for %s in state %d (%s)\n",
345        GCC_2s (cc),
346        cc->state,
347        (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy");
348   if (NULL != cc->task)
349   {
350     GNUNET_SCHEDULER_cancel (cc->task);
351     cc->task = NULL;
352   }
353   cc->state = CADET_CONNECTION_READY;
354   if (GNUNET_YES == cc->mqm_ready)
355   {
356     cc->ready_cb (cc->ready_cb_cls,
357                   GNUNET_YES);
358     if ( (NULL == cc->keepalive_qe) &&
359          (GNUNET_YES == cc->mqm_ready) &&
360          (NULL == cc->task) )
361       cc->task = GNUNET_SCHEDULER_add_delayed (keepalive_period,
362                                                &send_keepalive,
363                                                cc);
364   }
365 }
366
367
368 /**
369  * Handle KX message.
370  *
371  * @param cc connection that received encrypted message
372  * @param msg the key exchange message
373  */
374 void
375 GCC_handle_kx (struct CadetConnection *cc,
376                const struct GNUNET_CADET_TunnelKeyExchangeMessage *msg)
377 {
378   if (CADET_CONNECTION_SENT == cc->state)
379   {
380     /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine,
381        clearly something is working, so pretend we got an ACK. */
382     LOG (GNUNET_ERROR_TYPE_DEBUG,
383          "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n",
384          GCC_2s (cc));
385     GCC_handle_connection_create_ack (cc);
386   }
387   GCT_handle_kx (cc->ct,
388                  msg);
389 }
390
391
392 /**
393  * Handle KX_AUTH message.
394  *
395  * @param cc connection that received encrypted message
396  * @param msg the key exchange message
397  */
398 void
399 GCC_handle_kx_auth (struct CadetConnection *cc,
400                     const struct GNUNET_CADET_TunnelKeyExchangeAuthMessage *msg)
401 {
402   if (CADET_CONNECTION_SENT == cc->state)
403   {
404     /* We didn't get the CADET_CONNECTION_CREATE_ACK, but instead got payload. That's fine,
405        clearly something is working, so pretend we got an ACK. */
406     LOG (GNUNET_ERROR_TYPE_DEBUG,
407          "Faking connection CADET_CONNECTION_CREATE_ACK for %s due to KX\n",
408          GCC_2s (cc));
409     GCC_handle_connection_create_ack (cc);
410   }
411   GCT_handle_kx_auth (cc->ct,
412                       msg);
413 }
414
415
416 /**
417  * Handle encrypted message.
418  *
419  * @param cc connection that received encrypted message
420  * @param msg the encrypted message to decrypt
421  */
422 void
423 GCC_handle_encrypted (struct CadetConnection *cc,
424                       const struct GNUNET_CADET_TunnelEncryptedMessage *msg)
425 {
426   if (CADET_CONNECTION_SENT == cc->state)
427   {
428     /* We didn't get the CREATE_ACK, but instead got payload. That's fine,
429        clearly something is working, so pretend we got an ACK. */
430     LOG (GNUNET_ERROR_TYPE_DEBUG,
431          "Faking connection ACK for %s due to ENCRYPTED payload\n",
432          GCC_2s (cc));
433     GCC_handle_connection_create_ack (cc);
434   }
435   GCT_handle_encrypted (cc->ct,
436                         msg);
437 }
438
439
440 /**
441  * Send a #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE message to the
442  * first hop.
443  *
444  * @param cls the `struct CadetConnection` to initiate
445  */
446 static void
447 send_create (void *cls)
448 {
449   struct CadetConnection *cc = cls;
450   struct GNUNET_CADET_ConnectionCreateMessage *create_msg;
451   struct GNUNET_PeerIdentity *pids;
452   struct GNUNET_MQ_Envelope *env;
453   unsigned int path_length;
454
455   cc->task = NULL;
456   GNUNET_assert (GNUNET_YES == cc->mqm_ready);
457   path_length = GCPP_get_length (cc->path);
458   env = GNUNET_MQ_msg_extra (create_msg,
459                              (1 + path_length) * sizeof (struct GNUNET_PeerIdentity),
460                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE);
461   create_msg->cid = cc->cid;
462   pids = (struct GNUNET_PeerIdentity *) &create_msg[1];
463   pids[0] = my_full_id;
464   for (unsigned int i=0;i<path_length;i++)
465     pids[i + 1] = *GCP_get_id (GCPP_get_peer_at_offset (cc->path,
466                                                         i));
467   LOG (GNUNET_ERROR_TYPE_DEBUG,
468        "Sending CADET_CONNECTION_CREATE message for %s\n",
469        GCC_2s (cc));
470   cc->env = env;
471   cc->mqm_ready = GNUNET_NO;
472   cc->state = CADET_CONNECTION_SENT;
473   GCP_send (cc->mq_man,
474             env);
475 }
476
477
478 /**
479  * Send a CREATE_ACK message towards the origin.
480  *
481  * @param cls the `struct CadetConnection` to initiate
482  */
483 static void
484 send_create_ack (void *cls)
485 {
486   struct CadetConnection *cc = cls;
487   struct GNUNET_CADET_ConnectionCreateAckMessage *ack_msg;
488   struct GNUNET_MQ_Envelope *env;
489
490   cc->task = NULL;
491   GNUNET_assert (CADET_CONNECTION_CREATE_RECEIVED == cc->state);
492   LOG (GNUNET_ERROR_TYPE_DEBUG,
493        "Sending CONNECTION_CREATE_ACK message for %s\n",
494        GCC_2s (cc));
495   GNUNET_assert (GNUNET_YES == cc->mqm_ready);
496   env = GNUNET_MQ_msg (ack_msg,
497                        GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE_ACK);
498   ack_msg->cid = cc->cid;
499   cc->env = env;
500   cc->mqm_ready = GNUNET_NO;
501   cc->state = CADET_CONNECTION_READY;
502   GCP_send (cc->mq_man,
503             env);
504 }
505
506
507 /**
508  * We got a #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE for a
509  * connection that we already have.  Either our ACK got lost
510  * or something is fishy.  Consider retransmitting the ACK.
511  *
512  * @param cc connection that got the duplicate CREATE
513  */
514 void
515 GCC_handle_duplicate_create (struct CadetConnection *cc)
516 {
517   if (GNUNET_YES == cc->mqm_ready)
518   {
519     LOG (GNUNET_ERROR_TYPE_DEBUG,
520          "Got duplicate CREATE for %s, scheduling another ACK (%s)\n",
521          GCC_2s (cc),
522          (GNUNET_YES == cc->mqm_ready) ? "MQM ready" : "MQM busy");
523     /* Tell tunnel that we are not ready for transmission anymore
524        (until CREATE_ACK is done) */
525     cc->ready_cb (cc->ready_cb_cls,
526                   GNUNET_NO);
527     /* Revert back to the state of having only received the 'CREATE',
528        and immediately proceed to send the CREATE_ACK. */
529     cc->state = CADET_CONNECTION_CREATE_RECEIVED;
530     if (NULL != cc->task)
531       GNUNET_SCHEDULER_cancel (cc->task);
532     cc->task = GNUNET_SCHEDULER_add_now (&send_create_ack,
533                                          cc);
534   }
535   else
536   {
537     /* We are currently sending something else back, which
538        can only be an ACK or payload, either of which would
539        do. So actually no need to do anything. */
540     LOG (GNUNET_ERROR_TYPE_DEBUG,
541          "Got duplicate CREATE for %s. MQ is busy, not queueing another ACK\n",
542          GCC_2s (cc));
543   }
544 }
545
546
547 /**
548  * There has been a change in the message queue existence for our
549  * peer at the first hop.  Adjust accordingly.
550  *
551  * @param cls the `struct CadetConnection`
552  * @param available #GNUNET_YES if sending is now possible,
553  *                  #GNUNET_NO if sending is no longer possible
554  *                  #GNUNET_SYSERR if sending is no longer possible
555  *                                 and the last envelope was discarded
556  */
557 static void
558 manage_first_hop_mq (void *cls,
559                      int available)
560 {
561   struct CadetConnection *cc = cls;
562
563   if (GNUNET_YES != available)
564   {
565     /* Connection is down, for now... */
566     LOG (GNUNET_ERROR_TYPE_DEBUG,
567          "Core MQ for %s went down\n",
568          GCC_2s (cc));
569     cc->mqm_ready = GNUNET_NO;
570     cc->state = CADET_CONNECTION_NEW;
571     cc->retry_delay = GNUNET_TIME_UNIT_ZERO;
572     if (NULL != cc->task)
573     {
574       GNUNET_SCHEDULER_cancel (cc->task);
575       cc->task = NULL;
576     }
577     cc->ready_cb (cc->ready_cb_cls,
578                   GNUNET_NO);
579     return;
580   }
581
582   cc->mqm_ready = GNUNET_YES;
583   LOG (GNUNET_ERROR_TYPE_DEBUG,
584        "Core MQ for %s became available in state %d\n",
585        GCC_2s (cc),
586        cc->state);
587   switch (cc->state)
588   {
589   case CADET_CONNECTION_NEW:
590     /* Transmit immediately */
591     cc->task = GNUNET_SCHEDULER_add_now (&send_create,
592                                          cc);
593     break;
594   case CADET_CONNECTION_SENDING_CREATE:
595     /* Should not be possible to be called in this state. */
596     GNUNET_assert (0);
597     break;
598   case CADET_CONNECTION_SENT:
599     /* Retry a bit later... */
600     cc->retry_delay = GNUNET_TIME_STD_BACKOFF (cc->retry_delay);
601     cc->task = GNUNET_SCHEDULER_add_delayed (cc->retry_delay,
602                                              &send_create,
603                                              cc);
604     break;
605   case CADET_CONNECTION_CREATE_RECEIVED:
606     /* We got the 'CREATE' (incoming connection), should send the CREATE_ACK */
607     cc->task = GNUNET_SCHEDULER_add_now (&send_create_ack,
608                                          cc);
609     break;
610   case CADET_CONNECTION_READY:
611     cc->ready_cb (cc->ready_cb_cls,
612                   GNUNET_YES);
613     if ( (NULL == cc->keepalive_qe) &&
614          (GNUNET_YES == cc->mqm_ready) &&
615          (NULL == cc->task) )
616     {
617       LOG (GNUNET_ERROR_TYPE_DEBUG,
618            "Scheduling keepalive for %s in %s\n",
619            GCC_2s (cc),
620            GNUNET_STRINGS_relative_time_to_string (keepalive_period,
621                                                    GNUNET_YES));
622       cc->task = GNUNET_SCHEDULER_add_delayed (keepalive_period,
623                                                &send_keepalive,
624                                                cc);
625     }
626     break;
627   }
628 }
629
630
631 /**
632  * Create a connection to @a destination via @a path and notify @a cb
633  * whenever we are ready for more data.  Shared logic independent of
634  * who is initiating the connection.
635  *
636  * @param destination where to go
637  * @param path which path to take (may not be the full path)
638  * @param ct which tunnel uses this connection
639  * @param init_state initial state for the connection
640  * @param ready_cb function to call when ready to transmit
641  * @param ready_cb_cls closure for @a cb
642  * @return handle to the connection
643  */
644 static struct CadetConnection *
645 connection_create (struct CadetPeer *destination,
646                    struct CadetPeerPath *path,
647                    struct CadetTConnection *ct,
648                    const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
649                    enum CadetConnectionState init_state,
650                    GCC_ReadyCallback ready_cb,
651                    void *ready_cb_cls)
652 {
653   struct CadetConnection *cc;
654   struct CadetPeer *first_hop;
655   unsigned int off;
656
657   off = GCPP_find_peer (path,
658                         destination);
659   GNUNET_assert (UINT_MAX > off);
660   cc = GNUNET_new (struct CadetConnection);
661   cc->state = init_state;
662   cc->ct = ct;
663   cc->cid = *cid;
664   GNUNET_assert (GNUNET_OK ==
665                  GNUNET_CONTAINER_multishortmap_put (connections,
666                                                      &GCC_get_id (cc)->connection_of_tunnel,
667                                                      cc,
668                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
669   cc->ready_cb = ready_cb;
670   cc->ready_cb_cls = ready_cb_cls;
671   cc->path = path;
672   cc->off = off;
673   LOG (GNUNET_ERROR_TYPE_DEBUG,
674        "Creating %s using path %s\n",
675        GCC_2s (cc),
676        GCPP_2s (path));
677   GCPP_add_connection (path,
678                        off,
679                        cc);
680   for (unsigned int i=0;i<off;i++)
681     GCP_add_connection (GCPP_get_peer_at_offset (path,
682                                                  off),
683                         cc);
684
685   first_hop = GCPP_get_peer_at_offset (path,
686                                        0);
687   cc->mq_man = GCP_request_mq (first_hop,
688                                &manage_first_hop_mq,
689                                cc);
690   return cc;
691 }
692
693
694 /**
695  * Create a connection to @a destination via @a path and
696  * notify @a cb whenever we are ready for more data.  This
697  * is an inbound tunnel, so we must use the existing @a cid
698  *
699  * @param destination where to go
700  * @param path which path to take (may not be the full path)
701  * @param ct which tunnel uses this connection
702  * @param ready_cb function to call when ready to transmit
703  * @param ready_cb_cls closure for @a cb
704  * @return handle to the connection, NULL if we already have
705  *         a connection that takes precedence on @a path
706  */
707 struct CadetConnection *
708 GCC_create_inbound (struct CadetPeer *destination,
709                     struct CadetPeerPath *path,
710                     struct CadetTConnection *ct,
711                     const struct GNUNET_CADET_ConnectionTunnelIdentifier *cid,
712                     GCC_ReadyCallback ready_cb,
713                     void *ready_cb_cls)
714 {
715   struct CadetConnection *cc;
716   unsigned int off;
717
718   off = GCPP_find_peer (path,
719                         destination);
720   GNUNET_assert (UINT_MAX != off);
721   cc = GCPP_get_connection (path,
722                             destination,
723                             off);
724   if (NULL != cc)
725   {
726     int cmp;
727
728     cmp = memcmp (cid,
729                   &cc->cid,
730                   sizeof (*cid));
731     if (0 == cmp)
732     {
733       /* Two peers picked the SAME random connection identifier at the
734          same time for the same path? Must be malicious.  Drop
735          connection (existing and inbound), even if it is the only
736          one. */
737       GNUNET_break_op (0);
738       GCT_connection_lost (cc->ct);
739       GCC_destroy_without_tunnel (cc);
740       return NULL;
741     }
742     if (0 < cmp)
743     {
744       /* drop existing */
745       LOG (GNUNET_ERROR_TYPE_DEBUG,
746            "Got two connections on %s, dropping my existing %s\n",
747            GCPP_2s (path),
748            GCC_2s (cc));
749       GCT_connection_lost (cc->ct);
750       GCC_destroy_without_tunnel (cc);
751     }
752     else
753     {
754       /* keep existing */
755       LOG (GNUNET_ERROR_TYPE_DEBUG,
756            "Got two connections on %s, keeping my existing %s\n",
757            GCPP_2s (path),
758            GCC_2s (cc));
759       return NULL;
760     }
761   }
762
763   return connection_create (destination,
764                             path,
765                             ct,
766                             cid,
767                             CADET_CONNECTION_CREATE_RECEIVED,
768                             ready_cb,
769                             ready_cb_cls);
770 }
771
772
773 /**
774  * Create a connection to @a destination via @a path and
775  * notify @a cb whenever we are ready for more data.
776  *
777  * @param destination where to go
778  * @param path which path to take (may not be the full path)
779  * @param ct tunnel that uses the connection
780  * @param ready_cb function to call when ready to transmit
781  * @param ready_cb_cls closure for @a cb
782  * @return handle to the connection
783  */
784 struct CadetConnection *
785 GCC_create (struct CadetPeer *destination,
786             struct CadetPeerPath *path,
787             struct CadetTConnection *ct,
788             GCC_ReadyCallback ready_cb,
789             void *ready_cb_cls)
790 {
791   struct GNUNET_CADET_ConnectionTunnelIdentifier cid;
792
793   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_NONCE,
794                               &cid,
795                               sizeof (cid));
796   return connection_create (destination,
797                             path,
798                             ct,
799                             &cid,
800                             CADET_CONNECTION_NEW,
801                             ready_cb,
802                             ready_cb_cls);
803 }
804
805
806 /**
807  * Transmit message @a msg via connection @a cc.  Must only be called
808  * (once) after the connection has signalled that it is ready via the
809  * `ready_cb`.  Clients can also use #GCC_is_ready() to check if the
810  * connection is right now ready for transmission.
811  *
812  * @param cc connection identification
813  * @param env envelope with message to transmit; must NOT
814  *            yet have a #GNUNET_MQ_notify_sent() callback attached to it
815  */
816 void
817 GCC_transmit (struct CadetConnection *cc,
818               struct GNUNET_MQ_Envelope *env)
819 {
820   LOG (GNUNET_ERROR_TYPE_DEBUG,
821        "Scheduling message for transmission on %s\n",
822        GCC_2s (cc));
823   GNUNET_assert (GNUNET_YES == cc->mqm_ready);
824   GNUNET_assert (CADET_CONNECTION_READY == cc->state);
825   cc->mqm_ready = GNUNET_NO;
826   if (NULL != cc->task)
827   {
828     GNUNET_SCHEDULER_cancel (cc->task);
829     cc->task = NULL;
830   }
831   GCP_send (cc->mq_man,
832             env);
833 }
834
835
836 /**
837  * Obtain the path used by this connection.
838  *
839  * @param cc connection
840  * @return path to @a cc
841  */
842 struct CadetPeerPath *
843 GCC_get_path (struct CadetConnection *cc)
844 {
845   return cc->path;
846 }
847
848
849 /**
850  * Obtain unique ID for the connection.
851  *
852  * @param cc connection.
853  * @return unique number of the connection
854  */
855 const struct GNUNET_CADET_ConnectionTunnelIdentifier *
856 GCC_get_id (struct CadetConnection *cc)
857 {
858   return &cc->cid;
859 }
860
861
862 /**
863  * Get a (static) string for a connection.
864  *
865  * @param cc Connection.
866  */
867 const char *
868 GCC_2s (const struct CadetConnection *cc)
869 {
870   static char buf[128];
871
872   if (NULL == cc)
873     return "Connection(NULL)";
874
875   if (NULL != cc->ct)
876   {
877     GNUNET_snprintf (buf,
878                      sizeof (buf),
879                      "Connection %s (%s)",
880                      GNUNET_sh2s (&cc->cid.connection_of_tunnel),
881                      GCT_2s (cc->ct->t));
882     return buf;
883   }
884   GNUNET_snprintf (buf,
885                    sizeof (buf),
886                    "Connection %s",
887                    GNUNET_sh2s (&cc->cid.connection_of_tunnel));
888   return buf;
889 }
890
891
892 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-con",__VA_ARGS__)
893
894
895 /**
896  * Log connection info.
897  *
898  * @param cc connection
899  * @param level Debug level to use.
900  */
901 void
902 GCC_debug (struct CadetConnection *cc,
903            enum GNUNET_ErrorType level)
904 {
905   int do_log;
906
907   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
908                                        "cadet-con",
909                                        __FILE__, __FUNCTION__, __LINE__);
910   if (0 == do_log)
911     return;
912   if (NULL == cc)
913   {
914     LOG2 (level,
915           "Connection (NULL)\n");
916     return;
917   }
918   LOG2 (level,
919         "%s to %s via path %s in state %d is %s\n",
920         GCC_2s (cc),
921         GCP_2s (cc->destination),
922         GCPP_2s (cc->path),
923         cc->state,
924         (GNUNET_YES == cc->mqm_ready) ? "ready" : "busy");
925 }
926
927 /* end of gnunet-service-cadet-new_connection.c */