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