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