implementing new scheduler shutdown semantics
[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  * Struct containing info about a queued transmission to this peer
49  */
50 struct CadetPeerQueue
51 {
52   /**
53    * DLL next
54    */
55   struct CadetPeerQueue *next;
56
57   /**
58    * DLL previous
59    */
60   struct CadetPeerQueue *prev;
61
62   /**
63    * Peer this transmission is directed to.
64    */
65   struct CadetPeer *peer;
66
67   /**
68    * Connection this message belongs to.
69    */
70   struct CadetConnection *c;
71
72   /**
73    * Is FWD in c?
74    */
75   int fwd;
76
77   /**
78    * Pointer to info stucture used as cls.
79    */
80   void *cls;
81
82   /**
83    * Type of message
84    */
85   uint16_t type;
86
87   /**
88    * Type of message
89    */
90   uint16_t payload_type;
91
92   /**
93    * Type of message
94    */
95   uint32_t payload_id;
96
97   /**
98    * Size of the message
99    */
100   size_t size;
101
102   /**
103    * Set when this message starts waiting for CORE.
104    */
105   struct GNUNET_TIME_Absolute start_waiting;
106
107   /**
108    * Function to call on sending.
109    */
110   GCP_sent cont;
111
112   /**
113    * Closure for callback.
114    */
115   void *cont_cls;
116 };
117
118
119 /**
120  * Struct containing all information regarding a given peer
121  */
122 struct CadetPeer
123 {
124   /**
125    * ID of the peer
126    */
127   GNUNET_PEER_Id id;
128
129   /**
130    * Last time we heard from this peer
131    */
132   struct GNUNET_TIME_Absolute last_contact;
133
134   /**
135    * Paths to reach the peer, ordered by ascending hop count
136    */
137   struct CadetPeerPath *path_head;
138
139   /**
140    * Paths to reach the peer, ordered by ascending hop count
141    */
142   struct CadetPeerPath *path_tail;
143
144   /**
145    * Handle to stop the DHT search for paths to this peer
146    */
147   struct GCD_search_handle *search_h;
148
149   /**
150    * Handle to stop the DHT search for paths to this peer
151    */
152   struct GNUNET_SCHEDULER_Task *search_delayed;
153
154   /**
155    * Tunnel to this peer, if any.
156    */
157   struct CadetTunnel *tunnel;
158
159   /**
160    * Connections that go through this peer; indexed by tid.
161    */
162   struct GNUNET_CONTAINER_MultiHashMap *connections;
163
164   /**
165    * Handle for queued transmissions
166    */
167   struct GNUNET_CORE_TransmitHandle *core_transmit;
168
169   /**
170    * Timestamp
171    */
172   struct GNUNET_TIME_Absolute tmt_time;
173
174   /**
175    * Transmission queue to core DLL head
176    */
177   struct CadetPeerQueue *queue_head;
178
179   /**
180    * Transmission queue to core DLL tail
181    */
182   struct CadetPeerQueue *queue_tail;
183
184   /**
185    * How many messages are in the queue to this peer.
186    */
187   unsigned int queue_n;
188
189   /**
190    * Hello message.
191    */
192   struct GNUNET_HELLO_Message* hello;
193
194   /**
195    * Handle to us offering the HELLO to the transport.
196    */
197   struct GNUNET_TRANSPORT_OfferHelloHandle *hello_offer;
198
199   /**
200    * Handle to our ATS request asking ATS to suggest an address
201    * to TRANSPORT for this peer (to establish a direct link).
202    */
203   struct GNUNET_ATS_ConnectivitySuggestHandle *connectivity_suggestion;
204
205 };
206
207
208 /******************************************************************************/
209 /*******************************   GLOBALS  ***********************************/
210 /******************************************************************************/
211
212 /**
213  * Global handle to the statistics service.
214  */
215 extern struct GNUNET_STATISTICS_Handle *stats;
216
217 /**
218  * Local peer own ID (full value).
219  */
220 extern struct GNUNET_PeerIdentity my_full_id;
221
222 /**
223  * Local peer own ID (short)
224  */
225 extern GNUNET_PEER_Id myid;
226
227 /**
228  * Peers known, indexed by PeerIdentity, values of type `struct CadetPeer`.
229  */
230 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
231
232 /**
233  * How many peers do we want to remember?
234  */
235 static unsigned long long max_peers;
236
237 /**
238  * Percentage of messages that will be dropped (for test purposes only).
239  */
240 static unsigned long long drop_percent;
241
242 /**
243  * Handle to communicate with CORE.
244  */
245 static struct GNUNET_CORE_Handle *core_handle;
246
247 /**
248  * Handle to communicate with ATS.
249  */
250 static struct GNUNET_ATS_ConnectivityHandle *ats_ch;
251
252 /**
253  * Handle to try to start new connections.
254  */
255 static struct GNUNET_TRANSPORT_Handle *transport_handle;
256
257 /**
258  * Shutdown falg.
259  */
260 static int in_shutdown;
261
262
263 /******************************************************************************/
264 /*****************************     DEBUG      *********************************/
265 /******************************************************************************/
266
267 /**
268  * Log all kinds of info about the queueing status of a peer.
269  *
270  * @param p Peer whose queue to show.
271  * @param level Error level to use for logging.
272  */
273 static void
274 queue_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
275 {
276   struct GNUNET_TIME_Relative core_wait_time;
277   struct CadetPeerQueue *q;
278   int do_log;
279
280   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
281                                        "cadet-p2p",
282                                        __FILE__, __FUNCTION__, __LINE__);
283   if (0 == do_log)
284     return;
285
286   LOG2 (level, "QQQ Message queue towards %s\n", GCP_2s (p));
287   LOG2 (level, "QQQ  queue length: %u\n", p->queue_n);
288   LOG2 (level, "QQQ  core tmt rdy: %p\n", p->core_transmit);
289   if (NULL != p->core_transmit)
290   {
291     core_wait_time = GNUNET_TIME_absolute_get_duration (p->tmt_time);
292     LOG2 (level, "QQQ  core called %s ago\n",
293           GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_NO));
294   }
295   for (q = p->queue_head; NULL != q; q = q->next)
296   {
297     LOG2 (level, "QQQ  - %s %s on %s\n",
298          GC_m2s (q->type), GC_f2s (q->fwd), GCC_2s (q->c));
299     LOG2 (level, "QQQ    payload %s, %u\n",
300          GC_m2s (q->payload_type), q->payload_id);
301     LOG2 (level, "QQQ    size: %u bytes\n", q->size);
302   }
303
304   LOG2 (level, "QQQ End queue towards %s\n", GCP_2s (p));
305 }
306
307
308 /**
309  * Log all kinds of info about a peer.
310  *
311  * @param peer Peer.
312  */
313 void
314 GCP_debug (const struct CadetPeer *p, enum GNUNET_ErrorType level)
315 {
316   struct CadetPeerPath *path;
317   unsigned int conns;
318   int do_log;
319
320   do_log = GNUNET_get_log_call_status (level & (~GNUNET_ERROR_TYPE_BULK),
321                                        "cadet-p2p",
322                                        __FILE__, __FUNCTION__, __LINE__);
323   if (0 == do_log)
324     return;
325
326   if (NULL == p)
327   {
328     LOG2 (level, "PPP DEBUG PEER NULL\n");
329     return;
330   }
331
332   LOG2 (level, "PPP DEBUG PEER %s\n", GCP_2s (p));
333   LOG2 (level, "PPP last contact %s\n",
334        GNUNET_STRINGS_absolute_time_to_string (p->last_contact));
335   for (path = p->path_head; NULL != path; path = path->next)
336   {
337     char *s;
338
339     s = path_2s (path);
340     LOG2 (level, "PPP path: %s\n", s);
341     GNUNET_free (s);
342   }
343
344   LOG2 (level, "PPP core transmit handle %p\n", p->core_transmit);
345   LOG2 (level, "PPP DHT GET handle %p\n", p->search_h);
346   conns = 0;
347   if (NULL != p->connections)
348     conns += GNUNET_CONTAINER_multihashmap_size (p->connections);
349   LOG2 (level, "PPP # connections over link to peer: %u\n", conns);
350   queue_debug (p, level);
351   LOG2 (level, "PPP DEBUG END\n");
352 }
353
354
355 /******************************************************************************/
356 /*****************************  CORE HELPERS  *********************************/
357 /******************************************************************************/
358
359
360 /**
361  * Iterator to notify all connections of a broken link. Mark connections
362  * to destroy after all traffic has been sent.
363  *
364  * @param cls Closure (disconnected peer).
365  * @param key Current key code (peer id).
366  * @param value Value in the hash map (connection).
367  *
368  * @return #GNUNET_YES to continue to iterate.
369  */
370 static int
371 notify_broken (void *cls,
372                const struct GNUNET_HashCode *key,
373                void *value)
374 {
375   struct CadetPeer *peer = cls;
376   struct CadetConnection *c = value;
377
378   LOG (GNUNET_ERROR_TYPE_DEBUG,
379        "Notifying %s due to %s disconnect\n",
380        GCC_2s (c), GCP_2s (peer));
381   GCC_neighbor_disconnected (c, peer);
382   return GNUNET_YES;
383 }
384
385
386 /**
387  * Remove the direct path to the peer.
388  *
389  * @param peer Peer to remove the direct path from.
390  */
391 static struct CadetPeerPath *
392 pop_direct_path (struct CadetPeer *peer)
393 {
394   struct CadetPeerPath *iter;
395
396   for (iter = peer->path_head; NULL != iter; iter = iter->next)
397   {
398     if (2 >= iter->length)
399     {
400       GNUNET_CONTAINER_DLL_remove (peer->path_head,
401                                    peer->path_tail,
402                                    iter);
403       return iter;
404     }
405   }
406   return NULL;
407 }
408
409
410 /******************************************************************************/
411 /***************************** CORE CALLBACKS *********************************/
412 /******************************************************************************/
413
414
415 /**
416  * Method called whenever a given peer connects.
417  *
418  * @param cls closure
419  * @param peer peer identity this notification is about
420  */
421 static void
422 core_connect (void *cls,
423               const struct GNUNET_PeerIdentity *peer)
424 {
425   struct CadetPeer *neighbor;
426   struct CadetPeerPath *path;
427   char own_id[16];
428
429   GCC_check_connections ();
430   GNUNET_snprintf (own_id,
431                    sizeof (own_id),
432                    "%s",
433                    GNUNET_i2s (&my_full_id));
434   neighbor = GCP_get (peer, GNUNET_YES);
435   if (myid == neighbor->id)
436   {
437     LOG (GNUNET_ERROR_TYPE_INFO,
438          "CONNECTED %s (self)\n",
439          own_id);
440     path = path_new (1);
441   }
442   else
443   {
444     LOG (GNUNET_ERROR_TYPE_INFO,
445          "CONNECTED %s <= %s\n",
446          own_id,
447          GNUNET_i2s (peer));
448     path = path_new (2);
449     path->peers[1] = neighbor->id;
450     GNUNET_PEER_change_rc (neighbor->id, 1);
451   }
452   path->peers[0] = myid;
453   GNUNET_PEER_change_rc (myid, 1);
454   GCP_add_path (neighbor, path, GNUNET_YES);
455
456   GNUNET_assert (NULL == neighbor->connections);
457   neighbor->connections = GNUNET_CONTAINER_multihashmap_create (16, GNUNET_NO);
458   GNUNET_assert (NULL != neighbor->connections);
459
460   GNUNET_STATISTICS_update (stats,
461                             "# peers",
462                             1,
463                             GNUNET_NO);
464
465   if ( (NULL != GCP_get_tunnel (neighbor)) &&
466        (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, peer)) )
467     GCP_connect (neighbor);
468   GCC_check_connections ();
469 }
470
471
472 /**
473  * Method called whenever a peer disconnects.
474  *
475  * @param cls closure
476  * @param peer peer identity this notification is about
477  */
478 static void
479 core_disconnect (void *cls,
480                  const struct GNUNET_PeerIdentity *peer)
481 {
482   struct CadetPeer *p;
483   struct CadetPeerPath *direct_path;
484   char own_id[16];
485
486   GCC_check_connections ();
487   strncpy (own_id, GNUNET_i2s (&my_full_id), 16);
488   own_id[15] = '\0';
489   p = GNUNET_CONTAINER_multipeermap_get (peers, peer);
490   if (NULL == p)
491   {
492     GNUNET_break (GNUNET_YES == in_shutdown);
493     return;
494   }
495   if (myid == p->id)
496     LOG (GNUNET_ERROR_TYPE_INFO,
497          "DISCONNECTED %s (self)\n",
498          own_id);
499   else
500     LOG (GNUNET_ERROR_TYPE_INFO,
501          "DISCONNECTED %s <= %s\n",
502          own_id, GNUNET_i2s (peer));
503   direct_path = pop_direct_path (p);
504   GNUNET_CONTAINER_multihashmap_iterate (p->connections,
505                                          &notify_broken,
506                                          p);
507   GNUNET_CONTAINER_multihashmap_destroy (p->connections);
508   p->connections = NULL;
509   if (NULL != p->core_transmit)
510   {
511     GNUNET_CORE_notify_transmit_ready_cancel (p->core_transmit);
512     p->core_transmit = NULL;
513     p->tmt_time.abs_value_us = 0;
514   }
515   GNUNET_STATISTICS_update (stats,
516                             "# peers",
517                             -1,
518                             GNUNET_NO);
519   path_destroy (direct_path);
520   GCC_check_connections ();
521 }
522
523
524 /**
525  * Functions to handle messages from core
526  */
527 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
528   {&GCC_handle_create, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0},
529   {&GCC_handle_confirm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
530     sizeof (struct GNUNET_CADET_ConnectionACK)},
531   {&GCC_handle_broken, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
532     sizeof (struct GNUNET_CADET_ConnectionBroken)},
533   {&GCC_handle_destroy, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
534     sizeof (struct GNUNET_CADET_ConnectionDestroy)},
535   {&GCC_handle_ack, GNUNET_MESSAGE_TYPE_CADET_ACK,
536     sizeof (struct GNUNET_CADET_ACK)},
537   {&GCC_handle_poll, GNUNET_MESSAGE_TYPE_CADET_POLL,
538     sizeof (struct GNUNET_CADET_Poll)},
539   {&GCC_handle_kx, GNUNET_MESSAGE_TYPE_CADET_KX, 0},
540   {&GCC_handle_encrypted, GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED, 0},
541   {&GCC_handle_encrypted, GNUNET_MESSAGE_TYPE_CADET_AX, 0},
542   {NULL, 0, 0}
543 };
544
545
546 /**
547  * To be called on core init/fail.
548  *
549  * @param cls Closure (config)
550  * @param identity the public identity of this peer
551  */
552 static void
553 core_init (void *cls,
554            const struct GNUNET_PeerIdentity *identity)
555 {
556   const struct GNUNET_CONFIGURATION_Handle *c = cls;
557   static int i = 0;
558
559   LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
560   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
561   {
562     LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
563     LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (identity));
564     LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
565     GNUNET_CORE_disconnect (core_handle);
566     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
567                                        NULL,      /* Closure passed to CADET functions */
568                                        &core_init,        /* Call core_init once connected */
569                                        &core_connect,     /* Handle connects */
570                                        &core_disconnect,  /* remove peers on disconnects */
571                                        NULL,      /* Don't notify about all incoming messages */
572                                        GNUNET_NO, /* For header only in notification */
573                                        NULL,      /* Don't notify about all outbound messages */
574                                        GNUNET_NO, /* For header-only out notification */
575                                        core_handlers);    /* Register these handlers */
576     if (10 < i++)
577       GNUNET_assert (0);
578   }
579   GML_start ();
580 }
581
582
583 /**
584   * Core callback to write a pre-constructed data packet to core buffer
585   *
586   * @param cls Closure (CadetTransmissionDescriptor with data in "data" member).
587   * @param size Number of bytes available in buf.
588   * @param buf Where the to write the message.
589   *
590   * @return number of bytes written to buf
591   */
592 static size_t
593 send_core_data_raw (void *cls, size_t size, void *buf)
594 {
595   struct GNUNET_MessageHeader *msg = cls;
596   size_t total_size;
597
598   GNUNET_assert (NULL != msg);
599   total_size = ntohs (msg->size);
600
601   if (total_size > size)
602   {
603     GNUNET_break (0);
604     return 0;
605   }
606   memcpy (buf, msg, total_size);
607   GNUNET_free (cls);
608   return total_size;
609 }
610
611
612 /**
613  * Function to send a create connection message to a peer.
614  *
615  * @param c Connection to create.
616  * @param size number of bytes available in buf
617  * @param buf where the callee should write the message
618  * @return number of bytes written to buf
619  */
620 static size_t
621 send_core_connection_create (struct CadetConnection *c, size_t size, void *buf)
622 {
623   struct GNUNET_CADET_ConnectionCreate *msg;
624   struct GNUNET_PeerIdentity *peer_ptr;
625   const struct CadetPeerPath *p = GCC_get_path (c);
626   size_t size_needed;
627   int i;
628
629   if (NULL == p)
630     return 0;
631
632   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
633   size_needed =
634       sizeof (struct GNUNET_CADET_ConnectionCreate) +
635       p->length * sizeof (struct GNUNET_PeerIdentity);
636
637   if (size < size_needed || NULL == buf)
638   {
639     GNUNET_break (0);
640     return 0;
641   }
642   msg = (struct GNUNET_CADET_ConnectionCreate *) buf;
643   msg->header.size = htons (size_needed);
644   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE);
645   msg->cid = *GCC_get_id (c);
646
647   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
648   for (i = 0; i < p->length; i++)
649   {
650     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
651   }
652
653   LOG (GNUNET_ERROR_TYPE_DEBUG,
654        "CONNECTION CREATE (%u bytes long) sent!\n",
655        size_needed);
656   return size_needed;
657 }
658
659
660 /**
661  * Creates a path ack message in buf and frees all unused resources.
662  *
663  * @param c Connection to send an ACK on.
664  * @param size number of bytes available in buf
665  * @param buf where the callee should write the message
666  *
667  * @return number of bytes written to buf
668  */
669 static size_t
670 send_core_connection_ack (struct CadetConnection *c, size_t size, void *buf)
671 {
672   struct GNUNET_CADET_ConnectionACK *msg = buf;
673
674   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
675   if (sizeof (struct GNUNET_CADET_ConnectionACK) > size)
676   {
677     GNUNET_break (0);
678     return 0;
679   }
680   msg->header.size = htons (sizeof (struct GNUNET_CADET_ConnectionACK));
681   msg->header.type = htons (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK);
682   msg->cid = *GCC_get_id (c);
683
684   LOG (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
685   return sizeof (struct GNUNET_CADET_ConnectionACK);
686 }
687
688
689 /******************************************************************************/
690 /********************************   STATIC  ***********************************/
691 /******************************************************************************/
692
693
694 /**
695  * Get priority for a queued message.
696  *
697  * @param q Queued message
698  *
699  * @return CORE priority to use.
700  */
701 static enum GNUNET_CORE_Priority
702 get_priority (struct CadetPeerQueue *q)
703 {
704   enum GNUNET_CORE_Priority low;
705   enum GNUNET_CORE_Priority high;
706
707   if (NULL == q)
708   {
709     GNUNET_break (0);
710     return GNUNET_CORE_PRIO_BACKGROUND;
711   }
712
713   /* Relayed traffic has lower priority, our own traffic has higher */
714   if (NULL == q->c || GNUNET_NO == GCC_is_origin (q->c, q->fwd))
715   {
716     low = GNUNET_CORE_PRIO_BEST_EFFORT;
717     high = GNUNET_CORE_PRIO_URGENT;
718   }
719   else
720   {
721     low = GNUNET_CORE_PRIO_URGENT;
722     high = GNUNET_CORE_PRIO_CRITICAL_CONTROL;
723   }
724
725   /* Bulky payload has lower priority, control traffic has higher. */
726   if (GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED == q->type
727       || GNUNET_MESSAGE_TYPE_CADET_AX == q->type)
728     return low;
729   else
730     return high;
731 }
732
733
734 /**
735  * Destroy the peer_info and free any allocated resources linked to it
736  *
737  * @param peer The peer_info to destroy.
738  * @return #GNUNET_OK on success
739  */
740 static int
741 peer_destroy (struct CadetPeer *peer)
742 {
743   struct GNUNET_PeerIdentity id;
744   struct CadetPeerPath *p;
745   struct CadetPeerPath *nextp;
746
747   GNUNET_PEER_resolve (peer->id, &id);
748   GNUNET_PEER_change_rc (peer->id, -1);
749
750   LOG (GNUNET_ERROR_TYPE_INFO,
751        "destroying peer %s\n",
752        GNUNET_i2s (&id));
753
754   if (GNUNET_YES !=
755       GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
756   {
757     GNUNET_break (0);
758     LOG (GNUNET_ERROR_TYPE_WARNING, " peer not in peermap!!\n");
759   }
760   GCP_stop_search (peer);
761   p = peer->path_head;
762   while (NULL != p)
763   {
764     nextp = p->next;
765     GNUNET_CONTAINER_DLL_remove (peer->path_head,
766                                  peer->path_tail,
767                                  p);
768     path_destroy (p);
769     p = nextp;
770   }
771   if (NULL != peer->tunnel)
772     GCT_destroy_empty (peer->tunnel);
773   if (NULL != peer->connections)
774   {
775     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (peer->connections));
776     GNUNET_CONTAINER_multihashmap_destroy (peer->connections);
777   }
778   if (NULL != peer->core_transmit)
779     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
780   if (NULL != peer->hello_offer)
781   {
782     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
783     peer->hello_offer = NULL;
784   }
785   if (NULL != peer->connectivity_suggestion)
786   {
787     GNUNET_ATS_connectivity_suggest_cancel (peer->connectivity_suggestion);
788     peer->connectivity_suggestion = NULL;
789   }
790   while (NULL != peer->queue_head)
791   {
792     GCP_queue_destroy (peer->queue_head, GNUNET_YES, GNUNET_NO, 0);
793   }
794   GNUNET_free_non_null (peer->hello);
795   GNUNET_free (peer);
796   return GNUNET_OK;
797 }
798
799
800 /**
801  * Iterator over peer hash map entries to destroy the peer during in_shutdown.
802  *
803  * @param cls closure
804  * @param key current key code
805  * @param value value in the hash map
806  * @return #GNUNET_YES if we should continue to iterate,
807  *         #GNUNET_NO if not.
808  */
809 static int
810 shutdown_peer (void *cls,
811                const struct GNUNET_PeerIdentity *key,
812                void *value)
813 {
814   struct CadetPeer *p = value;
815   struct CadetTunnel *t = p->tunnel;
816   LOG (GNUNET_ERROR_TYPE_DEBUG, "  shutting down %s\n", GCP_2s (p));
817   if (NULL != t)
818     GCT_destroy (t);
819   p->tunnel = NULL;
820   peer_destroy (p);
821   return GNUNET_YES;
822 }
823
824
825
826 /**
827  * Check if peer is searching for a path (either active or delayed search).
828  *
829  * @param peer Peer to check
830  * @return #GNUNET_YES if there is a search active.
831  *         #GNUNET_NO otherwise.
832  */
833 static int
834 is_searching (const struct CadetPeer *peer)
835 {
836   return ( (NULL == peer->search_h) &&
837            (NULL == peer->search_delayed) ) ?
838     GNUNET_NO : GNUNET_YES;
839 }
840
841
842 /**
843  * @brief Start a search for a peer.
844  *
845  * @param cls Closure (Peer to search for).
846  */
847 static void
848 delayed_search (void *cls)
849 {
850   struct CadetPeer *peer = cls;
851
852   peer->search_delayed = NULL;
853   GCC_check_connections ();
854   GCP_start_search (peer);
855   GCC_check_connections ();
856 }
857
858
859 /**
860  * Returns if peer is used (has a tunnel or is neighbor).
861  *
862  * @param peer Peer to check.
863  * @return #GNUNET_YES if peer is in use.
864  */
865 static int
866 peer_is_used (struct CadetPeer *peer)
867 {
868   struct CadetPeerPath *p;
869
870   if (NULL != peer->tunnel)
871     return GNUNET_YES;
872
873   for (p = peer->path_head; NULL != p; p = p->next)
874   {
875     if (p->length < 3)
876       return GNUNET_YES;
877   }
878     return GNUNET_NO;
879 }
880
881
882 /**
883  * Iterator over all the peers to get the oldest timestamp.
884  *
885  * @param cls Closure (unsued).
886  * @param key ID of the peer.
887  * @param value Peer_Info of the peer.
888  */
889 static int
890 peer_get_oldest (void *cls,
891                  const struct GNUNET_PeerIdentity *key,
892                  void *value)
893 {
894   struct CadetPeer *p = value;
895   struct GNUNET_TIME_Absolute *abs = cls;
896
897   /* Don't count active peers */
898   if (GNUNET_YES == peer_is_used (p))
899     return GNUNET_YES;
900
901   if (abs->abs_value_us < p->last_contact.abs_value_us)
902     abs->abs_value_us = p->last_contact.abs_value_us;
903
904   return GNUNET_YES;
905 }
906
907
908 /**
909  * Iterator over all the peers to remove the oldest entry.
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_timeout (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   LOG (GNUNET_ERROR_TYPE_WARNING,
924        "peer %s timeout\n", GNUNET_i2s (key));
925
926   if (p->last_contact.abs_value_us == abs->abs_value_us &&
927       GNUNET_NO == peer_is_used (p))
928   {
929     peer_destroy (p);
930     return GNUNET_NO;
931   }
932     return GNUNET_YES;
933 }
934
935
936 /**
937  * Delete oldest unused peer.
938  */
939 static void
940 peer_delete_oldest (void)
941 {
942   struct GNUNET_TIME_Absolute abs;
943
944   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
945
946   GNUNET_CONTAINER_multipeermap_iterate (peers,
947                                          &peer_get_oldest,
948                                          &abs);
949   GNUNET_CONTAINER_multipeermap_iterate (peers,
950                                          &peer_timeout,
951                                          &abs);
952 }
953
954
955 /**
956  * Choose the best (yet unused) path towards a peer,
957  * considering the tunnel properties.
958  *
959  * @param peer The destination peer.
960  * @return Best current known path towards the peer, if any.
961  */
962 static struct CadetPeerPath *
963 peer_get_best_path (const struct CadetPeer *peer)
964 {
965   struct CadetPeerPath *best_p;
966   struct CadetPeerPath *p;
967   unsigned int best_cost;
968   unsigned int cost;
969
970   best_cost = UINT_MAX;
971   best_p = NULL;
972   for (p = peer->path_head; NULL != p; p = p->next)
973   {
974     if (GNUNET_NO == path_is_valid (p))
975       continue; /* Don't use invalid paths. */
976     if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
977       continue; /* If path is already in use, skip it. */
978
979     if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
980     {
981       best_cost = cost;
982       best_p = p;
983     }
984   }
985   return best_p;
986 }
987
988
989 /**
990  * Is this queue element sendable?
991  *
992  * - All management traffic is always sendable.
993  * - For payload traffic, check the connection flow control.
994  *
995  * @param q Queue element to inspect.
996  * @return #GNUNET_YES if it is sendable, #GNUNET_NO otherwise.
997  */
998 static int
999 queue_is_sendable (struct CadetPeerQueue *q)
1000 {
1001   /* Is PID-independent? */
1002   switch (q->type)
1003   {
1004     case GNUNET_MESSAGE_TYPE_CADET_ACK:
1005     case GNUNET_MESSAGE_TYPE_CADET_POLL:
1006     case GNUNET_MESSAGE_TYPE_CADET_KX:
1007     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1008     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1009     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1010     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1011       return GNUNET_YES;
1012
1013     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1014     case GNUNET_MESSAGE_TYPE_CADET_AX:
1015       break;
1016
1017     default:
1018       GNUNET_break (0);
1019   }
1020
1021   return GCC_is_sendable (q->c, q->fwd);
1022 }
1023
1024
1025 /**
1026  * Get first sendable message.
1027  *
1028  * @param peer The destination peer.
1029  *
1030  * @return First transmittable message, if any. Otherwise, NULL.
1031  */
1032 static struct CadetPeerQueue *
1033 peer_get_first_message (const struct CadetPeer *peer)
1034 {
1035   struct CadetPeerQueue *q;
1036
1037   for (q = peer->queue_head; NULL != q; q = q->next)
1038   {
1039     LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking q:%p on c:%s\n", q, GCC_2s (q->c));
1040     if (queue_is_sendable (q))
1041       return q;
1042   }
1043
1044   return NULL;
1045 }
1046
1047
1048 /**
1049  * Function to process paths received for a new peer addition. The recorded
1050  * paths form the initial tunnel, which can be optimized later.
1051  * Called on each result obtained for the DHT search.
1052  *
1053  * @param cls Closure (peer towards a path has been found).
1054  * @param path Path created from the DHT query. Will be freed afterwards.
1055  */
1056 static void
1057 search_handler (void *cls, const struct CadetPeerPath *path)
1058 {
1059   struct CadetPeer *peer = cls;
1060   unsigned int connection_count;
1061
1062   GCC_check_connections ();
1063   GCP_add_path_to_all (path, GNUNET_NO);
1064
1065   /* Count connections */
1066   connection_count = GCT_count_connections (peer->tunnel);
1067
1068   /* If we already have our minimum (or more) connections, it's enough */
1069   if (CONNECTIONS_PER_TUNNEL <= connection_count)
1070   {
1071     GCC_check_connections ();
1072     return;
1073   }
1074
1075   if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
1076   {
1077     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
1078     GCP_connect (peer);
1079   }
1080   GCC_check_connections ();
1081 }
1082
1083
1084 /**
1085  * Adjust core requested size to accomodate an ACK.
1086  *
1087  * @param message_size Requested size.
1088  *
1089  * @return Size enough to fit @c message_size and an ACK.
1090  */
1091 static size_t
1092 get_core_size (size_t message_size)
1093 {
1094   return message_size + sizeof (struct GNUNET_CADET_ACK);
1095 }
1096
1097 /**
1098  * Test if a message type is connection management traffic
1099  * or regular payload traffic.
1100  *
1101  * @param type Message type.
1102  *
1103  * @return #GNUNET_YES if connection management, #GNUNET_NO otherwise.
1104  */
1105 static int
1106 is_connection_management (uint16_t type)
1107 {
1108   return type == GNUNET_MESSAGE_TYPE_CADET_ACK ||
1109          type == GNUNET_MESSAGE_TYPE_CADET_POLL;
1110 }
1111
1112
1113 /**
1114  * Fill a core buffer with the appropriate data for the queued message.
1115  *
1116  * @param queue Queue element for the message.
1117  * @param buf Core buffer to fill.
1118  * @param size Size remaining in @c buf.
1119  * @param[out] pid In case its an encrypted payload, set payload.
1120  *
1121  * @return Bytes written to @c buf.
1122  */
1123 static size_t
1124 fill_buf (struct CadetPeerQueue *queue, void *buf, size_t size, uint32_t *pid)
1125 {
1126   struct CadetConnection *c = queue->c;
1127   size_t msg_size;
1128
1129   switch (queue->type)
1130   {
1131     case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1132       *pid = GCC_get_pid (queue->c, queue->fwd);
1133       LOG (GNUNET_ERROR_TYPE_DEBUG, "  otr payload ID %u\n", *pid);
1134       msg_size = send_core_data_raw (queue->cls, size, buf);
1135       ((struct GNUNET_CADET_Encrypted *) buf)->pid = htonl (*pid);
1136       break;
1137     case GNUNET_MESSAGE_TYPE_CADET_AX:
1138       *pid = GCC_get_pid (queue->c, queue->fwd);
1139       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ax payload ID %u\n", *pid);
1140       msg_size = send_core_data_raw (queue->cls, size, buf);
1141       ((struct GNUNET_CADET_AX *) buf)->pid = htonl (*pid);
1142       break;
1143     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1144     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1145     case GNUNET_MESSAGE_TYPE_CADET_KX:
1146     case GNUNET_MESSAGE_TYPE_CADET_ACK:
1147     case GNUNET_MESSAGE_TYPE_CADET_POLL:
1148       LOG (GNUNET_ERROR_TYPE_DEBUG, "  raw %s\n", GC_m2s (queue->type));
1149       msg_size = send_core_data_raw (queue->cls, size, buf);
1150       break;
1151     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1152       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path create\n");
1153       if (GCC_is_origin (c, GNUNET_YES))
1154         msg_size = send_core_connection_create (c, size, buf);
1155       else
1156         msg_size = send_core_data_raw (queue->cls, size, buf);
1157       break;
1158     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1159       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path ack\n");
1160       if (GCC_is_origin (c, GNUNET_NO) ||
1161           GCC_is_origin (c, GNUNET_YES))
1162       {
1163         msg_size = send_core_connection_ack (c, size, buf);
1164       }
1165       else
1166       {
1167         msg_size = send_core_data_raw (queue->cls, size, buf);
1168       }
1169       break;
1170     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1171     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1172     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1173       /* This should be encapsulted */
1174       msg_size = 0;
1175       GNUNET_assert (0);
1176       break;
1177     default:
1178       GNUNET_break (0);
1179       LOG (GNUNET_ERROR_TYPE_WARNING, "  type unknown: %u\n", queue->type);
1180       msg_size = 0;
1181   }
1182
1183   GNUNET_assert (size >= msg_size);
1184
1185   return msg_size;
1186 }
1187
1188
1189 /**
1190  * Debug function should NEVER return true in production code, useful to
1191  * simulate losses for testcases.
1192  *
1193  * @param q Queue handle with info about the message.
1194  *
1195  * @return #GNUNET_YES or #GNUNET_NO with the decision to drop.
1196  */
1197 static int
1198 should_I_drop (struct CadetPeerQueue *q)
1199 {
1200   if (0 == drop_percent)
1201     return GNUNET_NO;
1202
1203   if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
1204     return GNUNET_YES;
1205
1206   return GNUNET_NO;
1207 }
1208
1209
1210 /**
1211  * Core callback to write a queued packet to core buffer
1212  *
1213  * @param cls Closure (peer info).
1214  * @param size Number of bytes available in buf.
1215  * @param buf Where the to write the message.
1216  *
1217  * @return number of bytes written to buf
1218  */
1219 static size_t
1220 queue_send (void *cls, size_t size, void *buf)
1221 {
1222   struct CadetPeer *peer = cls;
1223   struct CadetConnection *c;
1224   struct CadetPeerQueue *queue;
1225   struct GNUNET_TIME_Relative core_wait_time;
1226   const char *wait_s;
1227   const struct GNUNET_PeerIdentity *dst_id;
1228   size_t msg_size;
1229   size_t total_size;
1230   size_t rest;
1231   char *dst;
1232   uint32_t pid;
1233
1234   GCC_check_connections ();
1235   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1236   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1237   LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue send towards %s (max %u)\n",
1238        GCP_2s (peer), size);
1239
1240   /* Sanity checking */
1241   if (NULL == buf || 0 == size)
1242   {
1243     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not allowed/\n");
1244     if (GNUNET_NO == in_shutdown)
1245     {
1246       queue = peer_get_first_message (peer);
1247       if (NULL == queue)
1248       {
1249         peer->core_transmit = NULL;
1250         peer->tmt_time.abs_value_us = 0;
1251         GCC_check_connections ();
1252         return 0;
1253       }
1254       dst_id = GNUNET_PEER_resolve2 (peer->id);
1255       peer->core_transmit =
1256           GNUNET_CORE_notify_transmit_ready (core_handle,
1257                                              GNUNET_NO, get_priority (queue),
1258                                              GNUNET_TIME_UNIT_FOREVER_REL,
1259                                              dst_id,
1260                                              get_core_size (queue->size),
1261                                              &queue_send,
1262                                              peer);
1263       peer->tmt_time = GNUNET_TIME_absolute_get ();
1264     }
1265     else
1266     {
1267       peer->core_transmit = NULL;
1268       peer->tmt_time.abs_value_us = 0;
1269     }
1270     GCC_check_connections ();
1271     return 0;
1272   }
1273
1274   /* Init */
1275   rest = size;
1276   total_size = 0;
1277   dst = (char *) buf;
1278   pid = 0;
1279   peer->core_transmit = NULL;
1280   queue = peer_get_first_message (peer);
1281   if (NULL == queue)
1282   {
1283     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
1284     peer->tmt_time.abs_value_us = 0;
1285     return 0;
1286   }
1287   core_wait_time = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1288   wait_s = GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_YES);
1289   if (core_wait_time.rel_value_us >= 1000000)
1290   {
1291     LOG (GNUNET_ERROR_TYPE_WARNING,
1292          " %s: core wait time %s (> 1 second) for %u bytes\n",
1293          GCP_2s (peer), wait_s, queue->size);
1294   }
1295   peer->tmt_time.abs_value_us = 0;
1296
1297   /* Copy all possible messages to the core buffer */
1298   while (NULL != queue && rest >= queue->size)
1299   {
1300     c = queue->c;
1301
1302     LOG (GNUNET_ERROR_TYPE_DEBUG, "  on conn %s %s\n",
1303          GCC_2s (c), GC_f2s(queue->fwd));
1304     LOG (GNUNET_ERROR_TYPE_DEBUG, "  size %u ok (%u/%u)\n",
1305          queue->size, total_size, size);
1306
1307     msg_size = fill_buf (queue, (void *) dst, size, &pid);
1308
1309     if (should_I_drop (queue))
1310     {
1311       LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on conn %s %s\n",
1312            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1313            queue->payload_id, GCC_2s (c), GC_f2s (queue->fwd));
1314       msg_size = 0;
1315     }
1316     else
1317     {
1318       LOG (GNUNET_ERROR_TYPE_INFO,
1319            ">>> %s (%s %4u) on conn %s (%p) %s [%5u], after %s\n",
1320            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1321            queue->payload_id, GCC_2s (c), c,
1322            GC_f2s (queue->fwd), msg_size, wait_s);
1323     }
1324     total_size += msg_size;
1325     rest -= msg_size;
1326     dst = &dst[msg_size];
1327     msg_size = 0;
1328
1329     /* Free queue, but cls was freed by send_core_* in fill_buf. */
1330     (void) GCP_queue_destroy (queue, GNUNET_NO, GNUNET_YES, pid);
1331
1332     /* Next! */
1333     queue = peer_get_first_message (peer);
1334   }
1335
1336   /* If more data in queue, send next */
1337   if (NULL != queue)
1338   {
1339     LOG (GNUNET_ERROR_TYPE_DEBUG, "  more data! (%u)\n", queue->size);
1340     if (NULL == peer->core_transmit)
1341     {
1342       dst_id = GNUNET_PEER_resolve2 (peer->id);
1343       peer->core_transmit =
1344           GNUNET_CORE_notify_transmit_ready (core_handle,
1345                                              GNUNET_NO, get_priority (queue),
1346                                              GNUNET_TIME_UNIT_FOREVER_REL,
1347                                              dst_id,
1348                                              get_core_size (queue->size),
1349                                              &queue_send,
1350                                              peer);
1351       peer->tmt_time = GNUNET_TIME_absolute_get ();
1352       queue->start_waiting = GNUNET_TIME_absolute_get ();
1353     }
1354     else
1355     {
1356       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   tmt rdy called somewhere else\n");
1357     }
1358 //     GCC_start_poll (); FIXME needed?
1359   }
1360   else
1361   {
1362 //     GCC_stop_poll(); FIXME needed?
1363   }
1364
1365   LOG (GNUNET_ERROR_TYPE_DEBUG, "  return %d\n", total_size);
1366   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1367   GCC_check_connections ();
1368   return total_size;
1369 }
1370
1371
1372 /******************************************************************************/
1373 /********************************    API    ***********************************/
1374 /******************************************************************************/
1375
1376
1377 /**
1378  * Free a transmission that was already queued with all resources
1379  * associated to the request.
1380  *
1381  * If connection was marked to be destroyed, and this was the last queued
1382  * message on it, the connection will be free'd as a result.
1383  *
1384  * @param queue Queue handler to cancel.
1385  * @param clear_cls Is it necessary to free associated cls?
1386  * @param sent Was it really sent? (Could have been canceled)
1387  * @param pid PID, if relevant (was sent and was a payload message).
1388  *
1389  * @return #GNUNET_YES if connection was destroyed as a result,
1390  *         #GNUNET_NO otherwise.
1391  */
1392 int
1393 GCP_queue_destroy (struct CadetPeerQueue *queue,
1394                    int clear_cls,
1395                    int sent,
1396                    uint32_t pid)
1397 {
1398   struct CadetPeer *peer;
1399   int connection_destroyed;
1400
1401   GCC_check_connections ();
1402   peer = queue->peer;
1403   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue destroy %s\n", GC_m2s (queue->type));
1404   if (GNUNET_YES == clear_cls)
1405   {
1406     LOG (GNUNET_ERROR_TYPE_DEBUG, " free cls\n");
1407     switch (queue->type)
1408     {
1409       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1410         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
1411         /* fall through */
1412       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1413       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1414       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1415       case GNUNET_MESSAGE_TYPE_CADET_KX:
1416       case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1417       case GNUNET_MESSAGE_TYPE_CADET_AX:
1418       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1419       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1420         GNUNET_free_non_null (queue->cls);
1421         break;
1422
1423       default:
1424         GNUNET_break (0);
1425         LOG (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
1426              GC_m2s (queue->type));
1427     }
1428   }
1429   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
1430
1431   if (!is_connection_management (queue->type))
1432   {
1433     peer->queue_n--;
1434   }
1435
1436   if (NULL != queue->cont)
1437   {
1438     struct GNUNET_TIME_Relative wait_time;
1439
1440     wait_time = GNUNET_TIME_absolute_get_duration (queue->start_waiting);
1441     LOG (GNUNET_ERROR_TYPE_DEBUG, " calling callback, time elapsed %s\n",
1442          GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
1443     connection_destroyed = queue->cont (queue->cont_cls,
1444                                         queue->c, sent, queue->type, pid,
1445                                         queue->fwd, queue->size, wait_time);
1446   }
1447   else
1448   {
1449     connection_destroyed = GNUNET_NO;
1450   }
1451
1452   if (NULL == peer_get_first_message (peer) && NULL != peer->core_transmit)
1453   {
1454     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1455     peer->core_transmit = NULL;
1456     peer->tmt_time.abs_value_us = 0;
1457   }
1458
1459   GNUNET_free (queue);
1460   GCC_check_connections ();
1461   return connection_destroyed;
1462 }
1463
1464
1465 /**
1466  * @brief Queue and pass message to core when possible.
1467  *
1468  * @param peer Peer towards which to queue the message.
1469  * @param cls Closure (@c type dependant). It will be used by queue_send to
1470  *            build the message to be sent if not already prebuilt.
1471  * @param type Type of the message.
1472  * @param payload_type Type of the message's payload
1473  *                     0 if the message is a retransmission (unknown payload).
1474  *                     UINT16_MAX if the message does not have payload.
1475  * @param payload_id ID of the payload (MID, ACK #, etc)
1476  * @param size Size of the message.
1477  * @param c Connection this message belongs to (can be NULL).
1478  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1479  * @param cont Continuation to be called once CORE has taken the message.
1480  * @param cont_cls Closure for @c cont.
1481  *
1482  * @return Handle to cancel the message before it is sent. Once cont is called
1483  *         message has been sent and therefore the handle is no longer valid.
1484  */
1485 struct CadetPeerQueue *
1486 GCP_queue_add (struct CadetPeer *peer,
1487                void *cls,
1488                uint16_t type,
1489                uint16_t payload_type,
1490                uint32_t payload_id,
1491                size_t size,
1492                struct CadetConnection *c,
1493                int fwd,
1494                GCP_sent cont,
1495                void *cont_cls)
1496 {
1497   struct CadetPeerQueue *q;
1498   int priority;
1499   int call_core;
1500
1501   GCC_check_connections ();
1502   LOG (GNUNET_ERROR_TYPE_DEBUG,
1503        "que %s (%s %4u) on conn %s (%p) %s towards %s (size %u)\n",
1504        GC_m2s (type), GC_m2s (payload_type), payload_id,
1505        GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1506
1507   if (NULL == peer->connections)
1508   {
1509     /* We are not connected to this peer, ignore request. */
1510     LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
1511     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1512                               GNUNET_NO);
1513     return NULL;
1514   }
1515
1516   priority = 0;
1517   if (is_connection_management (type))
1518   {
1519     priority = 100;
1520   }
1521   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1522
1523   call_core = (NULL == c || GNUNET_MESSAGE_TYPE_CADET_KX == type) ?
1524                GNUNET_YES : GCC_is_sendable (c, fwd);
1525   q = GNUNET_new (struct CadetPeerQueue);
1526   q->cls = cls;
1527   q->type = type;
1528   q->payload_type = payload_type;
1529   q->payload_id = payload_id;
1530   q->size = size;
1531   q->peer = peer;
1532   q->c = c;
1533   q->fwd = fwd;
1534   q->cont = cont;
1535   q->cont_cls = cont_cls;
1536   if (100 > priority)
1537   {
1538     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, q);
1539     peer->queue_n++;
1540   }
1541   else
1542   {
1543     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, q);
1544     call_core = GNUNET_YES;
1545   }
1546
1547   q->start_waiting = GNUNET_TIME_absolute_get ();
1548   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1549   {
1550     LOG (GNUNET_ERROR_TYPE_DEBUG,
1551          "calling core tmt rdy towards %s for %u bytes\n",
1552          GCP_2s (peer), size);
1553     peer->core_transmit =
1554         GNUNET_CORE_notify_transmit_ready (core_handle,
1555                                            GNUNET_NO, get_priority (q),
1556                                            GNUNET_TIME_UNIT_FOREVER_REL,
1557                                            GNUNET_PEER_resolve2 (peer->id),
1558                                            get_core_size (size),
1559                                            &queue_send, peer);
1560     peer->tmt_time = GNUNET_TIME_absolute_get ();
1561   }
1562   else if (GNUNET_NO == call_core)
1563   {
1564     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s not needed\n",
1565          GCP_2s (peer));
1566
1567   }
1568   else
1569   {
1570     struct GNUNET_TIME_Relative elapsed;
1571     elapsed = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1572     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s already called %s\n",
1573          GCP_2s (peer),
1574          GNUNET_STRINGS_relative_time_to_string (elapsed, GNUNET_NO));
1575
1576   }
1577   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1578   GCC_check_connections ();
1579   return q;
1580 }
1581
1582
1583 /**
1584  * Cancel all queued messages to a peer that belong to a certain connection.
1585  *
1586  * @param peer Peer towards whom to cancel.
1587  * @param c Connection whose queued messages to cancel. Might be destroyed by
1588  *          the sent continuation call.
1589  */
1590 void
1591 GCP_queue_cancel (struct CadetPeer *peer,
1592                   struct CadetConnection *c)
1593 {
1594   struct CadetPeerQueue *q;
1595   struct CadetPeerQueue *next;
1596   struct CadetPeerQueue *prev;
1597   int connection_destroyed;
1598
1599   GCC_check_connections ();
1600   connection_destroyed = GNUNET_NO;
1601   for (q = peer->queue_head; NULL != q; q = next)
1602   {
1603     prev = q->prev;
1604     if (q->c == c)
1605     {
1606       LOG (GNUNET_ERROR_TYPE_DEBUG,
1607            "GMP queue cancel %s\n",
1608            GC_m2s (q->type));
1609       GNUNET_assert (GNUNET_NO == connection_destroyed);
1610       if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY == q->type)
1611       {
1612         q->c = NULL;
1613       }
1614       else
1615       {
1616         connection_destroyed = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1617       }
1618
1619       /* Get next from prev, q->next might be already freed:
1620        * queue destroy -> callback -> GCC_destroy -> cancel_queues -> here
1621        */
1622       if (NULL == prev)
1623         next = peer->queue_head;
1624       else
1625         next = prev->next;
1626     }
1627     else
1628     {
1629       next = q->next;
1630     }
1631   }
1632
1633   if ( (NULL == peer->queue_head) &&
1634        (NULL != peer->core_transmit) )
1635   {
1636     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1637     peer->core_transmit = NULL;
1638     peer->tmt_time.abs_value_us = 0;
1639   }
1640   GCC_check_connections ();
1641 }
1642
1643
1644 /**
1645  * Get the first transmittable message for a connection.
1646  *
1647  * @param peer Neighboring peer.
1648  * @param c Connection.
1649  *
1650  * @return First transmittable message.
1651  */
1652 static struct CadetPeerQueue *
1653 connection_get_first_message (struct CadetPeer *peer, struct CadetConnection *c)
1654 {
1655   struct CadetPeerQueue *q;
1656
1657   for (q = peer->queue_head; NULL != q; q = q->next)
1658   {
1659     if (q->c != c)
1660       continue;
1661     if (queue_is_sendable (q))
1662     {
1663       LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
1664       return q;
1665     }
1666     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
1667   }
1668
1669   return NULL;
1670 }
1671
1672
1673 /**
1674  * Get the first message for a connection and unqueue it.
1675  *
1676  * Only tunnel (or higher) level messages are unqueued. Connection specific
1677  * messages are silently destroyed upon encounter.
1678  *
1679  * @param peer Neighboring peer.
1680  * @param c Connection.
1681  * @param destroyed[in/out] Was the connection destroyed (prev/as a result)?.
1682  *                          Can NOT be NULL.
1683  *
1684  * @return First message for this connection.
1685  */
1686 struct GNUNET_MessageHeader *
1687 GCP_connection_pop (struct CadetPeer *peer,
1688                     struct CadetConnection *c,
1689                     int *destroyed)
1690 {
1691   struct CadetPeerQueue *q;
1692   struct CadetPeerQueue *next;
1693   struct GNUNET_MessageHeader *msg;
1694   int dest;
1695
1696   GCC_check_connections ();
1697   GNUNET_assert (NULL != destroyed);
1698   LOG (GNUNET_ERROR_TYPE_DEBUG, "connection_pop on conn %p\n", c);
1699   for (q = peer->queue_head; NULL != q; q = next)
1700   {
1701     next = q->next;
1702     if (q->c != c)
1703       continue;
1704     LOG (GNUNET_ERROR_TYPE_DEBUG, " - queued: %s (%s %u), cont: %p\n",
1705          GC_m2s (q->type), GC_m2s (q->payload_type), q->payload_id,
1706          q->cont);
1707     switch (q->type)
1708     {
1709       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1710       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1711       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1712       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1713       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1714       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1715         dest = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1716         if (GNUNET_YES == dest)
1717         {
1718           GNUNET_break (GNUNET_NO == *destroyed);
1719           *destroyed = GNUNET_YES;
1720         }
1721         continue;
1722
1723       case GNUNET_MESSAGE_TYPE_CADET_KX:
1724       case GNUNET_MESSAGE_TYPE_CADET_ENCRYPTED:
1725       case GNUNET_MESSAGE_TYPE_CADET_AX:
1726       case GNUNET_MESSAGE_TYPE_CADET_AX_KX:
1727         msg = (struct GNUNET_MessageHeader *) q->cls;
1728         dest = GCP_queue_destroy (q, GNUNET_NO, GNUNET_NO, 0);
1729         if (GNUNET_YES == dest)
1730         {
1731           GNUNET_break (GNUNET_NO == *destroyed);
1732           *destroyed = GNUNET_YES;
1733         }
1734         return msg;
1735
1736       default:
1737         GNUNET_break (0);
1738         LOG (GNUNET_ERROR_TYPE_DEBUG, "Unknown message %s\n", GC_m2s (q->type));
1739     }
1740   }
1741   GCC_check_connections ();
1742   return NULL;
1743 }
1744
1745
1746 /**
1747  * Unlock a possibly locked queue for a connection.
1748  *
1749  * If there is a message that can be sent on this connection, call core for it.
1750  * Otherwise (if core transmit is already called or there is no sendable
1751  * message) do nothing.
1752  *
1753  * @param peer Peer who keeps the queue.
1754  * @param c Connection whose messages to unlock.
1755  */
1756 void
1757 GCP_queue_unlock (struct CadetPeer *peer, struct CadetConnection *c)
1758 {
1759   struct CadetPeerQueue *q;
1760   size_t size;
1761
1762   GCC_check_connections ();
1763   if (NULL != peer->core_transmit)
1764   {
1765     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
1766     return; /* Already unlocked */
1767   }
1768
1769   q = connection_get_first_message (peer, c);
1770   if (NULL == q)
1771   {
1772     LOG (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
1773     return; /* Nothing to transmit */
1774   }
1775
1776   size = q->size;
1777   peer->core_transmit =
1778       GNUNET_CORE_notify_transmit_ready (core_handle,
1779                                          GNUNET_NO, get_priority (q),
1780                                          GNUNET_TIME_UNIT_FOREVER_REL,
1781                                          GNUNET_PEER_resolve2 (peer->id),
1782                                          get_core_size (size),
1783                                          &queue_send,
1784                                          peer);
1785   peer->tmt_time = GNUNET_TIME_absolute_get ();
1786   GCC_check_connections ();
1787 }
1788
1789
1790 /**
1791  * Initialize the peer subsystem.
1792  *
1793  * @param c Configuration.
1794  */
1795 void
1796 GCP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1797 {
1798   LOG (GNUNET_ERROR_TYPE_DEBUG,
1799        "GCP_init\n");
1800   in_shutdown = GNUNET_NO;
1801   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1802   if (GNUNET_OK !=
1803       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1804                                              &max_peers))
1805   {
1806     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1807                                "CADET", "MAX_PEERS", "USING DEFAULT");
1808     max_peers = 1000;
1809   }
1810
1811   if (GNUNET_OK !=
1812       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1813                                              &drop_percent))
1814   {
1815     drop_percent = 0;
1816   }
1817   else
1818   {
1819     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1820     LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1821     LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1822     LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1823     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1824   }
1825   ats_ch = GNUNET_ATS_connectivity_init (c);
1826   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1827                                      NULL,      /* Closure passed to CADET functions */
1828                                      &core_init,        /* Call core_init once connected */
1829                                      &core_connect,     /* Handle connects */
1830                                      &core_disconnect,  /* remove peers on disconnects */
1831                                      NULL,      /* Don't notify about all incoming messages */
1832                                      GNUNET_NO, /* For header only in notification */
1833                                      NULL,      /* Don't notify about all outbound messages */
1834                                      GNUNET_NO, /* For header-only out notification */
1835                                      core_handlers);    /* Register these handlers */
1836   if (GNUNET_YES !=
1837       GNUNET_CONFIGURATION_get_value_yesno (c, "CADET", "DISABLE_TRY_CONNECT"))
1838   {
1839     transport_handle = GNUNET_TRANSPORT_connect (c, &my_full_id, NULL, /* cls */
1840                                                  /* Notify callbacks */
1841                                                  NULL, NULL, NULL);
1842   }
1843   else
1844   {
1845     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1846     LOG (GNUNET_ERROR_TYPE_WARNING, "*  DISABLE TRYING CONNECT in config  *\n");
1847     LOG (GNUNET_ERROR_TYPE_WARNING, "*  Use this only for test purposes.  *\n");
1848     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1849     transport_handle = NULL;
1850   }
1851
1852
1853
1854   if (NULL == core_handle)
1855   {
1856     GNUNET_break (0);
1857     GNUNET_SCHEDULER_shutdown ();
1858     return;
1859   }
1860
1861 }
1862
1863
1864 /**
1865  * Shut down the peer subsystem.
1866  */
1867 void
1868 GCP_shutdown (void)
1869 {
1870   LOG (GNUNET_ERROR_TYPE_DEBUG,
1871        "Shutting down peer subsystem\n");
1872   in_shutdown = GNUNET_YES;
1873   GNUNET_CONTAINER_multipeermap_iterate (peers,
1874                                          &shutdown_peer,
1875                                          NULL);
1876   if (NULL != core_handle)
1877   {
1878     GNUNET_CORE_disconnect (core_handle);
1879     core_handle = NULL;
1880   }
1881   if (NULL != transport_handle)
1882   {
1883     GNUNET_TRANSPORT_disconnect (transport_handle);
1884     transport_handle = NULL;
1885   }
1886   if (NULL != ats_ch)
1887   {
1888     GNUNET_ATS_connectivity_done (ats_ch);
1889     ats_ch = NULL;
1890   }
1891   GNUNET_PEER_change_rc (myid, -1);
1892   GNUNET_CONTAINER_multipeermap_destroy (peers);
1893   peers = NULL;
1894 }
1895
1896
1897 /**
1898  * Retrieve the CadetPeer stucture associated with the peer. Optionally create
1899  * one and insert it in the appropriate structures if the peer is not known yet.
1900  *
1901  * @param peer_id Full identity of the peer.
1902  * @param create #GNUNET_YES if a new peer should be created if unknown.
1903  *               #GNUNET_NO otherwise.
1904  *
1905  * @return Existing or newly created peer structure.
1906  *         NULL if unknown and not requested @a create
1907  */
1908 struct CadetPeer *
1909 GCP_get (const struct GNUNET_PeerIdentity *peer_id, int create)
1910 {
1911   struct CadetPeer *peer;
1912
1913   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1914   if (NULL == peer)
1915   {
1916     peer = GNUNET_new (struct CadetPeer);
1917     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1918     {
1919       peer_delete_oldest ();
1920     }
1921     GNUNET_assert (GNUNET_OK ==
1922                    GNUNET_CONTAINER_multipeermap_put (peers,
1923                                                       peer_id,
1924                                                       peer,
1925                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1926     peer->id = GNUNET_PEER_intern (peer_id);
1927   }
1928   peer->last_contact = GNUNET_TIME_absolute_get ();
1929
1930   return peer;
1931 }
1932
1933
1934 /**
1935  * Retrieve the CadetPeer stucture associated with the
1936  * peer. Optionally create one and insert it in the appropriate
1937  * structures if the peer is not known yet.
1938  *
1939  * @param peer Short identity of the peer.
1940  * @param create #GNUNET_YES if a new peer should be created if unknown.
1941  *               #GNUNET_NO otherwise.
1942  *
1943  * @return Existing or newly created peer structure.
1944  *         NULL if unknown and not requested @a create
1945  */
1946 struct CadetPeer *
1947 GCP_get_short (const GNUNET_PEER_Id peer, int create)
1948 {
1949   return GCP_get (GNUNET_PEER_resolve2 (peer), create);
1950 }
1951
1952
1953 /**
1954  * Function called once #GNUNET_TRANSPORT_offer_hello() is done.
1955  * Marks the operation as finished.
1956  *
1957  * @param cls Closure (our `struct CadetPeer`).
1958  */
1959 static void
1960 hello_offer_done (void *cls)
1961 {
1962   struct CadetPeer *peer = cls;
1963
1964   peer->hello_offer = NULL;
1965 }
1966
1967
1968 /**
1969  * Try to establish a new connection to this peer (in its tunnel).
1970  * If the peer doesn't have any path to it yet, try to get one.
1971  * If the peer already has some path, send a CREATE CONNECTION towards it.
1972  *
1973  * @param peer Peer to connect to.
1974  */
1975 void
1976 GCP_connect (struct CadetPeer *peer)
1977 {
1978   struct CadetTunnel *t;
1979   struct CadetPeerPath *path;
1980   struct CadetConnection *c;
1981   int rerun_search;
1982
1983   GCC_check_connections ();
1984   LOG (GNUNET_ERROR_TYPE_DEBUG,
1985        "peer_connect towards %s\n",
1986        GCP_2s (peer));
1987   /* If we have a current hello, try to connect using it. */
1988   GCP_try_connect (peer);
1989
1990   t = peer->tunnel;
1991   c = NULL;
1992   rerun_search = GNUNET_NO;
1993
1994   if (NULL != peer->path_head)
1995   {
1996     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1997     path = peer_get_best_path (peer);
1998     if (NULL != path)
1999     {
2000       char *s;
2001
2002       s = path_2s (path);
2003       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
2004       GNUNET_free (s);
2005
2006       c = GCT_use_path (t, path);
2007       if (NULL == c)
2008       {
2009         /* This case can happen when the path includes a first hop that is
2010          * not yet known to be connected.
2011          *
2012          * This happens quite often during testing when running cadet
2013          * under valgrind: core connect notifications come very late
2014          * and the DHT result has already come and created a valid
2015          * path.  In this case, the peer->connections
2016          * hashmaps will be NULL and tunnel_use_path will not be able
2017          * to create a connection from that path.
2018          *
2019          * Re-running the DHT GET should give core time to callback.
2020          *
2021          * GCT_use_path -> GCC_new -> register_neighbors takes care of
2022          * updating statistics about this issue.
2023          */
2024         rerun_search = GNUNET_YES;
2025       }
2026       else
2027       {
2028         GCC_send_create (c);
2029         return;
2030       }
2031     }
2032     else
2033     {
2034       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
2035     }
2036   }
2037
2038   if (GNUNET_YES == rerun_search)
2039   {
2040     struct GNUNET_TIME_Relative delay;
2041
2042     GCP_stop_search (peer);
2043     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
2044     peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay,
2045                                                          &delayed_search,
2046                                                          peer);
2047     GCC_check_connections ();
2048     return;
2049   }
2050
2051   if (GNUNET_NO == is_searching (peer))
2052     GCP_start_search (peer);
2053   GCC_check_connections ();
2054 }
2055
2056
2057 /**
2058  * Chech whether there is a direct (core level)  connection to peer.
2059  *
2060  * @param peer Peer to check.
2061  *
2062  * @return #GNUNET_YES if there is a direct connection.
2063  */
2064 int
2065 GCP_is_neighbor (const struct CadetPeer *peer)
2066 {
2067   struct CadetPeerPath *path;
2068
2069   if (NULL == peer->connections)
2070     return GNUNET_NO;
2071
2072   for (path = peer->path_head; NULL != path; path = path->next)
2073   {
2074     if (3 > path->length)
2075       return GNUNET_YES;
2076   }
2077
2078   /* Is not a neighbor but connections is not NULL, probably disconnecting */
2079   GNUNET_break (0);
2080   return GNUNET_NO;
2081 }
2082
2083
2084 /**
2085  * Create and initialize a new tunnel towards a peer, in case it has none.
2086  * In case the peer already has a tunnel, nothing is done.
2087  *
2088  * Does not generate any traffic, just creates the local data structures.
2089  *
2090  * @param peer Peer towards which to create the tunnel.
2091  */
2092 void
2093 GCP_add_tunnel (struct CadetPeer *peer)
2094 {
2095   GCC_check_connections ();
2096   if (NULL != peer->tunnel)
2097     return;
2098   peer->tunnel = GCT_new (peer);
2099   GCC_check_connections ();
2100 }
2101
2102
2103 /**
2104  * Add a connection to a neighboring peer.
2105  *
2106  * Store that the peer is the first hop of the connection in one
2107  * direction and that on peer disconnect the connection must be
2108  * notified and destroyed, for it will no longer be valid.
2109  *
2110  * @param peer Peer to add connection to.
2111  * @param c Connection to add.
2112  * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
2113  */
2114 void
2115 GCP_add_connection (struct CadetPeer *peer,
2116                     struct CadetConnection *c,
2117                     int pred)
2118 {
2119   LOG (GNUNET_ERROR_TYPE_DEBUG,
2120        "adding connection %s\n",
2121        GCC_2s (c));
2122   LOG (GNUNET_ERROR_TYPE_DEBUG,
2123        "to peer %s\n",
2124        GCP_2s (peer));
2125   GNUNET_assert (NULL != peer->connections);
2126   GNUNET_assert (GNUNET_OK ==
2127                  GNUNET_CONTAINER_multihashmap_put (peer->connections,
2128                                                     GCC_get_h (c),
2129                                                     c,
2130                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2131   LOG (GNUNET_ERROR_TYPE_DEBUG,
2132        "Peer %s has now %u connections.\n",
2133        GCP_2s (peer),
2134        GNUNET_CONTAINER_multihashmap_size (peer->connections));
2135 }
2136
2137
2138 /**
2139  * Add the path to the peer and update the path used to reach it in case this
2140  * is the shortest.
2141  *
2142  * @param peer Destination peer to add the path to.
2143  * @param path New path to add. Last peer must be @c peer.
2144  *             Path will be either used of freed if already known.
2145  * @param trusted Do we trust that this path is real?
2146  *
2147  * @return path if path was taken, pointer to existing duplicate if exists
2148  *         NULL on error.
2149  */
2150 struct CadetPeerPath *
2151 GCP_add_path (struct CadetPeer *peer,
2152               struct CadetPeerPath *path,
2153               int trusted)
2154 {
2155   struct CadetPeerPath *aux;
2156   unsigned int l;
2157   unsigned int l2;
2158
2159   GCC_check_connections ();
2160   LOG (GNUNET_ERROR_TYPE_DEBUG,
2161        "adding path [%u] to peer %s\n",
2162        path->length, GCP_2s (peer));
2163
2164   if (NULL == peer || NULL == path
2165       || path->peers[path->length - 1] != peer->id)
2166   {
2167     GNUNET_break (0);
2168     path_destroy (path);
2169     return NULL;
2170   }
2171
2172   for (l = 1; l < path->length; l++)
2173   {
2174     if (path->peers[l] == myid)
2175     {
2176       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
2177       for (l2 = 0; l2 < path->length - l; l2++)
2178       {
2179         path->peers[l2] = path->peers[l + l2];
2180       }
2181       path->length -= l;
2182       l = 1;
2183       path->peers = GNUNET_realloc (path->peers,
2184                                     path->length * sizeof (GNUNET_PEER_Id));
2185     }
2186   }
2187
2188   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
2189
2190   if (2 >= path->length && GNUNET_NO == trusted)
2191   {
2192     /* Only allow CORE to tell us about direct paths */
2193     path_destroy (path);
2194     return NULL;
2195   }
2196
2197   l = path_get_length (path);
2198   if (0 == l)
2199   {
2200     path_destroy (path);
2201     return NULL;
2202   }
2203
2204   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2205   for (aux = peer->path_head; aux != NULL; aux = aux->next)
2206   {
2207     l2 = path_get_length (aux);
2208     if (l2 > l)
2209     {
2210       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
2211       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
2212                                           peer->path_tail, aux, path);
2213       goto finish;
2214     }
2215     else
2216     {
2217       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2218       {
2219         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
2220         path_destroy (path);
2221         return aux;
2222       }
2223     }
2224   }
2225   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head,
2226                                     peer->path_tail,
2227                                     path);
2228   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
2229
2230 finish:
2231   if (NULL != peer->tunnel
2232       && CONNECTIONS_PER_TUNNEL > GCT_count_connections (peer->tunnel)
2233       && 2 < path->length) /* Direct paths are handled by core_connect */
2234   {
2235     GCP_connect (peer);
2236   }
2237   GCC_check_connections ();
2238   return path;
2239 }
2240
2241
2242 /**
2243  * Add the path to the origin peer and update the path used to reach it in case
2244  * this is the shortest.
2245  * The path is given in peer_info -> destination, therefore we turn the path
2246  * upside down first.
2247  *
2248  * @param peer Peer to add the path to, being the origin of the path.
2249  * @param path New path to add after being inversed.
2250  *             Path will be either used or freed.
2251  * @param trusted Do we trust that this path is real?
2252  *
2253  * @return path if path was taken, pointer to existing duplicate if exists
2254  *         NULL on error.
2255  */
2256 struct CadetPeerPath *
2257 GCP_add_path_to_origin (struct CadetPeer *peer,
2258                         struct CadetPeerPath *path,
2259                         int trusted)
2260 {
2261   if (NULL == path)
2262     return NULL;
2263   path_invert (path);
2264   return GCP_add_path (peer, path, trusted);
2265 }
2266
2267
2268 /**
2269  * Adds a path to the info of all the peers in the path
2270  *
2271  * @param p Path to process.
2272  * @param confirmed Whether we know if the path works or not.
2273  */
2274 void
2275 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
2276 {
2277   unsigned int i;
2278
2279   /* TODO: invert and add */
2280   GCC_check_connections ();
2281   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2282   for (i++; i < p->length; i++)
2283   {
2284     struct CadetPeer *peer;
2285     struct CadetPeerPath *copy;
2286
2287     peer = GCP_get_short (p->peers[i], GNUNET_YES);
2288     copy = path_duplicate (p);
2289     copy->length = i + 1;
2290     GCP_add_path (peer, copy, 3 > p->length ? GNUNET_NO : confirmed);
2291   }
2292   GCC_check_connections ();
2293 }
2294
2295
2296 /**
2297  * Remove any path to the peer that has the exact same peers as the one given.
2298  *
2299  * @param peer Peer to remove the path from.
2300  * @param path Path to remove. Is always destroyed .
2301  */
2302 void
2303 GCP_remove_path (struct CadetPeer *peer,
2304                  struct CadetPeerPath *path)
2305 {
2306   struct CadetPeerPath *iter;
2307   struct CadetPeerPath *next;
2308
2309   GCC_check_connections ();
2310   GNUNET_assert (myid == path->peers[0]);
2311   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2312
2313   LOG (GNUNET_ERROR_TYPE_INFO,
2314        "Removing path %p (%u) from %s\n",
2315        path, path->length, GCP_2s (peer));
2316
2317   for (iter = peer->path_head; NULL != iter; iter = next)
2318   {
2319     next = iter->next;
2320     if (0 == path_cmp (path, iter))
2321     {
2322       GNUNET_CONTAINER_DLL_remove (peer->path_head,
2323                                    peer->path_tail,
2324                                    iter);
2325       if (iter != path)
2326         path_destroy (iter);
2327     }
2328   }
2329   path_destroy (path);
2330   GCC_check_connections ();
2331 }
2332
2333
2334 /**
2335  * Check that we are aware of a connection from a neighboring peer.
2336  *
2337  * @param peer Peer to the connection is with
2338  * @param c Connection that should be in the map with this peer.
2339  */
2340 void
2341 GCP_check_connection (const struct CadetPeer *peer,
2342                       const struct CadetConnection *c)
2343 {
2344   GNUNET_assert (NULL != peer);
2345   GNUNET_assert (NULL != peer->connections);
2346     return;
2347   GNUNET_assert (GNUNET_YES ==
2348                  GNUNET_CONTAINER_multihashmap_contains_value (peer->connections,
2349                                                                GCC_get_h (c),
2350                                                                c));
2351 }
2352
2353
2354 /**
2355  * Remove a connection from a neighboring peer.
2356  *
2357  * @param peer Peer to remove connection from.
2358  * @param c Connection to remove.
2359  */
2360 void
2361 GCP_remove_connection (struct CadetPeer *peer,
2362                        const struct CadetConnection *c)
2363 {
2364   LOG (GNUNET_ERROR_TYPE_DEBUG,
2365        "Removing connection %s\n",
2366        GCC_2s (c));
2367   LOG (GNUNET_ERROR_TYPE_DEBUG,
2368        "from peer %s\n",
2369        GCP_2s (peer));
2370   if ( (NULL == peer) ||
2371        (NULL == peer->connections) )
2372     return;
2373   GNUNET_assert (GNUNET_YES ==
2374                  GNUNET_CONTAINER_multihashmap_remove (peer->connections,
2375                                                        GCC_get_h (c),
2376                                                        c));
2377   LOG (GNUNET_ERROR_TYPE_DEBUG,
2378        "Peer %s remains with %u connections.\n",
2379        GCP_2s (peer),
2380        GNUNET_CONTAINER_multihashmap_size (peer->connections));
2381 }
2382
2383
2384 /**
2385  * Start the DHT search for new paths towards the peer: we don't have
2386  * enough good connections.
2387  *
2388  * @param peer Destination peer.
2389  */
2390 void
2391 GCP_start_search (struct CadetPeer *peer)
2392 {
2393   const struct GNUNET_PeerIdentity *id;
2394   struct CadetTunnel *t = peer->tunnel;
2395
2396   GCC_check_connections ();
2397  if (NULL != peer->search_h)
2398   {
2399     GNUNET_break (0);
2400     return;
2401   }
2402
2403   if (NULL != peer->search_delayed)
2404     GCP_stop_search (peer);
2405
2406   id = GNUNET_PEER_resolve2 (peer->id);
2407   peer->search_h = GCD_search (id, &search_handler, peer);
2408
2409   if (NULL == t)
2410   {
2411     /* Why would we search for a peer with no tunnel towards it? */
2412     GNUNET_break (0);
2413     return;
2414   }
2415
2416   if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
2417       || 0 == GCT_count_any_connections (t))
2418   {
2419     GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2420   }
2421   GCC_check_connections ();
2422 }
2423
2424
2425 /**
2426  * Stop the DHT search for new paths towards the peer: we already have
2427  * enough good connections.
2428  *
2429  * @param peer Destination peer.
2430  */
2431 void
2432 GCP_stop_search (struct CadetPeer *peer)
2433 {
2434   GCC_check_connections ();
2435   if (NULL != peer->search_h)
2436   {
2437     GCD_search_stop (peer->search_h);
2438     peer->search_h = NULL;
2439   }
2440   if (NULL != peer->search_delayed)
2441   {
2442     GNUNET_SCHEDULER_cancel (peer->search_delayed);
2443     peer->search_delayed = NULL;
2444   }
2445   GCC_check_connections ();
2446 }
2447
2448
2449 /**
2450  * Get the Full ID of a peer.
2451  *
2452  * @param peer Peer to get from.
2453  *
2454  * @return Full ID of peer.
2455  */
2456 const struct GNUNET_PeerIdentity *
2457 GCP_get_id (const struct CadetPeer *peer)
2458 {
2459   return GNUNET_PEER_resolve2 (peer->id);
2460 }
2461
2462
2463 /**
2464  * Get the Short ID of a peer.
2465  *
2466  * @param peer Peer to get from.
2467  *
2468  * @return Short ID of peer.
2469  */
2470 GNUNET_PEER_Id
2471 GCP_get_short_id (const struct CadetPeer *peer)
2472 {
2473   return peer->id;
2474 }
2475
2476
2477 /**
2478  * Set tunnel.
2479  *
2480  * If tunnel is NULL and there was a search active, stop it, as it's useless.
2481  *
2482  * @param peer Peer.
2483  * @param t Tunnel.
2484  */
2485 void
2486 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
2487 {
2488   peer->tunnel = t;
2489   if (NULL == t && GNUNET_YES == is_searching (peer))
2490   {
2491     GCP_stop_search (peer);
2492   }
2493 }
2494
2495
2496 /**
2497  * Get the tunnel towards a peer.
2498  *
2499  * @param peer Peer to get from.
2500  *
2501  * @return Tunnel towards peer.
2502  */
2503 struct CadetTunnel *
2504 GCP_get_tunnel (const struct CadetPeer *peer)
2505 {
2506   if (NULL == peer)
2507     return NULL;
2508   return peer->tunnel;
2509 }
2510
2511
2512 /**
2513  * Set the hello message.
2514  *
2515  * @param peer Peer whose message to set.
2516  * @param hello Hello message.
2517  */
2518 void
2519 GCP_set_hello (struct CadetPeer *peer,
2520                const struct GNUNET_HELLO_Message *hello)
2521 {
2522   struct GNUNET_HELLO_Message *old;
2523   size_t size;
2524
2525   GCC_check_connections ();
2526  LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
2527   if (NULL == hello)
2528     return;
2529
2530   old = GCP_get_hello (peer);
2531   if (NULL == old)
2532   {
2533     size = GNUNET_HELLO_size (hello);
2534     peer->hello = GNUNET_malloc (size);
2535     memcpy (peer->hello, hello, size);
2536   }
2537   else
2538   {
2539     peer->hello = GNUNET_HELLO_merge (old, hello);
2540     GNUNET_free (old);
2541   }
2542   GCC_check_connections ();
2543 }
2544
2545
2546 /**
2547  * Get the hello message.
2548  *
2549  * @param peer Peer whose message to get.
2550  *
2551  * @return Hello message.
2552  */
2553 struct GNUNET_HELLO_Message *
2554 GCP_get_hello (struct CadetPeer *peer)
2555 {
2556   struct GNUNET_TIME_Absolute expiration;
2557   struct GNUNET_TIME_Relative remaining;
2558
2559   if (NULL == peer->hello)
2560     return NULL;
2561
2562   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2563   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2564   if (0 == remaining.rel_value_us)
2565   {
2566     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2567          GNUNET_STRINGS_absolute_time_to_string (expiration));
2568     GNUNET_free (peer->hello);
2569     peer->hello = NULL;
2570   }
2571   return peer->hello;
2572 }
2573
2574
2575 /**
2576  * Try to connect to a peer on TRANSPORT level.
2577  *
2578  * @param peer Peer to whom to connect.
2579  */
2580 void
2581 GCP_try_connect (struct CadetPeer *peer)
2582 {
2583   struct GNUNET_HELLO_Message *hello;
2584   struct GNUNET_MessageHeader *mh;
2585
2586   if (NULL == transport_handle)
2587     return;
2588   GCC_check_connections ();
2589   if (GNUNET_YES == GCP_is_neighbor (peer))
2590     return;
2591   hello = GCP_get_hello (peer);
2592   if (NULL == hello)
2593     return;
2594
2595   mh = GNUNET_HELLO_get_header (hello);
2596   if (NULL != peer->hello_offer)
2597   {
2598     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
2599     peer->hello_offer = NULL;
2600   }
2601   peer->hello_offer = GNUNET_TRANSPORT_offer_hello (transport_handle,
2602                                                     mh,
2603                                                     &hello_offer_done,
2604                                                     peer);
2605   if (NULL == peer->connectivity_suggestion)
2606     peer->connectivity_suggestion
2607       = GNUNET_ATS_connectivity_suggest (ats_ch,
2608                                          GNUNET_PEER_resolve2 (peer->id),
2609                                          1 /* strength */);
2610   GCC_check_connections ();
2611 }
2612
2613
2614 /**
2615  * Notify a peer that a link between two other peers is broken. If any path
2616  * used that link, eliminate it.
2617  *
2618  * @param peer Peer affected by the change.
2619  * @param peer1 Peer whose link is broken.
2620  * @param peer2 Peer whose link is broken.
2621  */
2622 void
2623 GCP_notify_broken_link (struct CadetPeer *peer,
2624                         const struct GNUNET_PeerIdentity *peer1,
2625                         const struct GNUNET_PeerIdentity *peer2)
2626 {
2627   struct CadetPeerPath *iter;
2628   struct CadetPeerPath *next;
2629   unsigned int i;
2630   GNUNET_PEER_Id p1;
2631   GNUNET_PEER_Id p2;
2632
2633   GCC_check_connections ();
2634   p1 = GNUNET_PEER_search (peer1);
2635   p2 = GNUNET_PEER_search (peer2);
2636
2637   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2638   if (0 == p1 || 0 == p2)
2639   {
2640     /* We don't even know them */
2641     return;
2642   }
2643
2644   for (iter = peer->path_head; NULL != iter; iter = next)
2645   {
2646     next = iter->next;
2647     for (i = 0; i < iter->length - 1; i++)
2648     {
2649       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2650           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2651       {
2652         char *s;
2653
2654         s = path_2s (iter);
2655         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2656         GNUNET_free (s);
2657
2658         path_invalidate (iter);
2659       }
2660     }
2661   }
2662   GCC_check_connections ();
2663 }
2664
2665
2666 /**
2667  * Count the number of known paths toward the peer.
2668  *
2669  * @param peer Peer to get path info.
2670  *
2671  * @return Number of known paths.
2672  */
2673 unsigned int
2674 GCP_count_paths (const struct CadetPeer *peer)
2675 {
2676   struct CadetPeerPath *iter;
2677   unsigned int i;
2678
2679   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2680     i++;
2681
2682   return i;
2683 }
2684
2685
2686 /**
2687  * Iterate over the paths to a peer.
2688  *
2689  * @param peer Peer to get path info.
2690  * @param callback Function to call for every path.
2691  * @param cls Closure for @a callback.
2692  *
2693  * @return Number of iterated paths.
2694  */
2695 unsigned int
2696 GCP_iterate_paths (struct CadetPeer *peer,
2697                    GCP_path_iterator callback,
2698                    void *cls)
2699 {
2700   struct CadetPeerPath *iter;
2701   unsigned int i;
2702
2703   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2704   {
2705     i++;
2706     if (GNUNET_YES != callback (cls, peer, iter))
2707       break;
2708   }
2709
2710   return i;
2711 }
2712
2713
2714 /**
2715  * Iterate all known peers.
2716  *
2717  * @param iter Iterator.
2718  * @param cls Closure for @c iter.
2719  */
2720 void
2721 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
2722                  void *cls)
2723 {
2724   GCC_check_connections ();
2725   GNUNET_CONTAINER_multipeermap_iterate (peers,
2726                                          iter,
2727                                          cls);
2728   GCC_check_connections ();
2729 }
2730
2731
2732 /**
2733  * Get the static string for a peer ID.
2734  *
2735  * @param peer Peer.
2736  *
2737  * @return Static string for it's ID.
2738  */
2739 const char *
2740 GCP_2s (const struct CadetPeer *peer)
2741 {
2742   if (NULL == peer)
2743     return "(NULL)";
2744   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2745 }
2746
2747
2748 /* end of gnunet-service-cadet_peer.c */