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