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