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