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