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