- add a peer debug function
[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  * Shut down the peer subsystem.
1468  */
1469 void
1470 GCP_shutdown (void)
1471 {
1472   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
1473
1474   if (core_handle != NULL)
1475   {
1476     GNUNET_CORE_disconnect (core_handle);
1477     core_handle = NULL;
1478   }
1479   if (transport_handle != NULL)
1480   {
1481     GNUNET_TRANSPORT_disconnect (transport_handle);
1482     transport_handle = NULL;
1483   }
1484   GNUNET_PEER_change_rc (myid, -1);
1485 }
1486
1487 /**
1488  * Retrieve the CadetPeer stucture associated with the peer, create one
1489  * and insert it in the appropriate structures if the peer is not known yet.
1490  *
1491  * @param peer_id Full identity of the peer.
1492  *
1493  * @return Existing or newly created peer structure.
1494  */
1495 struct CadetPeer *
1496 GCP_get (const struct GNUNET_PeerIdentity *peer_id)
1497 {
1498   struct CadetPeer *peer;
1499
1500   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1501   if (NULL == peer)
1502   {
1503     peer = GNUNET_new (struct CadetPeer);
1504     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1505     {
1506       peer_delete_oldest ();
1507     }
1508         GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1509                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1510         peer->id = GNUNET_PEER_intern (peer_id);
1511   }
1512   peer->last_contact = GNUNET_TIME_absolute_get();
1513
1514   return peer;
1515 }
1516
1517
1518 /**
1519  * Retrieve the CadetPeer stucture associated with the peer, create one
1520  * and insert it in the appropriate structures if the peer is not known yet.
1521  *
1522  * @param peer Short identity of the peer.
1523  *
1524  * @return Existing or newly created peer structure.
1525  */
1526 struct CadetPeer *
1527 GCP_get_short (const GNUNET_PEER_Id peer)
1528 {
1529   return GCP_get (GNUNET_PEER_resolve2 (peer));
1530 }
1531
1532
1533 /**
1534  * Try to connect to a peer on transport level.
1535  *
1536  * @param cls Closure (peer).
1537  * @param tc TaskContext.
1538  */
1539 static void
1540 try_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1541 {
1542   struct CadetPeer *peer = cls;
1543
1544   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1545     return;
1546
1547   GNUNET_TRANSPORT_try_connect (transport_handle,
1548                                 GNUNET_PEER_resolve2 (peer->id), NULL, NULL);
1549 }
1550
1551
1552 /**
1553  * Try to establish a new connection to this peer (in its tunnel).
1554  * If the peer doesn't have any path to it yet, try to get one.
1555  * If the peer already has some path, send a CREATE CONNECTION towards it.
1556  *
1557  * @param peer Peer to connect to.
1558  */
1559 void
1560 GCP_connect (struct CadetPeer *peer)
1561 {
1562   struct CadetTunnel *t;
1563   struct CadetPeerPath *p;
1564   struct CadetConnection *c;
1565   int rerun_search;
1566
1567   LOG (GNUNET_ERROR_TYPE_DEBUG, "peer_connect towards %s\n", GCP_2s (peer));
1568
1569   /* If we have a current hello, try to connect using it. */
1570   GCP_try_connect (peer);
1571
1572   t = peer->tunnel;
1573   c = NULL;
1574   rerun_search = GNUNET_NO;
1575
1576   if (NULL != peer->path_head)
1577   {
1578     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1579     p = peer_get_best_path (peer);
1580     if (NULL != p)
1581     {
1582       char *s;
1583
1584       s = path_2s (p);
1585       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1586       GNUNET_free (s);
1587
1588       c = GCT_use_path (t, p);
1589       if (NULL == c)
1590       {
1591         /* This case can happen when the path includes a first hop that is
1592          * not yet known to be connected.
1593          *
1594          * This happens quite often during testing when running cadet
1595          * under valgrind: core connect notifications come very late and the
1596          * DHT result has already come and created a valid path.
1597          * In this case, the peer->connections hashmap will be NULL and
1598          * tunnel_use_path will not be able to create a connection from that
1599          * path.
1600          *
1601          * Re-running the DHT GET should give core time to callback.
1602          *
1603          * GCT_use_path -> GCC_new -> register_neighbors takes care of
1604          * updating statistics about this issue.
1605          */
1606         rerun_search = GNUNET_YES;
1607       }
1608       else
1609       {
1610         GCC_send_create (c);
1611         return;
1612       }
1613     }
1614     else
1615     {
1616       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1617     }
1618   }
1619
1620   if (NULL != peer->search_h && GNUNET_YES == rerun_search)
1621   {
1622     GCD_search_stop (peer->search_h);
1623     peer->search_h = NULL;
1624     LOG (GNUNET_ERROR_TYPE_DEBUG,
1625          "  Stopping DHT GET for peer %s\n",
1626          GCP_2s (peer));
1627   }
1628
1629   if (NULL == peer->search_h)
1630   {
1631     const struct GNUNET_PeerIdentity *id;
1632
1633     id = GNUNET_PEER_resolve2 (peer->id);
1634     LOG (GNUNET_ERROR_TYPE_DEBUG,
1635                 "  Starting DHT GET for peer %s\n", GCP_2s (peer));
1636     peer->search_h = GCD_search (id, &search_handler, peer);
1637     if (CADET_TUNNEL_NEW == GCT_get_cstate (t))
1638       GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
1639   }
1640 }
1641
1642
1643 /**
1644  * Chech whether there is a direct (core level)  connection to peer.
1645  *
1646  * @param peer Peer to check.
1647  *
1648  * @return #GNUNET_YES if there is a direct connection.
1649  */
1650 int
1651 GCP_is_neighbor (const struct CadetPeer *peer)
1652 {
1653   struct CadetPeerPath *path;
1654
1655   if (NULL == peer->connections)
1656     return GNUNET_NO;
1657
1658   for (path = peer->path_head; NULL != path; path = path->next)
1659   {
1660     if (3 > path->length)
1661       return GNUNET_YES;
1662   }
1663
1664   /* Is not a neighbor but connections is not NULL, probably disconnecting */
1665   return GNUNET_NO;
1666 }
1667
1668
1669 /**
1670  * Create and initialize a new tunnel towards a peer, in case it has none.
1671  * In case the peer already has a tunnel, nothing is done.
1672  *
1673  * Does not generate any traffic, just creates the local data structures.
1674  *
1675  * @param peer Peer towards which to create the tunnel.
1676  */
1677 void
1678 GCP_add_tunnel (struct CadetPeer *peer)
1679 {
1680   if (NULL != peer->tunnel)
1681     return;
1682   peer->tunnel = GCT_new (peer);
1683 }
1684
1685
1686 /**
1687  * Add a connection to a neighboring peer.
1688  *
1689  * Store that the peer is the first hop of the connection in one
1690  * direction and that on peer disconnect the connection must be
1691  * notified and destroyed, for it will no longer be valid.
1692  *
1693  * @param peer Peer to add connection to.
1694  * @param c Connection to add.
1695  *
1696  * @return GNUNET_OK on success.
1697  */
1698 int
1699 GCP_add_connection (struct CadetPeer *peer,
1700                     struct CadetConnection *c)
1701 {
1702   int result;
1703   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding connection %s\n", GCC_2s (c));
1704   LOG (GNUNET_ERROR_TYPE_DEBUG, "to peer %s\n", GCP_2s (peer));
1705
1706   if (NULL == peer->connections)
1707   {
1708     GNUNET_break (0);
1709     LOG (GNUNET_ERROR_TYPE_DEBUG,
1710          "Peer %s is not a neighbor!\n",
1711          GCP_2s (peer));
1712     return GNUNET_SYSERR;
1713   }
1714   LOG (GNUNET_ERROR_TYPE_DEBUG,
1715        "peer %s ok, has %u connections.\n",
1716        GCP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
1717   result = GNUNET_CONTAINER_multihashmap_put (peer->connections,
1718                                               GCC_get_h (c),
1719                                               c,
1720                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1721   LOG (GNUNET_ERROR_TYPE_DEBUG,
1722        " now has %u connections.\n",
1723        GNUNET_CONTAINER_multihashmap_size (peer->connections));
1724   LOG (GNUNET_ERROR_TYPE_DEBUG, "result %u\n", result);
1725
1726   return result;
1727 }
1728
1729
1730 /**
1731  * Add the path to the peer and update the path used to reach it in case this
1732  * is the shortest.
1733  *
1734  * @param peer Destination peer to add the path to.
1735  * @param path New path to add. Last peer must be the peer in arg 1.
1736  *             Path will be either used of freed if already known.
1737  * @param trusted Do we trust that this path is real?
1738  *
1739  * @return path if path was taken, pointer to existing duplicate if exists
1740  *         NULL on error.
1741  */
1742 struct CadetPeerPath *
1743 GCP_add_path (struct CadetPeer *peer, struct CadetPeerPath *path,
1744               int trusted)
1745 {
1746   struct CadetPeerPath *aux;
1747   unsigned int l;
1748   unsigned int l2;
1749
1750   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1751        path->length, GCP_2s (peer));
1752
1753   if ((NULL == peer) || (NULL == path))
1754   {
1755     GNUNET_break (0);
1756     path_destroy (path);
1757     return NULL;
1758   }
1759   if (path->peers[path->length - 1] != peer->id)
1760   {
1761     GNUNET_break (0);
1762     path_destroy (path);
1763     return NULL;
1764   }
1765
1766   for (l = 1; l < path->length; l++)
1767   {
1768     if (path->peers[l] == myid)
1769     {
1770       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1771       for (l2 = 0; l2 < path->length - l; l2++)
1772       {
1773         path->peers[l2] = path->peers[l + l2];
1774       }
1775       path->length -= l;
1776       l = 1;
1777       path->peers = GNUNET_realloc (path->peers,
1778                                     path->length * sizeof (GNUNET_PEER_Id));
1779     }
1780   }
1781
1782   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
1783
1784   if (2 >= path->length && GNUNET_NO == trusted)
1785   {
1786     /* Only allow CORE to tell us about direct paths */
1787     path_destroy (path);
1788     return NULL;
1789   }
1790
1791   l = path_get_length (path);
1792   if (0 == l)
1793   {
1794     path_destroy (path);
1795     return NULL;
1796   }
1797
1798   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1799   for (aux = peer->path_head; aux != NULL; aux = aux->next)
1800   {
1801     l2 = path_get_length (aux);
1802     if (l2 > l)
1803     {
1804       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1805       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1806                                           peer->path_tail, aux, path);
1807       if (NULL != peer->tunnel && 3 < GCT_count_connections (peer->tunnel))
1808       {
1809         GCP_connect (peer);
1810       }
1811       return path;
1812     }
1813     else
1814     {
1815       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1816       {
1817         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1818         path_destroy (path);
1819         return aux;
1820       }
1821     }
1822   }
1823   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head, peer->path_tail,
1824                                     path);
1825   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1826   if (NULL != peer->tunnel && 3 < GCT_count_connections (peer->tunnel))
1827   {
1828     GCP_connect (peer);
1829   }
1830   return path;
1831 }
1832
1833
1834 /**
1835  * Add the path to the origin peer and update the path used to reach it in case
1836  * this is the shortest.
1837  * The path is given in peer_info -> destination, therefore we turn the path
1838  * upside down first.
1839  *
1840  * @param peer Peer to add the path to, being the origin of the path.
1841  * @param path New path to add after being inversed.
1842  *             Path will be either used or freed.
1843  * @param trusted Do we trust that this path is real?
1844  *
1845  * @return path if path was taken, pointer to existing duplicate if exists
1846  *         NULL on error.
1847  */
1848 struct CadetPeerPath *
1849 GCP_add_path_to_origin (struct CadetPeer *peer,
1850                         struct CadetPeerPath *path,
1851                         int trusted)
1852 {
1853   if (NULL == path)
1854     return NULL;
1855   path_invert (path);
1856   return GCP_add_path (peer, path, trusted);
1857 }
1858
1859
1860 /**
1861  * Adds a path to the info of all the peers in the path
1862  *
1863  * @param p Path to process.
1864  * @param confirmed Whether we know if the path works or not.
1865  */
1866 void
1867 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
1868 {
1869   unsigned int i;
1870
1871   /* TODO: invert and add */
1872   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1873   for (i++; i < p->length; i++)
1874   {
1875     struct CadetPeer *aux;
1876     struct CadetPeerPath *copy;
1877
1878     aux = GCP_get_short (p->peers[i]);
1879     copy = path_duplicate (p);
1880     copy->length = i + 1;
1881     GCP_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
1882   }
1883 }
1884
1885
1886 /**
1887  * Remove any path to the peer that has the extact same peers as the one given.
1888  *
1889  * @param peer Peer to remove the path from.
1890  * @param path Path to remove. Is always destroyed .
1891  */
1892 void
1893 GCP_remove_path (struct CadetPeer *peer, struct CadetPeerPath *path)
1894 {
1895   struct CadetPeerPath *iter;
1896   struct CadetPeerPath *next;
1897
1898   GNUNET_assert (myid == path->peers[0]);
1899   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1900
1901   for (iter = peer->path_head; NULL != iter; iter = next)
1902   {
1903     next = iter->next;
1904     if (0 == memcmp (path->peers, iter->peers,
1905                      sizeof (GNUNET_PEER_Id) * path->length))
1906     {
1907       GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
1908       if (iter != path)
1909         path_destroy (iter);
1910     }
1911   }
1912   path_destroy (path);
1913 }
1914
1915
1916 /**
1917  * Remove a connection from a neighboring peer.
1918  *
1919  * @param peer Peer to remove connection from.
1920  * @param c Connection to remove.
1921  *
1922  * @return GNUNET_OK on success.
1923  */
1924 int
1925 GCP_remove_connection (struct CadetPeer *peer,
1926                        const struct CadetConnection *c)
1927 {
1928   LOG (GNUNET_ERROR_TYPE_DEBUG, "removing connection %s\n", GCC_2s (c));
1929   LOG (GNUNET_ERROR_TYPE_DEBUG, "from peer %s\n", GCP_2s (peer));
1930
1931   if (NULL == peer || NULL == peer->connections)
1932   {
1933     LOG (GNUNET_ERROR_TYPE_DEBUG,
1934          "Peer %s is not a neighbor!\n",
1935          GCP_2s (peer));
1936     return GNUNET_SYSERR;
1937   }
1938   LOG (GNUNET_ERROR_TYPE_DEBUG,
1939        "peer %s ok, has %u connections.\n",
1940        GCP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
1941
1942   return GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1943                                                GCC_get_h (c),
1944                                                c);
1945 }
1946
1947 /**
1948  * Start the DHT search for new paths towards the peer: we don't have
1949  * enough good connections.
1950  *
1951  * @param peer Destination peer.
1952  */
1953 void
1954 GCP_start_search (struct CadetPeer *peer)
1955 {
1956   if (NULL != peer->search_h)
1957   {
1958     GNUNET_break (0);
1959     return;
1960   }
1961
1962   peer->search_h = GCD_search (GCP_get_id (peer), &search_handler, peer);
1963 }
1964
1965
1966 /**
1967  * Stop the DHT search for new paths towards the peer: we already have
1968  * enough good connections.
1969  *
1970  * @param peer Destination peer.
1971  */
1972 void
1973 GCP_stop_search (struct CadetPeer *peer)
1974 {
1975   if (NULL == peer->search_h)
1976   {
1977     return;
1978   }
1979
1980   GCD_search_stop (peer->search_h);
1981   peer->search_h = NULL;
1982 }
1983
1984
1985 /**
1986  * Get the Full ID of a peer.
1987  *
1988  * @param peer Peer to get from.
1989  *
1990  * @return Full ID of peer.
1991  */
1992 const struct GNUNET_PeerIdentity *
1993 GCP_get_id (const struct CadetPeer *peer)
1994 {
1995   return GNUNET_PEER_resolve2 (peer->id);
1996 }
1997
1998
1999 /**
2000  * Get the Short ID of a peer.
2001  *
2002  * @param peer Peer to get from.
2003  *
2004  * @return Short ID of peer.
2005  */
2006 GNUNET_PEER_Id
2007 GCP_get_short_id (const struct CadetPeer *peer)
2008 {
2009   return peer->id;
2010 }
2011
2012
2013 /**
2014  * Set tunnel.
2015  *
2016  * @param peer Peer.
2017  * @param t Tunnel.
2018  */
2019 void
2020 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
2021 {
2022   peer->tunnel = t;
2023   if (NULL == t && NULL != peer->search_h)
2024   {
2025     GCP_stop_search (peer);
2026   }
2027 }
2028
2029
2030 /**
2031  * Get the tunnel towards a peer.
2032  *
2033  * @param peer Peer to get from.
2034  *
2035  * @return Tunnel towards peer.
2036  */
2037 struct CadetTunnel *
2038 GCP_get_tunnel (const struct CadetPeer *peer)
2039 {
2040   return peer->tunnel;
2041 }
2042
2043
2044 /**
2045  * Set the hello message.
2046  *
2047  * @param peer Peer whose message to set.
2048  * @param hello Hello message.
2049  */
2050 void
2051 GCP_set_hello (struct CadetPeer *peer, const struct GNUNET_HELLO_Message *hello)
2052 {
2053   struct GNUNET_HELLO_Message *old;
2054   size_t size;
2055
2056   LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
2057   if (NULL == hello)
2058     return;
2059
2060   old = GCP_get_hello (peer);
2061   if (NULL == old)
2062   {
2063     size = GNUNET_HELLO_size (hello);
2064     LOG (GNUNET_ERROR_TYPE_DEBUG, " new (%u bytes)\n", size);
2065     peer->hello = GNUNET_malloc (size);
2066     memcpy (peer->hello, hello, size);
2067   }
2068   else
2069   {
2070     peer->hello = GNUNET_HELLO_merge (old, hello);
2071     LOG (GNUNET_ERROR_TYPE_DEBUG, " merge into %p (%u bytes)\n",
2072          peer->hello, GNUNET_HELLO_size (hello));
2073     GNUNET_free (old);
2074   }
2075 }
2076
2077
2078 /**
2079  * Get the hello message.
2080  *
2081  * @param peer Peer whose message to get.
2082  *
2083  * @return Hello message.
2084  */
2085 struct GNUNET_HELLO_Message *
2086 GCP_get_hello (struct CadetPeer *peer)
2087 {
2088   struct GNUNET_TIME_Absolute expiration;
2089   struct GNUNET_TIME_Relative remaining;
2090
2091   if (NULL == peer->hello)
2092     return NULL;
2093
2094   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2095   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2096   if (0 == remaining.rel_value_us)
2097   {
2098     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2099          GNUNET_STRINGS_absolute_time_to_string (expiration));
2100     GNUNET_free (peer->hello);
2101     peer->hello = NULL;
2102   }
2103   return peer->hello;
2104 }
2105
2106
2107 /**
2108  * Try to connect to a peer on TRANSPORT level.
2109  *
2110  * @param peer Peer to whom to connect.
2111  */
2112 void
2113 GCP_try_connect (struct CadetPeer *peer)
2114 {
2115   struct GNUNET_HELLO_Message *hello;
2116   struct GNUNET_MessageHeader *mh;
2117
2118   if (NULL == transport_handle)
2119     return;
2120
2121   hello = GCP_get_hello (peer);
2122   if (NULL == hello)
2123     return;
2124
2125   mh = GNUNET_HELLO_get_header (hello);
2126   GNUNET_TRANSPORT_offer_hello (transport_handle, mh, try_connect, peer);
2127 }
2128
2129
2130 /**
2131  * Notify a peer that a link between two other peers is broken. If any path
2132  * used that link, eliminate it.
2133  *
2134  * @param peer Peer affected by the change.
2135  * @param peer1 Peer whose link is broken.
2136  * @param peer2 Peer whose link is broken.
2137  */
2138 void
2139 GCP_notify_broken_link (struct CadetPeer *peer,
2140                         struct GNUNET_PeerIdentity *peer1,
2141                         struct GNUNET_PeerIdentity *peer2)
2142 {
2143   struct CadetPeerPath *iter;
2144   struct CadetPeerPath *next;
2145   unsigned int i;
2146   GNUNET_PEER_Id p1;
2147   GNUNET_PEER_Id p2;
2148
2149   p1 = GNUNET_PEER_search (peer1);
2150   p2 = GNUNET_PEER_search (peer2);
2151
2152   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2153   if (0 == p1 || 0 == p2)
2154   {
2155     /* We don't even know them */
2156     return;
2157   }
2158
2159   for (iter = peer->path_head; NULL != iter; iter = next)
2160   {
2161     next = iter->next;
2162     for (i = 0; i < iter->length - 1; i++)
2163     {
2164       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2165           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2166       {
2167         char *s;
2168
2169         s = path_2s (iter);
2170         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2171         GNUNET_free (s);
2172
2173         path_invalidate (iter);
2174       }
2175     }
2176   }
2177 }
2178
2179
2180 /**
2181  * Count the number of known paths toward the peer.
2182  *
2183  * @param peer Peer to get path info.
2184  *
2185  * @return Number of known paths.
2186  */
2187 unsigned int
2188 GCP_count_paths (const struct CadetPeer *peer)
2189 {
2190   struct CadetPeerPath *iter;
2191   unsigned int i;
2192
2193   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2194     i++;
2195
2196   return i;
2197 }
2198
2199
2200 /**
2201  * Iterate all known peers.
2202  *
2203  * @param iter Iterator.
2204  * @param cls Closure for @c iter.
2205  */
2206 void
2207 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2208 {
2209   GNUNET_CONTAINER_multipeermap_iterate (peers, iter, cls);
2210 }
2211
2212
2213 /**
2214  * Get the static string for a peer ID.
2215  *
2216  * @param peer Peer.
2217  *
2218  * @return Static string for it's ID.
2219  */
2220 const char *
2221 GCP_2s (const struct CadetPeer *peer)
2222 {
2223   if (NULL == peer)
2224     return "(NULL)";
2225   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2226 }
2227
2228
2229 /**
2230  * Log all kinds of info about a peer.
2231  *
2232  * @param peer Peer.
2233  */
2234 void
2235 GCP_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
2236 {
2237   struct CadetPeerPath *path;
2238   struct CadetPeerQueue *q;
2239   unsigned int conns;
2240
2241   if (NULL == p)
2242   {
2243     LOG (level, "PPP DEBUG PEER NULL\n");
2244     return;
2245   }
2246
2247   LOG (level, "PPP DEBUG PEER %s\n", GCP_2s (p));
2248   for (path = p->path_head; NULL != path; path = path->next)
2249   {
2250     char *s;
2251
2252     s = path_2s (path);
2253     LOG (level, "PPP path: %s\n", s);
2254     GNUNET_free (s);
2255   }
2256
2257   LOG (level, "PPP core transmit handle %p\n", p->core_transmit);
2258   conns = GNUNET_CONTAINER_multihashmap_size (p->connections);
2259   LOG (level, "PPP # connections over link to peer: %u\n", conns);
2260   LOG (level, "PPP queue length: %u\n", p->queue_n);
2261   for (q = p->queue_head; NULL != q; q = q->next)
2262   {
2263     LOG (level, "PPP - %s [payload %s, %u] on connection %s, %u bytes\n",
2264          GC_m2s (q->type), GC_m2s (q->payload_type), q->payload_id,
2265          GCC_2s (q->c), q->size);
2266   }
2267   LOG (level, "PPP DEBUG END\n");
2268
2269 }