- add connection info to timing log
[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  * Check if the Key eXchange message has the appropriate size.
552  *
553  * @param cls Closure (unused).
554  * @param msg Message to check.
555  *
556  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
557  */
558 static int
559 check_kx (void *cls, const struct GNUNET_CADET_KX *msg)
560 {
561     uint16_t size;
562     uint16_t expected_size;
563
564     size = ntohs (msg->header.size);
565     expected_size = sizeof (struct GNUNET_CADET_KX)
566                     + sizeof (struct GNUNET_MessageHeader);
567
568     if (size < expected_size)
569     {
570         GNUNET_break_op (0);
571         return GNUNET_NO;
572     }
573     return GNUNET_YES;
574 }
575
576 /**
577  * Handle for #GNUNET_MESSAGE_TYPE_CADET_KX
578  *
579  * @param cls Closure (CadetPeer for neighbor that sent the message).
580  * @param msg Message itself.
581  */
582 static void
583 handle_kx (void *cls, const struct GNUNET_CADET_KX *msg)
584 {
585     struct CadetPeer *peer = cls;
586     GCC_handle_kx (peer, msg);
587 }
588
589
590 /**
591  * Check if the encrypted message has the appropriate size.
592  *
593  * @param cls Closure (unused).
594  * @param msg Message to check.
595  *
596  * @return #GNUNET_YES if size is correct, #GNUNET_NO otherwise.
597  */
598 static int
599 check_encrypted (void *cls, const struct GNUNET_CADET_AX *msg)
600 {
601     uint16_t size;
602     uint16_t minimum_size;
603
604     size = ntohs (msg->header.size);
605     minimum_size = sizeof (struct GNUNET_CADET_AX)
606                    + sizeof (struct GNUNET_MessageHeader);
607
608     if (size < minimum_size)
609     {
610         GNUNET_break_op (0);
611         return GNUNET_NO;
612     }
613     return GNUNET_YES;
614 }
615
616 /**
617  * Handle for #GNUNET_MESSAGE_TYPE_CADET_AX (AXolotl encrypted traffic).
618  *
619  * @param cls Closure (CadetPeer for neighbor that sent the message).
620  * @param msg Message itself.
621  */
622 static void
623 handle_encrypted (void *cls, const struct GNUNET_CADET_AX *msg)
624 {
625     struct CadetPeer *peer = cls;
626     GCC_handle_encrypted (peer, msg);
627 }
628
629
630 /**
631  * To be called on core init/fail.
632  *
633  * @param cls Closure (config)
634  * @param identity The public identity of this peer.
635  */
636 static void
637 core_init_notify (void *cls,
638                   const struct GNUNET_PeerIdentity *identity);
639
640
641 static void
642 connect_to_core (const struct GNUNET_CONFIGURATION_Handle *c)
643 {
644     struct GNUNET_MQ_MessageHandler core_handlers[] = {
645         GNUNET_MQ_hd_var_size (create,
646         GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE,
647         struct GNUNET_CADET_ConnectionCreate,
648         NULL),
649         GNUNET_MQ_hd_fixed_size (confirm,
650         GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
651         struct GNUNET_CADET_ConnectionACK,
652         NULL),
653         GNUNET_MQ_hd_fixed_size (broken,
654         GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
655         struct GNUNET_CADET_ConnectionBroken,
656         NULL),
657         GNUNET_MQ_hd_fixed_size (destroy,
658         GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
659         struct GNUNET_CADET_ConnectionDestroy,
660         NULL),
661         GNUNET_MQ_hd_fixed_size (ack,
662         GNUNET_MESSAGE_TYPE_CADET_ACK,
663         struct GNUNET_CADET_ACK,
664         NULL),
665         GNUNET_MQ_hd_fixed_size (poll,
666         GNUNET_MESSAGE_TYPE_CADET_POLL,
667         struct GNUNET_CADET_Poll,
668         NULL),
669         GNUNET_MQ_hd_var_size (kx,
670         GNUNET_MESSAGE_TYPE_CADET_KX,
671         struct GNUNET_CADET_KX,
672         NULL),
673         GNUNET_MQ_hd_var_size (encrypted,
674         GNUNET_MESSAGE_TYPE_CADET_AX,
675         struct GNUNET_CADET_AX,
676         NULL),
677         GNUNET_MQ_handler_end ()
678     };
679     core_handle = GNUNET_CORE_connecT (c, NULL,
680                                        &core_init_notify,
681                                        &core_connect_handler,
682                                        &core_disconnect_handler,
683                                        core_handlers);
684 }
685
686 /******************************************************************************/
687 /******************************************************************************/
688 /******************************************************************************/
689 /******************************************************************************/
690 /******************************************************************************/
691
692 /**
693  * To be called on core init/fail.
694  *
695  * @param cls Closure (config)
696  * @param identity The public identity of this peer.
697  */
698 static void
699 core_init_notify (void *cls,
700                   const struct GNUNET_PeerIdentity *core_identity)
701 {
702     const struct GNUNET_CONFIGURATION_Handle *c = cls;
703
704     LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
705     if (0 != memcmp (core_identity, &my_full_id, sizeof (my_full_id)))
706     {
707         LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
708         LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (core_identity));
709         LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
710         GNUNET_CORE_disconnecT (core_handle);
711         connect_to_core (c);
712         return;
713     }
714     GML_start ();
715 }
716
717
718 /******************************************************************************/
719 /********************************   STATIC  ***********************************/
720 /******************************************************************************/
721
722
723 /**
724  * Get priority for a queued message.
725  *
726  * @param q Queued message
727  *
728  * @return CORE priority to use.
729  *
730  * FIXME make static
731  * FIXME use when sending
732  */
733 enum GNUNET_CORE_Priority
734 get_priority (struct CadetPeerQueue *q)
735 {
736     enum GNUNET_CORE_Priority low;
737     enum GNUNET_CORE_Priority high;
738
739     if (NULL == q)
740     {
741         GNUNET_break (0);
742         return GNUNET_CORE_PRIO_BACKGROUND;
743     }
744
745     /* Relayed traffic has lower priority, our own traffic has higher */
746     if (NULL == q->c || GNUNET_NO == GCC_is_origin (q->c, q->c_fwd))
747     {
748         low = GNUNET_CORE_PRIO_BEST_EFFORT;
749         high = GNUNET_CORE_PRIO_URGENT;
750     }
751     else
752     {
753         low = GNUNET_CORE_PRIO_URGENT;
754         high = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
755     }
756
757     /* Bulky payload has lower priority, control traffic has higher. */
758     if (GNUNET_MESSAGE_TYPE_CADET_AX == q->type)
759         return low;
760     return high;
761 }
762
763
764 /**
765  * Cancel all messages queued to CORE MQ towards this peer.
766  *
767  * @param peer Peer towards which to cancel all messages.
768  */
769 static void
770 cancel_queued_messages (struct CadetPeer *peer)
771 {
772     while (NULL != peer->q_head)
773     {
774         struct CadetPeerQueue *q;
775
776         q = peer->q_head;
777         call_peer_cont (q, GNUNET_NO);
778         GNUNET_free (q);
779     }
780 }
781
782
783 /**
784  * Destroy the peer_info and free any allocated resources linked to it
785  *
786  * @param peer The peer_info to destroy.
787  * @return #GNUNET_OK on success
788  */
789 static int
790 peer_destroy (struct CadetPeer *peer)
791 {
792     struct GNUNET_PeerIdentity id;
793     struct CadetPeerPath *p;
794     struct CadetPeerPath *nextp;
795
796     GNUNET_PEER_resolve (peer->id, &id);
797     GNUNET_PEER_change_rc (peer->id, -1);
798
799     LOG (GNUNET_ERROR_TYPE_INFO,
800          "destroying peer %s\n",
801          GNUNET_i2s (&id));
802
803     if (GNUNET_YES !=
804             GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
805     {
806         GNUNET_break (0);
807         LOG (GNUNET_ERROR_TYPE_WARNING, " peer not in peermap!!\n");
808     }
809     GCP_stop_search (peer);
810     p = peer->path_head;
811     while (NULL != p)
812     {
813         nextp = p->next;
814         GNUNET_CONTAINER_DLL_remove (peer->path_head,
815                                      peer->path_tail,
816                                      p);
817         path_destroy (p);
818         p = nextp;
819     }
820     if (NULL != peer->tunnel)
821         GCT_destroy_empty (peer->tunnel);
822     if (NULL != peer->connections)
823     {
824         GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (peer->connections));
825         GNUNET_CONTAINER_multihashmap_destroy (peer->connections);
826         peer->connections = NULL;
827     }
828     if (NULL != peer->hello_offer)
829     {
830         GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
831         peer->hello_offer = NULL;
832     }
833     if (NULL != peer->connectivity_suggestion)
834     {
835         GNUNET_ATS_connectivity_suggest_cancel (peer->connectivity_suggestion);
836         peer->connectivity_suggestion = NULL;
837     }
838     cancel_queued_messages (peer);
839
840     GNUNET_free_non_null (peer->hello);
841     GNUNET_free (peer);
842     return GNUNET_OK;
843 }
844
845
846 /**
847  * Iterator over peer hash map entries to destroy the peer during in_shutdown.
848  *
849  * @param cls closure
850  * @param key current key code
851  * @param value value in the hash map
852  * @return #GNUNET_YES if we should continue to iterate,
853  *         #GNUNET_NO if not.
854  */
855 static int
856 shutdown_peer (void *cls,
857                const struct GNUNET_PeerIdentity *key,
858                void *value)
859 {
860     struct CadetPeer *p = value;
861     struct CadetTunnel *t = p->tunnel;
862
863     LOG (GNUNET_ERROR_TYPE_DEBUG, "  shutting down %s\n", GCP_2s (p));
864     if (NULL != t)
865         GCT_destroy (t);
866     p->tunnel = NULL;
867     peer_destroy (p);
868     return GNUNET_YES;
869 }
870
871
872 /**
873  * Check if peer is searching for a path (either active or delayed search).
874  *
875  * @param peer Peer to check
876  * @return #GNUNET_YES if there is a search active.
877  *         #GNUNET_NO otherwise.
878  */
879 static int
880 is_searching (const struct CadetPeer *peer)
881 {
882     return ( (NULL == peer->search_h) &&
883              (NULL == peer->search_delayed) ) ?
884            GNUNET_NO : GNUNET_YES;
885 }
886
887
888 /**
889  * @brief Start a search for a peer.
890  *
891  * @param cls Closure (Peer to search for).
892  */
893 static void
894 delayed_search (void *cls)
895 {
896     struct CadetPeer *peer = cls;
897
898     peer->search_delayed = NULL;
899     GCC_check_connections ();
900     GCP_start_search (peer);
901     GCC_check_connections ();
902 }
903
904
905 /**
906  * Returns if peer is used (has a tunnel or is neighbor).
907  *
908  * @param peer Peer to check.
909  * @return #GNUNET_YES if peer is in use.
910  */
911 static int
912 peer_is_used (struct CadetPeer *peer)
913 {
914     struct CadetPeerPath *p;
915
916     if (NULL != peer->tunnel)
917         return GNUNET_YES;
918
919     for (p = peer->path_head; NULL != p; p = p->next)
920     {
921         if (p->length < 3)
922             return GNUNET_YES;
923     }
924     return GNUNET_NO;
925 }
926
927
928 /**
929  * Iterator over all the peers to get the oldest timestamp.
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_get_oldest (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     /* Don't count active peers */
944     if (GNUNET_YES == peer_is_used (p))
945         return GNUNET_YES;
946
947     if (abs->abs_value_us < p->last_contact.abs_value_us)
948         abs->abs_value_us = p->last_contact.abs_value_us;
949
950     return GNUNET_YES;
951 }
952
953
954 /**
955  * Iterator over all the peers to remove the oldest entry.
956  *
957  * @param cls Closure (unsued).
958  * @param key ID of the peer.
959  * @param value Peer_Info of the peer.
960  */
961 static int
962 peer_timeout (void *cls,
963               const struct GNUNET_PeerIdentity *key,
964               void *value)
965 {
966     struct CadetPeer *p = value;
967     struct GNUNET_TIME_Absolute *abs = cls;
968
969     LOG (GNUNET_ERROR_TYPE_WARNING,
970          "peer %s timeout\n", GNUNET_i2s (key));
971
972     if (p->last_contact.abs_value_us == abs->abs_value_us &&
973             GNUNET_NO == peer_is_used (p))
974     {
975         peer_destroy (p);
976         return GNUNET_NO;
977     }
978     return GNUNET_YES;
979 }
980
981
982 /**
983  * Delete oldest unused peer.
984  */
985 static void
986 peer_delete_oldest (void)
987 {
988     struct GNUNET_TIME_Absolute abs;
989
990     abs = GNUNET_TIME_UNIT_FOREVER_ABS;
991
992     GNUNET_CONTAINER_multipeermap_iterate (peers,
993                                            &peer_get_oldest,
994                                            &abs);
995     GNUNET_CONTAINER_multipeermap_iterate (peers,
996                                            &peer_timeout,
997                                            &abs);
998 }
999
1000
1001 /**
1002  * Choose the best (yet unused) path towards a peer,
1003  * considering the tunnel properties.
1004  *
1005  * @param peer The destination peer.
1006  * @return Best current known path towards the peer, if any.
1007  */
1008 static struct CadetPeerPath *
1009 peer_get_best_path (const struct CadetPeer *peer)
1010 {
1011     struct CadetPeerPath *best_p;
1012     struct CadetPeerPath *p;
1013     unsigned int best_cost;
1014     unsigned int cost;
1015
1016     best_cost = UINT_MAX;
1017     best_p = NULL;
1018     for (p = peer->path_head; NULL != p; p = p->next)
1019     {
1020         if (GNUNET_NO == path_is_valid (p))
1021             continue; /* Don't use invalid paths. */
1022         if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
1023             continue; /* If path is already in use, skip it. */
1024
1025         if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
1026         {
1027             best_cost = cost;
1028             best_p = p;
1029         }
1030     }
1031     return best_p;
1032 }
1033
1034
1035 /**
1036  * Function to process paths received for a new peer addition. The recorded
1037  * paths form the initial tunnel, which can be optimized later.
1038  * Called on each result obtained for the DHT search.
1039  *
1040  * @param cls Closure (peer towards a path has been found).
1041  * @param path Path created from the DHT query. Will be freed afterwards.
1042  */
1043 static void
1044 search_handler (void *cls, const struct CadetPeerPath *path)
1045 {
1046     struct CadetPeer *peer = cls;
1047     unsigned int connection_count;
1048
1049     GCC_check_connections ();
1050     GCP_add_path_to_all (path, GNUNET_NO);
1051
1052     /* Count connections */
1053     connection_count = GCT_count_connections (peer->tunnel);
1054
1055     /* If we already have our minimum (or more) connections, it's enough */
1056     if (CONNECTIONS_PER_TUNNEL <= connection_count)
1057     {
1058         GCC_check_connections ();
1059         return;
1060     }
1061
1062     if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
1063     {
1064         LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
1065         GCP_connect (peer);
1066     }
1067     GCC_check_connections ();
1068 }
1069
1070
1071 /**
1072  * Test if a message type is connection management traffic
1073  * or regular payload traffic.
1074  *
1075  * @param type Message type.
1076  *
1077  * @return #GNUNET_YES if connection management, #GNUNET_NO otherwise.
1078  */
1079 static int
1080 is_connection_management (uint16_t type)
1081 {
1082     return type == GNUNET_MESSAGE_TYPE_CADET_ACK ||
1083            type == GNUNET_MESSAGE_TYPE_CADET_POLL;
1084 }
1085
1086
1087 /**
1088  * Debug function should NEVER return true in production code, useful to
1089  * simulate losses for testcases.
1090  *
1091  * @return #GNUNET_YES or #GNUNET_NO with the decision to drop.
1092  */
1093 static int
1094 should_I_drop (void)
1095 {
1096     if (0 == drop_percent)
1097         return GNUNET_NO;
1098
1099     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
1100         return GNUNET_YES;
1101
1102     return GNUNET_NO;
1103 }
1104
1105
1106 /******************************************************************************/
1107 /********************************    API    ***********************************/
1108 /******************************************************************************/
1109
1110 /**
1111  * Call the continuation after a message has been sent or dropped.
1112  *
1113  * This funcion removes the message from the queue.
1114  *
1115  * @param q Queue handle.
1116  * @param sent #GNUNET_YES if was sent to CORE, #GNUNET_NO if dropped.
1117  */
1118 static void
1119 call_peer_cont (struct CadetPeerQueue *q, int sent)
1120 {
1121     LOG (GNUNET_ERROR_TYPE_DEBUG, " core mq just sent %s\n", GC_m2s (q->type));
1122     if (NULL != q->cont)
1123     {
1124         struct GNUNET_TIME_Relative wait_time;
1125
1126         wait_time = GNUNET_TIME_absolute_get_duration (q->queue_timestamp);
1127         LOG (GNUNET_ERROR_TYPE_INFO,
1128              " calling callback on %s after %s\n",
1129              GCC_2s (q->c),
1130              GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
1131         q->cont (q->cont_cls,
1132                  q->c, q->c_fwd, sent,
1133                  q->type, q->payload_type, q->payload_id,
1134                  q->size, wait_time);
1135     }
1136     GNUNET_CONTAINER_DLL_remove (q->peer->q_head, q->peer->q_tail, q);
1137 }
1138
1139
1140 /**
1141  * Function called by MQ when a message is sent to CORE.
1142  *
1143  * @param cls Closure (queue handle).
1144  */
1145 static void
1146 mq_sent (void *cls)
1147 {
1148     struct CadetPeerQueue *q = cls;
1149
1150     if (GNUNET_NO == q->management_traffic)
1151     {
1152         q->peer->queue_n--;
1153     }
1154     call_peer_cont (q, GNUNET_YES);
1155     GNUNET_free (q);
1156 }
1157
1158
1159 /**
1160  * @brief Send a message to another peer (using CORE).
1161  *
1162  * @param peer Peer towards which to queue the message.
1163  * @param message Message to send.
1164  * @param payload_type Type of the message's payload, for debug messages.
1165  *                     0 if the message is a retransmission (unknown payload).
1166  *                     UINT16_MAX if the message does not have payload.
1167  * @param payload_id ID of the payload (MID, ACK #, etc)
1168  * @param c Connection this message belongs to (can be NULL).
1169  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1170  * @param cont Continuation to be called once CORE has sent the message.
1171  * @param cont_cls Closure for @c cont.
1172  *
1173  * @return A handle to the message in the queue or NULL (if dropped).
1174  */
1175 struct CadetPeerQueue *
1176 GCP_send (struct CadetPeer *peer,
1177           const struct GNUNET_MessageHeader *message,
1178           uint16_t payload_type,
1179           uint32_t payload_id,
1180           struct CadetConnection *c,
1181           int fwd,
1182           GCP_sent cont,
1183           void *cont_cls)
1184 {
1185     struct CadetPeerQueue *q;
1186     uint16_t type;
1187     uint16_t size;
1188
1189     GCC_check_connections ();
1190     type = ntohs (message->type);
1191     size = ntohs (message->size);
1192     LOG (GNUNET_ERROR_TYPE_DEBUG,
1193          "que %s (%s %4u) on conn %s (%p) %s towards %s (size %u)\n",
1194          GC_m2s (type), GC_m2s (payload_type), payload_id,
1195          GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1196
1197     if (NULL == peer->connections)
1198     {
1199         /* We are not connected to this peer, ignore request. */
1200         GNUNET_break (0);
1201         LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
1202         GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1203                                   GNUNET_NO);
1204         return NULL;
1205     }
1206
1207     q = GNUNET_new (struct CadetPeerQueue);
1208     q->env = GNUNET_MQ_msg_copy (message);
1209     q->peer = peer;
1210     q->cont = cont;
1211     q->cont_cls = cont_cls;
1212     q->queue_timestamp = GNUNET_TIME_absolute_get ();
1213     q->management_traffic = is_connection_management (type);
1214     q->type = type;
1215     q->size = size;
1216     q->payload_type = payload_type;
1217     q->payload_id = payload_id;
1218     q->c = c;
1219     q->c_fwd = fwd;
1220     GNUNET_MQ_notify_sent (q->env, mq_sent, q);
1221
1222     if (GNUNET_YES == q->management_traffic)
1223     {
1224         GNUNET_MQ_send (peer->core_mq, q->env);  // FIXME implement "_urgent", use
1225     }
1226     else
1227     {
1228         if (GNUNET_YES == should_I_drop ())
1229         {
1230             LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on conn %s %s\n",
1231                  GC_m2s (q->type), GC_m2s (q->payload_type),
1232                  q->payload_id, GCC_2s (c), GC_f2s (q->c_fwd));
1233             GNUNET_MQ_discard (q->env);
1234             call_peer_cont (q, GNUNET_YES);
1235             GNUNET_free (q);
1236             return NULL;
1237         }
1238         GNUNET_MQ_send (peer->core_mq, q->env);
1239         peer->queue_n++;
1240     }
1241
1242     GNUNET_CONTAINER_DLL_insert (peer->q_head, peer->q_tail, q);
1243     GCC_check_connections ();
1244     return q;
1245 }
1246
1247
1248 /**
1249  * Cancel sending a message. Message must have been sent with
1250  * #GCP_send before.  May not be called after the notify sent
1251  * callback has been called.
1252  *
1253  * It DOES call the continuation given to #GCP_send.
1254  *
1255  * @param q Queue handle to cancel
1256  */
1257 void
1258 GCP_send_cancel (struct CadetPeerQueue *q)
1259 {
1260     call_peer_cont (q, GNUNET_NO);
1261     GNUNET_MQ_send_cancel (q->env);
1262     GNUNET_free (q);
1263 }
1264
1265
1266 /**
1267  * Initialize the peer subsystem.
1268  *
1269  * @param c Configuration.
1270  */
1271 void
1272 GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1273 {
1274     cfg = c;
1275     LOG (GNUNET_ERROR_TYPE_DEBUG,
1276          "GCP_init\n");
1277     in_shutdown = GNUNET_NO;
1278     peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1279     if (GNUNET_OK !=
1280             GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1281                     &max_peers))
1282     {
1283         GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1284                                    "CADET", "MAX_PEERS", "USING DEFAULT");
1285         max_peers = 1000;
1286     }
1287
1288     if (GNUNET_OK !=
1289             GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1290                     &drop_percent))
1291     {
1292         drop_percent = 0;
1293     }
1294     else
1295     {
1296         LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1297         LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1298         LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1299         LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1300         LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1301     }
1302     ats_ch = GNUNET_ATS_connectivity_init (c);
1303     connect_to_core (c);
1304     if (NULL == core_handle)
1305     {
1306         GNUNET_break (0);
1307         GNUNET_SCHEDULER_shutdown ();
1308     }
1309 }
1310
1311
1312 /**
1313  * Shut down the peer subsystem.
1314  */
1315 void
1316 GCP_shutdown (void)
1317 {
1318     LOG (GNUNET_ERROR_TYPE_DEBUG,
1319          "Shutting down peer subsystem\n");
1320     in_shutdown = GNUNET_YES;
1321     if (NULL != core_handle)
1322     {
1323         GNUNET_CORE_disconnecT (core_handle);
1324         core_handle = NULL;
1325     }
1326     GNUNET_PEER_change_rc (myid, -1);
1327     /* With MQ API, CORE calls the disconnect handler for every peer
1328      * after calling GNUNET_CORE_disconnecT, shutdown must occur *after* that.
1329      */
1330     GNUNET_CONTAINER_multipeermap_iterate (peers,
1331                                            &shutdown_peer,
1332                                            NULL);
1333     if (NULL != ats_ch)
1334     {
1335         GNUNET_ATS_connectivity_done (ats_ch);
1336         ats_ch = NULL;
1337     }
1338     GNUNET_CONTAINER_multipeermap_destroy (peers);
1339     peers = NULL;
1340 }
1341
1342
1343 /**
1344  * Retrieve the CadetPeer stucture associated with the peer. Optionally create
1345  * one and insert it in the appropriate structures if the peer is not known yet.
1346  *
1347  * @param peer_id Full identity of the peer.
1348  * @param create #GNUNET_YES if a new peer should be created if unknown.
1349  *               #GNUNET_NO otherwise.
1350  *
1351  * @return Existing or newly created peer structure.
1352  *         NULL if unknown and not requested @a create
1353  */
1354 struct CadetPeer *
1355 GCP_get (const struct GNUNET_PeerIdentity *peer_id, int create)
1356 {
1357     struct CadetPeer *peer;
1358
1359     peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1360     if (NULL == peer)
1361     {
1362         peer = GNUNET_new (struct CadetPeer);
1363         if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1364         {
1365             peer_delete_oldest ();
1366         }
1367         GNUNET_assert (GNUNET_OK ==
1368                        GNUNET_CONTAINER_multipeermap_put (peers,
1369                                peer_id,
1370                                peer,
1371                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1372         peer->id = GNUNET_PEER_intern (peer_id);
1373     }
1374     peer->last_contact = GNUNET_TIME_absolute_get ();
1375
1376     return peer;
1377 }
1378
1379
1380 /**
1381  * Retrieve the CadetPeer stucture associated with the
1382  * peer. Optionally create one and insert it in the appropriate
1383  * structures if the peer is not known yet.
1384  *
1385  * @param peer Short identity of the peer.
1386  * @param create #GNUNET_YES if a new peer should be created if unknown.
1387  *               #GNUNET_NO otherwise.
1388  *
1389  * @return Existing or newly created peer structure.
1390  *         NULL if unknown and not requested @a create
1391  */
1392 struct CadetPeer *
1393 GCP_get_short (const GNUNET_PEER_Id peer, int create)
1394 {
1395     return GCP_get (GNUNET_PEER_resolve2 (peer), create);
1396 }
1397
1398
1399 /**
1400  * Function called once #GNUNET_TRANSPORT_offer_hello() is done.
1401  * Marks the operation as finished.
1402  *
1403  * @param cls Closure (our `struct CadetPeer`).
1404  */
1405 static void
1406 hello_offer_done (void *cls)
1407 {
1408     struct CadetPeer *peer = cls;
1409
1410     peer->hello_offer = NULL;
1411 }
1412
1413
1414 /**
1415  * Try to establish a new connection to this peer (in its tunnel).
1416  * If the peer doesn't have any path to it yet, try to get one.
1417  * If the peer already has some path, send a CREATE CONNECTION towards it.
1418  *
1419  * @param peer Peer to connect to.
1420  */
1421 void
1422 GCP_connect (struct CadetPeer *peer)
1423 {
1424     struct CadetTunnel *t;
1425     struct CadetPeerPath *path;
1426     struct CadetConnection *c;
1427     int rerun_search;
1428
1429     GCC_check_connections ();
1430     LOG (GNUNET_ERROR_TYPE_DEBUG,
1431          "peer_connect towards %s\n",
1432          GCP_2s (peer));
1433     /* If we have a current hello, try to connect using it. */
1434     GCP_try_connect (peer);
1435
1436     t = peer->tunnel;
1437     c = NULL;
1438     rerun_search = GNUNET_NO;
1439
1440     if (NULL != peer->path_head)
1441     {
1442         LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1443         path = peer_get_best_path (peer);
1444         if (NULL != path)
1445         {
1446             char *s;
1447
1448             s = path_2s (path);
1449             LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1450             GNUNET_free (s);
1451
1452             c = GCT_use_path (t, path);
1453             if (NULL == c)
1454             {
1455                 /* This case can happen when the path includes a first hop that is
1456                  * not yet known to be connected.
1457                  *
1458                  * This happens quite often during testing when running cadet
1459                  * under valgrind: core connect notifications come very late
1460                  * and the DHT result has already come and created a valid
1461                  * path.  In this case, the peer->connections
1462                  * hashmaps will be NULL and tunnel_use_path will not be able
1463                  * to create a connection from that path.
1464                  *
1465                  * Re-running the DHT GET should give core time to callback.
1466                  *
1467                  * GCT_use_path -> GCC_new -> register_neighbors takes care of
1468                  * updating statistics about this issue.
1469                  */
1470                 rerun_search = GNUNET_YES;
1471             }
1472             else
1473             {
1474                 GCC_send_create (c);
1475                 return;
1476             }
1477         }
1478         else
1479         {
1480             LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1481         }
1482     }
1483
1484     if (GNUNET_YES == rerun_search)
1485     {
1486         struct GNUNET_TIME_Relative delay;
1487
1488         GCP_stop_search (peer);
1489         delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
1490         peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay,
1491                                &delayed_search,
1492                                peer);
1493         GCC_check_connections ();
1494         return;
1495     }
1496
1497     if (GNUNET_NO == is_searching (peer))
1498         GCP_start_search (peer);
1499     GCC_check_connections ();
1500 }
1501
1502
1503 /**
1504  * Chech whether there is a direct (core level)  connection to peer.
1505  *
1506  * @param peer Peer to check.
1507  *
1508  * @return #GNUNET_YES if there is a direct connection.
1509  */
1510 int
1511 GCP_is_neighbor (const struct CadetPeer *peer)
1512 {
1513     struct CadetPeerPath *path;
1514
1515     if (NULL == peer->connections)
1516         return GNUNET_NO;
1517
1518     for (path = peer->path_head; NULL != path; path = path->next)
1519     {
1520         if (3 > path->length)
1521             return GNUNET_YES;
1522     }
1523
1524     /* Is not a neighbor but connections is not NULL, probably disconnecting */
1525     return GNUNET_NO;
1526 }
1527
1528
1529 /**
1530  * Create and initialize a new tunnel towards a peer, in case it has none.
1531  * In case the peer already has a tunnel, nothing is done.
1532  *
1533  * Does not generate any traffic, just creates the local data structures.
1534  *
1535  * @param peer Peer towards which to create the tunnel.
1536  */
1537 void
1538 GCP_add_tunnel (struct CadetPeer *peer)
1539 {
1540     GCC_check_connections ();
1541     if (NULL != peer->tunnel)
1542         return;
1543     peer->tunnel = GCT_new (peer);
1544     GCC_check_connections ();
1545 }
1546
1547
1548 /**
1549  * Add a connection to a neighboring peer.
1550  *
1551  * Store that the peer is the first hop of the connection in one
1552  * direction and that on peer disconnect the connection must be
1553  * notified and destroyed, for it will no longer be valid.
1554  *
1555  * @param peer Peer to add connection to.
1556  * @param c Connection to add.
1557  * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
1558  */
1559 void
1560 GCP_add_connection (struct CadetPeer *peer,
1561                     struct CadetConnection *c,
1562                     int pred)
1563 {
1564     LOG (GNUNET_ERROR_TYPE_DEBUG,
1565          "adding connection %s\n",
1566          GCC_2s (c));
1567     LOG (GNUNET_ERROR_TYPE_DEBUG,
1568          "to peer %s\n",
1569          GCP_2s (peer));
1570     GNUNET_assert (NULL != peer->connections);
1571     GNUNET_assert (GNUNET_OK ==
1572                    GNUNET_CONTAINER_multihashmap_put (peer->connections,
1573                            GCC_get_h (c),
1574                            c,
1575                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1576     LOG (GNUNET_ERROR_TYPE_DEBUG,
1577          "Peer %s has now %u connections.\n",
1578          GCP_2s (peer),
1579          GNUNET_CONTAINER_multihashmap_size (peer->connections));
1580 }
1581
1582
1583 /**
1584  * Add the path to the peer and update the path used to reach it in case this
1585  * is the shortest.
1586  *
1587  * @param peer Destination peer to add the path to.
1588  * @param path New path to add. Last peer must be @c peer.
1589  *             Path will be either used of freed if already known.
1590  * @param trusted Do we trust that this path is real?
1591  *
1592  * @return path if path was taken, pointer to existing duplicate if exists
1593  *         NULL on error.
1594  */
1595 struct CadetPeerPath *
1596 GCP_add_path (struct CadetPeer *peer,
1597               struct CadetPeerPath *path,
1598               int trusted)
1599 {
1600     struct CadetPeerPath *aux;
1601     unsigned int l;
1602     unsigned int l2;
1603
1604     GCC_check_connections ();
1605     LOG (GNUNET_ERROR_TYPE_DEBUG,
1606          "adding path [%u] to peer %s\n",
1607          path->length, GCP_2s (peer));
1608
1609     if (NULL == peer || NULL == path
1610             || path->peers[path->length - 1] != peer->id)
1611     {
1612         GNUNET_break (0);
1613         path_destroy (path);
1614         return NULL;
1615     }
1616
1617     for (l = 1; l < path->length; l++)
1618     {
1619         if (path->peers[l] == myid)
1620         {
1621             LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1622             for (l2 = 0; l2 < path->length - l; l2++)
1623             {
1624                 path->peers[l2] = path->peers[l + l2];
1625             }
1626             path->length -= l;
1627             l = 1;
1628             path->peers = GNUNET_realloc (path->peers,
1629                                           path->length * sizeof (GNUNET_PEER_Id));
1630         }
1631     }
1632
1633     LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
1634
1635     if (2 >= path->length && GNUNET_NO == trusted)
1636     {
1637         /* Only allow CORE to tell us about direct paths */
1638         path_destroy (path);
1639         return NULL;
1640     }
1641
1642     l = path_get_length (path);
1643     if (0 == l)
1644     {
1645         path_destroy (path);
1646         return NULL;
1647     }
1648
1649     GNUNET_assert (peer->id == path->peers[path->length - 1]);
1650     for (aux = peer->path_head; aux != NULL; aux = aux->next)
1651     {
1652         l2 = path_get_length (aux);
1653         if (l2 > l)
1654         {
1655             LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1656             GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1657                                                 peer->path_tail, aux, path);
1658             goto finish;
1659         }
1660         else
1661         {
1662             if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1663             {
1664                 LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1665                 path_destroy (path);
1666                 return aux;
1667             }
1668         }
1669     }
1670     GNUNET_CONTAINER_DLL_insert_tail (peer->path_head,
1671                                       peer->path_tail,
1672                                       path);
1673     LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1674
1675 finish:
1676     if (NULL != peer->tunnel
1677             && CONNECTIONS_PER_TUNNEL > GCT_count_connections (peer->tunnel)
1678             && 2 < path->length) /* Direct paths are handled by core_connect */
1679     {
1680         GCP_connect (peer);
1681     }
1682     GCC_check_connections ();
1683     return path;
1684 }
1685
1686
1687 /**
1688  * Add the path to the origin peer and update the path used to reach it in case
1689  * this is the shortest.
1690  * The path is given in peer_info -> destination, therefore we turn the path
1691  * upside down first.
1692  *
1693  * @param peer Peer to add the path to, being the origin of the path.
1694  * @param path New path to add after being inversed.
1695  *             Path will be either used or freed.
1696  * @param trusted Do we trust that this path is real?
1697  *
1698  * @return path if path was taken, pointer to existing duplicate if exists
1699  *         NULL on error.
1700  */
1701 struct CadetPeerPath *
1702 GCP_add_path_to_origin (struct CadetPeer *peer,
1703                         struct CadetPeerPath *path,
1704                         int trusted)
1705 {
1706     if (NULL == path)
1707         return NULL;
1708     path_invert (path);
1709     return GCP_add_path (peer, path, trusted);
1710 }
1711
1712
1713 /**
1714  * Adds a path to the info of all the peers in the path
1715  *
1716  * @param p Path to process.
1717  * @param confirmed Whether we know if the path works or not.
1718  */
1719 void
1720 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
1721 {
1722     unsigned int i;
1723
1724     /* TODO: invert and add to origin */
1725     /* TODO: replace all "GCP_add_path" with this, make the other one static */
1726     GCC_check_connections ();
1727     for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1728     for (i++; i < p->length; i++)
1729     {
1730         struct CadetPeer *peer;
1731         struct CadetPeerPath *copy;
1732
1733         peer = GCP_get_short (p->peers[i], GNUNET_YES);
1734         copy = path_duplicate (p);
1735         copy->length = i + 1;
1736         GCP_add_path (peer, copy, 3 > p->length ? GNUNET_NO : confirmed);
1737     }
1738     GCC_check_connections ();
1739 }
1740
1741
1742 /**
1743  * Remove any path to the peer that has the exact same peers as the one given.
1744  *
1745  * @param peer Peer to remove the path from.
1746  * @param path Path to remove. Is always destroyed .
1747  */
1748 void
1749 GCP_remove_path (struct CadetPeer *peer,
1750                  struct CadetPeerPath *path)
1751 {
1752     struct CadetPeerPath *iter;
1753     struct CadetPeerPath *next;
1754
1755     GCC_check_connections ();
1756     GNUNET_assert (myid == path->peers[0]);
1757     GNUNET_assert (peer->id == path->peers[path->length - 1]);
1758
1759     LOG (GNUNET_ERROR_TYPE_INFO,
1760          "Removing path %p (%u) from %s\n",
1761          path, path->length, GCP_2s (peer));
1762
1763     for (iter = peer->path_head; NULL != iter; iter = next)
1764     {
1765         next = iter->next;
1766         if (0 == path_cmp (path, iter))
1767         {
1768             GNUNET_CONTAINER_DLL_remove (peer->path_head,
1769                                          peer->path_tail,
1770                                          iter);
1771             if (iter != path)
1772                 path_destroy (iter);
1773         }
1774     }
1775     path_destroy (path);
1776     GCC_check_connections ();
1777 }
1778
1779
1780 /**
1781  * Check that we are aware of a connection from a neighboring peer.
1782  *
1783  * @param peer Peer to the connection is with
1784  * @param c Connection that should be in the map with this peer.
1785  */
1786 void
1787 GCP_check_connection (const struct CadetPeer *peer,
1788                       const struct CadetConnection *c)
1789 {
1790     GNUNET_assert (NULL != peer);
1791     GNUNET_assert (NULL != peer->connections);
1792     return;
1793     GNUNET_assert (GNUNET_YES ==
1794                    GNUNET_CONTAINER_multihashmap_contains_value (peer->connections,
1795                            GCC_get_h (c),
1796                            c));
1797 }
1798
1799
1800 /**
1801  * Remove a connection from a neighboring peer.
1802  *
1803  * @param peer Peer to remove connection from.
1804  * @param c Connection to remove.
1805  */
1806 void
1807 GCP_remove_connection (struct CadetPeer *peer,
1808                        const struct CadetConnection *c)
1809 {
1810     LOG (GNUNET_ERROR_TYPE_DEBUG,
1811          "Removing connection %s\n",
1812          GCC_2s (c));
1813     LOG (GNUNET_ERROR_TYPE_DEBUG,
1814          "from peer %s\n",
1815          GCP_2s (peer));
1816     if ( (NULL == peer) ||
1817             (NULL == peer->connections) )
1818         return;
1819     GNUNET_assert (GNUNET_YES ==
1820                    GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1821                            GCC_get_h (c),
1822                            c));
1823     LOG (GNUNET_ERROR_TYPE_DEBUG,
1824          "Peer %s remains with %u connections.\n",
1825          GCP_2s (peer),
1826          GNUNET_CONTAINER_multihashmap_size (peer->connections));
1827 }
1828
1829
1830 /**
1831  * Start the DHT search for new paths towards the peer: we don't have
1832  * enough good connections.
1833  *
1834  * @param peer Destination peer.
1835  */
1836 void
1837 GCP_start_search (struct CadetPeer *peer)
1838 {
1839     const struct GNUNET_PeerIdentity *id;
1840     struct CadetTunnel *t = peer->tunnel;
1841
1842     GCC_check_connections ();
1843     if (NULL != peer->search_h)
1844     {
1845         GNUNET_break (0);
1846         return;
1847     }
1848
1849     if (NULL != peer->search_delayed)
1850         GCP_stop_search (peer);
1851
1852     id = GNUNET_PEER_resolve2 (peer->id);
1853     peer->search_h = GCD_search (id, &search_handler, peer);
1854
1855     if (NULL == t)
1856     {
1857         /* Why would we search for a peer with no tunnel towards it? */
1858         GNUNET_break (0);
1859         return;
1860     }
1861
1862     if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
1863             || 0 == GCT_count_any_connections (t))
1864     {
1865         GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
1866     }
1867     GCC_check_connections ();
1868 }
1869
1870
1871 /**
1872  * Stop the DHT search for new paths towards the peer: we already have
1873  * enough good connections.
1874  *
1875  * @param peer Destination peer.
1876  */
1877 void
1878 GCP_stop_search (struct CadetPeer *peer)
1879 {
1880     GCC_check_connections ();
1881     if (NULL != peer->search_h)
1882     {
1883         GCD_search_stop (peer->search_h);
1884         peer->search_h = NULL;
1885     }
1886     if (NULL != peer->search_delayed)
1887     {
1888         GNUNET_SCHEDULER_cancel (peer->search_delayed);
1889         peer->search_delayed = NULL;
1890     }
1891     GCC_check_connections ();
1892 }
1893
1894
1895 /**
1896  * Get the Full ID of a peer.
1897  *
1898  * @param peer Peer to get from.
1899  *
1900  * @return Full ID of peer.
1901  */
1902 const struct GNUNET_PeerIdentity *
1903 GCP_get_id (const struct CadetPeer *peer)
1904 {
1905     return GNUNET_PEER_resolve2 (peer->id);
1906 }
1907
1908
1909 /**
1910  * Get the Short ID of a peer.
1911  *
1912  * @param peer Peer to get from.
1913  *
1914  * @return Short ID of peer.
1915  */
1916 GNUNET_PEER_Id
1917 GCP_get_short_id (const struct CadetPeer *peer)
1918 {
1919     return peer->id;
1920 }
1921
1922
1923 /**
1924  * Set tunnel.
1925  *
1926  * If tunnel is NULL and there was a search active, stop it, as it's useless.
1927  *
1928  * @param peer Peer.
1929  * @param t Tunnel.
1930  */
1931 void
1932 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
1933 {
1934     peer->tunnel = t;
1935     if (NULL == t && GNUNET_YES == is_searching (peer))
1936     {
1937         GCP_stop_search (peer);
1938     }
1939 }
1940
1941
1942 /**
1943  * Get the tunnel towards a peer.
1944  *
1945  * @param peer Peer to get from.
1946  *
1947  * @return Tunnel towards peer.
1948  */
1949 struct CadetTunnel *
1950 GCP_get_tunnel (const struct CadetPeer *peer)
1951 {
1952     if (NULL == peer)
1953         return NULL;
1954     return peer->tunnel;
1955 }
1956
1957
1958 /**
1959  * Set the hello message.
1960  *
1961  * @param peer Peer whose message to set.
1962  * @param hello Hello message.
1963  */
1964 void
1965 GCP_set_hello (struct CadetPeer *peer,
1966                const struct GNUNET_HELLO_Message *hello)
1967 {
1968     struct GNUNET_HELLO_Message *old;
1969     size_t size;
1970
1971     GCC_check_connections ();
1972     LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
1973     if (NULL == hello)
1974         return;
1975
1976     old = GCP_get_hello (peer);
1977     if (NULL == old)
1978     {
1979         size = GNUNET_HELLO_size (hello);
1980         peer->hello = GNUNET_malloc (size);
1981         GNUNET_memcpy (peer->hello, hello, size);
1982     }
1983     else
1984     {
1985         peer->hello = GNUNET_HELLO_merge (old, hello);
1986         GNUNET_free (old);
1987     }
1988     GCC_check_connections ();
1989 }
1990
1991
1992 /**
1993  * Get the hello message.
1994  *
1995  * @param peer Peer whose message to get.
1996  *
1997  * @return Hello message.
1998  */
1999 struct GNUNET_HELLO_Message *
2000 GCP_get_hello (struct CadetPeer *peer)
2001 {
2002     struct GNUNET_TIME_Absolute expiration;
2003     struct GNUNET_TIME_Relative remaining;
2004
2005     if (NULL == peer->hello)
2006         return NULL;
2007
2008     expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2009     remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2010     if (0 == remaining.rel_value_us)
2011     {
2012         LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2013              GNUNET_STRINGS_absolute_time_to_string (expiration));
2014         GNUNET_free (peer->hello);
2015         peer->hello = NULL;
2016     }
2017     return peer->hello;
2018 }
2019
2020
2021 /**
2022  * Try to connect to a peer on TRANSPORT level.
2023  *
2024  * @param peer Peer to whom to connect.
2025  */
2026 void
2027 GCP_try_connect (struct CadetPeer *peer)
2028 {
2029     struct GNUNET_HELLO_Message *hello;
2030     struct GNUNET_MessageHeader *mh;
2031
2032     if (GNUNET_YES !=
2033             GNUNET_CONFIGURATION_get_value_yesno (cfg,
2034                     "CADET",
2035                     "DISABLE_TRY_CONNECT"))
2036         return;
2037     GCC_check_connections ();
2038     if (GNUNET_YES == GCP_is_neighbor (peer))
2039         return;
2040     hello = GCP_get_hello (peer);
2041     if (NULL == hello)
2042         return;
2043
2044     mh = GNUNET_HELLO_get_header (hello);
2045     if (NULL != peer->hello_offer)
2046     {
2047         GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
2048         peer->hello_offer = NULL;
2049     }
2050     peer->hello_offer = GNUNET_TRANSPORT_offer_hello (cfg,
2051                         mh,
2052                         &hello_offer_done,
2053                         peer);
2054     if (NULL == peer->connectivity_suggestion)
2055         peer->connectivity_suggestion
2056             = GNUNET_ATS_connectivity_suggest (ats_ch,
2057                                                GCP_get_id (peer),
2058                                                1);  /* strength */
2059     GCC_check_connections ();
2060 }
2061
2062
2063 /**
2064  * Notify a peer that a link between two other peers is broken. If any path
2065  * used that link, eliminate it.
2066  *
2067  * @param peer Peer affected by the change.
2068  * @param peer1 Peer whose link is broken.
2069  * @param peer2 Peer whose link is broken.
2070  */
2071 void
2072 GCP_notify_broken_link (struct CadetPeer *peer,
2073                         const struct GNUNET_PeerIdentity *peer1,
2074                         const struct GNUNET_PeerIdentity *peer2)
2075 {
2076     struct CadetPeerPath *iter;
2077     struct CadetPeerPath *next;
2078     unsigned int i;
2079     GNUNET_PEER_Id p1;
2080     GNUNET_PEER_Id p2;
2081
2082     GCC_check_connections ();
2083     p1 = GNUNET_PEER_search (peer1);
2084     p2 = GNUNET_PEER_search (peer2);
2085
2086     LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2087     if (0 == p1 || 0 == p2)
2088     {
2089         /* We don't even know them */
2090         return;
2091     }
2092
2093     for (iter = peer->path_head; NULL != iter; iter = next)
2094     {
2095         next = iter->next;
2096         for (i = 0; i < iter->length - 1; i++)
2097         {
2098             if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2099                     || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2100             {
2101                 char *s;
2102
2103                 s = path_2s (iter);
2104                 LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2105                 GNUNET_free (s);
2106
2107                 path_invalidate (iter);
2108             }
2109         }
2110     }
2111     GCC_check_connections ();
2112 }
2113
2114
2115 /**
2116  * Count the number of known paths toward the peer.
2117  *
2118  * @param peer Peer to get path info.
2119  *
2120  * @return Number of known paths.
2121  */
2122 unsigned int
2123 GCP_count_paths (const struct CadetPeer *peer)
2124 {
2125     struct CadetPeerPath *iter;
2126     unsigned int i;
2127
2128     for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2129         i++;
2130
2131     return i;
2132 }
2133
2134
2135 /**
2136  * Iterate over the paths to a peer.
2137  *
2138  * @param peer Peer to get path info.
2139  * @param callback Function to call for every path.
2140  * @param cls Closure for @a callback.
2141  *
2142  * @return Number of iterated paths.
2143  */
2144 unsigned int
2145 GCP_iterate_paths (struct CadetPeer *peer,
2146                    GCP_path_iterator callback,
2147                    void *cls)
2148 {
2149     struct CadetPeerPath *iter;
2150     unsigned int i;
2151
2152     for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2153     {
2154         i++;
2155         if (GNUNET_YES != callback (cls, peer, iter))
2156             break;
2157     }
2158
2159     return i;
2160 }
2161
2162
2163 /**
2164  * Iterate all known peers.
2165  *
2166  * @param iter Iterator.
2167  * @param cls Closure for @c iter.
2168  */
2169 void
2170 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
2171                  void *cls)
2172 {
2173     GCC_check_connections ();
2174     GNUNET_CONTAINER_multipeermap_iterate (peers,
2175                                            iter,
2176                                            cls);
2177     GCC_check_connections ();
2178 }
2179
2180
2181 /**
2182  * Get the static string for a peer ID.
2183  *
2184  * @param peer Peer.
2185  *
2186  * @return Static string for it's ID.
2187  */
2188 const char *
2189 GCP_2s (const struct CadetPeer *peer)
2190 {
2191     if (NULL == peer)
2192         return "(NULL)";
2193     return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2194 }
2195
2196
2197 /* end of gnunet-service-cadet_peer.c */