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