putting CADET on a diet: proper alignment for AX KX, kill obsolete OTR legacy code
[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  * Our configuration;
249  */
250 static const struct GNUNET_CONFIGURATION_Handle *cfg;
251
252 /**
253  * Handle to communicate with ATS.
254  */
255 static struct GNUNET_ATS_ConnectivityHandle *ats_ch;
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_STATISTICS_update (stats,
459                             "# peers",
460                             1,
461                             GNUNET_NO);
462
463   if ( (NULL != GCP_get_tunnel (neighbor)) &&
464        (0 > GNUNET_CRYPTO_cmp_peer_identity (&my_full_id, peer)) )
465     GCP_connect (neighbor);
466   GCC_check_connections ();
467 }
468
469
470 /**
471  * Method called whenever a peer disconnects.
472  *
473  * @param cls closure
474  * @param peer peer identity this notification is about
475  */
476 static void
477 core_disconnect (void *cls,
478                  const struct GNUNET_PeerIdentity *peer)
479 {
480   struct CadetPeer *p;
481   struct CadetPeerPath *direct_path;
482   char own_id[16];
483
484   GCC_check_connections ();
485   strncpy (own_id, GNUNET_i2s (&my_full_id), 16);
486   own_id[15] = '\0';
487   p = GNUNET_CONTAINER_multipeermap_get (peers, peer);
488   if (NULL == p)
489   {
490     GNUNET_break (GNUNET_YES == in_shutdown);
491     return;
492   }
493   if (myid == p->id)
494     LOG (GNUNET_ERROR_TYPE_INFO,
495          "DISCONNECTED %s (self)\n",
496          own_id);
497   else
498     LOG (GNUNET_ERROR_TYPE_INFO,
499          "DISCONNECTED %s <= %s\n",
500          own_id, GNUNET_i2s (peer));
501   direct_path = pop_direct_path (p);
502   if (NULL != p->connections)
503   {
504     GNUNET_CONTAINER_multihashmap_iterate (p->connections,
505                                            &notify_broken,
506                                            p);
507     GNUNET_CONTAINER_multihashmap_destroy (p->connections);
508     p->connections = NULL;
509   }
510   if (NULL != p->core_transmit)
511   {
512     GNUNET_CORE_notify_transmit_ready_cancel (p->core_transmit);
513     p->core_transmit = NULL;
514     p->tmt_time.abs_value_us = 0;
515   }
516   GNUNET_STATISTICS_update (stats,
517                             "# peers",
518                             -1,
519                             GNUNET_NO);
520   path_destroy (direct_path);
521   GCC_check_connections ();
522 }
523
524
525 /**
526  * Functions to handle messages from core
527  */
528 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
529   {&GCC_handle_create, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE, 0},
530   {&GCC_handle_confirm, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK,
531     sizeof (struct GNUNET_CADET_ConnectionACK)},
532   {&GCC_handle_broken, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN,
533     sizeof (struct GNUNET_CADET_ConnectionBroken)},
534   {&GCC_handle_destroy, GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY,
535     sizeof (struct GNUNET_CADET_ConnectionDestroy)},
536   {&GCC_handle_ack, GNUNET_MESSAGE_TYPE_CADET_ACK,
537     sizeof (struct GNUNET_CADET_ACK)},
538   {&GCC_handle_poll, GNUNET_MESSAGE_TYPE_CADET_POLL,
539     sizeof (struct GNUNET_CADET_Poll)},
540   {&GCC_handle_kx, GNUNET_MESSAGE_TYPE_CADET_KX, 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   GNUNET_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_AX == q->type)
727     return low;
728   return high;
729 }
730
731
732 /**
733  * Destroy the peer_info and free any allocated resources linked to it
734  *
735  * @param peer The peer_info to destroy.
736  * @return #GNUNET_OK on success
737  */
738 static int
739 peer_destroy (struct CadetPeer *peer)
740 {
741   struct GNUNET_PeerIdentity id;
742   struct CadetPeerPath *p;
743   struct CadetPeerPath *nextp;
744
745   GNUNET_PEER_resolve (peer->id, &id);
746   GNUNET_PEER_change_rc (peer->id, -1);
747
748   LOG (GNUNET_ERROR_TYPE_INFO,
749        "destroying peer %s\n",
750        GNUNET_i2s (&id));
751
752   if (GNUNET_YES !=
753       GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
754   {
755     GNUNET_break (0);
756     LOG (GNUNET_ERROR_TYPE_WARNING, " peer not in peermap!!\n");
757   }
758   GCP_stop_search (peer);
759   p = peer->path_head;
760   while (NULL != p)
761   {
762     nextp = p->next;
763     GNUNET_CONTAINER_DLL_remove (peer->path_head,
764                                  peer->path_tail,
765                                  p);
766     path_destroy (p);
767     p = nextp;
768   }
769   if (NULL != peer->tunnel)
770     GCT_destroy_empty (peer->tunnel);
771   if (NULL != peer->connections)
772   {
773     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (peer->connections));
774     GNUNET_CONTAINER_multihashmap_destroy (peer->connections);
775     peer->connections = NULL;
776   }
777   if (NULL != peer->hello_offer)
778   {
779     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
780     peer->hello_offer = NULL;
781   }
782   if (NULL != peer->connectivity_suggestion)
783   {
784     GNUNET_ATS_connectivity_suggest_cancel (peer->connectivity_suggestion);
785     peer->connectivity_suggestion = NULL;
786   }
787   while (NULL != peer->queue_head)
788   {
789     /* This function destroys the current peer->queue_head but
790      * replaces it with the next in the queue, so it is correct
791      * to while() here.
792      */
793     GCP_queue_destroy (peer->queue_head, GNUNET_YES, GNUNET_NO, 0);
794   }
795   if (NULL != peer->core_transmit)
796   {
797     GNUNET_break (0); /* GCP_queue_destroy should've cancelled it! */
798     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
799     peer->core_transmit = NULL;
800   }
801
802   GNUNET_free_non_null (peer->hello);
803   GNUNET_free (peer);
804   return GNUNET_OK;
805 }
806
807
808 /**
809  * Iterator over peer hash map entries to destroy the peer during in_shutdown.
810  *
811  * @param cls closure
812  * @param key current key code
813  * @param value value in the hash map
814  * @return #GNUNET_YES if we should continue to iterate,
815  *         #GNUNET_NO if not.
816  */
817 static int
818 shutdown_peer (void *cls,
819                const struct GNUNET_PeerIdentity *key,
820                void *value)
821 {
822   struct CadetPeer *p = value;
823   struct CadetTunnel *t = p->tunnel;
824
825   LOG (GNUNET_ERROR_TYPE_DEBUG, "  shutting down %s\n", GCP_2s (p));
826   if (NULL != t)
827     GCT_destroy (t);
828   p->tunnel = NULL;
829   peer_destroy (p);
830   return GNUNET_YES;
831 }
832
833
834
835 /**
836  * Check if peer is searching for a path (either active or delayed search).
837  *
838  * @param peer Peer to check
839  * @return #GNUNET_YES if there is a search active.
840  *         #GNUNET_NO otherwise.
841  */
842 static int
843 is_searching (const struct CadetPeer *peer)
844 {
845   return ( (NULL == peer->search_h) &&
846            (NULL == peer->search_delayed) ) ?
847     GNUNET_NO : GNUNET_YES;
848 }
849
850
851 /**
852  * @brief Start a search for a peer.
853  *
854  * @param cls Closure (Peer to search for).
855  */
856 static void
857 delayed_search (void *cls)
858 {
859   struct CadetPeer *peer = cls;
860
861   peer->search_delayed = NULL;
862   GCC_check_connections ();
863   GCP_start_search (peer);
864   GCC_check_connections ();
865 }
866
867
868 /**
869  * Returns if peer is used (has a tunnel or is neighbor).
870  *
871  * @param peer Peer to check.
872  * @return #GNUNET_YES if peer is in use.
873  */
874 static int
875 peer_is_used (struct CadetPeer *peer)
876 {
877   struct CadetPeerPath *p;
878
879   if (NULL != peer->tunnel)
880     return GNUNET_YES;
881
882   for (p = peer->path_head; NULL != p; p = p->next)
883   {
884     if (p->length < 3)
885       return GNUNET_YES;
886   }
887     return GNUNET_NO;
888 }
889
890
891 /**
892  * Iterator over all the peers to get the oldest timestamp.
893  *
894  * @param cls Closure (unsued).
895  * @param key ID of the peer.
896  * @param value Peer_Info of the peer.
897  */
898 static int
899 peer_get_oldest (void *cls,
900                  const struct GNUNET_PeerIdentity *key,
901                  void *value)
902 {
903   struct CadetPeer *p = value;
904   struct GNUNET_TIME_Absolute *abs = cls;
905
906   /* Don't count active peers */
907   if (GNUNET_YES == peer_is_used (p))
908     return GNUNET_YES;
909
910   if (abs->abs_value_us < p->last_contact.abs_value_us)
911     abs->abs_value_us = p->last_contact.abs_value_us;
912
913   return GNUNET_YES;
914 }
915
916
917 /**
918  * Iterator over all the peers to remove the oldest entry.
919  *
920  * @param cls Closure (unsued).
921  * @param key ID of the peer.
922  * @param value Peer_Info of the peer.
923  */
924 static int
925 peer_timeout (void *cls,
926               const struct GNUNET_PeerIdentity *key,
927               void *value)
928 {
929   struct CadetPeer *p = value;
930   struct GNUNET_TIME_Absolute *abs = cls;
931
932   LOG (GNUNET_ERROR_TYPE_WARNING,
933        "peer %s timeout\n", GNUNET_i2s (key));
934
935   if (p->last_contact.abs_value_us == abs->abs_value_us &&
936       GNUNET_NO == peer_is_used (p))
937   {
938     peer_destroy (p);
939     return GNUNET_NO;
940   }
941     return GNUNET_YES;
942 }
943
944
945 /**
946  * Delete oldest unused peer.
947  */
948 static void
949 peer_delete_oldest (void)
950 {
951   struct GNUNET_TIME_Absolute abs;
952
953   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
954
955   GNUNET_CONTAINER_multipeermap_iterate (peers,
956                                          &peer_get_oldest,
957                                          &abs);
958   GNUNET_CONTAINER_multipeermap_iterate (peers,
959                                          &peer_timeout,
960                                          &abs);
961 }
962
963
964 /**
965  * Choose the best (yet unused) path towards a peer,
966  * considering the tunnel properties.
967  *
968  * @param peer The destination peer.
969  * @return Best current known path towards the peer, if any.
970  */
971 static struct CadetPeerPath *
972 peer_get_best_path (const struct CadetPeer *peer)
973 {
974   struct CadetPeerPath *best_p;
975   struct CadetPeerPath *p;
976   unsigned int best_cost;
977   unsigned int cost;
978
979   best_cost = UINT_MAX;
980   best_p = NULL;
981   for (p = peer->path_head; NULL != p; p = p->next)
982   {
983     if (GNUNET_NO == path_is_valid (p))
984       continue; /* Don't use invalid paths. */
985     if (GNUNET_YES == GCT_is_path_used (peer->tunnel, p))
986       continue; /* If path is already in use, skip it. */
987
988     if ((cost = GCT_get_path_cost (peer->tunnel, p)) < best_cost)
989     {
990       best_cost = cost;
991       best_p = p;
992     }
993   }
994   return best_p;
995 }
996
997
998 /**
999  * Is this queue element sendable?
1000  *
1001  * - All management traffic is always sendable.
1002  * - For payload traffic, check the connection flow control.
1003  *
1004  * @param q Queue element to inspect.
1005  * @return #GNUNET_YES if it is sendable, #GNUNET_NO otherwise.
1006  */
1007 static int
1008 queue_is_sendable (struct CadetPeerQueue *q)
1009 {
1010   /* Is PID-independent? */
1011   switch (q->type)
1012   {
1013     case GNUNET_MESSAGE_TYPE_CADET_ACK:
1014     case GNUNET_MESSAGE_TYPE_CADET_POLL:
1015     case GNUNET_MESSAGE_TYPE_CADET_KX:
1016     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1017     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1018     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1019     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1020       return GNUNET_YES;
1021
1022     case GNUNET_MESSAGE_TYPE_CADET_AX:
1023       break;
1024
1025     default:
1026       GNUNET_break (0);
1027   }
1028
1029   return GCC_is_sendable (q->c, q->fwd);
1030 }
1031
1032
1033 /**
1034  * Get first sendable message.
1035  *
1036  * @param peer The destination peer.
1037  *
1038  * @return First transmittable message, if any. Otherwise, NULL.
1039  */
1040 static struct CadetPeerQueue *
1041 peer_get_first_message (const struct CadetPeer *peer)
1042 {
1043   struct CadetPeerQueue *q;
1044
1045   for (q = peer->queue_head; NULL != q; q = q->next)
1046   {
1047     LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking q:%p on c:%s\n", q, GCC_2s (q->c));
1048     if (queue_is_sendable (q))
1049       return q;
1050   }
1051
1052   return NULL;
1053 }
1054
1055
1056 /**
1057  * Function to process paths received for a new peer addition. The recorded
1058  * paths form the initial tunnel, which can be optimized later.
1059  * Called on each result obtained for the DHT search.
1060  *
1061  * @param cls Closure (peer towards a path has been found).
1062  * @param path Path created from the DHT query. Will be freed afterwards.
1063  */
1064 static void
1065 search_handler (void *cls, const struct CadetPeerPath *path)
1066 {
1067   struct CadetPeer *peer = cls;
1068   unsigned int connection_count;
1069
1070   GCC_check_connections ();
1071   GCP_add_path_to_all (path, GNUNET_NO);
1072
1073   /* Count connections */
1074   connection_count = GCT_count_connections (peer->tunnel);
1075
1076   /* If we already have our minimum (or more) connections, it's enough */
1077   if (CONNECTIONS_PER_TUNNEL <= connection_count)
1078   {
1079     GCC_check_connections ();
1080     return;
1081   }
1082
1083   if (CADET_TUNNEL_SEARCHING == GCT_get_cstate (peer->tunnel))
1084   {
1085     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
1086     GCP_connect (peer);
1087   }
1088   GCC_check_connections ();
1089 }
1090
1091
1092 /**
1093  * Adjust core requested size to accomodate an ACK.
1094  *
1095  * @param message_size Requested size.
1096  *
1097  * @return Size enough to fit @c message_size and an ACK.
1098  */
1099 static size_t
1100 get_core_size (size_t message_size)
1101 {
1102   return message_size + sizeof (struct GNUNET_CADET_ACK);
1103 }
1104
1105 /**
1106  * Test if a message type is connection management traffic
1107  * or regular payload traffic.
1108  *
1109  * @param type Message type.
1110  *
1111  * @return #GNUNET_YES if connection management, #GNUNET_NO otherwise.
1112  */
1113 static int
1114 is_connection_management (uint16_t type)
1115 {
1116   return type == GNUNET_MESSAGE_TYPE_CADET_ACK ||
1117          type == GNUNET_MESSAGE_TYPE_CADET_POLL;
1118 }
1119
1120
1121 /**
1122  * Fill a core buffer with the appropriate data for the queued message.
1123  *
1124  * @param queue Queue element for the message.
1125  * @param buf Core buffer to fill.
1126  * @param size Size remaining in @c buf.
1127  * @param[out] pid In case its an encrypted payload, set payload.
1128  *
1129  * @return Bytes written to @c buf.
1130  */
1131 static size_t
1132 fill_buf (struct CadetPeerQueue *queue, void *buf, size_t size, uint32_t *pid)
1133 {
1134   struct CadetConnection *c = queue->c;
1135   size_t msg_size;
1136
1137   switch (queue->type)
1138   {
1139     case GNUNET_MESSAGE_TYPE_CADET_AX:
1140       *pid = GCC_get_pid (queue->c, queue->fwd);
1141       LOG (GNUNET_ERROR_TYPE_DEBUG, "  ax payload ID %u\n", *pid);
1142       msg_size = send_core_data_raw (queue->cls, size, buf);
1143       ((struct GNUNET_CADET_AX *) buf)->pid = htonl (*pid);
1144       break;
1145     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1146     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1147     case GNUNET_MESSAGE_TYPE_CADET_KX:
1148     case GNUNET_MESSAGE_TYPE_CADET_ACK:
1149     case GNUNET_MESSAGE_TYPE_CADET_POLL:
1150       LOG (GNUNET_ERROR_TYPE_DEBUG, "  raw %s\n", GC_m2s (queue->type));
1151       msg_size = send_core_data_raw (queue->cls, size, buf);
1152       break;
1153     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1154       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path create\n");
1155       if (GCC_is_origin (c, GNUNET_YES))
1156         msg_size = send_core_connection_create (c, size, buf);
1157       else
1158         msg_size = send_core_data_raw (queue->cls, size, buf);
1159       break;
1160     case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1161       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path ack\n");
1162       if (GCC_is_origin (c, GNUNET_NO) ||
1163           GCC_is_origin (c, GNUNET_YES))
1164       {
1165         msg_size = send_core_connection_ack (c, size, buf);
1166       }
1167       else
1168       {
1169         msg_size = send_core_data_raw (queue->cls, size, buf);
1170       }
1171       break;
1172     case GNUNET_MESSAGE_TYPE_CADET_DATA:
1173     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_CREATE:
1174     case GNUNET_MESSAGE_TYPE_CADET_CHANNEL_DESTROY:
1175       /* This should be encapsulted */
1176       msg_size = 0;
1177       GNUNET_assert (0);
1178       break;
1179     default:
1180       GNUNET_break (0);
1181       LOG (GNUNET_ERROR_TYPE_WARNING, "  type unknown: %u\n", queue->type);
1182       msg_size = 0;
1183   }
1184
1185   GNUNET_assert (size >= msg_size);
1186
1187   return msg_size;
1188 }
1189
1190
1191 /**
1192  * Debug function should NEVER return true in production code, useful to
1193  * simulate losses for testcases.
1194  *
1195  * @param q Queue handle with info about the message.
1196  *
1197  * @return #GNUNET_YES or #GNUNET_NO with the decision to drop.
1198  */
1199 static int
1200 should_I_drop (struct CadetPeerQueue *q)
1201 {
1202   if (0 == drop_percent)
1203     return GNUNET_NO;
1204
1205   if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
1206     return GNUNET_YES;
1207
1208   return GNUNET_NO;
1209 }
1210
1211
1212 /**
1213  * Core callback to write a queued packet to core buffer
1214  *
1215  * @param cls Closure (peer info).
1216  * @param size Number of bytes available in buf.
1217  * @param buf Where the to write the message.
1218  *
1219  * @return number of bytes written to buf
1220  */
1221 static size_t
1222 queue_send (void *cls, size_t size, void *buf)
1223 {
1224   struct CadetPeer *peer = cls;
1225   struct CadetConnection *c;
1226   struct CadetPeerQueue *queue;
1227   struct GNUNET_TIME_Relative core_wait_time;
1228   const char *wait_s;
1229   const struct GNUNET_PeerIdentity *dst_id;
1230   size_t msg_size;
1231   size_t total_size;
1232   size_t rest;
1233   char *dst;
1234   uint32_t pid;
1235
1236   GCC_check_connections ();
1237   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1238   LOG (GNUNET_ERROR_TYPE_DEBUG, "\n");
1239   LOG (GNUNET_ERROR_TYPE_DEBUG, "Queue send towards %s (max %u)\n",
1240        GCP_2s (peer), size);
1241
1242   /* Sanity checking */
1243   if (NULL == buf || 0 == size)
1244   {
1245     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not allowed/\n");
1246     if (GNUNET_NO == in_shutdown)
1247     {
1248       queue = peer_get_first_message (peer);
1249       if (NULL == queue)
1250       {
1251         peer->core_transmit = NULL;
1252         peer->tmt_time.abs_value_us = 0;
1253         GCC_check_connections ();
1254         return 0;
1255       }
1256       dst_id = GNUNET_PEER_resolve2 (peer->id);
1257       peer->core_transmit =
1258           GNUNET_CORE_notify_transmit_ready (core_handle,
1259                                              GNUNET_NO, get_priority (queue),
1260                                              GNUNET_TIME_UNIT_FOREVER_REL,
1261                                              dst_id,
1262                                              get_core_size (queue->size),
1263                                              &queue_send,
1264                                              peer);
1265       peer->tmt_time = GNUNET_TIME_absolute_get ();
1266     }
1267     else
1268     {
1269       peer->core_transmit = NULL;
1270       peer->tmt_time.abs_value_us = 0;
1271     }
1272     GCC_check_connections ();
1273     return 0;
1274   }
1275
1276   /* Init */
1277   rest = size;
1278   total_size = 0;
1279   dst = (char *) buf;
1280   pid = 0;
1281   peer->core_transmit = NULL;
1282   queue = peer_get_first_message (peer);
1283   if (NULL == queue)
1284   {
1285     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
1286     peer->tmt_time.abs_value_us = 0;
1287     return 0;
1288   }
1289   core_wait_time = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1290   wait_s = GNUNET_STRINGS_relative_time_to_string (core_wait_time, GNUNET_YES);
1291   if (core_wait_time.rel_value_us >= 1000000)
1292   {
1293     LOG (GNUNET_ERROR_TYPE_WARNING,
1294          " %s: core wait time %s (> 1 second) for %u bytes\n",
1295          GCP_2s (peer), wait_s, queue->size);
1296   }
1297   peer->tmt_time.abs_value_us = 0;
1298
1299   /* Copy all possible messages to the core buffer */
1300   while (NULL != queue && rest >= queue->size)
1301   {
1302     c = queue->c;
1303
1304     LOG (GNUNET_ERROR_TYPE_DEBUG, "  on conn %s %s\n",
1305          GCC_2s (c), GC_f2s(queue->fwd));
1306     LOG (GNUNET_ERROR_TYPE_DEBUG, "  size %u ok (%u/%u)\n",
1307          queue->size, total_size, size);
1308
1309     msg_size = fill_buf (queue, (void *) dst, size, &pid);
1310
1311     if (should_I_drop (queue))
1312     {
1313       LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s (%s %u) on conn %s %s\n",
1314            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1315            queue->payload_id, GCC_2s (c), GC_f2s (queue->fwd));
1316       msg_size = 0;
1317     }
1318     else
1319     {
1320       LOG (GNUNET_ERROR_TYPE_INFO,
1321            ">>> %s (%s %4u) on conn %s (%p) %s [%5u], after %s\n",
1322            GC_m2s (queue->type), GC_m2s (queue->payload_type),
1323            queue->payload_id, GCC_2s (c), c,
1324            GC_f2s (queue->fwd), msg_size, wait_s);
1325     }
1326     total_size += msg_size;
1327     rest -= msg_size;
1328     dst = &dst[msg_size];
1329     msg_size = 0;
1330
1331     /* Free queue, but cls was freed by send_core_* in fill_buf. */
1332     (void) GCP_queue_destroy (queue, GNUNET_NO, GNUNET_YES, pid);
1333
1334     /* Next! */
1335     queue = peer_get_first_message (peer);
1336   }
1337
1338   /* If more data in queue, send next */
1339   if (NULL != queue)
1340   {
1341     LOG (GNUNET_ERROR_TYPE_DEBUG, "  more data! (%u)\n", queue->size);
1342     if (NULL == peer->core_transmit)
1343     {
1344       dst_id = GNUNET_PEER_resolve2 (peer->id);
1345       peer->core_transmit =
1346           GNUNET_CORE_notify_transmit_ready (core_handle,
1347                                              GNUNET_NO, get_priority (queue),
1348                                              GNUNET_TIME_UNIT_FOREVER_REL,
1349                                              dst_id,
1350                                              get_core_size (queue->size),
1351                                              &queue_send,
1352                                              peer);
1353       peer->tmt_time = GNUNET_TIME_absolute_get ();
1354       queue->start_waiting = GNUNET_TIME_absolute_get ();
1355     }
1356     else
1357     {
1358       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   tmt rdy called somewhere else\n");
1359     }
1360 //     GCC_start_poll (); FIXME needed?
1361   }
1362   else
1363   {
1364 //     GCC_stop_poll(); FIXME needed?
1365   }
1366
1367   LOG (GNUNET_ERROR_TYPE_DEBUG, "  return %d\n", total_size);
1368   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1369   GCC_check_connections ();
1370   return total_size;
1371 }
1372
1373
1374 /******************************************************************************/
1375 /********************************    API    ***********************************/
1376 /******************************************************************************/
1377
1378
1379 /**
1380  * Free a transmission that was already queued with all resources
1381  * associated to the request.
1382  *
1383  * If connection was marked to be destroyed, and this was the last queued
1384  * message on it, the connection will be free'd as a result.
1385  *
1386  * @param queue Queue handler to cancel.
1387  * @param clear_cls Is it necessary to free associated cls?
1388  * @param sent Was it really sent? (Could have been canceled)
1389  * @param pid PID, if relevant (was sent and was a payload message).
1390  *
1391  * @return #GNUNET_YES if connection was destroyed as a result,
1392  *         #GNUNET_NO otherwise.
1393  */
1394 int
1395 GCP_queue_destroy (struct CadetPeerQueue *queue,
1396                    int clear_cls,
1397                    int sent,
1398                    uint32_t pid)
1399 {
1400   struct CadetPeer *peer;
1401   int connection_destroyed;
1402
1403   GCC_check_connections ();
1404   peer = queue->peer;
1405   LOG (GNUNET_ERROR_TYPE_DEBUG, "queue destroy %s\n", GC_m2s (queue->type));
1406   if (GNUNET_YES == clear_cls)
1407   {
1408     LOG (GNUNET_ERROR_TYPE_DEBUG, " free cls\n");
1409     switch (queue->type)
1410     {
1411       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1412         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
1413         /* fall through */
1414       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1415       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1416       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1417       case GNUNET_MESSAGE_TYPE_CADET_KX:
1418       case GNUNET_MESSAGE_TYPE_CADET_AX:
1419       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1420       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1421         GNUNET_free_non_null (queue->cls);
1422         break;
1423
1424       default:
1425         GNUNET_break (0);
1426         LOG (GNUNET_ERROR_TYPE_ERROR, " type %s unknown!\n",
1427              GC_m2s (queue->type));
1428     }
1429   }
1430   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
1431
1432   if (!is_connection_management (queue->type))
1433   {
1434     peer->queue_n--;
1435   }
1436
1437   if (NULL != queue->cont)
1438   {
1439     struct GNUNET_TIME_Relative wait_time;
1440
1441     wait_time = GNUNET_TIME_absolute_get_duration (queue->start_waiting);
1442     LOG (GNUNET_ERROR_TYPE_DEBUG, " calling callback, time elapsed %s\n",
1443          GNUNET_STRINGS_relative_time_to_string (wait_time, GNUNET_NO));
1444     connection_destroyed = queue->cont (queue->cont_cls,
1445                                         queue->c, sent, queue->type, pid,
1446                                         queue->fwd, queue->size, wait_time);
1447   }
1448   else
1449   {
1450     connection_destroyed = GNUNET_NO;
1451   }
1452
1453   if (NULL == peer_get_first_message (peer) && NULL != peer->core_transmit)
1454   {
1455     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1456     peer->core_transmit = NULL;
1457     peer->tmt_time.abs_value_us = 0;
1458   }
1459
1460   GNUNET_free (queue);
1461   GCC_check_connections ();
1462   return connection_destroyed;
1463 }
1464
1465
1466 /**
1467  * @brief Queue and pass message to core when possible.
1468  *
1469  * @param peer Peer towards which to queue the message.
1470  * @param cls Closure (@c type dependant). It will be used by queue_send to
1471  *            build the message to be sent if not already prebuilt.
1472  * @param type Type of the message.
1473  * @param payload_type Type of the message's payload
1474  *                     0 if the message is a retransmission (unknown payload).
1475  *                     UINT16_MAX if the message does not have payload.
1476  * @param payload_id ID of the payload (MID, ACK #, etc)
1477  * @param size Size of the message.
1478  * @param c Connection this message belongs to (can be NULL).
1479  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1480  * @param cont Continuation to be called once CORE has taken the message.
1481  * @param cont_cls Closure for @c cont.
1482  *
1483  * @return Handle to cancel the message before it is sent. Once cont is called
1484  *         message has been sent and therefore the handle is no longer valid.
1485  */
1486 struct CadetPeerQueue *
1487 GCP_queue_add (struct CadetPeer *peer,
1488                void *cls,
1489                uint16_t type,
1490                uint16_t payload_type,
1491                uint32_t payload_id,
1492                size_t size,
1493                struct CadetConnection *c,
1494                int fwd,
1495                GCP_sent cont,
1496                void *cont_cls)
1497 {
1498   struct CadetPeerQueue *q;
1499   int priority;
1500   int call_core;
1501
1502   GCC_check_connections ();
1503   LOG (GNUNET_ERROR_TYPE_DEBUG,
1504        "que %s (%s %4u) on conn %s (%p) %s towards %s (size %u)\n",
1505        GC_m2s (type), GC_m2s (payload_type), payload_id,
1506        GCC_2s (c), c, GC_f2s (fwd), GCP_2s (peer), size);
1507
1508   if (NULL == peer->connections)
1509   {
1510     /* We are not connected to this peer, ignore request. */
1511     LOG (GNUNET_ERROR_TYPE_INFO, "%s not a neighbor\n", GCP_2s (peer));
1512     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1513                               GNUNET_NO);
1514     return NULL;
1515   }
1516
1517   priority = 0;
1518   if (is_connection_management (type))
1519   {
1520     priority = 100;
1521   }
1522   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1523
1524   call_core = (NULL == c || GNUNET_MESSAGE_TYPE_CADET_KX == type) ?
1525                GNUNET_YES : GCC_is_sendable (c, fwd);
1526   q = GNUNET_new (struct CadetPeerQueue);
1527   q->cls = cls;
1528   q->type = type;
1529   q->payload_type = payload_type;
1530   q->payload_id = payload_id;
1531   q->size = size;
1532   q->peer = peer;
1533   q->c = c;
1534   q->fwd = fwd;
1535   q->cont = cont;
1536   q->cont_cls = cont_cls;
1537   if (100 > priority)
1538   {
1539     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, q);
1540     peer->queue_n++;
1541   }
1542   else
1543   {
1544     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, q);
1545     call_core = GNUNET_YES;
1546   }
1547
1548   q->start_waiting = GNUNET_TIME_absolute_get ();
1549   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1550   {
1551     LOG (GNUNET_ERROR_TYPE_DEBUG,
1552          "calling core tmt rdy towards %s for %u bytes\n",
1553          GCP_2s (peer), size);
1554     peer->core_transmit =
1555         GNUNET_CORE_notify_transmit_ready (core_handle,
1556                                            GNUNET_NO, get_priority (q),
1557                                            GNUNET_TIME_UNIT_FOREVER_REL,
1558                                            GNUNET_PEER_resolve2 (peer->id),
1559                                            get_core_size (size),
1560                                            &queue_send, peer);
1561     peer->tmt_time = GNUNET_TIME_absolute_get ();
1562   }
1563   else if (GNUNET_NO == call_core)
1564   {
1565     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s not needed\n",
1566          GCP_2s (peer));
1567
1568   }
1569   else
1570   {
1571     struct GNUNET_TIME_Relative elapsed;
1572     elapsed = GNUNET_TIME_absolute_get_duration (peer->tmt_time);
1573     LOG (GNUNET_ERROR_TYPE_DEBUG, "core tmt rdy towards %s already called %s\n",
1574          GCP_2s (peer),
1575          GNUNET_STRINGS_relative_time_to_string (elapsed, GNUNET_NO));
1576
1577   }
1578   queue_debug (peer, GNUNET_ERROR_TYPE_DEBUG);
1579   GCC_check_connections ();
1580   return q;
1581 }
1582
1583
1584 /**
1585  * Cancel all queued messages to a peer that belong to a certain connection.
1586  *
1587  * @param peer Peer towards whom to cancel.
1588  * @param c Connection whose queued messages to cancel. Might be destroyed by
1589  *          the sent continuation call.
1590  */
1591 void
1592 GCP_queue_cancel (struct CadetPeer *peer,
1593                   struct CadetConnection *c)
1594 {
1595   struct CadetPeerQueue *q;
1596   struct CadetPeerQueue *next;
1597   struct CadetPeerQueue *prev;
1598   int connection_destroyed;
1599
1600   GCC_check_connections ();
1601   connection_destroyed = GNUNET_NO;
1602   for (q = peer->queue_head; NULL != q; q = next)
1603   {
1604     prev = q->prev;
1605     if (q->c == c)
1606     {
1607       LOG (GNUNET_ERROR_TYPE_DEBUG,
1608            "GMP queue cancel %s\n",
1609            GC_m2s (q->type));
1610       GNUNET_assert (GNUNET_NO == connection_destroyed);
1611       if (GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY == q->type)
1612       {
1613         q->c = NULL;
1614       }
1615       else
1616       {
1617         connection_destroyed = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1618       }
1619
1620       /* Get next from prev, q->next might be already freed:
1621        * queue destroy -> callback -> GCC_destroy -> cancel_queues -> here
1622        */
1623       if (NULL == prev)
1624         next = peer->queue_head;
1625       else
1626         next = prev->next;
1627     }
1628     else
1629     {
1630       next = q->next;
1631     }
1632   }
1633
1634   if ( (NULL == peer->queue_head) &&
1635        (NULL != peer->core_transmit) )
1636   {
1637     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1638     peer->core_transmit = NULL;
1639     peer->tmt_time.abs_value_us = 0;
1640   }
1641   GCC_check_connections ();
1642 }
1643
1644
1645 /**
1646  * Get the first transmittable message for a connection.
1647  *
1648  * @param peer Neighboring peer.
1649  * @param c Connection.
1650  *
1651  * @return First transmittable message.
1652  */
1653 static struct CadetPeerQueue *
1654 connection_get_first_message (struct CadetPeer *peer, struct CadetConnection *c)
1655 {
1656   struct CadetPeerQueue *q;
1657
1658   for (q = peer->queue_head; NULL != q; q = q->next)
1659   {
1660     if (q->c != c)
1661       continue;
1662     if (queue_is_sendable (q))
1663     {
1664       LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
1665       return q;
1666     }
1667     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
1668   }
1669
1670   return NULL;
1671 }
1672
1673
1674 /**
1675  * Get the first message for a connection and unqueue it.
1676  *
1677  * Only tunnel (or higher) level messages are unqueued. Connection specific
1678  * messages are silently destroyed upon encounter.
1679  *
1680  * @param peer Neighboring peer.
1681  * @param c Connection.
1682  * @param destroyed[in/out] Was the connection destroyed (prev/as a result)?.
1683  *                          Can NOT be NULL.
1684  *
1685  * @return First message for this connection.
1686  */
1687 struct GNUNET_MessageHeader *
1688 GCP_connection_pop (struct CadetPeer *peer,
1689                     struct CadetConnection *c,
1690                     int *destroyed)
1691 {
1692   struct CadetPeerQueue *q;
1693   struct CadetPeerQueue *next;
1694   struct GNUNET_MessageHeader *msg;
1695   int dest;
1696
1697   GCC_check_connections ();
1698   GNUNET_assert (NULL != destroyed);
1699   LOG (GNUNET_ERROR_TYPE_DEBUG, "connection_pop on conn %p\n", c);
1700   for (q = peer->queue_head; NULL != q; q = next)
1701   {
1702     next = q->next;
1703     if (q->c != c)
1704       continue;
1705     LOG (GNUNET_ERROR_TYPE_DEBUG, " - queued: %s (%s %u), cont: %p\n",
1706          GC_m2s (q->type), GC_m2s (q->payload_type), q->payload_id,
1707          q->cont);
1708     switch (q->type)
1709     {
1710       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_CREATE:
1711       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_ACK:
1712       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_DESTROY:
1713       case GNUNET_MESSAGE_TYPE_CADET_CONNECTION_BROKEN:
1714       case GNUNET_MESSAGE_TYPE_CADET_ACK:
1715       case GNUNET_MESSAGE_TYPE_CADET_POLL:
1716         dest = GCP_queue_destroy (q, GNUNET_YES, GNUNET_NO, 0);
1717         if (GNUNET_YES == dest)
1718         {
1719           GNUNET_break (GNUNET_NO == *destroyed);
1720           *destroyed = GNUNET_YES;
1721         }
1722         continue;
1723
1724       case GNUNET_MESSAGE_TYPE_CADET_KX:
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   cfg = c;
1799   LOG (GNUNET_ERROR_TYPE_DEBUG,
1800        "GCP_init\n");
1801   in_shutdown = GNUNET_NO;
1802   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1803   if (GNUNET_OK !=
1804       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "MAX_PEERS",
1805                                              &max_peers))
1806   {
1807     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1808                                "CADET", "MAX_PEERS", "USING DEFAULT");
1809     max_peers = 1000;
1810   }
1811
1812   if (GNUNET_OK !=
1813       GNUNET_CONFIGURATION_get_value_number (c, "CADET", "DROP_PERCENT",
1814                                              &drop_percent))
1815   {
1816     drop_percent = 0;
1817   }
1818   else
1819   {
1820     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1821     LOG (GNUNET_ERROR_TYPE_WARNING, "Cadet is running with DROP enabled.\n");
1822     LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1823     LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1824     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1825   }
1826   ats_ch = GNUNET_ATS_connectivity_init (c);
1827   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1828                                      NULL,      /* Closure passed to CADET functions */
1829                                      &core_init,        /* Call core_init once connected */
1830                                      &core_connect,     /* Handle connects */
1831                                      &core_disconnect,  /* remove peers on disconnects */
1832                                      NULL,      /* Don't notify about all incoming messages */
1833                                      GNUNET_NO, /* For header only in notification */
1834                                      NULL,      /* Don't notify about all outbound messages */
1835                                      GNUNET_NO, /* For header-only out notification */
1836                                      core_handlers);    /* Register these handlers */
1837   if (NULL == core_handle)
1838   {
1839     GNUNET_break (0);
1840     GNUNET_SCHEDULER_shutdown ();
1841     return;
1842   }
1843
1844 }
1845
1846
1847 /**
1848  * Shut down the peer subsystem.
1849  */
1850 void
1851 GCP_shutdown (void)
1852 {
1853   LOG (GNUNET_ERROR_TYPE_DEBUG,
1854        "Shutting down peer subsystem\n");
1855   in_shutdown = GNUNET_YES;
1856   GNUNET_CONTAINER_multipeermap_iterate (peers,
1857                                          &shutdown_peer,
1858                                          NULL);
1859   if (NULL != core_handle)
1860   {
1861     GNUNET_CORE_disconnect (core_handle);
1862     core_handle = NULL;
1863   }
1864   if (NULL != ats_ch)
1865   {
1866     GNUNET_ATS_connectivity_done (ats_ch);
1867     ats_ch = NULL;
1868   }
1869   GNUNET_PEER_change_rc (myid, -1);
1870   GNUNET_CONTAINER_multipeermap_destroy (peers);
1871   peers = NULL;
1872 }
1873
1874
1875 /**
1876  * Retrieve the CadetPeer stucture associated with the peer. Optionally create
1877  * one and insert it in the appropriate structures if the peer is not known yet.
1878  *
1879  * @param peer_id Full identity of the peer.
1880  * @param create #GNUNET_YES if a new peer should be created if unknown.
1881  *               #GNUNET_NO otherwise.
1882  *
1883  * @return Existing or newly created peer structure.
1884  *         NULL if unknown and not requested @a create
1885  */
1886 struct CadetPeer *
1887 GCP_get (const struct GNUNET_PeerIdentity *peer_id, int create)
1888 {
1889   struct CadetPeer *peer;
1890
1891   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1892   if (NULL == peer)
1893   {
1894     peer = GNUNET_new (struct CadetPeer);
1895     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1896     {
1897       peer_delete_oldest ();
1898     }
1899     GNUNET_assert (GNUNET_OK ==
1900                    GNUNET_CONTAINER_multipeermap_put (peers,
1901                                                       peer_id,
1902                                                       peer,
1903                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1904     peer->id = GNUNET_PEER_intern (peer_id);
1905   }
1906   peer->last_contact = GNUNET_TIME_absolute_get ();
1907
1908   return peer;
1909 }
1910
1911
1912 /**
1913  * Retrieve the CadetPeer stucture associated with the
1914  * peer. Optionally create one and insert it in the appropriate
1915  * structures if the peer is not known yet.
1916  *
1917  * @param peer Short identity of the peer.
1918  * @param create #GNUNET_YES if a new peer should be created if unknown.
1919  *               #GNUNET_NO otherwise.
1920  *
1921  * @return Existing or newly created peer structure.
1922  *         NULL if unknown and not requested @a create
1923  */
1924 struct CadetPeer *
1925 GCP_get_short (const GNUNET_PEER_Id peer, int create)
1926 {
1927   return GCP_get (GNUNET_PEER_resolve2 (peer), create);
1928 }
1929
1930
1931 /**
1932  * Function called once #GNUNET_TRANSPORT_offer_hello() is done.
1933  * Marks the operation as finished.
1934  *
1935  * @param cls Closure (our `struct CadetPeer`).
1936  */
1937 static void
1938 hello_offer_done (void *cls)
1939 {
1940   struct CadetPeer *peer = cls;
1941
1942   peer->hello_offer = NULL;
1943 }
1944
1945
1946 /**
1947  * Try to establish a new connection to this peer (in its tunnel).
1948  * If the peer doesn't have any path to it yet, try to get one.
1949  * If the peer already has some path, send a CREATE CONNECTION towards it.
1950  *
1951  * @param peer Peer to connect to.
1952  */
1953 void
1954 GCP_connect (struct CadetPeer *peer)
1955 {
1956   struct CadetTunnel *t;
1957   struct CadetPeerPath *path;
1958   struct CadetConnection *c;
1959   int rerun_search;
1960
1961   GCC_check_connections ();
1962   LOG (GNUNET_ERROR_TYPE_DEBUG,
1963        "peer_connect towards %s\n",
1964        GCP_2s (peer));
1965   /* If we have a current hello, try to connect using it. */
1966   GCP_try_connect (peer);
1967
1968   t = peer->tunnel;
1969   c = NULL;
1970   rerun_search = GNUNET_NO;
1971
1972   if (NULL != peer->path_head)
1973   {
1974     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1975     path = peer_get_best_path (peer);
1976     if (NULL != path)
1977     {
1978       char *s;
1979
1980       s = path_2s (path);
1981       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1982       GNUNET_free (s);
1983
1984       c = GCT_use_path (t, path);
1985       if (NULL == c)
1986       {
1987         /* This case can happen when the path includes a first hop that is
1988          * not yet known to be connected.
1989          *
1990          * This happens quite often during testing when running cadet
1991          * under valgrind: core connect notifications come very late
1992          * and the DHT result has already come and created a valid
1993          * path.  In this case, the peer->connections
1994          * hashmaps will be NULL and tunnel_use_path will not be able
1995          * to create a connection from that path.
1996          *
1997          * Re-running the DHT GET should give core time to callback.
1998          *
1999          * GCT_use_path -> GCC_new -> register_neighbors takes care of
2000          * updating statistics about this issue.
2001          */
2002         rerun_search = GNUNET_YES;
2003       }
2004       else
2005       {
2006         GCC_send_create (c);
2007         return;
2008       }
2009     }
2010     else
2011     {
2012       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
2013     }
2014   }
2015
2016   if (GNUNET_YES == rerun_search)
2017   {
2018     struct GNUNET_TIME_Relative delay;
2019
2020     GCP_stop_search (peer);
2021     delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
2022     peer->search_delayed = GNUNET_SCHEDULER_add_delayed (delay,
2023                                                          &delayed_search,
2024                                                          peer);
2025     GCC_check_connections ();
2026     return;
2027   }
2028
2029   if (GNUNET_NO == is_searching (peer))
2030     GCP_start_search (peer);
2031   GCC_check_connections ();
2032 }
2033
2034
2035 /**
2036  * Chech whether there is a direct (core level)  connection to peer.
2037  *
2038  * @param peer Peer to check.
2039  *
2040  * @return #GNUNET_YES if there is a direct connection.
2041  */
2042 int
2043 GCP_is_neighbor (const struct CadetPeer *peer)
2044 {
2045   struct CadetPeerPath *path;
2046
2047   if (NULL == peer->connections)
2048     return GNUNET_NO;
2049
2050   for (path = peer->path_head; NULL != path; path = path->next)
2051   {
2052     if (3 > path->length)
2053       return GNUNET_YES;
2054   }
2055
2056   /* Is not a neighbor but connections is not NULL, probably disconnecting */
2057   GNUNET_break (0);
2058   return GNUNET_NO;
2059 }
2060
2061
2062 /**
2063  * Create and initialize a new tunnel towards a peer, in case it has none.
2064  * In case the peer already has a tunnel, nothing is done.
2065  *
2066  * Does not generate any traffic, just creates the local data structures.
2067  *
2068  * @param peer Peer towards which to create the tunnel.
2069  */
2070 void
2071 GCP_add_tunnel (struct CadetPeer *peer)
2072 {
2073   GCC_check_connections ();
2074   if (NULL != peer->tunnel)
2075     return;
2076   peer->tunnel = GCT_new (peer);
2077   GCC_check_connections ();
2078 }
2079
2080
2081 /**
2082  * Add a connection to a neighboring peer.
2083  *
2084  * Store that the peer is the first hop of the connection in one
2085  * direction and that on peer disconnect the connection must be
2086  * notified and destroyed, for it will no longer be valid.
2087  *
2088  * @param peer Peer to add connection to.
2089  * @param c Connection to add.
2090  * @param pred #GNUNET_YES if we are predecessor, #GNUNET_NO if we are successor
2091  */
2092 void
2093 GCP_add_connection (struct CadetPeer *peer,
2094                     struct CadetConnection *c,
2095                     int pred)
2096 {
2097   LOG (GNUNET_ERROR_TYPE_DEBUG,
2098        "adding connection %s\n",
2099        GCC_2s (c));
2100   LOG (GNUNET_ERROR_TYPE_DEBUG,
2101        "to peer %s\n",
2102        GCP_2s (peer));
2103   GNUNET_assert (NULL != peer->connections);
2104   GNUNET_assert (GNUNET_OK ==
2105                  GNUNET_CONTAINER_multihashmap_put (peer->connections,
2106                                                     GCC_get_h (c),
2107                                                     c,
2108                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2109   LOG (GNUNET_ERROR_TYPE_DEBUG,
2110        "Peer %s has now %u connections.\n",
2111        GCP_2s (peer),
2112        GNUNET_CONTAINER_multihashmap_size (peer->connections));
2113 }
2114
2115
2116 /**
2117  * Add the path to the peer and update the path used to reach it in case this
2118  * is the shortest.
2119  *
2120  * @param peer Destination peer to add the path to.
2121  * @param path New path to add. Last peer must be @c peer.
2122  *             Path will be either used of freed if already known.
2123  * @param trusted Do we trust that this path is real?
2124  *
2125  * @return path if path was taken, pointer to existing duplicate if exists
2126  *         NULL on error.
2127  */
2128 struct CadetPeerPath *
2129 GCP_add_path (struct CadetPeer *peer,
2130               struct CadetPeerPath *path,
2131               int trusted)
2132 {
2133   struct CadetPeerPath *aux;
2134   unsigned int l;
2135   unsigned int l2;
2136
2137   GCC_check_connections ();
2138   LOG (GNUNET_ERROR_TYPE_DEBUG,
2139        "adding path [%u] to peer %s\n",
2140        path->length, GCP_2s (peer));
2141
2142   if (NULL == peer || NULL == path
2143       || path->peers[path->length - 1] != peer->id)
2144   {
2145     GNUNET_break (0);
2146     path_destroy (path);
2147     return NULL;
2148   }
2149
2150   for (l = 1; l < path->length; l++)
2151   {
2152     if (path->peers[l] == myid)
2153     {
2154       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
2155       for (l2 = 0; l2 < path->length - l; l2++)
2156       {
2157         path->peers[l2] = path->peers[l + l2];
2158       }
2159       path->length -= l;
2160       l = 1;
2161       path->peers = GNUNET_realloc (path->peers,
2162                                     path->length * sizeof (GNUNET_PEER_Id));
2163     }
2164   }
2165
2166   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
2167
2168   if (2 >= path->length && GNUNET_NO == trusted)
2169   {
2170     /* Only allow CORE to tell us about direct paths */
2171     path_destroy (path);
2172     return NULL;
2173   }
2174
2175   l = path_get_length (path);
2176   if (0 == l)
2177   {
2178     path_destroy (path);
2179     return NULL;
2180   }
2181
2182   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2183   for (aux = peer->path_head; aux != NULL; aux = aux->next)
2184   {
2185     l2 = path_get_length (aux);
2186     if (l2 > l)
2187     {
2188       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
2189       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
2190                                           peer->path_tail, aux, path);
2191       goto finish;
2192     }
2193     else
2194     {
2195       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
2196       {
2197         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
2198         path_destroy (path);
2199         return aux;
2200       }
2201     }
2202   }
2203   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head,
2204                                     peer->path_tail,
2205                                     path);
2206   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
2207
2208 finish:
2209   if (NULL != peer->tunnel
2210       && CONNECTIONS_PER_TUNNEL > GCT_count_connections (peer->tunnel)
2211       && 2 < path->length) /* Direct paths are handled by core_connect */
2212   {
2213     GCP_connect (peer);
2214   }
2215   GCC_check_connections ();
2216   return path;
2217 }
2218
2219
2220 /**
2221  * Add the path to the origin peer and update the path used to reach it in case
2222  * this is the shortest.
2223  * The path is given in peer_info -> destination, therefore we turn the path
2224  * upside down first.
2225  *
2226  * @param peer Peer to add the path to, being the origin of the path.
2227  * @param path New path to add after being inversed.
2228  *             Path will be either used or freed.
2229  * @param trusted Do we trust that this path is real?
2230  *
2231  * @return path if path was taken, pointer to existing duplicate if exists
2232  *         NULL on error.
2233  */
2234 struct CadetPeerPath *
2235 GCP_add_path_to_origin (struct CadetPeer *peer,
2236                         struct CadetPeerPath *path,
2237                         int trusted)
2238 {
2239   if (NULL == path)
2240     return NULL;
2241   path_invert (path);
2242   return GCP_add_path (peer, path, trusted);
2243 }
2244
2245
2246 /**
2247  * Adds a path to the info of all the peers in the path
2248  *
2249  * @param p Path to process.
2250  * @param confirmed Whether we know if the path works or not.
2251  */
2252 void
2253 GCP_add_path_to_all (const struct CadetPeerPath *p, int confirmed)
2254 {
2255   unsigned int i;
2256
2257   /* TODO: invert and add */
2258   GCC_check_connections ();
2259   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
2260   for (i++; i < p->length; i++)
2261   {
2262     struct CadetPeer *peer;
2263     struct CadetPeerPath *copy;
2264
2265     peer = GCP_get_short (p->peers[i], GNUNET_YES);
2266     copy = path_duplicate (p);
2267     copy->length = i + 1;
2268     GCP_add_path (peer, copy, 3 > p->length ? GNUNET_NO : confirmed);
2269   }
2270   GCC_check_connections ();
2271 }
2272
2273
2274 /**
2275  * Remove any path to the peer that has the exact same peers as the one given.
2276  *
2277  * @param peer Peer to remove the path from.
2278  * @param path Path to remove. Is always destroyed .
2279  */
2280 void
2281 GCP_remove_path (struct CadetPeer *peer,
2282                  struct CadetPeerPath *path)
2283 {
2284   struct CadetPeerPath *iter;
2285   struct CadetPeerPath *next;
2286
2287   GCC_check_connections ();
2288   GNUNET_assert (myid == path->peers[0]);
2289   GNUNET_assert (peer->id == path->peers[path->length - 1]);
2290
2291   LOG (GNUNET_ERROR_TYPE_INFO,
2292        "Removing path %p (%u) from %s\n",
2293        path, path->length, GCP_2s (peer));
2294
2295   for (iter = peer->path_head; NULL != iter; iter = next)
2296   {
2297     next = iter->next;
2298     if (0 == path_cmp (path, iter))
2299     {
2300       GNUNET_CONTAINER_DLL_remove (peer->path_head,
2301                                    peer->path_tail,
2302                                    iter);
2303       if (iter != path)
2304         path_destroy (iter);
2305     }
2306   }
2307   path_destroy (path);
2308   GCC_check_connections ();
2309 }
2310
2311
2312 /**
2313  * Check that we are aware of a connection from a neighboring peer.
2314  *
2315  * @param peer Peer to the connection is with
2316  * @param c Connection that should be in the map with this peer.
2317  */
2318 void
2319 GCP_check_connection (const struct CadetPeer *peer,
2320                       const struct CadetConnection *c)
2321 {
2322   GNUNET_assert (NULL != peer);
2323   GNUNET_assert (NULL != peer->connections);
2324     return;
2325   GNUNET_assert (GNUNET_YES ==
2326                  GNUNET_CONTAINER_multihashmap_contains_value (peer->connections,
2327                                                                GCC_get_h (c),
2328                                                                c));
2329 }
2330
2331
2332 /**
2333  * Remove a connection from a neighboring peer.
2334  *
2335  * @param peer Peer to remove connection from.
2336  * @param c Connection to remove.
2337  */
2338 void
2339 GCP_remove_connection (struct CadetPeer *peer,
2340                        const struct CadetConnection *c)
2341 {
2342   LOG (GNUNET_ERROR_TYPE_DEBUG,
2343        "Removing connection %s\n",
2344        GCC_2s (c));
2345   LOG (GNUNET_ERROR_TYPE_DEBUG,
2346        "from peer %s\n",
2347        GCP_2s (peer));
2348   if ( (NULL == peer) ||
2349        (NULL == peer->connections) )
2350     return;
2351   GNUNET_assert (GNUNET_YES ==
2352                  GNUNET_CONTAINER_multihashmap_remove (peer->connections,
2353                                                        GCC_get_h (c),
2354                                                        c));
2355   LOG (GNUNET_ERROR_TYPE_DEBUG,
2356        "Peer %s remains with %u connections.\n",
2357        GCP_2s (peer),
2358        GNUNET_CONTAINER_multihashmap_size (peer->connections));
2359 }
2360
2361
2362 /**
2363  * Start the DHT search for new paths towards the peer: we don't have
2364  * enough good connections.
2365  *
2366  * @param peer Destination peer.
2367  */
2368 void
2369 GCP_start_search (struct CadetPeer *peer)
2370 {
2371   const struct GNUNET_PeerIdentity *id;
2372   struct CadetTunnel *t = peer->tunnel;
2373
2374   GCC_check_connections ();
2375  if (NULL != peer->search_h)
2376   {
2377     GNUNET_break (0);
2378     return;
2379   }
2380
2381   if (NULL != peer->search_delayed)
2382     GCP_stop_search (peer);
2383
2384   id = GNUNET_PEER_resolve2 (peer->id);
2385   peer->search_h = GCD_search (id, &search_handler, peer);
2386
2387   if (NULL == t)
2388   {
2389     /* Why would we search for a peer with no tunnel towards it? */
2390     GNUNET_break (0);
2391     return;
2392   }
2393
2394   if (CADET_TUNNEL_NEW == GCT_get_cstate (t)
2395       || 0 == GCT_count_any_connections (t))
2396   {
2397     GCT_change_cstate (t, CADET_TUNNEL_SEARCHING);
2398   }
2399   GCC_check_connections ();
2400 }
2401
2402
2403 /**
2404  * Stop the DHT search for new paths towards the peer: we already have
2405  * enough good connections.
2406  *
2407  * @param peer Destination peer.
2408  */
2409 void
2410 GCP_stop_search (struct CadetPeer *peer)
2411 {
2412   GCC_check_connections ();
2413   if (NULL != peer->search_h)
2414   {
2415     GCD_search_stop (peer->search_h);
2416     peer->search_h = NULL;
2417   }
2418   if (NULL != peer->search_delayed)
2419   {
2420     GNUNET_SCHEDULER_cancel (peer->search_delayed);
2421     peer->search_delayed = NULL;
2422   }
2423   GCC_check_connections ();
2424 }
2425
2426
2427 /**
2428  * Get the Full ID of a peer.
2429  *
2430  * @param peer Peer to get from.
2431  *
2432  * @return Full ID of peer.
2433  */
2434 const struct GNUNET_PeerIdentity *
2435 GCP_get_id (const struct CadetPeer *peer)
2436 {
2437   return GNUNET_PEER_resolve2 (peer->id);
2438 }
2439
2440
2441 /**
2442  * Get the Short ID of a peer.
2443  *
2444  * @param peer Peer to get from.
2445  *
2446  * @return Short ID of peer.
2447  */
2448 GNUNET_PEER_Id
2449 GCP_get_short_id (const struct CadetPeer *peer)
2450 {
2451   return peer->id;
2452 }
2453
2454
2455 /**
2456  * Set tunnel.
2457  *
2458  * If tunnel is NULL and there was a search active, stop it, as it's useless.
2459  *
2460  * @param peer Peer.
2461  * @param t Tunnel.
2462  */
2463 void
2464 GCP_set_tunnel (struct CadetPeer *peer, struct CadetTunnel *t)
2465 {
2466   peer->tunnel = t;
2467   if (NULL == t && GNUNET_YES == is_searching (peer))
2468   {
2469     GCP_stop_search (peer);
2470   }
2471 }
2472
2473
2474 /**
2475  * Get the tunnel towards a peer.
2476  *
2477  * @param peer Peer to get from.
2478  *
2479  * @return Tunnel towards peer.
2480  */
2481 struct CadetTunnel *
2482 GCP_get_tunnel (const struct CadetPeer *peer)
2483 {
2484   if (NULL == peer)
2485     return NULL;
2486   return peer->tunnel;
2487 }
2488
2489
2490 /**
2491  * Set the hello message.
2492  *
2493  * @param peer Peer whose message to set.
2494  * @param hello Hello message.
2495  */
2496 void
2497 GCP_set_hello (struct CadetPeer *peer,
2498                const struct GNUNET_HELLO_Message *hello)
2499 {
2500   struct GNUNET_HELLO_Message *old;
2501   size_t size;
2502
2503   GCC_check_connections ();
2504  LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GCP_2s (peer));
2505   if (NULL == hello)
2506     return;
2507
2508   old = GCP_get_hello (peer);
2509   if (NULL == old)
2510   {
2511     size = GNUNET_HELLO_size (hello);
2512     peer->hello = GNUNET_malloc (size);
2513     GNUNET_memcpy (peer->hello, hello, size);
2514   }
2515   else
2516   {
2517     peer->hello = GNUNET_HELLO_merge (old, hello);
2518     GNUNET_free (old);
2519   }
2520   GCC_check_connections ();
2521 }
2522
2523
2524 /**
2525  * Get the hello message.
2526  *
2527  * @param peer Peer whose message to get.
2528  *
2529  * @return Hello message.
2530  */
2531 struct GNUNET_HELLO_Message *
2532 GCP_get_hello (struct CadetPeer *peer)
2533 {
2534   struct GNUNET_TIME_Absolute expiration;
2535   struct GNUNET_TIME_Relative remaining;
2536
2537   if (NULL == peer->hello)
2538     return NULL;
2539
2540   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2541   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2542   if (0 == remaining.rel_value_us)
2543   {
2544     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2545          GNUNET_STRINGS_absolute_time_to_string (expiration));
2546     GNUNET_free (peer->hello);
2547     peer->hello = NULL;
2548   }
2549   return peer->hello;
2550 }
2551
2552
2553 /**
2554  * Try to connect to a peer on TRANSPORT level.
2555  *
2556  * @param peer Peer to whom to connect.
2557  */
2558 void
2559 GCP_try_connect (struct CadetPeer *peer)
2560 {
2561   struct GNUNET_HELLO_Message *hello;
2562   struct GNUNET_MessageHeader *mh;
2563
2564   if (GNUNET_YES !=
2565       GNUNET_CONFIGURATION_get_value_yesno (cfg,
2566                                             "CADET",
2567                                             "DISABLE_TRY_CONNECT"))
2568     return;
2569   GCC_check_connections ();
2570   if (GNUNET_YES == GCP_is_neighbor (peer))
2571     return;
2572   hello = GCP_get_hello (peer);
2573   if (NULL == hello)
2574     return;
2575
2576   mh = GNUNET_HELLO_get_header (hello);
2577   if (NULL != peer->hello_offer)
2578   {
2579     GNUNET_TRANSPORT_offer_hello_cancel (peer->hello_offer);
2580     peer->hello_offer = NULL;
2581   }
2582   peer->hello_offer = GNUNET_TRANSPORT_offer_hello (cfg,
2583                                                     mh,
2584                                                     &hello_offer_done,
2585                                                     peer);
2586   if (NULL == peer->connectivity_suggestion)
2587     peer->connectivity_suggestion
2588       = GNUNET_ATS_connectivity_suggest (ats_ch,
2589                                          GNUNET_PEER_resolve2 (peer->id),
2590                                          1 /* strength */);
2591   GCC_check_connections ();
2592 }
2593
2594
2595 /**
2596  * Notify a peer that a link between two other peers is broken. If any path
2597  * used that link, eliminate it.
2598  *
2599  * @param peer Peer affected by the change.
2600  * @param peer1 Peer whose link is broken.
2601  * @param peer2 Peer whose link is broken.
2602  */
2603 void
2604 GCP_notify_broken_link (struct CadetPeer *peer,
2605                         const struct GNUNET_PeerIdentity *peer1,
2606                         const struct GNUNET_PeerIdentity *peer2)
2607 {
2608   struct CadetPeerPath *iter;
2609   struct CadetPeerPath *next;
2610   unsigned int i;
2611   GNUNET_PEER_Id p1;
2612   GNUNET_PEER_Id p2;
2613
2614   GCC_check_connections ();
2615   p1 = GNUNET_PEER_search (peer1);
2616   p2 = GNUNET_PEER_search (peer2);
2617
2618   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2619   if (0 == p1 || 0 == p2)
2620   {
2621     /* We don't even know them */
2622     return;
2623   }
2624
2625   for (iter = peer->path_head; NULL != iter; iter = next)
2626   {
2627     next = iter->next;
2628     for (i = 0; i < iter->length - 1; i++)
2629     {
2630       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2631           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2632       {
2633         char *s;
2634
2635         s = path_2s (iter);
2636         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2637         GNUNET_free (s);
2638
2639         path_invalidate (iter);
2640       }
2641     }
2642   }
2643   GCC_check_connections ();
2644 }
2645
2646
2647 /**
2648  * Count the number of known paths toward the peer.
2649  *
2650  * @param peer Peer to get path info.
2651  *
2652  * @return Number of known paths.
2653  */
2654 unsigned int
2655 GCP_count_paths (const struct CadetPeer *peer)
2656 {
2657   struct CadetPeerPath *iter;
2658   unsigned int i;
2659
2660   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2661     i++;
2662
2663   return i;
2664 }
2665
2666
2667 /**
2668  * Iterate over the paths to a peer.
2669  *
2670  * @param peer Peer to get path info.
2671  * @param callback Function to call for every path.
2672  * @param cls Closure for @a callback.
2673  *
2674  * @return Number of iterated paths.
2675  */
2676 unsigned int
2677 GCP_iterate_paths (struct CadetPeer *peer,
2678                    GCP_path_iterator callback,
2679                    void *cls)
2680 {
2681   struct CadetPeerPath *iter;
2682   unsigned int i;
2683
2684   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2685   {
2686     i++;
2687     if (GNUNET_YES != callback (cls, peer, iter))
2688       break;
2689   }
2690
2691   return i;
2692 }
2693
2694
2695 /**
2696  * Iterate all known peers.
2697  *
2698  * @param iter Iterator.
2699  * @param cls Closure for @c iter.
2700  */
2701 void
2702 GCP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter,
2703                  void *cls)
2704 {
2705   GCC_check_connections ();
2706   GNUNET_CONTAINER_multipeermap_iterate (peers,
2707                                          iter,
2708                                          cls);
2709   GCC_check_connections ();
2710 }
2711
2712
2713 /**
2714  * Get the static string for a peer ID.
2715  *
2716  * @param peer Peer.
2717  *
2718  * @return Static string for it's ID.
2719  */
2720 const char *
2721 GCP_2s (const struct CadetPeer *peer)
2722 {
2723   if (NULL == peer)
2724     return "(NULL)";
2725   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2726 }
2727
2728
2729 /* end of gnunet-service-cadet_peer.c */