a99960587c303ee4ae73cec1db1a7b47f854054a
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_peer.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 Christian Grothoff (and other contributing authors)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21
22 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_signatures.h"
26
27 #include "gnunet_transport_service.h"
28 #include "gnunet_core_service.h"
29 #include "gnunet_statistics_service.h"
30
31 #include "cadet_protocol.h"
32
33 #include "gnunet-service-cadet_peer.h"
34 #include "gnunet-service-cadet_dht.h"
35 #include "gnunet-service-cadet_connection.h"
36 #include "gnunet-service-cadet_tunnel.h"
37 #include "cadet_path.h"
38
39 #define LOG(level, ...) GNUNET_log_from (level,"cadet-p2p",__VA_ARGS__)
40 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-p2p",__VA_ARGS__)
41
42
43 /******************************************************************************/
44 /********************************   STRUCTS  **********************************/
45 /******************************************************************************/
46
47 /**
48  * Struct containing info about a queued transmission to this peer
49  */
50 struct CadetPeerQueue
51 {
52     /**
53       * DLL next
54       */
55   struct CadetPeerQueue *next;
56
57     /**
58       * DLL previous
59       */
60   struct CadetPeerQueue *prev;
61
62     /**
63      * Peer this transmission is directed to.
64      */
65   struct CadetPeer *peer;
66
67     /**
68      * Connection this message belongs to.
69      */
70   struct CadetConnection *c;
71
72     /**
73      * Is FWD in c?
74      */
75   int fwd;
76
77     /**
78      * Pointer to info stucture used as cls.
79      */
80   void *cls;
81
82   /**
83    * Type of message
84    */
85   uint16_t type;
86
87   /**
88    * Type of message
89    */
90   uint16_t payload_type;
91
92   /**
93    * Type of message
94    */
95   uint32_t payload_id;
96
97   /**
98      * Size of the message
99      */
100   size_t size;
101
102     /**
103      * Set when this message starts waiting for CORE.
104      */
105   struct GNUNET_TIME_Absolute start_waiting;
106
107     /**
108      * Function to call on sending.
109      */
110   GCP_sent callback;
111
112     /**
113      * Closure for callback.
114      */
115   void *callback_cls;
116 };
117
118 /**
119  * Struct containing all information regarding a given peer
120  */
121 struct CadetPeer
122 {
123     /**
124      * ID of the peer
125      */
126   GNUNET_PEER_Id id;
127
128     /**
129      * Axolotl permanent public key.
130      */
131   struct GNUNET_CRYPTO_EcdhePublicKey ax_key;
132
133     /**
134      * Last time we heard from this peer
135      */
136   struct GNUNET_TIME_Absolute last_contact;
137
138     /**
139      * Paths to reach the peer, ordered by ascending hop count
140      */
141   struct CadetPeerPath *path_head;
142
143     /**
144      * Paths to reach the peer, ordered by ascending hop count
145      */
146   struct CadetPeerPath *path_tail;
147
148     /**
149      * Handle to stop the DHT search for paths to this peer
150      */
151   struct GCD_search_handle *search_h;
152
153   /**
154    * Handle to stop the DHT search for paths to this peer
155    */
156   struct GNUNET_SCHEDULER_Task *search_delayed;
157
158     /**
159      * Tunnel to this peer, if any.
160      */
161   struct CadetTunnel *tunnel;
162
163     /**
164      * Connections that go through this peer, indexed by tid;
165      */
166   struct GNUNET_CONTAINER_MultiHashMap *connections;
167
168     /**
169      * Handle for queued transmissions
170      */
171   struct GNUNET_CORE_TransmitHandle *core_transmit;
172
173   /**
174    * Timestamp
175    */
176   struct GNUNET_TIME_Absolute tmt_time;
177
178   /**
179    * Transmission queue to core DLL head
180    */
181   struct CadetPeerQueue *queue_head;
182
183   /**
184    * Transmission queue to core DLL tail
185    */
186   struct CadetPeerQueue *queue_tail;
187
188   /**
189    * How many messages are in the queue to this peer.
190    */
191   unsigned int queue_n;
192
193   /**
194    * Hello message.
195    */
196   struct GNUNET_HELLO_Message* hello;
197 };
198
199
200 /******************************************************************************/
201 /*******************************   GLOBALS  ***********************************/
202 /******************************************************************************/
203
204 /**
205  * Global handle to the statistics service.
206  */
207 extern struct GNUNET_STATISTICS_Handle *stats;
208
209 /**
210  * Local peer own ID (full value).
211  */
212 extern struct GNUNET_PeerIdentity my_full_id;
213
214 /**
215  * Local peer own ID (short)
216  */
217 extern GNUNET_PEER_Id myid;
218
219 /**
220  * Peers known, indexed by PeerIdentity (CadetPeer).
221  */
222 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
223
224 /**
225  * How many peers do we want to remember?
226  */
227 static unsigned long long max_peers;
228
229 /**
230  * Percentage of messages that will be dropped (for test purposes only).
231  */
232 static unsigned long long drop_percent;
233
234 /**
235  * Handle to communicate with core.
236  */
237 static struct GNUNET_CORE_Handle *core_handle;
238
239 /**
240  * Handle to try to start new connections.
241  */
242 static struct GNUNET_TRANSPORT_Handle *transport_handle;
243
244
245 /******************************************************************************/
246 /*****************************     DEBUG      *********************************/
247 /******************************************************************************/
248
249 /**
250  * Log all kinds of info about the queueing status of a peer.
251  *
252  * @param p Peer whose queue to show.
253  * @param level Error level to use for logging.
254  */
255 static void
256 queue_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
257 {
258   struct CadetPeerQueue *q;
259   int do_log;
260
261   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
262                                        "cadet-p2p",
263                                        __FILE__, __FUNCTION__, __LINE__);
264   if (0 == do_log)
265     return;
266
267   LOG2 (level, "QQQ Message queue towards %s\n", GCP_2s (p));
268   LOG2 (level, "QQQ  queue length: %u\n", p->queue_n);
269   LOG2 (level, "QQQ  core tmt rdy: %p\n", p->core_transmit);
270
271   for (q = p->queue_head; NULL != q; q = q->next)
272   {
273     LOG2 (level, "QQQ  - %s %s on %s\n",
274          GC_m2s (q->type), GC_f2s (q->fwd), GCC_2s (q->c));
275     LOG2 (level, "QQQ    payload %s, %u\n",
276          GC_m2s (q->payload_type), q->payload_id);
277     LOG2 (level, "QQQ    size: %u bytes\n", q->size);
278   }
279
280   LOG2 (level, "QQQ End queue towards %s\n", GCP_2s (p));
281 }
282
283
284 /**
285  * Log all kinds of info about a peer.
286  *
287  * @param peer Peer.
288  */
289 void
290 GCP_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
291 {
292   struct CadetPeerPath *path;
293   unsigned int conns;
294   int do_log;
295
296   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
297                                        "cadet-p2p",
298                                        __FILE__, __FUNCTION__, __LINE__);
299   if (0 == do_log)
300     return;
301
302   if (NULL == p)
303   {
304     LOG2 (level, "PPP DEBUG PEER NULL\n");
305     return;
306   }
307
308   LOG2 (level, "PPP DEBUG PEER %s\n", GCP_2s (p));
309   LOG2 (level, "PPP last contact %s\n",
310        GNUNET_STRINGS_absolute_time_to_string (p->last_contact));
311   for (path = p->path_head; NULL != path; path = path->next)
312   {
313     char *s;
314
315     s = path_2s (path);
316     LOG2 (level, "PPP path: %s\n", s);
317     GNUNET_free (s);
318   }
319
320   LOG2 (level, "PPP core transmit handle %p\n", p->core_transmit);
321   LOG2 (level, "PPP DHT GET handle %p\n", p->search_h);
322   if (NULL != p->connections)
323     conns = GNUNET_CONTAINER_multihashmap_size (p->connections);
324   else
325     conns = 0;
326   LOG2 (level, "PPP # connections over link to peer: %u\n", conns);
327   queue_debug (p, level);
328   LOG2 (level, "PPP DEBUG END\n");
329 }
330
331
332 /******************************************************************************/
333 /*****************************  CORE HELPERS  *********************************/
334 /******************************************************************************/
335
336
337 /**
338  * Iterator to notify all connections of a broken link. Mark connections
339  * to destroy after all traffic has been sent.
340  *
341  * @param cls Closure (peer disconnected).
342  * @param key Current key code (peer id).
343  * @param value Value in the hash map (connection).
344  *
345  * @return #GNUNET_YES to continue to iterate.
346  */
347 static int
348 notify_broken (void *cls,
349                const struct GNUNET_HashCode *key,
350                void *value)
351 {
352   struct CadetPeer *peer = cls;
353   struct CadetConnection *c = value;
354
355   LOG (GNUNET_ERROR_TYPE_DEBUG, "  notifying %s due to %s\n",
356        GCC_2s (c), GCP_2s (peer));
357   GCC_notify_broken (c, peer);
358
359   return GNUNET_YES;
360 }
361
362
363 /**
364  * Remove the direct path to the peer.
365  *
366  * @param peer Peer to remove the direct path from.
367  *
368  */
369 static struct CadetPeerPath *
370 pop_direct_path (struct CadetPeer *peer)
371 {
372   struct CadetPeerPath *iter;
373
374   for (iter = peer->path_head; NULL != iter; iter = iter->next)
375   {
376     if (2 >= iter->length)
377     {
378       GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
379       return iter;
380     }
381   }
382   return NULL;
383 }
384
385
386 /******************************************************************************/
387 /***************************** CORE CALLBACKS *********************************/
388 /******************************************************************************/
389
390 /**
391  * Method called whenever a given peer connects.
392  *
393  * @param cls closure
394  * @param peer peer identity this notification is about
395  */
396 static void
397 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
398 {
399   struct CadetPeer *mp;
400   struct CadetPeerPath *path;
401   char own_id[16];
402
403   strncpy (own_id, GNUNET_i2s (&my_full_id), 15);
404   mp = GCP_get (peer);
405   if (myid == mp->id)
406   {
407     LOG (GNUNET_ERROR_TYPE_INFO, "CONNECTED %s (self)\n", own_id);
408     path = path_new (1);
409   }
410   else
411   {
412     LOG (GNUNET_ERROR_TYPE_INFO, "CONNECTED %s <= %s\n",
413          own_id, GNUNET_i2s (peer));
414     path = path_new (2);
415     path->peers[1] = mp->id;
416     GNUNET_PEER_change_rc (mp->id, 1);
417     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
418   }
419   path->peers[0] = myid;
420   GNUNET_PEER_change_rc (myid, 1);
421   GCP_add_path (mp, path, GNUNET_YES);
422
423   mp->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
424
425   if (NULL != GCP_get_tunnel (mp) &&
426       0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, peer))
427   {
428     GCP_connect (mp);
429   }
430
431   return;
432 }
433
434
435 /**
436  * Method called whenever a peer disconnects.
437  *
438  * @param cls closure
439  * @param peer peer identity this notification is about
440  */
441 static void
442 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
443 {
444   struct CadetPeer *p;
445   struct CadetPeerPath *direct_path;
446   char own_id[16];
447
448   strncpy (own_id, GNUNET_i2s (&my_full_id), 15);
449   p = GNUNET_CONTAINER_multipeermap_get (peers, peer);
450   if (NULL == p)
451   {
452     GNUNET_break (0);
453     return;
454   }
455   if (myid == p->id)
456     LOG (GNUNET_ERROR_TYPE_INFO, "DISCONNECTED %s (self)\n", own_id);
457   else
458     LOG (GNUNET_ERROR_TYPE_INFO, "DISCONNECTED %s <= %s\n",
459          own_id, GNUNET_i2s (peer));
460   direct_path = pop_direct_path (p);
461   GNUNET_CONTAINER_multihashmap_iterate (p->connections, &notify_broken, p);
462   GNUNET_CONTAINER_multihashmap_destroy (p->connections);
463   p->connections = NULL;
464   if (NULL != p->core_transmit)
465     {
466       GNUNET_CORE_notify_transmit_ready_cancel (p->core_transmit);
467       p->core_transmit = NULL;
468       p->tmt_time.abs_value_us = 0;
469     }
470   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
471
472   path_destroy (direct_path);
473   return;
474 }
475
476
477 /**
478  * Functions to handle messages from core
479  */
480 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
481   {&GCC_handle_create, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0},
482   {&GCC_handle_confirm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
483     sizeof (struct GNUNET_CADET_ConnectionACK)},
484   {&GCC_handle_broken, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
485     sizeof (struct GNUNET_CADET_ConnectionBroken)},
486   {&GCC_handle_destroy, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
487     sizeof (struct GNUNET_CADET_ConnectionDestroy)},
488   {&GCC_handle_ack, GNUNET_MESSAGE_TYPE_CADET_ACK,
489     sizeof (struct GNUNET_CADET_ACK)},
490   {&GCC_handle_poll, GNUNET_MESSAGE_TYPE_CADET_POLL,
491     sizeof (struct GNUNET_CADET_Poll)},
492   {&GCC_handle_kx, GNUNET_MESSAGE_TYPE_CADET_KX, 0},
493   {&GCC_handle_encrypted, GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED, 0}
494 };
495
496
497 /**
498  * To be called on core init/fail.
499  *
500  * @param cls Closure (config)
501  * @param identity the public identity of this peer
502  */
503 static void
504 core_init (void *cls,
505            const struct GNUNET_PeerIdentity *identity)
506 {
507   const struct GNUNET_CONFIGURATION_Handle *c = cls;
508   static int i = 0;
509
510   LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
511   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
512   {
513     LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
514     LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (identity));
515     LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
516     GNUNET_CORE_disconnect (core_handle);
517     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
518                                        NULL,      /* Closure passed to CADET functions */
519                                        &core_init,        /* Call core_init once connected */
520                                        &core_connect,     /* Handle connects */
521                                        &core_disconnect,  /* remove peers on disconnects */
522                                        NULL,      /* Don't notify about all incoming messages */
523                                        GNUNET_NO, /* For header only in notification */
524                                        NULL,      /* Don't notify about all outbound messages */
525                                        GNUNET_NO, /* For header-only out notification */
526                                        core_handlers);    /* Register these handlers */
527     if (10 < i++)
528       GNUNET_assert (0);
529   }
530   GML_start ();
531   return;
532 }
533
534
535 /**
536   * Core callback to write a pre-constructed data packet to core buffer
537   *
538   * @param cls Closure (CadetTransmissionDescriptor with data in "data" member).
539   * @param size Number of bytes available in buf.
540   * @param buf Where the to write the message.
541   *
542   * @return number of bytes written to buf
543   */
544 static size_t
545 send_core_data_raw (void *cls, size_t size, void *buf)
546 {
547   struct GNUNET_MessageHeader *msg = cls;
548   size_t total_size;
549
550   GNUNET_assert (NULL != msg);
551   total_size = ntohs (msg->size);
552
553   if (total_size > size)
554   {
555     GNUNET_break (0);
556     return 0;
557   }
558   memcpy (buf, msg, total_size);
559   GNUNET_free (cls);
560   return total_size;
561 }
562
563
564 /**
565  * Function to send a create connection message to a peer.
566  *
567  * @param c Connection to create.
568  * @param size number of bytes available in buf
569  * @param buf where the callee should write the message
570  * @return number of bytes written to buf
571  */
572 static size_t
573 send_core_connection_create (struct CadetConnection *c, size_t size, void *buf)
574 {
575   struct GNUNET_CADET_ConnectionCreate *msg;
576   struct GNUNET_PeerIdentity *peer_ptr;
577   const struct CadetPeerPath *p = GCC_get_path (c);
578   size_t size_needed;
579   int i;
580
581   if (NULL == p)
582     return 0;
583
584   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
585   size_needed =
586       sizeof (struct GNUNET_CADET_ConnectionCreate) +
587       p->length * sizeof (struct GNUNET_PeerIdentity);
588
589   if (size < size_needed || NULL == buf)
590   {
591     GNUNET_break (0);
592     return 0;
593   }
594   msg = (struct GNUNET_CADET_ConnectionCreate *) buf;
595   msg->header.size = htons (size_needed);
596   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE);
597   msg->cid = *GCC_get_id (c);
598
599   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
600   for (i = 0; i < p->length; i++)
601   {
602     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
603   }
604
605   LOG (GNUNET_ERROR_TYPE_DEBUG,
606        "CONNECTION CREATE (%u bytes long) sent!\n",
607        size_needed);
608   return size_needed;
609 }
610
611
612 /**
613  * Creates a path ack message in buf and frees all unused resources.
614  *
615  * @param c Connection to send an ACK on.
616  * @param size number of bytes available in buf
617  * @param buf where the callee should write the message
618  *
619  * @return number of bytes written to buf
620  */
621 static size_t
622 send_core_connection_ack (struct CadetConnection *c, size_t size, void *buf)
623 {
624   struct GNUNET_CADET_ConnectionACK *msg = buf;
625
626   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
627   if (sizeof (struct GNUNET_CADET_ConnectionACK) > size)
628   {
629     GNUNET_break (0);
630     return 0;
631   }
632   msg->header.size = htons (sizeof (struct GNUNET_CADET_ConnectionACK));
633   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK);
634   msg->cid = *GCC_get_id (c);
635
636   LOG (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
637   return sizeof (struct GNUNET_CADET_ConnectionACK);
638 }
639
640
641 /******************************************************************************/
642 /********************************   STATIC  ***********************************/
643 /******************************************************************************/
644
645
646 /**
647  * Get priority for a queued message.
648  *
649  * @param q Queued message
650  *
651  * @return CORE priority to use.
652  */
653 static enum GNUNET_CORE_Priority
654 get_priority (struct CadetPeerQueue *q)
655 {
656   enum GNUNET_CORE_Priority low;
657   enum GNUNET_CORE_Priority high;
658
659   if (NULL == q)
660   {
661     GNUNET_break (0);
662     return GNUNET_CORE_PRIO_BACKGROUND;
663   }
664
665   /* Relayed traffic has lower priority, our own traffic has higher */
666   if (NULL == q->c || GNUNET_NO == GCC_is_origin (q->c, q->fwd))
667   {
668     low = GNUNET_CORE_PRIO_BEST_EFFORT;
669     high = GNUNET_CORE_PRIO_URGENT;
670   }
671   else
672   {
673     low = GNUNET_CORE_PRIO_URGENT;
674     high = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
675   }
676
677   /* Bulky payload has lower priority, control traffic has higher. */
678   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == q->type)
679     return low;
680   else
681     return high;
682 }
683
684
685 /**
686  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
687  *
688  * @param cls closure
689  * @param key current key code
690  * @param value value in the hash map
691  * @return #GNUNET_YES if we should continue to iterate,
692  *         #GNUNET_NO if not.
693  */
694 static int
695 shutdown_tunnel (void *cls,
696                  const struct GNUNET_PeerIdentity *key,
697                  void *value)
698 {
699   struct CadetPeer *p = value;
700   struct CadetTunnel *t = p->tunnel;
701
702   if (NULL != t)
703     GCT_destroy (t);
704   return GNUNET_YES;
705 }
706
707
708
709 /**
710  * Check if peer is searching for a path (either active or delayed search).
711  *
712  * @param peer Peer to check
713  *
714  * @return GNUNET_YES if there is a search active.
715  *         GNUNET_NO otherwise.
716  */
717 static int
718 is_searching (const struct CadetPeer *peer)
719 {
720   return (NULL == peer->search_h && NULL == peer->search_delayed) ?
721          GNUNET_NO : GNUNET_YES;
722 }
723
724
725 /**
726  * @brief Start a search for a peer.
727  *
728  * @param cls Closure (Peer to search for).
729  * @param tc Task context.
730  */
731 static void
732 delayed_search (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
733 {
734   struct CadetPeer *peer = cls;
735
736   peer->search_delayed = NULL;
737
738   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
739     return;
740
741   GCP_start_search (peer);
742 }
743
744
745 /**
746  * Destroy the peer_info and free any allocated resources linked to it
747  *
748  * @param peer The peer_info to destroy.
749  *
750  * @return GNUNET_OK on success
751  */
752 static int
753 peer_destroy (struct CadetPeer *peer)
754 {
755   struct GNUNET_PeerIdentity id;
756   struct CadetPeerPath *p;
757   struct CadetPeerPath *nextp;
758
759   GNUNET_PEER_resolve (peer->id, &id);
760   GNUNET_PEER_change_rc (peer->id, -1);
761
762   LOG (GNUNET_ERROR_TYPE_WARNING, "destroying peer %s\n", GNUNET_i2s (&id));
763
764   if (GNUNET_YES !=
765     GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
766   {
767     GNUNET_break (0);
768     LOG (GNUNET_ERROR_TYPE_WARNING, " not in peermap!!\n");
769   }
770   GCP_stop_search (peer);
771   p = peer->path_head;
772   while (NULL != p)
773   {
774     nextp = p->next;
775     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
776     path_destroy (p);
777     p = nextp;
778   }
779   GCT_destroy_empty (peer->tunnel);
780   GNUNET_free (peer);
781   return GNUNET_OK;
782 }
783
784
785 /**
786  * Returns if peer is used (has a tunnel or is neighbor).
787  *
788  * @param peer Peer to check.
789  *
790  * @return #GNUNET_YES if peer is in use.
791  */
792 static int
793 peer_is_used (struct CadetPeer *peer)
794 {
795   struct CadetPeerPath *p;
796
797   if (NULL != peer->tunnel)
798     return GNUNET_YES;
799
800   for (p = peer->path_head; NULL != p; p = p->next)
801   {
802     if (p->length < 3)
803       return GNUNET_YES;
804   }
805     return GNUNET_NO;
806 }
807
808
809 /**
810  * Iterator over all the peers to get the oldest timestamp.
811  *
812  * @param cls Closure (unsued).
813  * @param key ID of the peer.
814  * @param value Peer_Info of the peer.
815  */
816 static int
817 peer_get_oldest (void *cls,
818                  const struct GNUNET_PeerIdentity *key,
819                  void *value)
820 {
821   struct CadetPeer *p = value;
822   struct GNUNET_TIME_Absolute *abs = cls;
823
824   /* Don't count active peers */
825   if (GNUNET_YES == peer_is_used (p))
826     return GNUNET_YES;
827
828   if (abs->abs_value_us < p->last_contact.abs_value_us)
829     abs->abs_value_us = p->last_contact.abs_value_us;
830
831   return GNUNET_YES;
832 }
833
834
835 /**
836  * Iterator over all the peers to remove the oldest entry.
837  *
838  * @param cls Closure (unsued).
839  * @param key ID of the peer.
840  * @param value Peer_Info of the peer.
841  */
842 static int
843 peer_timeout (void *cls,
844               const struct GNUNET_PeerIdentity *key,
845               void *value)
846 {
847   struct CadetPeer *p = value;
848   struct GNUNET_TIME_Absolute *abs = cls;
849
850   LOG (GNUNET_ERROR_TYPE_WARNING,
851        "peer %s timeout\n", GNUNET_i2s (key));
852
853   if (p->last_contact.abs_value_us == abs->abs_value_us &&
854       GNUNET_NO == peer_is_used (p))
855   {
856     peer_destroy (p);
857     return GNUNET_NO;
858   }
859     return GNUNET_YES;
860 }
861
862
863 /**
864  * Delete oldest unused peer.
865  */
866 static void
867 peer_delete_oldest (void)
868 {
869   struct GNUNET_TIME_Absolute abs;
870
871   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
872
873   GNUNET_CONTAINER_multipeermap_iterate (peers,
874                                          &peer_get_oldest,
875                                          &abs);
876   GNUNET_CONTAINER_multipeermap_iterate (peers,
877                                          &peer_timeout,
878                                          &abs);
879 }
880
881
882 /**
883  * Choose the best (yet unused) path towards a peer,
884  * considering the tunnel properties.
885  *
886  * @param peer The destination peer.
887  *
888  * @return Best current known path towards the peer, if any.
889  */
890 static struct CadetPeerPath *
891 peer_get_best_path (const struct CadetPeer *peer)
892 {
893   struct CadetPeerPath *best_p;
894   struct CadetPeerPath *p;
895   unsigned int best_cost;
896   unsigned int cost;
897
898   best_cost = UINT_MAX;
899   best_p = NULL;
900   for (p = peer->path_head; NULL != p; p = p->next)
901   {
902     if (GNUNET_NO == path_is_valid (p))
903       continue; /* Don't use invalid paths. */
904     if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
905       continue; /* If path is already in use, skip it. */
906
907     if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
908     {
909       best_cost = cost;
910       best_p = p;
911     }
912   }
913   return best_p;
914 }
915
916
917 /**
918  * Is this queue element sendable?
919  *
920  * - All management traffic is always sendable.
921  * - For payload traffic, check the connection flow control.
922  *
923  * @param q Queue element to inspect.
924  *
925  * @return #GNUNET_YES if it is sendable, #GNUNET_NO otherwise.
926  */
927 static int
928 queue_is_sendable (struct CadetPeerQueue *q)
929 {
930   /* Is PID-independent? */
931   switch (q->type)
932   {
933     case GNUNET_MESSAGE_TYPE_CADET_ACK:
934     case GNUNET_MESSAGE_TYPE_CADET_POLL:
935     case GNUNET_MESSAGE_TYPE_CADET_KX:
936     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
937     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
938     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
939     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
940       return GNUNET_YES;
941
942     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
943     case GNUNET_MESSAGE_TYPE_CADET_AX:
944       break;
945
946     default:
947       GNUNET_break (0);
948   }
949
950   return GCC_is_sendable (q->c, q->fwd);
951 }
952
953
954 /**
955  * Get first sendable message.
956  *
957  * @param peer The destination peer.
958  *
959  * @return First transmittable message, if any. Otherwise, NULL.
960  */
961 static struct CadetPeerQueue *
962 peer_get_first_message (const struct CadetPeer *peer)
963 {
964   struct CadetPeerQueue *q;
965
966   for (q = peer->queue_head; NULL != q; q = q->next)
967   {
968     LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking q:%p on c:%s\n", q, GCC_2s (q->c));
969     if (queue_is_sendable (q))
970       return q;
971   }
972
973   return NULL;
974 }
975
976
977 /**
978  * Function to process paths received for a new peer addition. The recorded
979  * paths form the initial tunnel, which can be optimized later.
980  * Called on each result obtained for the DHT search.
981  *
982  * @param cls closure
983  * @param path
984  */
985 static void
986 search_handler (void *cls, const struct CadetPeerPath *path)
987 {
988   struct CadetPeer *peer = cls;
989   unsigned int connection_count;
990
991   GCP_add_path_to_all (path, GNUNET_NO);
992
993   /* Count connections */
994   connection_count = GCT_count_connections (peer->tunnel);
995
996   /* If we already have our minimum (or more) connections, it's enough */
997   if (CONNECTIONS_PER_TUNNEL <= connection_count)
998     return;
999
1000   if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
1001   {
1002     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
1003     GCP_connect (peer);
1004   }
1005   return;
1006 }
1007
1008
1009 /**
1010  * Adjust core requested size to accomodate an ACK.
1011  *
1012  * @param message_size Requested size.
1013  *
1014  * @return Size enough to fit @c message_size and an ACK.
1015  */
1016 static size_t
1017 get_core_size (size_t message_size)
1018 {
1019   return message_size + sizeof (struct GNUNET_CADET_ACK);
1020 }
1021
1022
1023 /**
1024  * Fill a core buffer with the appropriate data for the queued message.
1025  *
1026  * @param queue Queue element for the message.
1027  * @param buf Core buffer to fill.
1028  * @param size Size remaining in @c buf.
1029  * @param[out] pid In case its an encrypted payload, set payload.
1030  *
1031  * @return Bytes written to @c buf.
1032  */
1033 static size_t
1034 fill_buf (struct CadetPeerQueue *queue, void *buf, size_t size, uint32_t *pid)
1035 {
1036   struct CadetConnection *c = queue->c;
1037   size_t msg_size;
1038
1039   switch (queue->type)
1040   {
1041     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1042       *pid = GCC_get_pid (queue->c, queue->fwd);
1043       LOG (GNUNET_ERROR_TYPE_DEBUG, "  payload ID %u\n", *pid);
1044       msg_size = send_core_data_raw (queue->cls, size, buf);
1045       ((struct GNUNET_CADET_Encrypted *) buf)->pid = htonl (*pid);
1046       break;
1047     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1048     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1049     case GNUNET_MESSAGE_TYPE_CADET_KX:
1050     case GNUNET_MESSAGE_TYPE_CADET_ACK:
1051     case GNUNET_MESSAGE_TYPE_CADET_POLL:
1052       LOG (GNUNET_ERROR_TYPE_DEBUG, "  raw %s\n", GC_m2s (queue->type));
1053       msg_size = send_core_data_raw (queue->cls, size, buf);
1054       break;
1055     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1056       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path create\n");
1057       if (GCC_is_origin (c, GNUNET_YES))
1058         msg_size = send_core_connection_create (c, size, buf);
1059       else
1060         msg_size = send_core_data_raw (queue->cls, size, buf);
1061       break;
1062     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1063       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path ack\n");
1064       if (GCC_is_origin (c, GNUNET_NO) ||
1065           GCC_is_origin (c, GNUNET_YES))
1066       {
1067         msg_size = send_core_connection_ack (c, size, buf);
1068       }
1069       else
1070       {
1071         msg_size = send_core_data_raw (queue->cls, size, buf);
1072       }
1073       break;
1074     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1075     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1076     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1077       /* This should be encapsulted */
1078       msg_size = 0;
1079       GNUNET_assert (0);
1080       break;
1081     default:
1082       GNUNET_break (0);
1083       LOG (GNUNET_ERROR_TYPE_WARNING, "  type unknown: %u\n", queue->type);
1084       msg_size = 0;
1085   }
1086
1087   GNUNET_assert (size >= msg_size);
1088
1089   return msg_size;
1090 }
1091
1092
1093 /**
1094  * Core callback to write a queued packet to core buffer
1095  *
1096  * @param cls Closure (peer info).
1097  * @param size Number of bytes available in buf.
1098  * @param buf Where the to write the message.
1099  *
1100  * @return number of bytes written to buf
1101  */
1102 static size_t
1103 queue_send (void *cls, size_t size, void *buf)
1104 {
1105   struct CadetPeer *peer = cls;
1106   struct CadetConnection *c;
1107   struct CadetPeerQueue *queue;
1108   struct GNUNET_TIME_Relative core_wait_time;
1109   const struct GNUNET_PeerIdentity *dst_id;
1110   size_t msg_size;
1111   size_t total_size;
1112   size_t rest;
1113   char *dst;
1114   uint32_t pid;
1115
1116   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1117   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1118   LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue send towards %s (max %u)\n",
1119        GCP_2s (peer), size);
1120
1121   /* Sanity checking */
1122   if (NULL == buf || 0 == size)
1123   {
1124     LOG (GNUNET_ERROR_TYPE_DEBUG, "Buffer size 0.\n");
1125     peer->tmt_time.abs_value_us = 0;
1126     peer->core_transmit = NULL;
1127     return 0;
1128   }
1129
1130   /* Init */
1131   rest = size;
1132   total_size = 0;
1133   dst = (char *) buf;
1134   pid = 0;
1135   peer->core_transmit = NULL;
1136   queue = peer_get_first_message (peer);
1137   if (NULL == queue)
1138   {
1139     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
1140     peer->tmt_time.abs_value_us = 0;
1141     return 0;
1142   }
1143   core_wait_time = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1144   LOG (GNUNET_ERROR_TYPE_DEBUG, " core wait time %s\n",
1145        GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_NO));
1146   peer->tmt_time.abs_value_us = 0;
1147
1148   /* Copy all possible messages to the core buffer */
1149   while (NULL != queue && rest >= queue->size)
1150   {
1151     c = queue->c;
1152
1153     LOG (GNUNET_ERROR_TYPE_DEBUG, "  on connection %s %s\n",
1154          GCC_2s (c), GC_f2s(queue->fwd));
1155     LOG (GNUNET_ERROR_TYPE_DEBUG, "  size %u ok (%u/%u)\n",
1156          queue->size, total_size, size);
1157
1158     msg_size = fill_buf (queue, (void *) dst, size, &pid);
1159
1160     if (0 < drop_percent &&
1161         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
1162     {
1163       LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on connection %s %s\n",
1164            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1165            queue->payload_id, GCC_2s (c), GC_f2s (queue->fwd));
1166       msg_size = 0;
1167     }
1168     else
1169     {
1170       LOG (GNUNET_ERROR_TYPE_INFO,
1171            "snd %s (%s %4u) on connection %s (%p) %s (size %u)\n",
1172            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1173            queue->payload_id, GCC_2s (c), c, GC_f2s (queue->fwd), msg_size);
1174     }
1175     total_size += msg_size;
1176     rest -= msg_size;
1177     dst = &dst[msg_size];
1178     msg_size = 0;
1179
1180     /* Free queue, but cls was freed by send_core_* in fill_buf. */
1181     (void) GCP_queue_destroy (queue, GNUNET_NO, GNUNET_YES, pid);
1182
1183     /* Next! */
1184     queue = peer_get_first_message (peer);
1185   }
1186
1187   /* If more data in queue, send next */
1188   if (NULL != queue)
1189   {
1190     LOG (GNUNET_ERROR_TYPE_DEBUG, "  more data! (%u)\n", queue->size);
1191     if (NULL == peer->core_transmit)
1192     {
1193       dst_id = GNUNET_PEER_resolve2 (peer->id);
1194       peer->core_transmit =
1195           GNUNET_CORE_notify_transmit_ready (core_handle,
1196                                              GNUNET_NO, get_priority (queue),
1197                                              GNUNET_TIME_UNIT_FOREVER_REL,
1198                                              dst_id,
1199                                              get_core_size (queue->size),
1200                                              &queue_send,
1201                                              peer);
1202       peer->tmt_time = GNUNET_TIME_absolute_get ();
1203       queue->start_waiting = GNUNET_TIME_absolute_get ();
1204     }
1205     else
1206     {
1207       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   tmt rdy called somewhere else\n");
1208     }
1209 //     GCC_start_poll (); FIXME needed?
1210   }
1211   else
1212   {
1213 //     GCC_stop_poll(); FIXME needed?
1214   }
1215
1216   LOG (GNUNET_ERROR_TYPE_DEBUG, "  return %d\n", total_size);
1217   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1218
1219   return total_size;
1220 }
1221
1222
1223 /******************************************************************************/
1224 /********************************    API    ***********************************/
1225 /******************************************************************************/
1226
1227
1228 /**
1229  * Free a transmission that was already queued with all resources
1230  * associated to the request.
1231  *
1232  * If connection was marked to be destroyed, and this was the last queued
1233  * message on it, the connection will be free'd as a result.
1234  *
1235  * @param queue Queue handler to cancel.
1236  * @param clear_cls Is it necessary to free associated cls?
1237  * @param sent Was it really sent? (Could have been canceled)
1238  * @param pid PID, if relevant (was sent and was a payload message).
1239  *
1240  * @return #GNUNET_YES if connection was destroyed as a result,
1241  *         #GNUNET_NO otherwise.
1242  */
1243 int
1244 GCP_queue_destroy (struct CadetPeerQueue *queue, int clear_cls,
1245                    int sent, uint32_t pid)
1246 {
1247   struct CadetPeer *peer;
1248   int connection_destroyed;
1249
1250   peer = queue->peer;
1251   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue destroy %s\n", GC_m2s (queue->type));
1252   if (GNUNET_YES == clear_cls)
1253   {
1254     LOG (GNUNET_ERROR_TYPE_DEBUG, " free cls\n");
1255     switch (queue->type)
1256     {
1257       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1258         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
1259         /* fall through */
1260       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1261       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1262       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1263       case GNUNET_MESSAGE_TYPE_CADET_KX:
1264       case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1265       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1266       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1267         GNUNET_free_non_null (queue->cls);
1268         break;
1269
1270       default:
1271         GNUNET_break (0);
1272         LOG (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
1273              GC_m2s (queue->type));
1274     }
1275   }
1276   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
1277
1278   if (queue->type != GNUNET_MESSAGE_TYPE_CADET_ACK &&
1279       queue->type != GNUNET_MESSAGE_TYPE_CADET_POLL)
1280   {
1281     peer->queue_n--;
1282   }
1283
1284   if (NULL != queue->callback)
1285   {
1286     struct GNUNET_TIME_Relative wait_time;
1287
1288     wait_time = GNUNET_TIME_absolute_get_duration (queue->start_waiting);
1289     LOG (GNUNET_ERROR_TYPE_DEBUG, " calling callback, time elapsed %s\n",
1290          GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
1291     connection_destroyed = queue->callback (queue->callback_cls,
1292                                             queue->c, sent, queue->type, pid,
1293                                             queue->fwd, queue->size,
1294                                             wait_time);
1295   }
1296   else
1297   {
1298     connection_destroyed = GNUNET_NO;
1299   }
1300
1301   if (NULL == peer_get_first_message (peer) && NULL != peer->core_transmit)
1302   {
1303     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1304     peer->core_transmit = NULL;
1305     peer->tmt_time.abs_value_us = 0;
1306   }
1307
1308   GNUNET_free (queue);
1309   return connection_destroyed;
1310 }
1311
1312
1313 /**
1314  * @brief Queue and pass message to core when possible.
1315  *
1316  * @param peer Peer towards which to queue the message.
1317  * @param cls Closure (@c type dependant). It will be used by queue_send to
1318  *            build the message to be sent if not already prebuilt.
1319  * @param type Type of the message, 0 for a raw message.
1320  * @param size Size of the message.
1321  * @param c Connection this message belongs to (can be NULL).
1322  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1323  * @param cont Continuation to be called once CORE has taken the message.
1324  * @param cont_cls Closure for @c cont.
1325  *
1326  * @return Handle to cancel the message before it is sent. Once cont is called
1327  *         message has been sent and therefore the handle is no longer valid.
1328  */
1329 struct CadetPeerQueue *
1330 GCP_queue_add (struct CadetPeer *peer, void *cls, uint16_t type,
1331                uint16_t payload_type, uint32_t payload_id, size_t size,
1332                struct CadetConnection *c, int fwd,
1333                GCP_sent cont, void *cont_cls)
1334 {
1335   struct CadetPeerQueue *q;
1336   int error_level;
1337   int priority;
1338   int call_core;
1339
1340   if (NULL == c && GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN != type)
1341     error_level = GNUNET_ERROR_TYPE_ERROR;
1342   else
1343     error_level = GNUNET_ERROR_TYPE_INFO;
1344   LOG (error_level,
1345        "que %s (%s %9u) on connection %s (%p) %s towards %s (size %u)\n",
1346        GC_m2s (type), GC_m2s (payload_type), payload_id,
1347        GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1348
1349   if (error_level == GNUNET_ERROR_TYPE_ERROR)
1350     GNUNET_assert (0);
1351   if (NULL == peer->connections)
1352   {
1353     /* We are not connected to this peer, ignore request. */
1354     LOG (GNUNET_ERROR_TYPE_WARNING, "%s not a neighbor\n", GCP_2s (peer));
1355     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1356                               GNUNET_NO);
1357     return NULL;
1358   }
1359
1360   priority = 0;
1361
1362   if (GNUNET_MESSAGE_TYPE_CADET_POLL == type ||
1363       GNUNET_MESSAGE_TYPE_CADET_ACK == type)
1364   {
1365     priority = 100;
1366   }
1367
1368   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1369
1370   call_core = (NULL == c || type == GNUNET_MESSAGE_TYPE_CADET_KX) ?
1371                GNUNET_YES : GCC_is_sendable (c, fwd);
1372   q = GNUNET_new (struct CadetPeerQueue);
1373   q->cls = cls;
1374   q->type = type;
1375   q->payload_type = payload_type;
1376   q->payload_id = payload_id;
1377   q->size = size;
1378   q->peer = peer;
1379   q->c = c;
1380   q->fwd = fwd;
1381   q->callback = cont;
1382   q->callback_cls = cont_cls;
1383   if (100 > priority)
1384   {
1385     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, q);
1386     peer->queue_n++;
1387   }
1388   else
1389   {
1390     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, q);
1391     call_core = GNUNET_YES;
1392   }
1393
1394   q->start_waiting = GNUNET_TIME_absolute_get ();
1395   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1396   {
1397     LOG (GNUNET_ERROR_TYPE_DEBUG,
1398          "calling core tmt rdy towards %s for %u bytes\n",
1399          GCP_2s (peer), size);
1400     peer->core_transmit =
1401         GNUNET_CORE_notify_transmit_ready (core_handle,
1402                                            GNUNET_NO, get_priority (q),
1403                                            GNUNET_TIME_UNIT_FOREVER_REL,
1404                                            GNUNET_PEER_resolve2 (peer->id),
1405                                            get_core_size (size),
1406                                            &queue_send, peer);
1407     peer->tmt_time = GNUNET_TIME_absolute_get ();
1408   }
1409   else if (GNUNET_NO == call_core)
1410   {
1411     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s not needed\n",
1412          GCP_2s (peer));
1413
1414   }
1415   else
1416   {
1417     struct GNUNET_TIME_Relative elapsed;
1418     elapsed = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1419     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s already called %s\n",
1420          GCP_2s (peer),
1421          GNUNET_STRINGS_relative_time_to_string (elapsed, GNUNET_NO));
1422
1423   }
1424   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1425   return q;
1426 }
1427
1428
1429 /**
1430  * Cancel all queued messages to a peer that belong to a certain connection.
1431  *
1432  * @param peer Peer towards whom to cancel.
1433  * @param c Connection whose queued messages to cancel. Might be destroyed by
1434  *          the sent continuation call.
1435  */
1436 void
1437 GCP_queue_cancel (struct CadetPeer *peer, struct CadetConnection *c)
1438 {
1439   struct CadetPeerQueue *q;
1440   struct CadetPeerQueue *next;
1441   struct CadetPeerQueue *prev;
1442   int connection_destroyed;
1443
1444   connection_destroyed = GNUNET_NO;
1445   for (q = peer->queue_head; NULL != q; q = next)
1446   {
1447     prev = q->prev;
1448     if (q->c == c)
1449     {
1450       LOG (GNUNET_ERROR_TYPE_DEBUG, "GMP queue cancel %s\n", GC_m2s (q->type));
1451       GNUNET_break (GNUNET_NO == connection_destroyed);
1452       if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY == q->type)
1453       {
1454         q->c = NULL;
1455       }
1456       else
1457       {
1458         connection_destroyed = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1459       }
1460
1461       /* Get next from prev, q->next might be already freed:
1462        * queue destroy -> callback -> GCC_destroy -> cancel_queues -> here
1463        */
1464       if (NULL == prev)
1465         next = peer->queue_head;
1466       else
1467         next = prev->next;
1468     }
1469     else
1470     {
1471       next = q->next;
1472     }
1473   }
1474
1475   if (NULL == peer->queue_head && NULL != peer->core_transmit)
1476   {
1477     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1478     peer->core_transmit = NULL;
1479     peer->tmt_time.abs_value_us = 0;
1480   }
1481 }
1482
1483
1484 /**
1485  * Get the first transmittable message for a connection.
1486  *
1487  * @param peer Neighboring peer.
1488  * @param c Connection.
1489  *
1490  * @return First transmittable message.
1491  */
1492 static struct CadetPeerQueue *
1493 connection_get_first_message (struct CadetPeer *peer, struct CadetConnection *c)
1494 {
1495   struct CadetPeerQueue *q;
1496
1497   for (q = peer->queue_head; NULL != q; q = q->next)
1498   {
1499     if (q->c != c)
1500       continue;
1501     if (queue_is_sendable (q))
1502     {
1503       LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
1504       return q;
1505     }
1506     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
1507   }
1508
1509   return NULL;
1510 }
1511
1512
1513 /**
1514  * Get the first message for a connection and unqueue it.
1515  *
1516  * Only tunnel (or higher) level messages are unqueued. Connection specific
1517  * messages are silently destroyed upon encounter.
1518  *
1519  * @param peer Neighboring peer.
1520  * @param c Connection.
1521  * @param destroyed[in/out] Was the connection destroyed (prev/as a result)?.
1522  *                          Can NOT be NULL.
1523  *
1524  * @return First message for this connection.
1525  */
1526 struct GNUNET_MessageHeader *
1527 GCP_connection_pop (struct CadetPeer *peer,
1528                     struct CadetConnection *c,
1529                     int *destroyed)
1530 {
1531   struct CadetPeerQueue *q;
1532   struct CadetPeerQueue *next;
1533   struct GNUNET_MessageHeader *msg;
1534   int dest;
1535
1536   GNUNET_assert (NULL != destroyed);
1537   LOG (GNUNET_ERROR_TYPE_DEBUG, "connection_pop on connection %p\n", c);
1538   for (q = peer->queue_head; NULL != q; q = next)
1539   {
1540     next = q->next;
1541     if (q->c != c)
1542       continue;
1543     LOG (GNUNET_ERROR_TYPE_DEBUG, " - queued: %s (%s %u), callback: %p\n",
1544          GC_m2s (q->type), GC_m2s (q->payload_type), q->payload_id,
1545          q->callback);
1546     switch (q->type)
1547     {
1548       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1549       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1550       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1551       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1552       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1553       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1554         dest = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1555         if (GNUNET_YES == dest)
1556         {
1557           GNUNET_break (GNUNET_NO == *destroyed);
1558           *destroyed = GNUNET_YES;
1559         }
1560         continue;
1561
1562       case GNUNET_MESSAGE_TYPE_CADET_KX:
1563       case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1564         msg = (struct GNUNET_MessageHeader *) q->cls;
1565         dest = GCP_queue_destroy (q, GNUNET_NO, GNUNET_NO, 0);
1566         if (GNUNET_YES == dest)
1567         {
1568           GNUNET_break (GNUNET_NO == *destroyed);
1569           *destroyed = GNUNET_YES;
1570         }
1571         return msg;
1572
1573       default:
1574         GNUNET_break (0);
1575         LOG (GNUNET_ERROR_TYPE_DEBUG, "Unknown message %s\n", GC_m2s (q->type));
1576     }
1577   }
1578
1579   return NULL;
1580 }
1581
1582 /**
1583  * Unlock a possibly locked queue for a connection.
1584  *
1585  * If there is a message that can be sent on this connection, call core for it.
1586  * Otherwise (if core transmit is already called or there is no sendable
1587  * message) do nothing.
1588  *
1589  * @param peer Peer who keeps the queue.
1590  * @param c Connection whose messages to unlock.
1591  */
1592 void
1593 GCP_queue_unlock (struct CadetPeer *peer, struct CadetConnection *c)
1594 {
1595   struct CadetPeerQueue *q;
1596   size_t size;
1597
1598   if (NULL != peer->core_transmit)
1599   {
1600     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
1601     return; /* Already unlocked */
1602   }
1603
1604   q = connection_get_first_message (peer, c);
1605   if (NULL == q)
1606   {
1607     LOG (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
1608     return; /* Nothing to transmit */
1609   }
1610
1611   size = q->size;
1612   peer->core_transmit =
1613       GNUNET_CORE_notify_transmit_ready (core_handle,
1614                                          GNUNET_NO, get_priority (q),
1615                                          GNUNET_TIME_UNIT_FOREVER_REL,
1616                                          GNUNET_PEER_resolve2 (peer->id),
1617                                          get_core_size (size),
1618                                          &queue_send,
1619                                          peer);
1620   peer->tmt_time = GNUNET_TIME_absolute_get ();
1621 }
1622
1623
1624 /**
1625  * Initialize the peer subsystem.
1626  *
1627  * @param c Configuration.
1628  */
1629 void
1630 GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1631 {
1632   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1633   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1634   if (GNUNET_OK !=
1635       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1636                                              &max_peers))
1637   {
1638     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1639                                "CADET", "MAX_PEERS", "USING DEFAULT");
1640     max_peers = 1000;
1641   }
1642
1643   if (GNUNET_OK !=
1644       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1645                                              &drop_percent))
1646   {
1647     drop_percent = 0;
1648   }
1649   else
1650   {
1651     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1652     LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1653     LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1654     LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1655     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1656   }
1657
1658   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1659                                      NULL,      /* Closure passed to CADET functions */
1660                                      &core_init,        /* Call core_init once connected */
1661                                      &core_connect,     /* Handle connects */
1662                                      &core_disconnect,  /* remove peers on disconnects */
1663                                      NULL,      /* Don't notify about all incoming messages */
1664                                      GNUNET_NO, /* For header only in notification */
1665                                      NULL,      /* Don't notify about all outbound messages */
1666                                      GNUNET_NO, /* For header-only out notification */
1667                                      core_handlers);    /* Register these handlers */
1668   if (GNUNET_YES !=
1669       GNUNET_CONFIGURATION_get_value_yesno (c, "CADET", "DISABLE_TRY_CONNECT"))
1670   {
1671     transport_handle = GNUNET_TRANSPORT_connect (c, &my_full_id, NULL, /* cls */
1672                                                  /* Notify callbacks */
1673                                                  NULL, NULL, NULL);
1674   }
1675   else
1676   {
1677     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1678     LOG (GNUNET_ERROR_TYPE_WARNING, "*  DISABLE TRYING CONNECT in config  *\n");
1679     LOG (GNUNET_ERROR_TYPE_WARNING, "*  Use this only for test purposes.  *\n");
1680     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1681     transport_handle = NULL;
1682   }
1683
1684
1685
1686   if (NULL == core_handle)
1687   {
1688     GNUNET_break (0);
1689     GNUNET_SCHEDULER_shutdown ();
1690     return;
1691   }
1692
1693 }
1694
1695
1696 /**
1697  * Shut down the peer subsystem.
1698  */
1699 void
1700 GCP_shutdown (void)
1701 {
1702   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
1703
1704   if (core_handle != NULL)
1705   {
1706     GNUNET_CORE_disconnect (core_handle);
1707     core_handle = NULL;
1708   }
1709   if (transport_handle != NULL)
1710   {
1711     GNUNET_TRANSPORT_disconnect (transport_handle);
1712     transport_handle = NULL;
1713   }
1714   GNUNET_PEER_change_rc (myid, -1);
1715 }
1716
1717
1718 /**
1719  * Retrieve the CadetPeer stucture associated with the peer, create one
1720  * and insert it in the appropriate structures if the peer is not known yet.
1721  *
1722  * @param peer_id Full identity of the peer.
1723  *
1724  * @return Existing or newly created peer structure.
1725  */
1726 struct CadetPeer *
1727 GCP_get (const struct GNUNET_PeerIdentity *peer_id)
1728 {
1729   struct CadetPeer *peer;
1730
1731   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1732   if (NULL == peer)
1733   {
1734     peer = GNUNET_new (struct CadetPeer);
1735     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1736     {
1737       peer_delete_oldest ();
1738     }
1739         GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1740                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1741         peer->id = GNUNET_PEER_intern (peer_id);
1742   }
1743   peer->last_contact = GNUNET_TIME_absolute_get ();
1744
1745   return peer;
1746 }
1747
1748
1749 /**
1750  * Retrieve the CadetPeer stucture associated with the peer, create one
1751  * and insert it in the appropriate structures if the peer is not known yet.
1752  *
1753  * @param peer Short identity of the peer.
1754  *
1755  * @return Existing or newly created peer structure.
1756  */
1757 struct CadetPeer *
1758 GCP_get_short (const GNUNET_PEER_Id peer)
1759 {
1760   return GCP_get (GNUNET_PEER_resolve2 (peer));
1761 }
1762
1763
1764 /**
1765  * Try to connect to a peer on transport level.
1766  *
1767  * @param cls Closure (peer).
1768  * @param tc TaskContext.
1769  */
1770 static void
1771 try_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1772 {
1773   struct CadetPeer *peer = cls;
1774
1775   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1776     return;
1777
1778   GNUNET_TRANSPORT_try_connect (transport_handle,
1779                                 GNUNET_PEER_resolve2 (peer->id), NULL, NULL);
1780 }
1781
1782
1783 /**
1784  * Try to establish a new connection to this peer (in its tunnel).
1785  * If the peer doesn't have any path to it yet, try to get one.
1786  * If the peer already has some path, send a CREATE CONNECTION towards it.
1787  *
1788  * @param peer Peer to connect to.
1789  */
1790 void
1791 GCP_connect (struct CadetPeer *peer)
1792 {
1793   struct CadetTunnel *t;
1794   struct CadetPeerPath *p;
1795   struct CadetConnection *c;
1796   int rerun_search;
1797
1798   LOG (GNUNET_ERROR_TYPE_DEBUG, "peer_connect towards %s\n", GCP_2s (peer));
1799
1800   /* If we have a current hello, try to connect using it. */
1801   GCP_try_connect (peer);
1802
1803   t = peer->tunnel;
1804   c = NULL;
1805   rerun_search = GNUNET_NO;
1806
1807   if (NULL != peer->path_head)
1808   {
1809     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1810     p = peer_get_best_path (peer);
1811     if (NULL != p)
1812     {
1813       char *s;
1814
1815       s = path_2s (p);
1816       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1817       GNUNET_free (s);
1818
1819       c = GCT_use_path (t, p);
1820       if (NULL == c)
1821       {
1822         /* This case can happen when the path includes a first hop that is
1823          * not yet known to be connected.
1824          *
1825          * This happens quite often during testing when running cadet
1826          * under valgrind: core connect notifications come very late and the
1827          * DHT result has already come and created a valid path.
1828          * In this case, the peer->connections hashmap will be NULL and
1829          * tunnel_use_path will not be able to create a connection from that
1830          * path.
1831          *
1832          * Re-running the DHT GET should give core time to callback.
1833          *
1834          * GCT_use_path -> GCC_new -> register_neighbors takes care of
1835          * updating statistics about this issue.
1836          */
1837         rerun_search = GNUNET_YES;
1838       }
1839       else
1840       {
1841         GCC_send_create (c);
1842         return;
1843       }
1844     }
1845     else
1846     {
1847       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1848     }
1849   }
1850
1851   if (GNUNET_YES == rerun_search)
1852   {
1853     struct GNUNET_TIME_Relative delay;
1854
1855     GCP_stop_search (peer);
1856     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
1857     peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay, &delayed_search,
1858                                                          peer);
1859     return;
1860   }
1861
1862   if (GNUNET_NO == is_searching (peer))
1863     GCP_start_search (peer);
1864 }
1865
1866
1867 /**
1868  * Chech whether there is a direct (core level)  connection to peer.
1869  *
1870  * @param peer Peer to check.
1871  *
1872  * @return #GNUNET_YES if there is a direct connection.
1873  */
1874 int
1875 GCP_is_neighbor (const struct CadetPeer *peer)
1876 {
1877   struct CadetPeerPath *path;
1878
1879   if (NULL == peer->connections)
1880     return GNUNET_NO;
1881
1882   for (path = peer->path_head; NULL != path; path = path->next)
1883   {
1884     if (3 > path->length)
1885       return GNUNET_YES;
1886   }
1887
1888   /* Is not a neighbor but connections is not NULL, probably disconnecting */
1889   return GNUNET_NO;
1890 }
1891
1892
1893 /**
1894  * Create and initialize a new tunnel towards a peer, in case it has none.
1895  * In case the peer already has a tunnel, nothing is done.
1896  *
1897  * Does not generate any traffic, just creates the local data structures.
1898  *
1899  * @param peer Peer towards which to create the tunnel.
1900  */
1901 void
1902 GCP_add_tunnel (struct CadetPeer *peer)
1903 {
1904   if (NULL != peer->tunnel)
1905     return;
1906   peer->tunnel = GCT_new (peer);
1907 }
1908
1909
1910 /**
1911  * Add a connection to a neighboring peer.
1912  *
1913  * Store that the peer is the first hop of the connection in one
1914  * direction and that on peer disconnect the connection must be
1915  * notified and destroyed, for it will no longer be valid.
1916  *
1917  * @param peer Peer to add connection to.
1918  * @param c Connection to add.
1919  *
1920  * @return GNUNET_OK on success.
1921  */
1922 int
1923 GCP_add_connection (struct CadetPeer *peer,
1924                     struct CadetConnection *c)
1925 {
1926   int result;
1927   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding connection %s\n", GCC_2s (c));
1928   LOG (GNUNET_ERROR_TYPE_DEBUG, "to peer %s\n", GCP_2s (peer));
1929
1930   if (NULL == peer->connections)
1931   {
1932     GNUNET_break (0);
1933     LOG (GNUNET_ERROR_TYPE_DEBUG,
1934          "Peer %s is not a neighbor!\n",
1935          GCP_2s (peer));
1936     return GNUNET_SYSERR;
1937   }
1938   LOG (GNUNET_ERROR_TYPE_DEBUG,
1939        "peer %s ok, has %u connections.\n",
1940        GCP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
1941   result = GNUNET_CONTAINER_multihashmap_put (peer->connections,
1942                                               GCC_get_h (c),
1943                                               c,
1944                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1945   LOG (GNUNET_ERROR_TYPE_DEBUG,
1946        " now has %u connections.\n",
1947        GNUNET_CONTAINER_multihashmap_size (peer->connections));
1948   LOG (GNUNET_ERROR_TYPE_DEBUG, "result %u\n", result);
1949
1950   return result;
1951 }
1952
1953
1954 /**
1955  * Add the path to the peer and update the path used to reach it in case this
1956  * is the shortest.
1957  *
1958  * @param peer Destination peer to add the path to.
1959  * @param path New path to add. Last peer must be the peer in arg 1.
1960  *             Path will be either used of freed if already known.
1961  * @param trusted Do we trust that this path is real?
1962  *
1963  * @return path if path was taken, pointer to existing duplicate if exists
1964  *         NULL on error.
1965  */
1966 struct CadetPeerPath *
1967 GCP_add_path (struct CadetPeer *peer, struct CadetPeerPath *path,
1968               int trusted)
1969 {
1970   struct CadetPeerPath *aux;
1971   unsigned int l;
1972   unsigned int l2;
1973
1974   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1975        path->length, GCP_2s (peer));
1976
1977   if (NULL == peer || NULL == path
1978       || path->peers[path->length - 1] != peer->id)
1979   {
1980     GNUNET_break (0);
1981     path_destroy (path);
1982     return NULL;
1983   }
1984
1985   for (l = 1; l < path->length; l++)
1986   {
1987     if (path->peers[l] == myid)
1988     {
1989       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1990       for (l2 = 0; l2 < path->length - l; l2++)
1991       {
1992         path->peers[l2] = path->peers[l + l2];
1993       }
1994       path->length -= l;
1995       l = 1;
1996       path->peers = GNUNET_realloc (path->peers,
1997                                     path->length * sizeof (GNUNET_PEER_Id));
1998     }
1999   }
2000
2001   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
2002
2003   if (2 >= path->length && GNUNET_NO == trusted)
2004   {
2005     /* Only allow CORE to tell us about direct paths */
2006     path_destroy (path);
2007     return NULL;
2008   }
2009
2010   l = path_get_length (path);
2011   if (0 == l)
2012   {
2013     path_destroy (path);
2014     return NULL;
2015   }
2016
2017   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2018   for (aux = peer->path_head; aux != NULL; aux = aux->next)
2019   {
2020     l2 = path_get_length (aux);
2021     if (l2 > l)
2022     {
2023       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
2024       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
2025                                           peer->path_tail, aux, path);
2026       goto finish;
2027     }
2028     else
2029     {
2030       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2031       {
2032         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
2033         path_destroy (path);
2034         return aux;
2035       }
2036     }
2037   }
2038   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head, peer->path_tail,
2039                                     path);
2040   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
2041
2042 finish:
2043   if (NULL != peer->tunnel
2044       && CONNECTIONS_PER_TUNNEL < GCT_count_connections (peer->tunnel))
2045   {
2046     GCP_connect (peer);
2047   }
2048   return path;
2049 }
2050
2051
2052 /**
2053  * Add the path to the origin peer and update the path used to reach it in case
2054  * this is the shortest.
2055  * The path is given in peer_info -> destination, therefore we turn the path
2056  * upside down first.
2057  *
2058  * @param peer Peer to add the path to, being the origin of the path.
2059  * @param path New path to add after being inversed.
2060  *             Path will be either used or freed.
2061  * @param trusted Do we trust that this path is real?
2062  *
2063  * @return path if path was taken, pointer to existing duplicate if exists
2064  *         NULL on error.
2065  */
2066 struct CadetPeerPath *
2067 GCP_add_path_to_origin (struct CadetPeer *peer,
2068                         struct CadetPeerPath *path,
2069                         int trusted)
2070 {
2071   if (NULL == path)
2072     return NULL;
2073   path_invert (path);
2074   return GCP_add_path (peer, path, trusted);
2075 }
2076
2077
2078 /**
2079  * Adds a path to the info of all the peers in the path
2080  *
2081  * @param p Path to process.
2082  * @param confirmed Whether we know if the path works or not.
2083  */
2084 void
2085 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
2086 {
2087   unsigned int i;
2088
2089   /* TODO: invert and add */
2090   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2091   for (i++; i < p->length; i++)
2092   {
2093     struct CadetPeer *aux;
2094     struct CadetPeerPath *copy;
2095
2096     aux = GCP_get_short (p->peers[i]);
2097     copy = path_duplicate (p);
2098     copy->length = i + 1;
2099     GCP_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
2100   }
2101 }
2102
2103
2104 /**
2105  * Remove any path to the peer that has the extact same peers as the one given.
2106  *
2107  * @param peer Peer to remove the path from.
2108  * @param path Path to remove. Is always destroyed .
2109  */
2110 void
2111 GCP_remove_path (struct CadetPeer *peer, struct CadetPeerPath *path)
2112 {
2113   struct CadetPeerPath *iter;
2114   struct CadetPeerPath *next;
2115
2116   GNUNET_assert (myid == path->peers[0]);
2117   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2118
2119   LOG (GNUNET_ERROR_TYPE_INFO, "Removing path %p (%u) from %s\n",
2120        path, path->length, GCP_2s (peer));
2121
2122   for (iter = peer->path_head; NULL != iter; iter = next)
2123   {
2124     next = iter->next;
2125     if (0 == path_cmp (path, iter))
2126     {
2127       GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
2128       if (iter != path)
2129         path_destroy (iter);
2130     }
2131   }
2132   path_destroy (path);
2133 }
2134
2135
2136 /**
2137  * Remove a connection from a neighboring peer.
2138  *
2139  * @param peer Peer to remove connection from.
2140  * @param c Connection to remove.
2141  *
2142  * @return GNUNET_OK on success.
2143  */
2144 int
2145 GCP_remove_connection (struct CadetPeer *peer,
2146                        const struct CadetConnection *c)
2147 {
2148   LOG (GNUNET_ERROR_TYPE_DEBUG, "removing connection %s\n", GCC_2s (c));
2149   LOG (GNUNET_ERROR_TYPE_DEBUG, "from peer %s\n", GCP_2s (peer));
2150
2151   if (NULL == peer || NULL == peer->connections)
2152   {
2153     LOG (GNUNET_ERROR_TYPE_DEBUG,
2154          "Peer %s is not a neighbor!\n",
2155          GCP_2s (peer));
2156     return GNUNET_SYSERR;
2157   }
2158   LOG (GNUNET_ERROR_TYPE_DEBUG,
2159        "peer %s ok, has %u connections.\n",
2160        GCP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
2161
2162   return GNUNET_CONTAINER_multihashmap_remove (peer->connections,
2163                                                GCC_get_h (c),
2164                                                c);
2165 }
2166
2167 /**
2168  * Start the DHT search for new paths towards the peer: we don't have
2169  * enough good connections.
2170  *
2171  * @param peer Destination peer.
2172  */
2173 void
2174 GCP_start_search (struct CadetPeer *peer)
2175 {
2176   const struct GNUNET_PeerIdentity *id;
2177   struct CadetTunnel *t = peer->tunnel;
2178
2179   if (NULL != peer->search_h)
2180   {
2181     GNUNET_break (0);
2182     return;
2183   }
2184
2185   if (NULL != peer->search_delayed)
2186     GCP_stop_search (peer);
2187
2188   id = GNUNET_PEER_resolve2 (peer->id);
2189   peer->search_h = GCD_search (id, &search_handler, peer);
2190
2191   if (NULL == t)
2192   {
2193     /* Why would we search for a peer with no tunnel towards it? */
2194     GNUNET_break (0);
2195     return;
2196   }
2197
2198   if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
2199       || 0 == GCT_count_any_connections (t))
2200   {
2201     GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2202   }
2203 }
2204
2205
2206 /**
2207  * Stop the DHT search for new paths towards the peer: we already have
2208  * enough good connections.
2209  *
2210  * @param peer Destination peer.
2211  */
2212 void
2213 GCP_stop_search (struct CadetPeer *peer)
2214 {
2215   if (NULL != peer->search_h)
2216   {
2217     GCD_search_stop (peer->search_h);
2218     peer->search_h = NULL;
2219   }
2220   if (NULL != peer->search_delayed)
2221   {
2222     GNUNET_SCHEDULER_cancel (peer->search_delayed);
2223     peer->search_delayed = NULL;
2224   }
2225 }
2226
2227
2228 /**
2229  * Get the Full ID of a peer.
2230  *
2231  * @param peer Peer to get from.
2232  *
2233  * @return Full ID of peer.
2234  */
2235 const struct GNUNET_PeerIdentity *
2236 GCP_get_id (const struct CadetPeer *peer)
2237 {
2238   return GNUNET_PEER_resolve2 (peer->id);
2239 }
2240
2241
2242 /**
2243  * Get the Short ID of a peer.
2244  *
2245  * @param peer Peer to get from.
2246  *
2247  * @return Short ID of peer.
2248  */
2249 GNUNET_PEER_Id
2250 GCP_get_short_id (const struct CadetPeer *peer)
2251 {
2252   return peer->id;
2253 }
2254
2255
2256 /**
2257  * Set tunnel.
2258  *
2259  * If tunnel is NULL and there was a search active, stop it, as it's useless.
2260  *
2261  * @param peer Peer.
2262  * @param t Tunnel.
2263  */
2264 void
2265 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
2266 {
2267   peer->tunnel = t;
2268   if (NULL == t && GNUNET_YES == is_searching (peer))
2269   {
2270     GCP_stop_search (peer);
2271   }
2272 }
2273
2274
2275 /**
2276  * Get the tunnel towards a peer.
2277  *
2278  * @param peer Peer to get from.
2279  *
2280  * @return Tunnel towards peer.
2281  */
2282 struct CadetTunnel *
2283 GCP_get_tunnel (const struct CadetPeer *peer)
2284 {
2285   return peer->tunnel;
2286 }
2287
2288
2289 /**
2290  * Set the hello message.
2291  *
2292  * @param peer Peer whose message to set.
2293  * @param hello Hello message.
2294  */
2295 void
2296 GCP_set_hello (struct CadetPeer *peer, const struct GNUNET_HELLO_Message *hello)
2297 {
2298   struct GNUNET_HELLO_Message *old;
2299   size_t size;
2300
2301   LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
2302   if (NULL == hello)
2303     return;
2304
2305   old = GCP_get_hello (peer);
2306   if (NULL == old)
2307   {
2308     size = GNUNET_HELLO_size (hello);
2309     LOG (GNUNET_ERROR_TYPE_DEBUG, " new (%u bytes)\n", size);
2310     peer->hello = GNUNET_malloc (size);
2311     memcpy (peer->hello, hello, size);
2312   }
2313   else
2314   {
2315     peer->hello = GNUNET_HELLO_merge (old, hello);
2316     LOG (GNUNET_ERROR_TYPE_DEBUG, " merge into %p (%u bytes)\n",
2317          peer->hello, GNUNET_HELLO_size (hello));
2318     GNUNET_free (old);
2319   }
2320 }
2321
2322
2323 /**
2324  * Get the hello message.
2325  *
2326  * @param peer Peer whose message to get.
2327  *
2328  * @return Hello message.
2329  */
2330 struct GNUNET_HELLO_Message *
2331 GCP_get_hello (struct CadetPeer *peer)
2332 {
2333   struct GNUNET_TIME_Absolute expiration;
2334   struct GNUNET_TIME_Relative remaining;
2335
2336   if (NULL == peer->hello)
2337     return NULL;
2338
2339   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2340   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2341   if (0 == remaining.rel_value_us)
2342   {
2343     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2344          GNUNET_STRINGS_absolute_time_to_string (expiration));
2345     GNUNET_free (peer->hello);
2346     peer->hello = NULL;
2347   }
2348   return peer->hello;
2349 }
2350
2351
2352 /**
2353  * Try to connect to a peer on TRANSPORT level.
2354  *
2355  * @param peer Peer to whom to connect.
2356  */
2357 void
2358 GCP_try_connect (struct CadetPeer *peer)
2359 {
2360   struct GNUNET_HELLO_Message *hello;
2361   struct GNUNET_MessageHeader *mh;
2362
2363   if (NULL == transport_handle)
2364     return;
2365
2366   hello = GCP_get_hello (peer);
2367   if (NULL == hello)
2368     return;
2369
2370   mh = GNUNET_HELLO_get_header (hello);
2371   GNUNET_TRANSPORT_offer_hello (transport_handle, mh, try_connect, peer);
2372 }
2373
2374
2375 /**
2376  * Check if the given ECDH key is correct for the peer.
2377  *
2378  * This function caches the results if the key has been previoulsy checked,
2379  * otherwise checks that the key is signed with the peer's ID (EdDSA key).
2380  *
2381  * TODO: save the cached public key to permanent storage / peerinfo.
2382  *
2383  * @param peer Peer whose key to check.
2384  * @param key ECDH key to check.
2385  * @param purpose Purpose of the signature (followed by the key).
2386  * @param sig Signature with the peer's EdDSA key (PeerID).
2387  */
2388 int
2389 GCP_check_key (struct CadetPeer *peer,
2390                const struct GNUNET_CRYPTO_EcdhePublicKey *key,
2391                const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
2392                const struct GNUNET_CRYPTO_EddsaSignature *sig)
2393 {
2394   struct GNUNET_CRYPTO_EddsaPublicKey *pub;
2395   int verified;
2396
2397   /* Is it the same as the cached key? */
2398   if (0 == memcmp (&peer->ax_key, key, sizeof (*key)))
2399     return GNUNET_OK;
2400
2401   /* New key, verify. */
2402   pub = (struct GNUNET_CRYPTO_EddsaPublicKey *) GCP_get_id (peer);
2403   verified = GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_CADET_AXKX,
2404                                          purpose, sig, pub);
2405
2406   if (GNUNET_OK != verified)
2407     return GNUNET_SYSERR;
2408
2409   /* Cache key for later. */
2410   peer->ax_key = *key;
2411   return GNUNET_OK;
2412 }
2413
2414
2415 /**
2416  * Notify a peer that a link between two other peers is broken. If any path
2417  * used that link, eliminate it.
2418  *
2419  * @param peer Peer affected by the change.
2420  * @param peer1 Peer whose link is broken.
2421  * @param peer2 Peer whose link is broken.
2422  */
2423 void
2424 GCP_notify_broken_link (struct CadetPeer *peer,
2425                         struct GNUNET_PeerIdentity *peer1,
2426                         struct GNUNET_PeerIdentity *peer2)
2427 {
2428   struct CadetPeerPath *iter;
2429   struct CadetPeerPath *next;
2430   unsigned int i;
2431   GNUNET_PEER_Id p1;
2432   GNUNET_PEER_Id p2;
2433
2434   p1 = GNUNET_PEER_search (peer1);
2435   p2 = GNUNET_PEER_search (peer2);
2436
2437   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2438   if (0 == p1 || 0 == p2)
2439   {
2440     /* We don't even know them */
2441     return;
2442   }
2443
2444   for (iter = peer->path_head; NULL != iter; iter = next)
2445   {
2446     next = iter->next;
2447     for (i = 0; i < iter->length - 1; i++)
2448     {
2449       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2450           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2451       {
2452         char *s;
2453
2454         s = path_2s (iter);
2455         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2456         GNUNET_free (s);
2457
2458         path_invalidate (iter);
2459       }
2460     }
2461   }
2462 }
2463
2464
2465 /**
2466  * Count the number of known paths toward the peer.
2467  *
2468  * @param peer Peer to get path info.
2469  *
2470  * @return Number of known paths.
2471  */
2472 unsigned int
2473 GCP_count_paths (const struct CadetPeer *peer)
2474 {
2475   struct CadetPeerPath *iter;
2476   unsigned int i;
2477
2478   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2479     i++;
2480
2481   return i;
2482 }
2483
2484
2485 /**
2486  * Iterate all known peers.
2487  *
2488  * @param iter Iterator.
2489  * @param cls Closure for @c iter.
2490  */
2491 void
2492 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2493 {
2494   GNUNET_CONTAINER_multipeermap_iterate (peers, iter, cls);
2495 }
2496
2497
2498 /**
2499  * Get the static string for a peer ID.
2500  *
2501  * @param peer Peer.
2502  *
2503  * @return Static string for it's ID.
2504  */
2505 const char *
2506 GCP_2s (const struct CadetPeer *peer)
2507 {
2508   if (NULL == peer)
2509     return "(NULL)";
2510   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2511 }