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