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