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