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