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