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