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