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