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