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