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