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