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