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