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