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