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