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