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