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