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