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