c312d56bfc82364ac67128042ec4f2663a2a35d9
[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     }
1110     GNUNET_CONTAINER_DLL_remove (q->peer->q_head, q->peer->q_tail, q);
1111 }
1112
1113
1114 /**
1115  * Function called by MQ when a message is sent to CORE.
1116  *
1117  * @param cls Closure (queue handle).
1118  */
1119 static void
1120 mq_sent (void *cls)
1121 {
1122     struct CadetPeerQueue *q = cls;
1123
1124     if (GNUNET_NO == q->management_traffic)
1125     {
1126         q->peer->queue_n--;
1127     }
1128     call_peer_cont (q, GNUNET_YES);
1129     GNUNET_free (q);
1130 }
1131
1132
1133 /**
1134  * @brief Send a message to another peer (using CORE).
1135  *
1136  * @param peer Peer towards which to queue the message.
1137  * @param message Message to send.
1138  * @param payload_type Type of the message's payload, for debug messages.
1139  *                     0 if the message is a retransmission (unknown payload).
1140  *                     UINT16_MAX if the message does not have payload.
1141  * @param payload_id ID of the payload (MID, ACK #, etc)
1142  * @param c Connection this message belongs to (can be NULL).
1143  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1144  * @param cont Continuation to be called once CORE has sent the message.
1145  * @param cont_cls Closure for @c cont.
1146  *
1147  * @return A handle to the message in the queue or NULL (if dropped).
1148  */
1149 struct CadetPeerQueue *
1150 GCP_send (struct CadetPeer *peer,
1151           const struct GNUNET_MessageHeader *message,
1152           uint16_t payload_type,
1153           uint32_t payload_id,
1154           struct CadetConnection *c,
1155           int fwd,
1156           GCP_sent cont,
1157           void *cont_cls)
1158 {
1159     struct CadetPeerQueue *q;
1160     uint16_t type;
1161     uint16_t size;
1162
1163     GCC_check_connections ();
1164     type = ntohs (message->type);
1165     size = ntohs (message->size);
1166     LOG (GNUNET_ERROR_TYPE_DEBUG,
1167          "que %s (%s %4u) on conn %s (%p) %s towards %s (size %u)\n",
1168          GC_m2s (type), GC_m2s (payload_type), payload_id,
1169          GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1170
1171     if (NULL == peer->connections)
1172     {
1173         /* We are not connected to this peer, ignore request. */
1174         GNUNET_break (0);
1175         LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
1176         GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1177                                   GNUNET_NO);
1178         return NULL;
1179     }
1180
1181     q = GNUNET_new (struct CadetPeerQueue);
1182     q->env = GNUNET_MQ_msg_copy (message);
1183     q->peer = peer;
1184     q->cont = cont;
1185     q->cont_cls = cont_cls;
1186     q->queue_timestamp = GNUNET_TIME_absolute_get ();
1187     q->management_traffic = is_connection_management (type);
1188     q->type = type;
1189     q->size = size;
1190     q->payload_type = payload_type;
1191     q->payload_id = payload_id;
1192     q->c = c;
1193     q->c_fwd = fwd;
1194     GNUNET_MQ_notify_sent (q->env, mq_sent, q);
1195
1196     if (GNUNET_YES == q->management_traffic)
1197     {
1198         GNUNET_MQ_send (peer->core_mq, q->env);  // FIXME implement "_urgent", use
1199     }
1200     else
1201     {
1202         if (GNUNET_YES == should_I_drop ())
1203         {
1204             LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on conn %s %s\n",
1205                  GC_m2s (q->type), GC_m2s (q->payload_type),
1206                  q->payload_id, GCC_2s (c), GC_f2s (q->c_fwd));
1207             GNUNET_MQ_discard (q->env);
1208             call_peer_cont (q, GNUNET_YES);
1209             GNUNET_free (q);
1210             return NULL;
1211         }
1212         GNUNET_MQ_send (peer->core_mq, q->env);
1213         peer->queue_n++;
1214     }
1215
1216     GNUNET_CONTAINER_DLL_insert (peer->q_head, peer->q_tail, q);
1217     GCC_check_connections ();
1218     return q;
1219 }
1220
1221
1222 /**
1223  * Cancel sending a message. Message must have been sent with
1224  * #GCP_send before.  May not be called after the notify sent
1225  * callback has been called.
1226  *
1227  * It DOES call the continuation given to #GCP_send.
1228  *
1229  * @param q Queue handle to cancel
1230  */
1231 void
1232 GCP_send_cancel (struct CadetPeerQueue *q)
1233 {
1234     call_peer_cont (q, GNUNET_NO);
1235     GNUNET_MQ_send_cancel (q->env);
1236     GNUNET_free (q);
1237 }
1238
1239
1240 /**
1241  * Initialize the peer subsystem.
1242  *
1243  * @param c Configuration.
1244  */
1245 void
1246 GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1247 {
1248     cfg = c;
1249     LOG (GNUNET_ERROR_TYPE_DEBUG,
1250          "GCP_init\n");
1251     in_shutdown = GNUNET_NO;
1252     peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1253     if (GNUNET_OK !=
1254             GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1255                     &max_peers))
1256     {
1257         GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1258                                    "CADET", "MAX_PEERS", "USING DEFAULT");
1259         max_peers = 1000;
1260     }
1261
1262     if (GNUNET_OK !=
1263             GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1264                     &drop_percent))
1265     {
1266         drop_percent = 0;
1267     }
1268     else
1269     {
1270         LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1271         LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1272         LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1273         LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1274         LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1275     }
1276     ats_ch = GNUNET_ATS_connectivity_init (c);
1277     connect_to_core (c);
1278     if (NULL == core_handle)
1279     {
1280         GNUNET_break (0);
1281         GNUNET_SCHEDULER_shutdown ();
1282     }
1283 }
1284
1285
1286 /**
1287  * Shut down the peer subsystem.
1288  */
1289 void
1290 GCP_shutdown (void)
1291 {
1292     LOG (GNUNET_ERROR_TYPE_DEBUG,
1293          "Shutting down peer subsystem\n");
1294     in_shutdown = GNUNET_YES;
1295     if (NULL != core_handle)
1296     {
1297         GNUNET_CORE_disconnecT (core_handle);
1298         core_handle = NULL;
1299     }
1300     GNUNET_PEER_change_rc (myid, -1);
1301     /* With MQ API, CORE calls the disconnect handler for every peer
1302      * after calling GNUNET_CORE_disconnecT, shutdown must occur *after* that.
1303      */
1304     GNUNET_CONTAINER_multipeermap_iterate (peers,
1305                                            &shutdown_peer,
1306                                            NULL);
1307     if (NULL != ats_ch)
1308     {
1309         GNUNET_ATS_connectivity_done (ats_ch);
1310         ats_ch = NULL;
1311     }
1312     GNUNET_CONTAINER_multipeermap_destroy (peers);
1313     peers = NULL;
1314 }
1315
1316
1317 /**
1318  * Retrieve the CadetPeer stucture associated with the peer. Optionally create
1319  * one and insert it in the appropriate structures if the peer is not known yet.
1320  *
1321  * @param peer_id Full identity of the peer.
1322  * @param create #GNUNET_YES if a new peer should be created if unknown.
1323  *               #GNUNET_NO otherwise.
1324  *
1325  * @return Existing or newly created peer structure.
1326  *         NULL if unknown and not requested @a create
1327  */
1328 struct CadetPeer *
1329 GCP_get (const struct GNUNET_PeerIdentity *peer_id, int create)
1330 {
1331     struct CadetPeer *peer;
1332
1333     peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1334     if (NULL == peer)
1335     {
1336         peer = GNUNET_new (struct CadetPeer);
1337         if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1338         {
1339             peer_delete_oldest ();
1340         }
1341         GNUNET_assert (GNUNET_OK ==
1342                        GNUNET_CONTAINER_multipeermap_put (peers,
1343                                peer_id,
1344                                peer,
1345                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1346         peer->id = GNUNET_PEER_intern (peer_id);
1347     }
1348     peer->last_contact = GNUNET_TIME_absolute_get ();
1349
1350     return peer;
1351 }
1352
1353
1354 /**
1355  * Retrieve the CadetPeer stucture associated with the
1356  * peer. Optionally create one and insert it in the appropriate
1357  * structures if the peer is not known yet.
1358  *
1359  * @param peer Short identity of the peer.
1360  * @param create #GNUNET_YES if a new peer should be created if unknown.
1361  *               #GNUNET_NO otherwise.
1362  *
1363  * @return Existing or newly created peer structure.
1364  *         NULL if unknown and not requested @a create
1365  */
1366 struct CadetPeer *
1367 GCP_get_short (const GNUNET_PEER_Id peer, int create)
1368 {
1369     return GCP_get (GNUNET_PEER_resolve2 (peer), create);
1370 }
1371
1372
1373 /**
1374  * Function called once #GNUNET_TRANSPORT_offer_hello() is done.
1375  * Marks the operation as finished.
1376  *
1377  * @param cls Closure (our `struct CadetPeer`).
1378  */
1379 static void
1380 hello_offer_done (void *cls)
1381 {
1382     struct CadetPeer *peer = cls;
1383
1384     peer->hello_offer = NULL;
1385 }
1386
1387
1388 /**
1389  * Try to establish a new connection to this peer (in its tunnel).
1390  * If the peer doesn't have any path to it yet, try to get one.
1391  * If the peer already has some path, send a CREATE CONNECTION towards it.
1392  *
1393  * @param peer Peer to connect to.
1394  */
1395 void
1396 GCP_connect (struct CadetPeer *peer)
1397 {
1398     struct CadetTunnel *t;
1399     struct CadetPeerPath *path;
1400     struct CadetConnection *c;
1401     int rerun_search;
1402
1403     GCC_check_connections ();
1404     LOG (GNUNET_ERROR_TYPE_DEBUG,
1405          "peer_connect towards %s\n",
1406          GCP_2s (peer));
1407     /* If we have a current hello, try to connect using it. */
1408     GCP_try_connect (peer);
1409
1410     t = peer->tunnel;
1411     c = NULL;
1412     rerun_search = GNUNET_NO;
1413
1414     if (NULL != peer->path_head)
1415     {
1416         LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1417         path = peer_get_best_path (peer);
1418         if (NULL != path)
1419         {
1420             char *s;
1421
1422             s = path_2s (path);
1423             LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1424             GNUNET_free (s);
1425
1426             c = GCT_use_path (t, path);
1427             if (NULL == c)
1428             {
1429                 /* This case can happen when the path includes a first hop that is
1430                  * not yet known to be connected.
1431                  *
1432                  * This happens quite often during testing when running cadet
1433                  * under valgrind: core connect notifications come very late
1434                  * and the DHT result has already come and created a valid
1435                  * path.  In this case, the peer->connections
1436                  * hashmaps will be NULL and tunnel_use_path will not be able
1437                  * to create a connection from that path.
1438                  *
1439                  * Re-running the DHT GET should give core time to callback.
1440                  *
1441                  * GCT_use_path -> GCC_new -> register_neighbors takes care of
1442                  * updating statistics about this issue.
1443                  */
1444                 rerun_search = GNUNET_YES;
1445             }
1446             else
1447             {
1448                 GCC_send_create (c);
1449                 return;
1450             }
1451         }
1452         else
1453         {
1454             LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1455         }
1456     }
1457
1458     if (GNUNET_YES == rerun_search)
1459     {
1460         struct GNUNET_TIME_Relative delay;
1461
1462         GCP_stop_search (peer);
1463         delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
1464         peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay,
1465                                &delayed_search,
1466                                peer);
1467         GCC_check_connections ();
1468         return;
1469     }
1470
1471     if (GNUNET_NO == is_searching (peer))
1472         GCP_start_search (peer);
1473     GCC_check_connections ();
1474 }
1475
1476
1477 /**
1478  * Chech whether there is a direct (core level)  connection to peer.
1479  *
1480  * @param peer Peer to check.
1481  *
1482  * @return #GNUNET_YES if there is a direct connection.
1483  */
1484 int
1485 GCP_is_neighbor (const struct CadetPeer *peer)
1486 {
1487     struct CadetPeerPath *path;
1488
1489     if (NULL == peer->connections)
1490         return GNUNET_NO;
1491
1492     for (path = peer->path_head; NULL != path; path = path->next)
1493     {
1494         if (3 > path->length)
1495             return GNUNET_YES;
1496     }
1497
1498     /* Is not a neighbor but connections is not NULL, probably disconnecting */
1499     return GNUNET_NO;
1500 }
1501
1502
1503 /**
1504  * Create and initialize a new tunnel towards a peer, in case it has none.
1505  * In case the peer already has a tunnel, nothing is done.
1506  *
1507  * Does not generate any traffic, just creates the local data structures.
1508  *
1509  * @param peer Peer towards which to create the tunnel.
1510  */
1511 void
1512 GCP_add_tunnel (struct CadetPeer *peer)
1513 {
1514     GCC_check_connections ();
1515     if (NULL != peer->tunnel)
1516         return;
1517     peer->tunnel = GCT_new (peer);
1518     GCC_check_connections ();
1519 }
1520
1521
1522 /**
1523  * Add a connection to a neighboring peer.
1524  *
1525  * Store that the peer is the first hop of the connection in one
1526  * direction and that on peer disconnect the connection must be
1527  * notified and destroyed, for it will no longer be valid.
1528  *
1529  * @param peer Peer to add connection to.
1530  * @param c Connection to add.
1531  * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
1532  */
1533 void
1534 GCP_add_connection (struct CadetPeer *peer,
1535                     struct CadetConnection *c,
1536                     int pred)
1537 {
1538     LOG (GNUNET_ERROR_TYPE_DEBUG,
1539          "adding connection %s\n",
1540          GCC_2s (c));
1541     LOG (GNUNET_ERROR_TYPE_DEBUG,
1542          "to peer %s\n",
1543          GCP_2s (peer));
1544     GNUNET_assert (NULL != peer->connections);
1545     GNUNET_assert (GNUNET_OK ==
1546                    GNUNET_CONTAINER_multihashmap_put (peer->connections,
1547                            GCC_get_h (c),
1548                            c,
1549                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1550     LOG (GNUNET_ERROR_TYPE_DEBUG,
1551          "Peer %s has now %u connections.\n",
1552          GCP_2s (peer),
1553          GNUNET_CONTAINER_multihashmap_size (peer->connections));
1554 }
1555
1556
1557 /**
1558  * Add the path to the peer and update the path used to reach it in case this
1559  * is the shortest.
1560  *
1561  * @param peer Destination peer to add the path to.
1562  * @param path New path to add. Last peer must be @c peer.
1563  *             Path will be either used of freed if already known.
1564  * @param trusted Do we trust that this path is real?
1565  *
1566  * @return path if path was taken, pointer to existing duplicate if exists
1567  *         NULL on error.
1568  */
1569 struct CadetPeerPath *
1570 GCP_add_path (struct CadetPeer *peer,
1571               struct CadetPeerPath *path,
1572               int trusted)
1573 {
1574     struct CadetPeerPath *aux;
1575     unsigned int l;
1576     unsigned int l2;
1577
1578     GCC_check_connections ();
1579     LOG (GNUNET_ERROR_TYPE_DEBUG,
1580          "adding path [%u] to peer %s\n",
1581          path->length, GCP_2s (peer));
1582
1583     if (NULL == peer || NULL == path
1584             || path->peers[path->length - 1] != peer->id)
1585     {
1586         GNUNET_break (0);
1587         path_destroy (path);
1588         return NULL;
1589     }
1590
1591     for (l = 1; l < path->length; l++)
1592     {
1593         if (path->peers[l] == myid)
1594         {
1595             LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1596             for (l2 = 0; l2 < path->length - l; l2++)
1597             {
1598                 path->peers[l2] = path->peers[l + l2];
1599             }
1600             path->length -= l;
1601             l = 1;
1602             path->peers = GNUNET_realloc (path->peers,
1603                                           path->length * sizeof (GNUNET_PEER_Id));
1604         }
1605     }
1606
1607     LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
1608
1609     if (2 >= path->length && GNUNET_NO == trusted)
1610     {
1611         /* Only allow CORE to tell us about direct paths */
1612         path_destroy (path);
1613         return NULL;
1614     }
1615
1616     l = path_get_length (path);
1617     if (0 == l)
1618     {
1619         path_destroy (path);
1620         return NULL;
1621     }
1622
1623     GNUNET_assert (peer->id == path->peers[path->length - 1]);
1624     for (aux = peer->path_head; aux != NULL; aux = aux->next)
1625     {
1626         l2 = path_get_length (aux);
1627         if (l2 > l)
1628         {
1629             LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1630             GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1631                                                 peer->path_tail, aux, path);
1632             goto finish;
1633         }
1634         else
1635         {
1636             if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1637             {
1638                 LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1639                 path_destroy (path);
1640                 return aux;
1641             }
1642         }
1643     }
1644     GNUNET_CONTAINER_DLL_insert_tail (peer->path_head,
1645                                       peer->path_tail,
1646                                       path);
1647     LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1648
1649 finish:
1650     if (NULL != peer->tunnel
1651             && CONNECTIONS_PER_TUNNEL > GCT_count_connections (peer->tunnel)
1652             && 2 < path->length) /* Direct paths are handled by core_connect */
1653     {
1654         GCP_connect (peer);
1655     }
1656     GCC_check_connections ();
1657     return path;
1658 }
1659
1660
1661 /**
1662  * Add the path to the origin peer and update the path used to reach it in case
1663  * this is the shortest.
1664  * The path is given in peer_info -> destination, therefore we turn the path
1665  * upside down first.
1666  *
1667  * @param peer Peer to add the path to, being the origin of the path.
1668  * @param path New path to add after being inversed.
1669  *             Path will be either used or freed.
1670  * @param trusted Do we trust that this path is real?
1671  *
1672  * @return path if path was taken, pointer to existing duplicate if exists
1673  *         NULL on error.
1674  */
1675 struct CadetPeerPath *
1676 GCP_add_path_to_origin (struct CadetPeer *peer,
1677                         struct CadetPeerPath *path,
1678                         int trusted)
1679 {
1680     if (NULL == path)
1681         return NULL;
1682     path_invert (path);
1683     return GCP_add_path (peer, path, trusted);
1684 }
1685
1686
1687 /**
1688  * Adds a path to the info of all the peers in the path
1689  *
1690  * @param p Path to process.
1691  * @param confirmed Whether we know if the path works or not.
1692  */
1693 void
1694 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
1695 {
1696     unsigned int i;
1697
1698     /* TODO: invert and add to origin */
1699     /* TODO: replace all "GCP_add_path" with this, make the other one static */
1700     GCC_check_connections ();
1701     for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1702     for (i++; i < p->length; i++)
1703     {
1704         struct CadetPeer *peer;
1705         struct CadetPeerPath *copy;
1706
1707         peer = GCP_get_short (p->peers[i], GNUNET_YES);
1708         copy = path_duplicate (p);
1709         copy->length = i + 1;
1710         GCP_add_path (peer, copy, 3 > p->length ? GNUNET_NO : confirmed);
1711     }
1712     GCC_check_connections ();
1713 }
1714
1715
1716 /**
1717  * Remove any path to the peer that has the exact same peers as the one given.
1718  *
1719  * @param peer Peer to remove the path from.
1720  * @param path Path to remove. Is always destroyed .
1721  */
1722 void
1723 GCP_remove_path (struct CadetPeer *peer,
1724                  struct CadetPeerPath *path)
1725 {
1726     struct CadetPeerPath *iter;
1727     struct CadetPeerPath *next;
1728
1729     GCC_check_connections ();
1730     GNUNET_assert (myid == path->peers[0]);
1731     GNUNET_assert (peer->id == path->peers[path->length - 1]);
1732
1733     LOG (GNUNET_ERROR_TYPE_INFO,
1734          "Removing path %p (%u) from %s\n",
1735          path, path->length, GCP_2s (peer));
1736
1737     for (iter = peer->path_head; NULL != iter; iter = next)
1738     {
1739         next = iter->next;
1740         if (0 == path_cmp (path, iter))
1741         {
1742             GNUNET_CONTAINER_DLL_remove (peer->path_head,
1743                                          peer->path_tail,
1744                                          iter);
1745             if (iter != path)
1746                 path_destroy (iter);
1747         }
1748     }
1749     path_destroy (path);
1750     GCC_check_connections ();
1751 }
1752
1753
1754 /**
1755  * Check that we are aware of a connection from a neighboring peer.
1756  *
1757  * @param peer Peer to the connection is with
1758  * @param c Connection that should be in the map with this peer.
1759  */
1760 void
1761 GCP_check_connection (const struct CadetPeer *peer,
1762                       const struct CadetConnection *c)
1763 {
1764     GNUNET_assert (NULL != peer);
1765     GNUNET_assert (NULL != peer->connections);
1766     return;
1767     GNUNET_assert (GNUNET_YES ==
1768                    GNUNET_CONTAINER_multihashmap_contains_value (peer->connections,
1769                            GCC_get_h (c),
1770                            c));
1771 }
1772
1773
1774 /**
1775  * Remove a connection from a neighboring peer.
1776  *
1777  * @param peer Peer to remove connection from.
1778  * @param c Connection to remove.
1779  */
1780 void
1781 GCP_remove_connection (struct CadetPeer *peer,
1782                        const struct CadetConnection *c)
1783 {
1784     LOG (GNUNET_ERROR_TYPE_DEBUG,
1785          "Removing connection %s\n",
1786          GCC_2s (c));
1787     LOG (GNUNET_ERROR_TYPE_DEBUG,
1788          "from peer %s\n",
1789          GCP_2s (peer));
1790     if ( (NULL == peer) ||
1791             (NULL == peer->connections) )
1792         return;
1793     GNUNET_assert (GNUNET_YES ==
1794                    GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1795                            GCC_get_h (c),
1796                            c));
1797     LOG (GNUNET_ERROR_TYPE_DEBUG,
1798          "Peer %s remains with %u connections.\n",
1799          GCP_2s (peer),
1800          GNUNET_CONTAINER_multihashmap_size (peer->connections));
1801 }
1802
1803
1804 /**
1805  * Start the DHT search for new paths towards the peer: we don't have
1806  * enough good connections.
1807  *
1808  * @param peer Destination peer.
1809  */
1810 void
1811 GCP_start_search (struct CadetPeer *peer)
1812 {
1813     const struct GNUNET_PeerIdentity *id;
1814     struct CadetTunnel *t = peer->tunnel;
1815
1816     GCC_check_connections ();
1817     if (NULL != peer->search_h)
1818     {
1819         GNUNET_break (0);
1820         return;
1821     }
1822
1823     if (NULL != peer->search_delayed)
1824         GCP_stop_search (peer);
1825
1826     id = GNUNET_PEER_resolve2 (peer->id);
1827     peer->search_h = GCD_search (id, &search_handler, peer);
1828
1829     if (NULL == t)
1830     {
1831         /* Why would we search for a peer with no tunnel towards it? */
1832         GNUNET_break (0);
1833         return;
1834     }
1835
1836     if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
1837             || 0 == GCT_count_any_connections (t))
1838     {
1839         GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
1840     }
1841     GCC_check_connections ();
1842 }
1843
1844
1845 /**
1846  * Stop the DHT search for new paths towards the peer: we already have
1847  * enough good connections.
1848  *
1849  * @param peer Destination peer.
1850  */
1851 void
1852 GCP_stop_search (struct CadetPeer *peer)
1853 {
1854     GCC_check_connections ();
1855     if (NULL != peer->search_h)
1856     {
1857         GCD_search_stop (peer->search_h);
1858         peer->search_h = NULL;
1859     }
1860     if (NULL != peer->search_delayed)
1861     {
1862         GNUNET_SCHEDULER_cancel (peer->search_delayed);
1863         peer->search_delayed = NULL;
1864     }
1865     GCC_check_connections ();
1866 }
1867
1868
1869 /**
1870  * Get the Full ID of a peer.
1871  *
1872  * @param peer Peer to get from.
1873  *
1874  * @return Full ID of peer.
1875  */
1876 const struct GNUNET_PeerIdentity *
1877 GCP_get_id (const struct CadetPeer *peer)
1878 {
1879     return GNUNET_PEER_resolve2 (peer->id);
1880 }
1881
1882
1883 /**
1884  * Get the Short ID of a peer.
1885  *
1886  * @param peer Peer to get from.
1887  *
1888  * @return Short ID of peer.
1889  */
1890 GNUNET_PEER_Id
1891 GCP_get_short_id (const struct CadetPeer *peer)
1892 {
1893     return peer->id;
1894 }
1895
1896
1897 /**
1898  * Set tunnel.
1899  *
1900  * If tunnel is NULL and there was a search active, stop it, as it's useless.
1901  *
1902  * @param peer Peer.
1903  * @param t Tunnel.
1904  */
1905 void
1906 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
1907 {
1908     peer->tunnel = t;
1909     if (NULL == t && GNUNET_YES == is_searching (peer))
1910     {
1911         GCP_stop_search (peer);
1912     }
1913 }
1914
1915
1916 /**
1917  * Get the tunnel towards a peer.
1918  *
1919  * @param peer Peer to get from.
1920  *
1921  * @return Tunnel towards peer.
1922  */
1923 struct CadetTunnel *
1924 GCP_get_tunnel (const struct CadetPeer *peer)
1925 {
1926     if (NULL == peer)
1927         return NULL;
1928     return peer->tunnel;
1929 }
1930
1931
1932 /**
1933  * Set the hello message.
1934  *
1935  * @param peer Peer whose message to set.
1936  * @param hello Hello message.
1937  */
1938 void
1939 GCP_set_hello (struct CadetPeer *peer,
1940                const struct GNUNET_HELLO_Message *hello)
1941 {
1942     struct GNUNET_HELLO_Message *old;
1943     size_t size;
1944
1945     GCC_check_connections ();
1946     LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
1947     if (NULL == hello)
1948         return;
1949
1950     old = GCP_get_hello (peer);
1951     if (NULL == old)
1952     {
1953         size = GNUNET_HELLO_size (hello);
1954         peer->hello = GNUNET_malloc (size);
1955         GNUNET_memcpy (peer->hello, hello, size);
1956     }
1957     else
1958     {
1959         peer->hello = GNUNET_HELLO_merge (old, hello);
1960         GNUNET_free (old);
1961     }
1962     GCC_check_connections ();
1963 }
1964
1965
1966 /**
1967  * Get the hello message.
1968  *
1969  * @param peer Peer whose message to get.
1970  *
1971  * @return Hello message.
1972  */
1973 struct GNUNET_HELLO_Message *
1974 GCP_get_hello (struct CadetPeer *peer)
1975 {
1976     struct GNUNET_TIME_Absolute expiration;
1977     struct GNUNET_TIME_Relative remaining;
1978
1979     if (NULL == peer->hello)
1980         return NULL;
1981
1982     expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
1983     remaining = GNUNET_TIME_absolute_get_remaining (expiration);
1984     if (0 == remaining.rel_value_us)
1985     {
1986         LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
1987              GNUNET_STRINGS_absolute_time_to_string (expiration));
1988         GNUNET_free (peer->hello);
1989         peer->hello = NULL;
1990     }
1991     return peer->hello;
1992 }
1993
1994
1995 /**
1996  * Try to connect to a peer on TRANSPORT level.
1997  *
1998  * @param peer Peer to whom to connect.
1999  */
2000 void
2001 GCP_try_connect (struct CadetPeer *peer)
2002 {
2003     struct GNUNET_HELLO_Message *hello;
2004     struct GNUNET_MessageHeader *mh;
2005
2006     if (GNUNET_YES !=
2007             GNUNET_CONFIGURATION_get_value_yesno (cfg,
2008                     "CADET",
2009                     "DISABLE_TRY_CONNECT"))
2010         return;
2011     GCC_check_connections ();
2012     if (GNUNET_YES == GCP_is_neighbor (peer))
2013         return;
2014     hello = GCP_get_hello (peer);
2015     if (NULL == hello)
2016         return;
2017
2018     mh = GNUNET_HELLO_get_header (hello);
2019     if (NULL != peer->hello_offer)
2020     {
2021         GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
2022         peer->hello_offer = NULL;
2023     }
2024     peer->hello_offer = GNUNET_TRANSPORT_offer_hello (cfg,
2025                         mh,
2026                         &hello_offer_done,
2027                         peer);
2028     if (NULL == peer->connectivity_suggestion)
2029         peer->connectivity_suggestion
2030             = GNUNET_ATS_connectivity_suggest (ats_ch,
2031                                                GCP_get_id (peer),
2032                                                1);  /* strength */
2033     GCC_check_connections ();
2034 }
2035
2036
2037 /**
2038  * Notify a peer that a link between two other peers is broken. If any path
2039  * used that link, eliminate it.
2040  *
2041  * @param peer Peer affected by the change.
2042  * @param peer1 Peer whose link is broken.
2043  * @param peer2 Peer whose link is broken.
2044  */
2045 void
2046 GCP_notify_broken_link (struct CadetPeer *peer,
2047                         const struct GNUNET_PeerIdentity *peer1,
2048                         const struct GNUNET_PeerIdentity *peer2)
2049 {
2050     struct CadetPeerPath *iter;
2051     struct CadetPeerPath *next;
2052     unsigned int i;
2053     GNUNET_PEER_Id p1;
2054     GNUNET_PEER_Id p2;
2055
2056     GCC_check_connections ();
2057     p1 = GNUNET_PEER_search (peer1);
2058     p2 = GNUNET_PEER_search (peer2);
2059
2060     LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2061     if (0 == p1 || 0 == p2)
2062     {
2063         /* We don't even know them */
2064         return;
2065     }
2066
2067     for (iter = peer->path_head; NULL != iter; iter = next)
2068     {
2069         next = iter->next;
2070         for (i = 0; i < iter->length - 1; i++)
2071         {
2072             if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2073                     || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2074             {
2075                 char *s;
2076
2077                 s = path_2s (iter);
2078                 LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2079                 GNUNET_free (s);
2080
2081                 path_invalidate (iter);
2082             }
2083         }
2084     }
2085     GCC_check_connections ();
2086 }
2087
2088
2089 /**
2090  * Count the number of known paths toward the peer.
2091  *
2092  * @param peer Peer to get path info.
2093  *
2094  * @return Number of known paths.
2095  */
2096 unsigned int
2097 GCP_count_paths (const struct CadetPeer *peer)
2098 {
2099     struct CadetPeerPath *iter;
2100     unsigned int i;
2101
2102     for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2103         i++;
2104
2105     return i;
2106 }
2107
2108
2109 /**
2110  * Iterate over the paths to a peer.
2111  *
2112  * @param peer Peer to get path info.
2113  * @param callback Function to call for every path.
2114  * @param cls Closure for @a callback.
2115  *
2116  * @return Number of iterated paths.
2117  */
2118 unsigned int
2119 GCP_iterate_paths (struct CadetPeer *peer,
2120                    GCP_path_iterator callback,
2121                    void *cls)
2122 {
2123     struct CadetPeerPath *iter;
2124     unsigned int i;
2125
2126     for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2127     {
2128         i++;
2129         if (GNUNET_YES != callback (cls, peer, iter))
2130             break;
2131     }
2132
2133     return i;
2134 }
2135
2136
2137 /**
2138  * Iterate all known peers.
2139  *
2140  * @param iter Iterator.
2141  * @param cls Closure for @c iter.
2142  */
2143 void
2144 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
2145                  void *cls)
2146 {
2147     GCC_check_connections ();
2148     GNUNET_CONTAINER_multipeermap_iterate (peers,
2149                                            iter,
2150                                            cls);
2151     GCC_check_connections ();
2152 }
2153
2154
2155 /**
2156  * Get the static string for a peer ID.
2157  *
2158  * @param peer Peer.
2159  *
2160  * @return Static string for it's ID.
2161  */
2162 const char *
2163 GCP_2s (const struct CadetPeer *peer)
2164 {
2165     if (NULL == peer)
2166         return "(NULL)";
2167     return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2168 }
2169
2170
2171 /* end of gnunet-service-cadet_peer.c */