refactor DHT for new service API
[oweals/gnunet.git] / src / cadet / gnunet-service-cadet_peer.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2015 GNUnet e.V.
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_ats_service.h"
30 #include "gnunet_core_service.h"
31 #include "gnunet_statistics_service.h"
32 #include "cadet_protocol.h"
33 #include "gnunet-service-cadet_peer.h"
34 #include "gnunet-service-cadet_dht.h"
35 #include "gnunet-service-cadet_connection.h"
36 #include "gnunet-service-cadet_tunnel.h"
37 #include "cadet_path.h"
38
39 #define LOG(level, ...) GNUNET_log_from (level,"cadet-p2p",__VA_ARGS__)
40 #define LOG2(level, ...) GNUNET_log_from_nocheck(level,"cadet-p2p",__VA_ARGS__)
41
42
43 /******************************************************************************/
44 /********************************   STRUCTS  **********************************/
45 /******************************************************************************/
46
47
48 /**
49  * Struct containing all information regarding a given peer
50  */
51 struct CadetPeer
52 {
53   /**
54    * ID of the peer
55    */
56   GNUNET_PEER_Id id;
57
58   /**
59    * Last time we heard from this peer
60    */
61   struct GNUNET_TIME_Absolute last_contact;
62
63   /**
64    * Paths to reach the peer, ordered by ascending hop count
65    */
66   struct CadetPeerPath *path_head;
67
68   /**
69    * Paths to reach the peer, ordered by ascending hop count
70    */
71   struct CadetPeerPath *path_tail;
72
73   /**
74    * Handle to stop the DHT search for paths to this peer
75    */
76   struct GCD_search_handle *search_h;
77
78   /**
79    * Handle to stop the DHT search for paths to this peer
80    */
81   struct GNUNET_SCHEDULER_Task *search_delayed;
82
83   /**
84    * Tunnel to this peer, if any.
85    */
86   struct CadetTunnel *tunnel;
87
88   /**
89    * Connections that go through this peer; indexed by tid.
90    */
91   struct GNUNET_CONTAINER_MultiHashMap *connections;
92
93   /**
94    * Handle for core transmissions.
95    */
96   struct GNUNET_MQ_Handle *core_mq;
97
98   /**
99    * How many messages are in the queue to this peer.
100    */
101   unsigned int queue_n;
102
103   /**
104    * Hello message.
105    */
106   struct GNUNET_HELLO_Message* hello;
107
108   /**
109    * Handle to us offering the HELLO to the transport.
110    */
111   struct GNUNET_TRANSPORT_OfferHelloHandle *hello_offer;
112
113   /**
114    * Handle to our ATS request asking ATS to suggest an address
115    * to TRANSPORT for this peer (to establish a direct link).
116    */
117   struct GNUNET_ATS_ConnectivitySuggestHandle *connectivity_suggestion;
118
119 };
120
121
122 /**
123  * Information about a queued message on the peer level.
124  */
125 struct CadetPeerQueue {
126
127   /**
128    * Envelope to cancel message before MQ sends it.
129    */
130   struct GNUNET_MQ_Envelope *env;
131
132   /**
133    * Peer (neighbor) this message is being sent to.
134    */
135   struct CadetPeer *peer;
136
137   /**
138    * Continuation to call to notify higher layers about message sent.
139    */
140   GCP_sent cont;
141
142   /**
143    * Closure for @a cont.
144    */
145   void *cont_cls;
146
147   /**
148    * Time when message was queued for sending.
149    */
150   struct GNUNET_TIME_Absolute queue_timestamp;
151
152   /**
153    * #GNUNET_YES if message was management traffic (POLL, ACK, ...).
154    */
155   int management_traffic;
156
157   /**
158    * Message type.
159    */
160   uint16_t type;
161
162   /**
163    * Message size.
164    */
165   uint16_t size;
166
167   /**
168    * Type of the message's payload, if it was encrypted data.
169    */
170   uint16_t payload_type;
171
172   /**
173    *ID of the payload (PID, ACK #, ...).
174    */
175   uint16_t payload_id;
176
177   /**
178    * Connection this message was sent on.
179    */
180   struct CadetConnection *c;
181
182   /**
183    * Direction in @a c this message was send on (#GNUNET_YES = FWD).
184    */
185   int c_fwd;
186 };
187
188
189 /******************************************************************************/
190 /*******************************   GLOBALS  ***********************************/
191 /******************************************************************************/
192
193 /**
194  * Global handle to the statistics service.
195  */
196 extern struct GNUNET_STATISTICS_Handle *stats;
197
198 /**
199  * Local peer own ID (full value).
200  */
201 extern struct GNUNET_PeerIdentity my_full_id;
202
203 /**
204  * Local peer own ID (short)
205  */
206 extern GNUNET_PEER_Id myid;
207
208 /**
209  * Peers known, indexed by PeerIdentity, values of type `struct CadetPeer`.
210  */
211 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
212
213 /**
214  * How many peers do we want to remember?
215  */
216 static unsigned long long max_peers;
217
218 /**
219  * Percentage of messages that will be dropped (for test purposes only).
220  */
221 static unsigned long long drop_percent;
222
223 /**
224  * Handle to communicate with CORE.
225  */
226 static struct GNUNET_CORE_Handle *core_handle;
227
228 /**
229  * Our configuration;
230  */
231 static const struct GNUNET_CONFIGURATION_Handle *cfg;
232
233 /**
234  * Handle to communicate with ATS.
235  */
236 static struct GNUNET_ATS_ConnectivityHandle *ats_ch;
237
238 /**
239  * Shutdown falg.
240  */
241 static int in_shutdown;
242
243
244 /******************************************************************************/
245 /*****************************  CORE HELPERS  *********************************/
246 /******************************************************************************/
247
248
249 /**
250  * Iterator to notify all connections of a broken link. Mark connections
251  * to destroy after all traffic has been sent.
252  *
253  * @param cls Closure (disconnected peer).
254  * @param key Current key code (peer id).
255  * @param value Value in the hash map (connection).
256  *
257  * @return #GNUNET_YES to continue to iterate.
258  */
259 static int
260 notify_broken (void *cls,
261                const struct GNUNET_HashCode *key,
262                void *value)
263 {
264   struct CadetPeer *peer = cls;
265   struct CadetConnection *c = value;
266
267   LOG (GNUNET_ERROR_TYPE_DEBUG,
268        "Notifying %s due to %s disconnect\n",
269        GCC_2s (c), GCP_2s (peer));
270   GCC_neighbor_disconnected (c, peer);
271   return GNUNET_YES;
272 }
273
274
275 /**
276  * Remove the direct path to the peer.
277  *
278  * @param peer Peer to remove the direct path from.
279  */
280 static struct CadetPeerPath *
281 pop_direct_path (struct CadetPeer *peer)
282 {
283   struct CadetPeerPath *iter;
284
285   for (iter = peer->path_head; NULL != iter; iter = iter->next)
286   {
287     if (2 >= iter->length)
288     {
289       GNUNET_CONTAINER_DLL_remove (peer->path_head,
290                                    peer->path_tail,
291                                    iter);
292       return iter;
293     }
294   }
295   return NULL;
296 }
297
298
299 /******************************************************************************/
300 /***************************** CORE CALLBACKS *********************************/
301 /******************************************************************************/
302
303
304 /**
305  * Method called whenever a given peer connects.
306  *
307  * @param cls Core closure (unused).
308  * @param peer Peer identity this notification is about
309  * @param mq Message Queue to this peer.
310  *
311  * @return Internal closure for handlers (CadetPeer struct).
312  */
313 static void *
314 core_connect_handler (void *cls,
315                       const struct GNUNET_PeerIdentity *peer,
316                       struct GNUNET_MQ_Handle *mq)
317 {
318   struct CadetPeer *neighbor;
319   struct CadetPeerPath *path;
320   char own_id[16];
321
322   GCC_check_connections ();
323   GNUNET_snprintf (own_id,
324                    sizeof (own_id),
325                    "%s",
326                    GNUNET_i2s (&my_full_id));
327
328   /* Save a path to the neighbor */
329   neighbor = GCP_get (peer, GNUNET_YES);
330   if (myid == neighbor->id)
331   {
332     LOG (GNUNET_ERROR_TYPE_INFO,
333          "CONNECTED %s (self)\n",
334          own_id);
335     path = path_new (1);
336   }
337   else
338   {
339     LOG (GNUNET_ERROR_TYPE_INFO,
340          "CONNECTED %s <= %s\n",
341          own_id,
342          GNUNET_i2s (peer));
343     path = path_new (2);
344     path->peers[1] = neighbor->id;
345     GNUNET_PEER_change_rc (neighbor->id, 1);
346     GNUNET_assert (NULL == neighbor->core_mq);
347     neighbor->core_mq = mq;
348   }
349   path->peers[0] = myid;
350   GNUNET_PEER_change_rc (myid, 1);
351   GCP_add_path (neighbor, path, GNUNET_YES);
352
353   /* Create the connections hashmap */
354   GNUNET_assert (NULL == neighbor->connections);
355   neighbor->connections = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);
356   GNUNET_STATISTICS_update (stats,
357                             "# peers",
358                             1,
359                             GNUNET_NO);
360
361   if ( (NULL != GCP_get_tunnel (neighbor)) &&
362        (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, peer)) )
363   {
364     GCP_connect (neighbor);
365   }
366   GCC_check_connections ();
367
368   return neighbor;
369 }
370
371
372 /**
373  * Method called whenever a peer disconnects.
374  *
375  * @param cls Core closure (unused).
376  * @param peer Peer identity this notification is about.
377  * @param internal_cls Internal closure (CadetPeer struct).
378  */
379 static void
380 core_disconnect_handler (void *cls,
381                          const struct GNUNET_PeerIdentity *peer,
382                          void *internal_cls)
383 {
384   struct CadetPeer *p = internal_cls;
385   struct CadetPeerPath *direct_path;
386   char own_id[16];
387
388   GCC_check_connections ();
389   strncpy (own_id, GNUNET_i2s (&my_full_id), 16);
390   own_id[15] = '\0';
391   if (myid == p->id)
392   {
393     LOG (GNUNET_ERROR_TYPE_INFO,
394          "DISCONNECTED %s (self)\n",
395          own_id);
396   }
397   else
398   {
399     LOG (GNUNET_ERROR_TYPE_INFO,
400          "DISCONNECTED %s <= %s\n",
401          own_id, GNUNET_i2s (peer));
402     p->core_mq = NULL;
403   }
404   direct_path = pop_direct_path (p);
405   if (NULL != p->connections)
406   {
407     GNUNET_CONTAINER_multihashmap_iterate (p->connections,
408                                            &notify_broken,
409                                            p);
410     GNUNET_CONTAINER_multihashmap_destroy (p->connections);
411     p->connections = NULL;
412   }
413   GNUNET_STATISTICS_update (stats,
414                             "# peers",
415                             -1,
416                             GNUNET_NO);
417   path_destroy (direct_path);
418   GCC_check_connections ();
419 }
420
421
422 /******************************************************************************/
423 /******************************************************************************/
424 /******************************************************************************/
425 /******************************************************************************/
426 /******************************************************************************/
427
428 /**
429  * Check if the create_connection message has the appropriate size.
430  *
431  * @param cls Closure (unused).
432  * @param msg Message to check.
433  *
434  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
435  */
436 static int
437 check_create (void *cls, const struct GNUNET_CADET_ConnectionCreate *msg)
438 {
439   uint16_t size;
440
441   size = ntohs (msg->header.size);
442   if (size < sizeof (*msg))
443   {
444     GNUNET_break_op (0);
445     return GNUNET_NO;
446   }
447   return GNUNET_YES;
448 }
449
450 /**
451  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE
452  *
453  * @param cls Closure (CadetPeer for neighbor that sent the message).
454  * @param msg Message itself.
455  */
456 static void
457 handle_create (void *cls, const struct GNUNET_CADET_ConnectionCreate *msg)
458 {
459   struct CadetPeer *peer = cls;
460   GCC_handle_create (peer, msg);
461 }
462
463
464 /**
465  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK
466  *
467  * @param cls Closure (CadetPeer for neighbor that sent the message).
468  * @param msg Message itself.
469  */
470 static void
471 handle_confirm (void *cls, const struct GNUNET_CADET_ConnectionACK *msg)
472 {
473   struct CadetPeer *peer = cls;
474   GCC_handle_confirm (peer, msg);
475 }
476
477
478 /**
479  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN
480  *
481  * @param cls Closure (CadetPeer for neighbor that sent the message).
482  * @param msg Message itself.
483  */
484 static void
485 handle_broken (void *cls, const struct GNUNET_CADET_ConnectionBroken *msg)
486 {
487   struct CadetPeer *peer = cls;
488   GCC_handle_broken (peer, msg);
489 }
490
491
492 /**
493  * Handle for #GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY
494  *
495  * @param cls Closure (CadetPeer for neighbor that sent the message).
496  * @param msg Message itself.
497  */
498 static void
499 handle_destroy (void *cls, const struct GNUNET_CADET_ConnectionDestroy *msg)
500 {
501   struct CadetPeer *peer = cls;
502   GCC_handle_destroy (peer, msg);
503 }
504
505
506 /**
507  * Handle for #GNUNET_MESSAGE_TYPE_CADET_ACK
508  *
509  * @param cls Closure (CadetPeer for neighbor that sent the message).
510  * @param msg Message itself.
511  */
512 static void
513 handle_ack (void *cls, const struct GNUNET_CADET_ACK *msg)
514 {
515   struct CadetPeer *peer = cls;
516   GCC_handle_ack (peer, msg);
517 }
518
519
520 /**
521  * Handle for #GNUNET_MESSAGE_TYPE_CADET_POLL
522  *
523  * @param cls Closure (CadetPeer for neighbor that sent the message).
524  * @param msg Message itself.
525  */
526 static void
527 handle_poll (void *cls, const struct GNUNET_CADET_Poll *msg)
528 {
529   struct CadetPeer *peer = cls;
530   GCC_handle_poll (peer, msg);
531 }
532
533
534 /**
535  * Check if the Key eXchange message has the appropriate size.
536  *
537  * @param cls Closure (unused).
538  * @param msg Message to check.
539  *
540  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
541  */
542 static int
543 check_kx (void *cls, const struct GNUNET_CADET_KX *msg)
544 {
545   uint16_t size;
546   uint16_t expected_size;
547
548   size = ntohs (msg->header.size);
549   expected_size = sizeof (struct GNUNET_CADET_KX)
550                   + sizeof (struct GNUNET_MessageHeader);
551
552   if (size < expected_size)
553   {
554     GNUNET_break_op (0);
555     return GNUNET_NO;
556   }
557   return GNUNET_YES;
558 }
559
560 /**
561  * Handle for #GNUNET_MESSAGE_TYPE_CADET_KX
562  *
563  * @param cls Closure (CadetPeer for neighbor that sent the message).
564  * @param msg Message itself.
565  */
566 static void
567 handle_kx (void *cls, const struct GNUNET_CADET_KX *msg)
568 {
569   struct CadetPeer *peer = cls;
570   GCC_handle_kx (peer, msg);
571 }
572
573
574 /**
575  * Check if the encrypted message has the appropriate size.
576  *
577  * @param cls Closure (unused).
578  * @param msg Message to check.
579  *
580  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
581  */
582 static int
583 check_encrypted (void *cls, const struct GNUNET_CADET_AX *msg)
584 {
585   uint16_t size;
586   uint16_t minimum_size;
587
588   size = ntohs (msg->header.size);
589   minimum_size = sizeof (struct GNUNET_CADET_AX)
590                  + sizeof (struct GNUNET_MessageHeader);
591
592   if (size < minimum_size)
593   {
594     GNUNET_break_op (0);
595     return GNUNET_NO;
596   }
597   return GNUNET_YES;
598 }
599
600 /**
601  * Handle for #GNUNET_MESSAGE_TYPE_CADET_AX (AXolotl encrypted traffic).
602  *
603  * @param cls Closure (CadetPeer for neighbor that sent the message).
604  * @param msg Message itself.
605  */
606 static void
607 handle_encrypted (void *cls, const struct GNUNET_CADET_AX *msg)
608 {
609   struct CadetPeer *peer = cls;
610   GCC_handle_encrypted (peer, msg);
611 }
612
613
614 /**
615  * To be called on core init/fail.
616  *
617  * @param cls Closure (config)
618  * @param identity The public identity of this peer.
619  */
620 static void
621 core_init_notify (void *cls,
622                   const struct GNUNET_PeerIdentity *identity);
623
624
625 static void
626 connect_to_core (const struct GNUNET_CONFIGURATION_Handle *c)
627 {
628   struct GNUNET_MQ_MessageHandler core_handlers[] = {
629     GNUNET_MQ_hd_var_size (create,
630                            GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE,
631                            struct GNUNET_CADET_ConnectionCreate,
632                            NULL),
633     GNUNET_MQ_hd_fixed_size (confirm,
634                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
635                              struct GNUNET_CADET_ConnectionACK,
636                              NULL),
637     GNUNET_MQ_hd_fixed_size (broken,
638                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
639                              struct GNUNET_CADET_ConnectionBroken,
640                              NULL),
641     GNUNET_MQ_hd_fixed_size (destroy,
642                              GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
643                              struct GNUNET_CADET_ConnectionDestroy,
644                              NULL),
645     GNUNET_MQ_hd_fixed_size (ack,
646                              GNUNET_MESSAGE_TYPE_CADET_ACK,
647                              struct GNUNET_CADET_ACK,
648                              NULL),
649     GNUNET_MQ_hd_fixed_size (poll,
650                              GNUNET_MESSAGE_TYPE_CADET_POLL,
651                              struct GNUNET_CADET_Poll,
652                              NULL),
653     GNUNET_MQ_hd_var_size (kx,
654                            GNUNET_MESSAGE_TYPE_CADET_KX,
655                            struct GNUNET_CADET_KX,
656                            NULL),
657     GNUNET_MQ_hd_var_size (encrypted,
658                            GNUNET_MESSAGE_TYPE_CADET_AX,
659                            struct GNUNET_CADET_AX,
660                            NULL),
661     GNUNET_MQ_handler_end ()
662   };
663     core_handle = GNUNET_CORE_connecT (c, NULL,
664                                      &core_init_notify,
665                                      &core_connect_handler,
666                                      &core_disconnect_handler,
667                                      core_handlers);
668 }
669
670 /******************************************************************************/
671 /******************************************************************************/
672 /******************************************************************************/
673 /******************************************************************************/
674 /******************************************************************************/
675
676 /**
677  * To be called on core init/fail.
678  *
679  * @param cls Closure (config)
680  * @param identity The public identity of this peer.
681  */
682 static void
683 core_init_notify (void *cls,
684                   const struct GNUNET_PeerIdentity *core_identity)
685 {
686   const struct GNUNET_CONFIGURATION_Handle *c = cls;
687
688   LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
689   if (0 != memcmp (core_identity, &my_full_id, sizeof (my_full_id)))
690   {
691     LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
692     LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (core_identity));
693     LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
694     GNUNET_CORE_disconnecT (core_handle);
695     connect_to_core (c);
696     return;
697   }
698   GML_start ();
699 }
700
701
702 /******************************************************************************/
703 /********************************   STATIC  ***********************************/
704 /******************************************************************************/
705
706
707 /**
708  * Get priority for a queued message.
709  *
710  * @param q Queued message
711  *
712  * @return CORE priority to use.
713  *
714  * FIXME make static
715  * FIXME use when sending
716  */
717 enum GNUNET_CORE_Priority
718 get_priority (struct CadetPeerQueue *q)
719 {
720   enum GNUNET_CORE_Priority low;
721   enum GNUNET_CORE_Priority high;
722
723   if (NULL == q)
724   {
725     GNUNET_break (0);
726     return GNUNET_CORE_PRIO_BACKGROUND;
727   }
728
729   /* Relayed traffic has lower priority, our own traffic has higher */
730   if (NULL == q->c || GNUNET_NO == GCC_is_origin (q->c, q->c_fwd))
731   {
732     low = GNUNET_CORE_PRIO_BEST_EFFORT;
733     high = GNUNET_CORE_PRIO_URGENT;
734   }
735   else
736   {
737     low = GNUNET_CORE_PRIO_URGENT;
738     high = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
739   }
740
741   /* Bulky payload has lower priority, control traffic has higher. */
742   if (GNUNET_MESSAGE_TYPE_CADET_AX == q->type)
743     return low;
744   return high;
745 }
746
747
748 /**
749  * Destroy the peer_info and free any allocated resources linked to it
750  *
751  * @param peer The peer_info to destroy.
752  * @return #GNUNET_OK on success
753  */
754 static int
755 peer_destroy (struct CadetPeer *peer)
756 {
757   struct GNUNET_PeerIdentity id;
758   struct CadetPeerPath *p;
759   struct CadetPeerPath *nextp;
760
761   GNUNET_PEER_resolve (peer->id, &id);
762   GNUNET_PEER_change_rc (peer->id, -1);
763
764   LOG (GNUNET_ERROR_TYPE_INFO,
765        "destroying peer %s\n",
766        GNUNET_i2s (&id));
767
768   if (GNUNET_YES !=
769       GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
770   {
771     GNUNET_break (0);
772     LOG (GNUNET_ERROR_TYPE_WARNING, " peer not in peermap!!\n");
773   }
774   GCP_stop_search (peer);
775   p = peer->path_head;
776   while (NULL != p)
777   {
778     nextp = p->next;
779     GNUNET_CONTAINER_DLL_remove (peer->path_head,
780                                  peer->path_tail,
781                                  p);
782     path_destroy (p);
783     p = nextp;
784   }
785   if (NULL != peer->tunnel)
786     GCT_destroy_empty (peer->tunnel);
787   if (NULL != peer->connections)
788   {
789     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (peer->connections));
790     GNUNET_CONTAINER_multihashmap_destroy (peer->connections);
791     peer->connections = NULL;
792   }
793   if (NULL != peer->hello_offer)
794   {
795     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
796     peer->hello_offer = NULL;
797   }
798   if (NULL != peer->connectivity_suggestion)
799   {
800     GNUNET_ATS_connectivity_suggest_cancel (peer->connectivity_suggestion);
801     peer->connectivity_suggestion = NULL;
802   }
803
804   GNUNET_free_non_null (peer->hello);
805   GNUNET_free (peer);
806   return GNUNET_OK;
807 }
808
809
810 /**
811  * Iterator over peer hash map entries to destroy the peer during in_shutdown.
812  *
813  * @param cls closure
814  * @param key current key code
815  * @param value value in the hash map
816  * @return #GNUNET_YES if we should continue to iterate,
817  *         #GNUNET_NO if not.
818  */
819 static int
820 shutdown_peer (void *cls,
821                const struct GNUNET_PeerIdentity *key,
822                void *value)
823 {
824   struct CadetPeer *p = value;
825   struct CadetTunnel *t = p->tunnel;
826
827   LOG (GNUNET_ERROR_TYPE_DEBUG, "  shutting down %s\n", GCP_2s (p));
828   if (NULL != t)
829     GCT_destroy (t);
830   p->tunnel = NULL;
831   peer_destroy (p);
832   return GNUNET_YES;
833 }
834
835
836 /**
837  * Check if peer is searching for a path (either active or delayed search).
838  *
839  * @param peer Peer to check
840  * @return #GNUNET_YES if there is a search active.
841  *         #GNUNET_NO otherwise.
842  */
843 static int
844 is_searching (const struct CadetPeer *peer)
845 {
846   return ( (NULL == peer->search_h) &&
847            (NULL == peer->search_delayed) ) ?
848     GNUNET_NO : GNUNET_YES;
849 }
850
851
852 /**
853  * @brief Start a search for a peer.
854  *
855  * @param cls Closure (Peer to search for).
856  */
857 static void
858 delayed_search (void *cls)
859 {
860   struct CadetPeer *peer = cls;
861
862   peer->search_delayed = NULL;
863   GCC_check_connections ();
864   GCP_start_search (peer);
865   GCC_check_connections ();
866 }
867
868
869 /**
870  * Returns if peer is used (has a tunnel or is neighbor).
871  *
872  * @param peer Peer to check.
873  * @return #GNUNET_YES if peer is in use.
874  */
875 static int
876 peer_is_used (struct CadetPeer *peer)
877 {
878   struct CadetPeerPath *p;
879
880   if (NULL != peer->tunnel)
881     return GNUNET_YES;
882
883   for (p = peer->path_head; NULL != p; p = p->next)
884   {
885     if (p->length < 3)
886       return GNUNET_YES;
887   }
888     return GNUNET_NO;
889 }
890
891
892 /**
893  * Iterator over all the peers to get the oldest timestamp.
894  *
895  * @param cls Closure (unsued).
896  * @param key ID of the peer.
897  * @param value Peer_Info of the peer.
898  */
899 static int
900 peer_get_oldest (void *cls,
901                  const struct GNUNET_PeerIdentity *key,
902                  void *value)
903 {
904   struct CadetPeer *p = value;
905   struct GNUNET_TIME_Absolute *abs = cls;
906
907   /* Don't count active peers */
908   if (GNUNET_YES == peer_is_used (p))
909     return GNUNET_YES;
910
911   if (abs->abs_value_us < p->last_contact.abs_value_us)
912     abs->abs_value_us = p->last_contact.abs_value_us;
913
914   return GNUNET_YES;
915 }
916
917
918 /**
919  * Iterator over all the peers to remove the oldest entry.
920  *
921  * @param cls Closure (unsued).
922  * @param key ID of the peer.
923  * @param value Peer_Info of the peer.
924  */
925 static int
926 peer_timeout (void *cls,
927               const struct GNUNET_PeerIdentity *key,
928               void *value)
929 {
930   struct CadetPeer *p = value;
931   struct GNUNET_TIME_Absolute *abs = cls;
932
933   LOG (GNUNET_ERROR_TYPE_WARNING,
934        "peer %s timeout\n", GNUNET_i2s (key));
935
936   if (p->last_contact.abs_value_us == abs->abs_value_us &&
937       GNUNET_NO == peer_is_used (p))
938   {
939     peer_destroy (p);
940     return GNUNET_NO;
941   }
942     return GNUNET_YES;
943 }
944
945
946 /**
947  * Delete oldest unused peer.
948  */
949 static void
950 peer_delete_oldest (void)
951 {
952   struct GNUNET_TIME_Absolute abs;
953
954   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
955
956   GNUNET_CONTAINER_multipeermap_iterate (peers,
957                                          &peer_get_oldest,
958                                          &abs);
959   GNUNET_CONTAINER_multipeermap_iterate (peers,
960                                          &peer_timeout,
961                                          &abs);
962 }
963
964
965 /**
966  * Choose the best (yet unused) path towards a peer,
967  * considering the tunnel properties.
968  *
969  * @param peer The destination peer.
970  * @return Best current known path towards the peer, if any.
971  */
972 static struct CadetPeerPath *
973 peer_get_best_path (const struct CadetPeer *peer)
974 {
975   struct CadetPeerPath *best_p;
976   struct CadetPeerPath *p;
977   unsigned int best_cost;
978   unsigned int cost;
979
980   best_cost = UINT_MAX;
981   best_p = NULL;
982   for (p = peer->path_head; NULL != p; p = p->next)
983   {
984     if (GNUNET_NO == path_is_valid (p))
985       continue; /* Don't use invalid paths. */
986     if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
987       continue; /* If path is already in use, skip it. */
988
989     if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
990     {
991       best_cost = cost;
992       best_p = p;
993     }
994   }
995   return best_p;
996 }
997
998
999 /**
1000  * Function to process paths received for a new peer addition. The recorded
1001  * paths form the initial tunnel, which can be optimized later.
1002  * Called on each result obtained for the DHT search.
1003  *
1004  * @param cls Closure (peer towards a path has been found).
1005  * @param path Path created from the DHT query. Will be freed afterwards.
1006  */
1007 static void
1008 search_handler (void *cls, const struct CadetPeerPath *path)
1009 {
1010   struct CadetPeer *peer = cls;
1011   unsigned int connection_count;
1012
1013   GCC_check_connections ();
1014   GCP_add_path_to_all (path, GNUNET_NO);
1015
1016   /* Count connections */
1017   connection_count = GCT_count_connections (peer->tunnel);
1018
1019   /* If we already have our minimum (or more) connections, it's enough */
1020   if (CONNECTIONS_PER_TUNNEL <= connection_count)
1021   {
1022     GCC_check_connections ();
1023     return;
1024   }
1025
1026   if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
1027   {
1028     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
1029     GCP_connect (peer);
1030   }
1031   GCC_check_connections ();
1032 }
1033
1034
1035 /**
1036  * Test if a message type is connection management traffic
1037  * or regular payload traffic.
1038  *
1039  * @param type Message type.
1040  *
1041  * @return #GNUNET_YES if connection management, #GNUNET_NO otherwise.
1042  */
1043 static int
1044 is_connection_management (uint16_t type)
1045 {
1046   return type == GNUNET_MESSAGE_TYPE_CADET_ACK ||
1047          type == GNUNET_MESSAGE_TYPE_CADET_POLL;
1048 }
1049
1050
1051 /**
1052  * Debug function should NEVER return true in production code, useful to
1053  * simulate losses for testcases.
1054  *
1055  * @return #GNUNET_YES or #GNUNET_NO with the decision to drop.
1056  */
1057 static int
1058 should_I_drop (void)
1059 {
1060   if (0 == drop_percent)
1061     return GNUNET_NO;
1062
1063   if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
1064     return GNUNET_YES;
1065
1066   return GNUNET_NO;
1067 }
1068
1069
1070 /******************************************************************************/
1071 /********************************    API    ***********************************/
1072 /******************************************************************************/
1073
1074 /**
1075  * Call the continuation after a message has been sent or dropped.
1076  *
1077  * @param q Queue handle.
1078  * @param sent #GNUNET_YES if was sent to CORE, #GNUNET_NO if dropped.
1079  */
1080 static void
1081 call_peer_cont (const struct CadetPeerQueue *q, int sent)
1082 {
1083   LOG (GNUNET_ERROR_TYPE_DEBUG, " core mq just sent %s\n", GC_m2s (q->type));
1084   if (NULL != q->cont)
1085   {
1086     struct GNUNET_TIME_Relative wait_time;
1087
1088     wait_time = GNUNET_TIME_absolute_get_duration (q->queue_timestamp);
1089     LOG (GNUNET_ERROR_TYPE_DEBUG, " calling callback, time elapsed %s\n",
1090          GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
1091     q->cont (q->cont_cls,
1092              q->c, q->c_fwd, sent,
1093              q->type, q->payload_type, q->payload_id,
1094              q->size, wait_time);
1095   }
1096 }
1097
1098
1099 /**
1100  * Function called by MQ when a message is sent to CORE.
1101  *
1102  * @param cls Closure (queue handle).
1103  */
1104 static void
1105 mq_sent (void *cls)
1106 {
1107   struct CadetPeerQueue *q = cls;
1108
1109   if (GNUNET_NO == q->management_traffic)
1110   {
1111     q->peer->queue_n--;
1112   }
1113   call_peer_cont (q, GNUNET_YES);
1114   GNUNET_free (q);
1115 }
1116
1117
1118 /**
1119  * @brief Send a message to another peer (using CORE).
1120  *
1121  * @param peer Peer towards which to queue the message.
1122  * @param message Message to send.
1123  * @param payload_type Type of the message's payload, for debug messages.
1124  *                     0 if the message is a retransmission (unknown payload).
1125  *                     UINT16_MAX if the message does not have payload.
1126  * @param payload_id ID of the payload (MID, ACK #, etc)
1127  * @param c Connection this message belongs to (can be NULL).
1128  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1129  * @param cont Continuation to be called once CORE has sent the message.
1130  * @param cont_cls Closure for @c cont.
1131  *
1132  * @return A handle to the message in the queue or NULL (if dropped).
1133  */
1134 struct CadetPeerQueue *
1135 GCP_send (struct CadetPeer *peer,
1136           const struct GNUNET_MessageHeader *message,
1137           uint16_t payload_type,
1138           uint32_t payload_id,
1139           struct CadetConnection *c,
1140           int fwd,
1141           GCP_sent cont,
1142           void *cont_cls)
1143 {
1144   struct CadetPeerQueue *q;
1145   uint16_t type;
1146   uint16_t size;
1147
1148   GCC_check_connections ();
1149   type = ntohs (message->type);
1150   size = ntohs (message->size);
1151   LOG (GNUNET_ERROR_TYPE_DEBUG,
1152        "que %s (%s %4u) on conn %s (%p) %s towards %s (size %u)\n",
1153        GC_m2s (type), GC_m2s (payload_type), payload_id,
1154        GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1155
1156   if (NULL == peer->connections)
1157   {
1158     /* We are not connected to this peer, ignore request. */
1159     GNUNET_break (0);
1160     LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
1161     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1162                               GNUNET_NO);
1163     return NULL;
1164   }
1165
1166   q = GNUNET_new (struct CadetPeerQueue);
1167   q->env = GNUNET_MQ_msg_copy (message);
1168   q->peer = peer;
1169   q->cont = cont;
1170   q->cont_cls = cont_cls;
1171   q->queue_timestamp = GNUNET_TIME_absolute_get ();
1172   q->management_traffic = is_connection_management (type);
1173   q->type = type;
1174   q->size = size;
1175   q->payload_type = payload_type;
1176   q->payload_id = payload_id;
1177   q->c = c;
1178   q->c_fwd = fwd;
1179   GNUNET_MQ_notify_sent (q->env, mq_sent, q);
1180
1181   if (GNUNET_YES == q->management_traffic)
1182   {
1183     GNUNET_MQ_send (peer->core_mq, q->env);  // FIXME implement "_urgent", use
1184   }
1185   else
1186   {
1187     if (GNUNET_YES == should_I_drop())
1188     {
1189       LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on conn %s %s\n",
1190            GC_m2s (q->type), GC_m2s (q->payload_type),
1191            q->payload_id, GCC_2s (c), GC_f2s (q->c_fwd));
1192       GNUNET_MQ_discard (q->env);
1193       call_peer_cont (q, GNUNET_NO);
1194       GNUNET_free (q);
1195       return NULL;
1196     }
1197     GNUNET_MQ_send (peer->core_mq, q->env);
1198     peer->queue_n++;
1199   }
1200
1201   GCC_check_connections ();
1202   return q;
1203 }
1204
1205
1206 /**
1207  * Cancel sending a message. Message must have been sent with
1208  * #GCP_send before.  May not be called after the notify sent
1209  * callback has been called.
1210  *
1211  * It DOES call the continuation given to #GCP_send.
1212  *
1213  * @param q Queue handle to cancel
1214  */
1215 void
1216 GCP_send_cancel (struct CadetPeerQueue *q)
1217 {
1218   call_peer_cont (q, GNUNET_NO);
1219   GNUNET_MQ_send_cancel (q->env);
1220   GNUNET_free (q);
1221 }
1222
1223
1224 /**
1225  * Initialize the peer subsystem.
1226  *
1227  * @param c Configuration.
1228  */
1229 void
1230 GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1231 {
1232   cfg = c;
1233   LOG (GNUNET_ERROR_TYPE_DEBUG,
1234        "GCP_init\n");
1235   in_shutdown = GNUNET_NO;
1236   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1237   if (GNUNET_OK !=
1238       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1239                                              &max_peers))
1240   {
1241     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1242                                "CADET", "MAX_PEERS", "USING DEFAULT");
1243     max_peers = 1000;
1244   }
1245
1246   if (GNUNET_OK !=
1247       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1248                                              &drop_percent))
1249   {
1250     drop_percent = 0;
1251   }
1252   else
1253   {
1254     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1255     LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1256     LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1257     LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1258     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1259   }
1260   ats_ch = GNUNET_ATS_connectivity_init (c);
1261   connect_to_core (c);
1262   if (NULL == core_handle)
1263   {
1264     GNUNET_break (0);
1265     GNUNET_SCHEDULER_shutdown ();
1266   }
1267 }
1268
1269
1270 /**
1271  * Shut down the peer subsystem.
1272  */
1273 void
1274 GCP_shutdown (void)
1275 {
1276   LOG (GNUNET_ERROR_TYPE_DEBUG,
1277        "Shutting down peer subsystem\n");
1278   in_shutdown = GNUNET_YES;
1279   if (NULL != core_handle)
1280   {
1281     GNUNET_CORE_disconnecT (core_handle);
1282         core_handle = NULL;
1283   }
1284   GNUNET_PEER_change_rc (myid, -1);
1285   /* With MQ API, CORE calls the disconnect handler for every peer
1286    * after calling GNUNET_CORE_disconnecT, shutdown must occur *after* that.
1287    */
1288   GNUNET_CONTAINER_multipeermap_iterate (peers,
1289                                          &shutdown_peer,
1290                                          NULL);
1291   if (NULL != ats_ch)
1292   {
1293     GNUNET_ATS_connectivity_done (ats_ch);
1294     ats_ch = NULL;
1295   }
1296   GNUNET_CONTAINER_multipeermap_destroy (peers);
1297   peers = NULL;
1298 }
1299
1300
1301 /**
1302  * Retrieve the CadetPeer stucture associated with the peer. Optionally create
1303  * one and insert it in the appropriate structures if the peer is not known yet.
1304  *
1305  * @param peer_id Full identity of the peer.
1306  * @param create #GNUNET_YES if a new peer should be created if unknown.
1307  *               #GNUNET_NO otherwise.
1308  *
1309  * @return Existing or newly created peer structure.
1310  *         NULL if unknown and not requested @a create
1311  */
1312 struct CadetPeer *
1313 GCP_get (const struct GNUNET_PeerIdentity *peer_id, int create)
1314 {
1315   struct CadetPeer *peer;
1316
1317   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1318   if (NULL == peer)
1319   {
1320     peer = GNUNET_new (struct CadetPeer);
1321     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1322     {
1323       peer_delete_oldest ();
1324     }
1325     GNUNET_assert (GNUNET_OK ==
1326                    GNUNET_CONTAINER_multipeermap_put (peers,
1327                                                       peer_id,
1328                                                       peer,
1329                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1330     peer->id = GNUNET_PEER_intern (peer_id);
1331   }
1332   peer->last_contact = GNUNET_TIME_absolute_get ();
1333
1334   return peer;
1335 }
1336
1337
1338 /**
1339  * Retrieve the CadetPeer stucture associated with the
1340  * peer. Optionally create one and insert it in the appropriate
1341  * structures if the peer is not known yet.
1342  *
1343  * @param peer Short identity of the peer.
1344  * @param create #GNUNET_YES if a new peer should be created if unknown.
1345  *               #GNUNET_NO otherwise.
1346  *
1347  * @return Existing or newly created peer structure.
1348  *         NULL if unknown and not requested @a create
1349  */
1350 struct CadetPeer *
1351 GCP_get_short (const GNUNET_PEER_Id peer, int create)
1352 {
1353   return GCP_get (GNUNET_PEER_resolve2 (peer), create);
1354 }
1355
1356
1357 /**
1358  * Function called once #GNUNET_TRANSPORT_offer_hello() is done.
1359  * Marks the operation as finished.
1360  *
1361  * @param cls Closure (our `struct CadetPeer`).
1362  */
1363 static void
1364 hello_offer_done (void *cls)
1365 {
1366   struct CadetPeer *peer = cls;
1367
1368   peer->hello_offer = NULL;
1369 }
1370
1371
1372 /**
1373  * Try to establish a new connection to this peer (in its tunnel).
1374  * If the peer doesn't have any path to it yet, try to get one.
1375  * If the peer already has some path, send a CREATE CONNECTION towards it.
1376  *
1377  * @param peer Peer to connect to.
1378  */
1379 void
1380 GCP_connect (struct CadetPeer *peer)
1381 {
1382   struct CadetTunnel *t;
1383   struct CadetPeerPath *path;
1384   struct CadetConnection *c;
1385   int rerun_search;
1386
1387   GCC_check_connections ();
1388   LOG (GNUNET_ERROR_TYPE_DEBUG,
1389        "peer_connect towards %s\n",
1390        GCP_2s (peer));
1391   /* If we have a current hello, try to connect using it. */
1392   GCP_try_connect (peer);
1393
1394   t = peer->tunnel;
1395   c = NULL;
1396   rerun_search = GNUNET_NO;
1397
1398   if (NULL != peer->path_head)
1399   {
1400     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1401     path = peer_get_best_path (peer);
1402     if (NULL != path)
1403     {
1404       char *s;
1405
1406       s = path_2s (path);
1407       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1408       GNUNET_free (s);
1409
1410       c = GCT_use_path (t, path);
1411       if (NULL == c)
1412       {
1413         /* This case can happen when the path includes a first hop that is
1414          * not yet known to be connected.
1415          *
1416          * This happens quite often during testing when running cadet
1417          * under valgrind: core connect notifications come very late
1418          * and the DHT result has already come and created a valid
1419          * path.  In this case, the peer->connections
1420          * hashmaps will be NULL and tunnel_use_path will not be able
1421          * to create a connection from that path.
1422          *
1423          * Re-running the DHT GET should give core time to callback.
1424          *
1425          * GCT_use_path -> GCC_new -> register_neighbors takes care of
1426          * updating statistics about this issue.
1427          */
1428         rerun_search = GNUNET_YES;
1429       }
1430       else
1431       {
1432         GCC_send_create (c);
1433         return;
1434       }
1435     }
1436     else
1437     {
1438       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1439     }
1440   }
1441
1442   if (GNUNET_YES == rerun_search)
1443   {
1444     struct GNUNET_TIME_Relative delay;
1445
1446     GCP_stop_search (peer);
1447     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
1448     peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay,
1449                                                          &delayed_search,
1450                                                          peer);
1451     GCC_check_connections ();
1452     return;
1453   }
1454
1455   if (GNUNET_NO == is_searching (peer))
1456     GCP_start_search (peer);
1457   GCC_check_connections ();
1458 }
1459
1460
1461 /**
1462  * Chech whether there is a direct (core level)  connection to peer.
1463  *
1464  * @param peer Peer to check.
1465  *
1466  * @return #GNUNET_YES if there is a direct connection.
1467  */
1468 int
1469 GCP_is_neighbor (const struct CadetPeer *peer)
1470 {
1471   struct CadetPeerPath *path;
1472
1473   if (NULL == peer->connections)
1474     return GNUNET_NO;
1475
1476   for (path = peer->path_head; NULL != path; path = path->next)
1477   {
1478     if (3 > path->length)
1479       return GNUNET_YES;
1480   }
1481
1482   /* Is not a neighbor but connections is not NULL, probably disconnecting */
1483   return GNUNET_NO;
1484 }
1485
1486
1487 /**
1488  * Create and initialize a new tunnel towards a peer, in case it has none.
1489  * In case the peer already has a tunnel, nothing is done.
1490  *
1491  * Does not generate any traffic, just creates the local data structures.
1492  *
1493  * @param peer Peer towards which to create the tunnel.
1494  */
1495 void
1496 GCP_add_tunnel (struct CadetPeer *peer)
1497 {
1498   GCC_check_connections ();
1499   if (NULL != peer->tunnel)
1500     return;
1501   peer->tunnel = GCT_new (peer);
1502   GCC_check_connections ();
1503 }
1504
1505
1506 /**
1507  * Add a connection to a neighboring peer.
1508  *
1509  * Store that the peer is the first hop of the connection in one
1510  * direction and that on peer disconnect the connection must be
1511  * notified and destroyed, for it will no longer be valid.
1512  *
1513  * @param peer Peer to add connection to.
1514  * @param c Connection to add.
1515  * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
1516  */
1517 void
1518 GCP_add_connection (struct CadetPeer *peer,
1519                     struct CadetConnection *c,
1520                     int pred)
1521 {
1522   LOG (GNUNET_ERROR_TYPE_DEBUG,
1523        "adding connection %s\n",
1524        GCC_2s (c));
1525   LOG (GNUNET_ERROR_TYPE_DEBUG,
1526        "to peer %s\n",
1527        GCP_2s (peer));
1528   GNUNET_assert (NULL != peer->connections);
1529   GNUNET_assert (GNUNET_OK ==
1530                  GNUNET_CONTAINER_multihashmap_put (peer->connections,
1531                                                     GCC_get_h (c),
1532                                                     c,
1533                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1534   LOG (GNUNET_ERROR_TYPE_DEBUG,
1535        "Peer %s has now %u connections.\n",
1536        GCP_2s (peer),
1537        GNUNET_CONTAINER_multihashmap_size (peer->connections));
1538 }
1539
1540
1541 /**
1542  * Add the path to the peer and update the path used to reach it in case this
1543  * is the shortest.
1544  *
1545  * @param peer Destination peer to add the path to.
1546  * @param path New path to add. Last peer must be @c peer.
1547  *             Path will be either used of freed if already known.
1548  * @param trusted Do we trust that this path is real?
1549  *
1550  * @return path if path was taken, pointer to existing duplicate if exists
1551  *         NULL on error.
1552  */
1553 struct CadetPeerPath *
1554 GCP_add_path (struct CadetPeer *peer,
1555               struct CadetPeerPath *path,
1556               int trusted)
1557 {
1558   struct CadetPeerPath *aux;
1559   unsigned int l;
1560   unsigned int l2;
1561
1562   GCC_check_connections ();
1563   LOG (GNUNET_ERROR_TYPE_DEBUG,
1564        "adding path [%u] to peer %s\n",
1565        path->length, GCP_2s (peer));
1566
1567   if (NULL == peer || NULL == path
1568       || path->peers[path->length - 1] != peer->id)
1569   {
1570     GNUNET_break (0);
1571     path_destroy (path);
1572     return NULL;
1573   }
1574
1575   for (l = 1; l < path->length; l++)
1576   {
1577     if (path->peers[l] == myid)
1578     {
1579       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1580       for (l2 = 0; l2 < path->length - l; l2++)
1581       {
1582         path->peers[l2] = path->peers[l + l2];
1583       }
1584       path->length -= l;
1585       l = 1;
1586       path->peers = GNUNET_realloc (path->peers,
1587                                     path->length * sizeof (GNUNET_PEER_Id));
1588     }
1589   }
1590
1591   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
1592
1593   if (2 >= path->length && GNUNET_NO == trusted)
1594   {
1595     /* Only allow CORE to tell us about direct paths */
1596     path_destroy (path);
1597     return NULL;
1598   }
1599
1600   l = path_get_length (path);
1601   if (0 == l)
1602   {
1603     path_destroy (path);
1604     return NULL;
1605   }
1606
1607   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1608   for (aux = peer->path_head; aux != NULL; aux = aux->next)
1609   {
1610     l2 = path_get_length (aux);
1611     if (l2 > l)
1612     {
1613       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1614       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1615                                           peer->path_tail, aux, path);
1616       goto finish;
1617     }
1618     else
1619     {
1620       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1621       {
1622         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1623         path_destroy (path);
1624         return aux;
1625       }
1626     }
1627   }
1628   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head,
1629                                     peer->path_tail,
1630                                     path);
1631   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1632
1633 finish:
1634   if (NULL != peer->tunnel
1635       && CONNECTIONS_PER_TUNNEL > GCT_count_connections (peer->tunnel)
1636       && 2 < path->length) /* Direct paths are handled by core_connect */
1637   {
1638     GCP_connect (peer);
1639   }
1640   GCC_check_connections ();
1641   return path;
1642 }
1643
1644
1645 /**
1646  * Add the path to the origin peer and update the path used to reach it in case
1647  * this is the shortest.
1648  * The path is given in peer_info -> destination, therefore we turn the path
1649  * upside down first.
1650  *
1651  * @param peer Peer to add the path to, being the origin of the path.
1652  * @param path New path to add after being inversed.
1653  *             Path will be either used or freed.
1654  * @param trusted Do we trust that this path is real?
1655  *
1656  * @return path if path was taken, pointer to existing duplicate if exists
1657  *         NULL on error.
1658  */
1659 struct CadetPeerPath *
1660 GCP_add_path_to_origin (struct CadetPeer *peer,
1661                         struct CadetPeerPath *path,
1662                         int trusted)
1663 {
1664   if (NULL == path)
1665     return NULL;
1666   path_invert (path);
1667   return GCP_add_path (peer, path, trusted);
1668 }
1669
1670
1671 /**
1672  * Adds a path to the info of all the peers in the path
1673  *
1674  * @param p Path to process.
1675  * @param confirmed Whether we know if the path works or not.
1676  */
1677 void
1678 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
1679 {
1680   unsigned int i;
1681
1682   /* TODO: invert and add to origin */
1683   /* TODO: replace all "GCP_add_path" with this, make the other one static */
1684   GCC_check_connections ();
1685   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1686   for (i++; i < p->length; i++)
1687   {
1688     struct CadetPeer *peer;
1689     struct CadetPeerPath *copy;
1690
1691     peer = GCP_get_short (p->peers[i], GNUNET_YES);
1692     copy = path_duplicate (p);
1693     copy->length = i + 1;
1694     GCP_add_path (peer, copy, 3 > p->length ? GNUNET_NO : confirmed);
1695   }
1696   GCC_check_connections ();
1697 }
1698
1699
1700 /**
1701  * Remove any path to the peer that has the exact same peers as the one given.
1702  *
1703  * @param peer Peer to remove the path from.
1704  * @param path Path to remove. Is always destroyed .
1705  */
1706 void
1707 GCP_remove_path (struct CadetPeer *peer,
1708                  struct CadetPeerPath *path)
1709 {
1710   struct CadetPeerPath *iter;
1711   struct CadetPeerPath *next;
1712
1713   GCC_check_connections ();
1714   GNUNET_assert (myid == path->peers[0]);
1715   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1716
1717   LOG (GNUNET_ERROR_TYPE_INFO,
1718        "Removing path %p (%u) from %s\n",
1719        path, path->length, GCP_2s (peer));
1720
1721   for (iter = peer->path_head; NULL != iter; iter = next)
1722   {
1723     next = iter->next;
1724     if (0 == path_cmp (path, iter))
1725     {
1726       GNUNET_CONTAINER_DLL_remove (peer->path_head,
1727                                    peer->path_tail,
1728                                    iter);
1729       if (iter != path)
1730         path_destroy (iter);
1731     }
1732   }
1733   path_destroy (path);
1734   GCC_check_connections ();
1735 }
1736
1737
1738 /**
1739  * Check that we are aware of a connection from a neighboring peer.
1740  *
1741  * @param peer Peer to the connection is with
1742  * @param c Connection that should be in the map with this peer.
1743  */
1744 void
1745 GCP_check_connection (const struct CadetPeer *peer,
1746                       const struct CadetConnection *c)
1747 {
1748   GNUNET_assert (NULL != peer);
1749   GNUNET_assert (NULL != peer->connections);
1750     return;
1751   GNUNET_assert (GNUNET_YES ==
1752                  GNUNET_CONTAINER_multihashmap_contains_value (peer->connections,
1753                                                                GCC_get_h (c),
1754                                                                c));
1755 }
1756
1757
1758 /**
1759  * Remove a connection from a neighboring peer.
1760  *
1761  * @param peer Peer to remove connection from.
1762  * @param c Connection to remove.
1763  */
1764 void
1765 GCP_remove_connection (struct CadetPeer *peer,
1766                        const struct CadetConnection *c)
1767 {
1768   LOG (GNUNET_ERROR_TYPE_DEBUG,
1769        "Removing connection %s\n",
1770        GCC_2s (c));
1771   LOG (GNUNET_ERROR_TYPE_DEBUG,
1772        "from peer %s\n",
1773        GCP_2s (peer));
1774   if ( (NULL == peer) ||
1775        (NULL == peer->connections) )
1776     return;
1777   GNUNET_assert (GNUNET_YES ==
1778                  GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1779                                                        GCC_get_h (c),
1780                                                        c));
1781   LOG (GNUNET_ERROR_TYPE_DEBUG,
1782        "Peer %s remains with %u connections.\n",
1783        GCP_2s (peer),
1784        GNUNET_CONTAINER_multihashmap_size (peer->connections));
1785 }
1786
1787
1788 /**
1789  * Start the DHT search for new paths towards the peer: we don't have
1790  * enough good connections.
1791  *
1792  * @param peer Destination peer.
1793  */
1794 void
1795 GCP_start_search (struct CadetPeer *peer)
1796 {
1797   const struct GNUNET_PeerIdentity *id;
1798   struct CadetTunnel *t = peer->tunnel;
1799
1800   GCC_check_connections ();
1801  if (NULL != peer->search_h)
1802   {
1803     GNUNET_break (0);
1804     return;
1805   }
1806
1807   if (NULL != peer->search_delayed)
1808     GCP_stop_search (peer);
1809
1810   id = GNUNET_PEER_resolve2 (peer->id);
1811   peer->search_h = GCD_search (id, &search_handler, peer);
1812
1813   if (NULL == t)
1814   {
1815     /* Why would we search for a peer with no tunnel towards it? */
1816     GNUNET_break (0);
1817     return;
1818   }
1819
1820   if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
1821       || 0 == GCT_count_any_connections (t))
1822   {
1823     GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
1824   }
1825   GCC_check_connections ();
1826 }
1827
1828
1829 /**
1830  * Stop the DHT search for new paths towards the peer: we already have
1831  * enough good connections.
1832  *
1833  * @param peer Destination peer.
1834  */
1835 void
1836 GCP_stop_search (struct CadetPeer *peer)
1837 {
1838   GCC_check_connections ();
1839   if (NULL != peer->search_h)
1840   {
1841     GCD_search_stop (peer->search_h);
1842     peer->search_h = NULL;
1843   }
1844   if (NULL != peer->search_delayed)
1845   {
1846     GNUNET_SCHEDULER_cancel (peer->search_delayed);
1847     peer->search_delayed = NULL;
1848   }
1849   GCC_check_connections ();
1850 }
1851
1852
1853 /**
1854  * Get the Full ID of a peer.
1855  *
1856  * @param peer Peer to get from.
1857  *
1858  * @return Full ID of peer.
1859  */
1860 const struct GNUNET_PeerIdentity *
1861 GCP_get_id (const struct CadetPeer *peer)
1862 {
1863   return GNUNET_PEER_resolve2 (peer->id);
1864 }
1865
1866
1867 /**
1868  * Get the Short ID of a peer.
1869  *
1870  * @param peer Peer to get from.
1871  *
1872  * @return Short ID of peer.
1873  */
1874 GNUNET_PEER_Id
1875 GCP_get_short_id (const struct CadetPeer *peer)
1876 {
1877   return peer->id;
1878 }
1879
1880
1881 /**
1882  * Set tunnel.
1883  *
1884  * If tunnel is NULL and there was a search active, stop it, as it's useless.
1885  *
1886  * @param peer Peer.
1887  * @param t Tunnel.
1888  */
1889 void
1890 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
1891 {
1892   peer->tunnel = t;
1893   if (NULL == t && GNUNET_YES == is_searching (peer))
1894   {
1895     GCP_stop_search (peer);
1896   }
1897 }
1898
1899
1900 /**
1901  * Get the tunnel towards a peer.
1902  *
1903  * @param peer Peer to get from.
1904  *
1905  * @return Tunnel towards peer.
1906  */
1907 struct CadetTunnel *
1908 GCP_get_tunnel (const struct CadetPeer *peer)
1909 {
1910   if (NULL == peer)
1911     return NULL;
1912   return peer->tunnel;
1913 }
1914
1915
1916 /**
1917  * Set the hello message.
1918  *
1919  * @param peer Peer whose message to set.
1920  * @param hello Hello message.
1921  */
1922 void
1923 GCP_set_hello (struct CadetPeer *peer,
1924                const struct GNUNET_HELLO_Message *hello)
1925 {
1926   struct GNUNET_HELLO_Message *old;
1927   size_t size;
1928
1929   GCC_check_connections ();
1930  LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
1931   if (NULL == hello)
1932     return;
1933
1934   old = GCP_get_hello (peer);
1935   if (NULL == old)
1936   {
1937     size = GNUNET_HELLO_size (hello);
1938     peer->hello = GNUNET_malloc (size);
1939     GNUNET_memcpy (peer->hello, hello, size);
1940   }
1941   else
1942   {
1943     peer->hello = GNUNET_HELLO_merge (old, hello);
1944     GNUNET_free (old);
1945   }
1946   GCC_check_connections ();
1947 }
1948
1949
1950 /**
1951  * Get the hello message.
1952  *
1953  * @param peer Peer whose message to get.
1954  *
1955  * @return Hello message.
1956  */
1957 struct GNUNET_HELLO_Message *
1958 GCP_get_hello (struct CadetPeer *peer)
1959 {
1960   struct GNUNET_TIME_Absolute expiration;
1961   struct GNUNET_TIME_Relative remaining;
1962
1963   if (NULL == peer->hello)
1964     return NULL;
1965
1966   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
1967   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
1968   if (0 == remaining.rel_value_us)
1969   {
1970     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
1971          GNUNET_STRINGS_absolute_time_to_string (expiration));
1972     GNUNET_free (peer->hello);
1973     peer->hello = NULL;
1974   }
1975   return peer->hello;
1976 }
1977
1978
1979 /**
1980  * Try to connect to a peer on TRANSPORT level.
1981  *
1982  * @param peer Peer to whom to connect.
1983  */
1984 void
1985 GCP_try_connect (struct CadetPeer *peer)
1986 {
1987   struct GNUNET_HELLO_Message *hello;
1988   struct GNUNET_MessageHeader *mh;
1989
1990   if (GNUNET_YES !=
1991       GNUNET_CONFIGURATION_get_value_yesno (cfg,
1992                                             "CADET",
1993                                             "DISABLE_TRY_CONNECT"))
1994     return;
1995   GCC_check_connections ();
1996   if (GNUNET_YES == GCP_is_neighbor (peer))
1997     return;
1998   hello = GCP_get_hello (peer);
1999   if (NULL == hello)
2000     return;
2001
2002   mh = GNUNET_HELLO_get_header (hello);
2003   if (NULL != peer->hello_offer)
2004   {
2005     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
2006     peer->hello_offer = NULL;
2007   }
2008   peer->hello_offer = GNUNET_TRANSPORT_offer_hello (cfg,
2009                                                     mh,
2010                                                     &hello_offer_done,
2011                                                     peer);
2012   if (NULL == peer->connectivity_suggestion)
2013     peer->connectivity_suggestion
2014       = GNUNET_ATS_connectivity_suggest (ats_ch,
2015                                          GNUNET_PEER_resolve2 (peer->id),
2016                                          1 /* strength */);
2017   GCC_check_connections ();
2018 }
2019
2020
2021 /**
2022  * Notify a peer that a link between two other peers is broken. If any path
2023  * used that link, eliminate it.
2024  *
2025  * @param peer Peer affected by the change.
2026  * @param peer1 Peer whose link is broken.
2027  * @param peer2 Peer whose link is broken.
2028  */
2029 void
2030 GCP_notify_broken_link (struct CadetPeer *peer,
2031                         const struct GNUNET_PeerIdentity *peer1,
2032                         const struct GNUNET_PeerIdentity *peer2)
2033 {
2034   struct CadetPeerPath *iter;
2035   struct CadetPeerPath *next;
2036   unsigned int i;
2037   GNUNET_PEER_Id p1;
2038   GNUNET_PEER_Id p2;
2039
2040   GCC_check_connections ();
2041   p1 = GNUNET_PEER_search (peer1);
2042   p2 = GNUNET_PEER_search (peer2);
2043
2044   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2045   if (0 == p1 || 0 == p2)
2046   {
2047     /* We don't even know them */
2048     return;
2049   }
2050
2051   for (iter = peer->path_head; NULL != iter; iter = next)
2052   {
2053     next = iter->next;
2054     for (i = 0; i < iter->length - 1; i++)
2055     {
2056       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2057           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2058       {
2059         char *s;
2060
2061         s = path_2s (iter);
2062         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2063         GNUNET_free (s);
2064
2065         path_invalidate (iter);
2066       }
2067     }
2068   }
2069   GCC_check_connections ();
2070 }
2071
2072
2073 /**
2074  * Count the number of known paths toward the peer.
2075  *
2076  * @param peer Peer to get path info.
2077  *
2078  * @return Number of known paths.
2079  */
2080 unsigned int
2081 GCP_count_paths (const struct CadetPeer *peer)
2082 {
2083   struct CadetPeerPath *iter;
2084   unsigned int i;
2085
2086   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2087     i++;
2088
2089   return i;
2090 }
2091
2092
2093 /**
2094  * Iterate over the paths to a peer.
2095  *
2096  * @param peer Peer to get path info.
2097  * @param callback Function to call for every path.
2098  * @param cls Closure for @a callback.
2099  *
2100  * @return Number of iterated paths.
2101  */
2102 unsigned int
2103 GCP_iterate_paths (struct CadetPeer *peer,
2104                    GCP_path_iterator callback,
2105                    void *cls)
2106 {
2107   struct CadetPeerPath *iter;
2108   unsigned int i;
2109
2110   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2111   {
2112     i++;
2113     if (GNUNET_YES != callback (cls, peer, iter))
2114       break;
2115   }
2116
2117   return i;
2118 }
2119
2120
2121 /**
2122  * Iterate all known peers.
2123  *
2124  * @param iter Iterator.
2125  * @param cls Closure for @c iter.
2126  */
2127 void
2128 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
2129                  void *cls)
2130 {
2131   GCC_check_connections ();
2132   GNUNET_CONTAINER_multipeermap_iterate (peers,
2133                                          iter,
2134                                          cls);
2135   GCC_check_connections ();
2136 }
2137
2138
2139 /**
2140  * Get the static string for a peer ID.
2141  *
2142  * @param peer Peer.
2143  *
2144  * @return Static string for it's ID.
2145  */
2146 const char *
2147 GCP_2s (const struct CadetPeer *peer)
2148 {
2149   if (NULL == peer)
2150     return "(NULL)";
2151   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2152 }
2153
2154
2155 /* end of gnunet-service-cadet_peer.c */