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