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