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