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