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