- dont destroy a path right away, broken paths can cause long loops with outdated...
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_peer.c
1 /*
2      This file is part of GNUnet.
3      (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_core_service.h"
26 #include "gnunet_statistics_service.h"
27
28 #include "mesh_protocol.h"
29
30 #include "gnunet-service-mesh_peer.h"
31 #include "gnunet-service-mesh_dht.h"
32 #include "gnunet-service-mesh_connection.h"
33 #include "gnunet-service-mesh_tunnel.h"
34 #include "mesh_path.h"
35
36 #define LOG(level, ...) GNUNET_log_from (level,"mesh-p2p",__VA_ARGS__)
37
38 /******************************************************************************/
39 /********************************   STRUCTS  **********************************/
40 /******************************************************************************/
41
42 /**
43  * Struct containing info about a queued transmission to this peer
44  */
45 struct MeshPeerQueue
46 {
47     /**
48       * DLL next
49       */
50   struct MeshPeerQueue *next;
51
52     /**
53       * DLL previous
54       */
55   struct MeshPeerQueue *prev;
56
57     /**
58      * Peer this transmission is directed to.
59      */
60   struct MeshPeer *peer;
61
62     /**
63      * Connection this message belongs to.
64      */
65   struct MeshConnection *c;
66
67     /**
68      * Is FWD in c?
69      */
70   int fwd;
71
72     /**
73      * Pointer to info stucture used as cls.
74      */
75   void *cls;
76
77     /**
78      * Type of message
79      */
80   uint16_t type;
81
82     /**
83      * Size of the message
84      */
85   size_t size;
86
87     /**
88      * Set when this message starts waiting for CORE.
89      */
90   struct GNUNET_TIME_Absolute start_waiting;
91
92     /**
93      * Function to call on sending.
94      */
95   GMP_sent callback;
96
97     /**
98      * Closure for callback.
99      */
100   void *callback_cls;
101 };
102
103 /**
104  * Struct containing all information regarding a given peer
105  */
106 struct MeshPeer
107 {
108     /**
109      * ID of the peer
110      */
111   GNUNET_PEER_Id id;
112
113     /**
114      * Last time we heard from this peer
115      */
116   struct GNUNET_TIME_Absolute last_contact;
117
118     /**
119      * Paths to reach the peer, ordered by ascending hop count
120      */
121   struct MeshPeerPath *path_head;
122
123     /**
124      * Paths to reach the peer, ordered by ascending hop count
125      */
126   struct MeshPeerPath *path_tail;
127
128     /**
129      * Handle to stop the DHT search for paths to this peer
130      */
131   struct GMD_search_handle *search_h;
132
133     /**
134      * Tunnel to this peer, if any.
135      */
136   struct MeshTunnel3 *tunnel;
137
138     /**
139      * Connections that go through this peer, indexed by tid;
140      */
141   struct GNUNET_CONTAINER_MultiHashMap *connections;
142
143     /**
144      * Handle for queued transmissions
145      */
146   struct GNUNET_CORE_TransmitHandle *core_transmit;
147
148   /**
149    * Transmission queue to core DLL head
150    */
151   struct MeshPeerQueue *queue_head;
152
153   /**
154    * Transmission queue to core DLL tail
155    */
156   struct MeshPeerQueue *queue_tail;
157
158   /**
159    * How many messages are in the queue to this peer.
160    */
161   unsigned int queue_n;
162 };
163
164
165 /******************************************************************************/
166 /*******************************   GLOBALS  ***********************************/
167 /******************************************************************************/
168
169 /**
170  * Global handle to the statistics service.
171  */
172 extern struct GNUNET_STATISTICS_Handle *stats;
173
174 /**
175  * Local peer own ID (full value).
176  */
177 extern struct GNUNET_PeerIdentity my_full_id;
178
179 /**
180  * Local peer own ID (short)
181  */
182 extern GNUNET_PEER_Id myid;
183
184 /**
185  * Peers known, indexed by PeerIdentity (MeshPeer).
186  */
187 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
188
189 /**
190  * How many peers do we want to remember?
191  */
192 static unsigned long long max_peers;
193
194 /**
195  * Percentage of messages that will be dropped (for test purposes only).
196  */
197 static unsigned long long drop_percent;
198
199 /**
200  * Handle to communicate with core.
201  */
202 static struct GNUNET_CORE_Handle *core_handle;
203
204
205 /******************************************************************************/
206 /***************************** CORE CALLBACKS *********************************/
207 /******************************************************************************/
208
209
210 /**
211  * Iterator to notify all connections of a broken link. Mark connections
212  * to destroy after all traffic has been sent.
213  *
214  * @param cls Closure (peer disconnected).
215  * @param key Current key code (peer id).
216  * @param value Value in the hash map (connection).
217  *
218  * @return #GNUNET_YES to continue to iterate.
219  */
220 static int
221 notify_broken (void *cls,
222                const struct GNUNET_HashCode *key,
223                void *value)
224 {
225   struct MeshPeer *peer = cls;
226   struct MeshConnection *c = value;
227
228   LOG (GNUNET_ERROR_TYPE_DEBUG, "  notifying %s due to %s\n",
229        GMC_2s (c), GMP_2s (peer));
230   GMC_notify_broken (c, peer);
231
232   return GNUNET_YES;
233 }
234
235
236 /**
237  * Method called whenever a given peer connects.
238  *
239  * @param cls closure
240  * @param peer peer identity this notification is about
241  */
242 static void
243 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
244 {
245   struct MeshPeer *mp;
246   struct MeshPeerPath *path;
247
248   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer connected\n");
249   LOG (GNUNET_ERROR_TYPE_DEBUG, "     %s\n", GNUNET_i2s (&my_full_id));
250   mp = GMP_get (peer);
251   if (myid == mp->id)
252   {
253     LOG (GNUNET_ERROR_TYPE_DEBUG, "     (self)\n");
254     path = path_new (1);
255   }
256   else
257   {
258     LOG (GNUNET_ERROR_TYPE_DEBUG, "     %s\n", GNUNET_i2s (peer));
259     path = path_new (2);
260     path->peers[1] = mp->id;
261     GNUNET_PEER_change_rc (mp->id, 1);
262     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
263   }
264   path->peers[0] = myid;
265   GNUNET_PEER_change_rc (myid, 1);
266   GMP_add_path (mp, path, GNUNET_YES);
267
268   mp->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
269   return;
270 }
271
272
273 /**
274  * Method called whenever a peer disconnects.
275  *
276  * @param cls closure
277  * @param peer peer identity this notification is about
278  */
279 static void
280 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
281 {
282   struct MeshPeer *p;
283
284   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer disconnected\n");
285   p = GNUNET_CONTAINER_multipeermap_get (peers, peer);
286   if (NULL == p)
287   {
288     GNUNET_break (0);
289     return;
290   }
291   if (myid == p->id)
292     LOG (GNUNET_ERROR_TYPE_DEBUG, "     (self: %s)\n", GMP_2s (p));
293   else
294     LOG (GNUNET_ERROR_TYPE_DEBUG, "     %s\n", GMP_2s (p));
295
296
297   GNUNET_CONTAINER_multihashmap_iterate (p->connections, &notify_broken, p);
298   GNUNET_CONTAINER_multihashmap_destroy (p->connections);
299   p->connections = NULL;
300   if (NULL != p->core_transmit)
301     {
302       GNUNET_CORE_notify_transmit_ready_cancel (p->core_transmit);
303       p->core_transmit = NULL;
304     }
305   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
306
307   return;
308 }
309
310
311 /**
312  * Functions to handle messages from core
313  */
314 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
315   {&GMC_handle_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
316     0},
317   {&GMC_handle_confirm, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
318     sizeof (struct GNUNET_MESH_ConnectionACK)},
319   {&GMC_handle_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
320     sizeof (struct GNUNET_MESH_ConnectionBroken)},
321   {&GMC_handle_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
322     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
323   {&GMC_handle_keepalive, GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE,
324     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
325   {&GMC_handle_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
326     sizeof (struct GNUNET_MESH_ACK)},
327   {&GMC_handle_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
328     sizeof (struct GNUNET_MESH_Poll)},
329   {&GMC_handle_encrypted, GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED, 0},
330   {&GMC_handle_kx, GNUNET_MESSAGE_TYPE_MESH_KX, 0},
331   {NULL, 0, 0}
332 };
333
334
335 /**
336  * To be called on core init/fail.
337  *
338  * @param cls Closure (config)
339  * @param identity the public identity of this peer
340  */
341 static void
342 core_init (void *cls,
343            const struct GNUNET_PeerIdentity *identity)
344 {
345   const struct GNUNET_CONFIGURATION_Handle *c = cls;
346   static int i = 0;
347
348   LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
349   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
350   {
351     LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
352     LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (identity));
353     LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
354     GNUNET_CORE_disconnect (core_handle);
355     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
356                                        NULL,      /* Closure passed to MESH functions */
357                                        &core_init,        /* Call core_init once connected */
358                                        &core_connect,     /* Handle connects */
359                                        &core_disconnect,  /* remove peers on disconnects */
360                                        NULL,      /* Don't notify about all incoming messages */
361                                        GNUNET_NO, /* For header only in notification */
362                                        NULL,      /* Don't notify about all outbound messages */
363                                        GNUNET_NO, /* For header-only out notification */
364                                        core_handlers);    /* Register these handlers */
365     if (10 < i++)
366       GNUNET_abort();
367   }
368   GML_start ();
369   return;
370 }
371
372 /**
373   * Core callback to write a pre-constructed data packet to core buffer
374   *
375   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
376   * @param size Number of bytes available in buf.
377   * @param buf Where the to write the message.
378   *
379   * @return number of bytes written to buf
380   */
381 static size_t
382 send_core_data_raw (void *cls, size_t size, void *buf)
383 {
384   struct GNUNET_MessageHeader *msg = cls;
385   size_t total_size;
386
387   GNUNET_assert (NULL != msg);
388   total_size = ntohs (msg->size);
389
390   if (total_size > size)
391   {
392     GNUNET_break (0);
393     return 0;
394   }
395   memcpy (buf, msg, total_size);
396   GNUNET_free (cls);
397   return total_size;
398 }
399
400
401 /**
402  * Function to send a create connection message to a peer.
403  *
404  * @param c Connection to create.
405  * @param size number of bytes available in buf
406  * @param buf where the callee should write the message
407  * @return number of bytes written to buf
408  */
409 static size_t
410 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
411 {
412   struct GNUNET_MESH_ConnectionCreate *msg;
413   struct GNUNET_PeerIdentity *peer_ptr;
414   const struct MeshPeerPath *p = GMC_get_path (c);
415   size_t size_needed;
416   int i;
417
418   if (NULL == p)
419     return 0;
420
421   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
422   size_needed =
423       sizeof (struct GNUNET_MESH_ConnectionCreate) +
424       p->length * sizeof (struct GNUNET_PeerIdentity);
425
426   if (size < size_needed || NULL == buf)
427   {
428     GNUNET_break (0);
429     return 0;
430   }
431   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
432   msg->header.size = htons (size_needed);
433   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
434   msg->cid = *GMC_get_id (c);
435
436   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
437   for (i = 0; i < p->length; i++)
438   {
439     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
440   }
441
442   LOG (GNUNET_ERROR_TYPE_DEBUG,
443        "CONNECTION CREATE (%u bytes long) sent!\n",
444        size_needed);
445   return size_needed;
446 }
447
448
449 /**
450  * Creates a path ack message in buf and frees all unused resources.
451  *
452  * @param c Connection to send an ACK on.
453  * @param size number of bytes available in buf
454  * @param buf where the callee should write the message
455  *
456  * @return number of bytes written to buf
457  */
458 static size_t
459 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
460 {
461   struct GNUNET_MESH_ConnectionACK *msg = buf;
462
463   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
464   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
465   {
466     GNUNET_break (0);
467     return 0;
468   }
469   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
470   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
471   msg->cid = *GMC_get_id (c);
472   msg->reserved = 0;
473
474   /* TODO add signature */
475
476   LOG (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
477   return sizeof (struct GNUNET_MESH_ConnectionACK);
478 }
479
480
481 /******************************************************************************/
482 /********************************   STATIC  ***********************************/
483 /******************************************************************************/
484
485 /**
486  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
487  *
488  * @param cls closure
489  * @param key current key code
490  * @param value value in the hash map
491  * @return #GNUNET_YES if we should continue to iterate,
492  *         #GNUNET_NO if not.
493  */
494 static int
495 shutdown_tunnel (void *cls,
496                  const struct GNUNET_PeerIdentity *key,
497                  void *value)
498 {
499   struct MeshPeer *p = value;
500   struct MeshTunnel3 *t = p->tunnel;
501
502   if (NULL != t)
503     GMT_destroy (t);
504   return GNUNET_YES;
505 }
506
507
508
509 /**
510  * Destroy the peer_info and free any allocated resources linked to it
511  *
512  * @param peer The peer_info to destroy.
513  *
514  * @return GNUNET_OK on success
515  */
516 static int
517 peer_destroy (struct MeshPeer *peer)
518 {
519   struct GNUNET_PeerIdentity id;
520   struct MeshPeerPath *p;
521   struct MeshPeerPath *nextp;
522
523   GNUNET_PEER_resolve (peer->id, &id);
524   GNUNET_PEER_change_rc (peer->id, -1);
525
526   LOG (GNUNET_ERROR_TYPE_WARNING, "destroying peer %s\n", GNUNET_i2s (&id));
527
528   if (GNUNET_YES !=
529     GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
530   {
531     GNUNET_break (0);
532     LOG (GNUNET_ERROR_TYPE_WARNING, " not in peermap!!\n");
533   }
534   if (NULL != peer->search_h)
535   {
536     GMD_search_stop (peer->search_h);
537   }
538   p = peer->path_head;
539   while (NULL != p)
540   {
541     nextp = p->next;
542     GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
543     path_destroy (p);
544     p = nextp;
545   }
546   GMT_destroy_empty (peer->tunnel);
547   GNUNET_free (peer);
548   return GNUNET_OK;
549 }
550
551
552 /**
553  * Returns if peer is used (has a tunnel or is neighbor).
554  *
555  * @param peer Peer to check.
556  *
557  * @return #GNUNET_YES if peer is in use.
558  */
559 static int
560 peer_is_used (struct MeshPeer *peer)
561 {
562   struct MeshPeerPath *p;
563
564   if (NULL != peer->tunnel)
565     return GNUNET_YES;
566
567   for (p = peer->path_head; NULL != p; p = p->next)
568   {
569     if (p->length < 3)
570       return GNUNET_YES;
571   }
572     return GNUNET_NO;
573 }
574
575
576 /**
577  * Iterator over all the peers to get the oldest timestamp.
578  *
579  * @param cls Closure (unsued).
580  * @param key ID of the peer.
581  * @param value Peer_Info of the peer.
582  */
583 static int
584 peer_get_oldest (void *cls,
585                  const struct GNUNET_PeerIdentity *key,
586                  void *value)
587 {
588   struct MeshPeer *p = value;
589   struct GNUNET_TIME_Absolute *abs = cls;
590
591   /* Don't count active peers */
592   if (GNUNET_YES == peer_is_used (p))
593     return GNUNET_YES;
594
595   if (abs->abs_value_us < p->last_contact.abs_value_us)
596     abs->abs_value_us = p->last_contact.abs_value_us;
597
598   return GNUNET_YES;
599 }
600
601
602 /**
603  * Iterator over all the peers to remove the oldest entry.
604  *
605  * @param cls Closure (unsued).
606  * @param key ID of the peer.
607  * @param value Peer_Info of the peer.
608  */
609 static int
610 peer_timeout (void *cls,
611               const struct GNUNET_PeerIdentity *key,
612               void *value)
613 {
614   struct MeshPeer *p = value;
615   struct GNUNET_TIME_Absolute *abs = cls;
616
617   LOG (GNUNET_ERROR_TYPE_WARNING,
618        "peer %s timeout\n", GNUNET_i2s (key));
619
620   if (p->last_contact.abs_value_us == abs->abs_value_us &&
621       GNUNET_NO == peer_is_used (p))
622   {
623     peer_destroy (p);
624     return GNUNET_NO;
625   }
626     return GNUNET_YES;
627 }
628
629
630 /**
631  * Delete oldest unused peer.
632  */
633 static void
634 peer_delete_oldest (void)
635 {
636   struct GNUNET_TIME_Absolute abs;
637
638   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
639
640   GNUNET_CONTAINER_multipeermap_iterate (peers,
641                                          &peer_get_oldest,
642                                          &abs);
643   GNUNET_CONTAINER_multipeermap_iterate (peers,
644                                          &peer_timeout,
645                                          &abs);
646 }
647
648
649 /**
650  * Choose the best (yet unused) path towards a peer,
651  * considering the tunnel properties.
652  *
653  * @param peer The destination peer.
654  *
655  * @return Best current known path towards the peer, if any.
656  */
657 static struct MeshPeerPath *
658 peer_get_best_path (const struct MeshPeer *peer)
659 {
660   struct MeshPeerPath *best_p;
661   struct MeshPeerPath *p;
662   unsigned int best_cost;
663   unsigned int cost;
664
665   best_cost = UINT_MAX;
666   best_p = NULL;
667   for (p = peer->path_head; NULL != p; p = p->next)
668   {
669     if (GNUNET_YES == GMT_is_path_used (peer->tunnel, p))
670       continue; /* If path is already in use, skip it. */
671
672     if (GNUNET_NO == path_is_valid (p))
673       continue; /* Don't use invalid paths. */
674
675     if ((cost = GMT_get_path_cost (peer->tunnel, p)) < best_cost)
676     {
677       best_cost = cost;
678       best_p = p;
679     }
680   }
681   return best_p;
682 }
683
684
685 static int
686 queue_is_sendable (struct MeshPeerQueue *q)
687 {
688   /* Is PID-independent? */
689   switch (q->type)
690   {
691     case GNUNET_MESSAGE_TYPE_MESH_ACK:
692     case GNUNET_MESSAGE_TYPE_MESH_POLL:
693     case GNUNET_MESSAGE_TYPE_MESH_KX:
694     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
695     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
696     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
697     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
698     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
699       return GNUNET_YES;
700
701     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
702       break;
703
704     default:
705       GNUNET_break (0);
706   }
707
708   if (GMC_is_sendable (q->c, q->fwd))
709     return GNUNET_YES;
710
711   return GNUNET_NO;
712 }
713
714
715 /**
716  * Get first sendable message.
717  *
718  * @param peer The destination peer.
719  *
720  * @return Best current known path towards the peer, if any.
721  */
722 static struct MeshPeerQueue *
723 peer_get_first_message (const struct MeshPeer *peer)
724 {
725   struct MeshPeerQueue *q;
726
727   for (q = peer->queue_head; NULL != q; q = q->next)
728   {
729     if (queue_is_sendable (q))
730       return q;
731   }
732
733   return NULL;
734 }
735
736
737 /**
738  * Function to process paths received for a new peer addition. The recorded
739  * paths form the initial tunnel, which can be optimized later.
740  * Called on each result obtained for the DHT search.
741  *
742  * @param cls closure
743  * @param path
744  */
745 static void
746 search_handler (void *cls, const struct MeshPeerPath *path)
747 {
748   struct MeshPeer *peer = cls;
749   unsigned int connection_count;
750
751   GMP_add_path_to_all (path, GNUNET_NO);
752
753   /* Count connections */
754   connection_count = GMT_count_connections (peer->tunnel);
755
756   /* If we already have 3 (or more (?!)) connections, it's enough */
757   if (3 <= connection_count)
758     return;
759
760   if (MESH_TUNNEL3_SEARCHING == GMT_get_cstate (peer->tunnel))
761   {
762     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
763     GMP_connect (peer);
764   }
765   return;
766 }
767
768
769 /**
770  * Core callback to write a queued packet to core buffer
771  *
772  * @param cls Closure (peer info).
773  * @param size Number of bytes available in buf.
774  * @param buf Where the to write the message.
775  *
776  * @return number of bytes written to buf
777  */
778 static size_t
779 queue_send (void *cls, size_t size, void *buf)
780 {
781   struct MeshPeer *peer = cls;
782   struct MeshConnection *c;
783   struct MeshPeerQueue *queue;
784   const struct GNUNET_PeerIdentity *dst_id;
785   size_t data_size;
786
787   peer->core_transmit = NULL;
788   LOG (GNUNET_ERROR_TYPE_DEBUG, "* Queue send towards %s (max %u)\n",
789        GMP_2s (peer), size);
790
791   if (NULL == buf || 0 == size)
792   {
793     LOG (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
794     return 0;
795   }
796
797   /* Initialize */
798   queue = peer_get_first_message (peer);
799   if (NULL == queue)
800   {
801     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
802     return 0;
803   }
804   c = queue->c;
805
806   dst_id = GNUNET_PEER_resolve2 (peer->id);
807   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   on connection %s\n", GMC_2s (c));
808   /* Check if buffer size is enough for the message */
809   if (queue->size > size)
810   {
811       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
812       peer->core_transmit =
813           GNUNET_CORE_notify_transmit_ready (core_handle,
814                                              GNUNET_NO,
815                                              0,
816                                              GNUNET_TIME_UNIT_FOREVER_REL,
817                                              dst_id,
818                                              queue->size,
819                                              &queue_send,
820                                              peer);
821       return 0;
822   }
823   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
824
825   /* Fill buf */
826   switch (queue->type)
827   {
828     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
829     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
830     case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
831     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
832     case GNUNET_MESSAGE_TYPE_MESH_KX:
833     case GNUNET_MESSAGE_TYPE_MESH_ACK:
834     case GNUNET_MESSAGE_TYPE_MESH_POLL:
835       LOG (GNUNET_ERROR_TYPE_DEBUG,
836                   "*   raw: %s\n",
837                   GM_m2s (queue->type));
838       data_size = send_core_data_raw (queue->cls, size, buf);
839       break;
840     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
841       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
842       if (GMC_is_origin (c, GNUNET_YES))
843         data_size = send_core_connection_create (queue->c, size, buf);
844       else
845         data_size = send_core_data_raw (queue->cls, size, buf);
846       break;
847     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
848       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
849       if (GMC_is_origin (c, GNUNET_NO) ||
850           GMC_is_origin (c, GNUNET_YES))
851         data_size = send_core_connection_ack (queue->c, size, buf);
852       else
853         data_size = send_core_data_raw (queue->cls, size, buf);
854       break;
855     case GNUNET_MESSAGE_TYPE_MESH_DATA:
856     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
857     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
858       /* This should be encapsulted */
859       GNUNET_break (0);
860       data_size = 0;
861       break;
862     default:
863       GNUNET_break (0);
864       LOG (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n", queue->type);
865       data_size = 0;
866   }
867
868   if (0 < drop_percent &&
869       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
870   {
871     LOG (GNUNET_ERROR_TYPE_WARNING,
872                 "Dropping message of type %s\n",
873                 GM_m2s (queue->type));
874     data_size = 0;
875   }
876
877   /* Free queue, but cls was freed by send_core_* */
878   GMP_queue_destroy (queue, GNUNET_NO);
879
880   /* If more data in queue, send next */
881   queue = peer_get_first_message (peer);
882   if (NULL != queue)
883   {
884     LOG (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
885     if (NULL == peer->core_transmit)
886     {
887       peer->core_transmit =
888           GNUNET_CORE_notify_transmit_ready(core_handle,
889                                             0,
890                                             0,
891                                             GNUNET_TIME_UNIT_FOREVER_REL,
892                                             dst_id,
893                                             queue->size,
894                                             &queue_send,
895                                             peer);
896       queue->start_waiting = GNUNET_TIME_absolute_get ();
897     }
898     else
899     {
900       LOG (GNUNET_ERROR_TYPE_DEBUG,
901                   "*   tmt rdy called somewhere else\n");
902     }
903 //     GMC_start_poll (); FIXME needed?
904   }
905   else
906   {
907 //     GMC_stop_poll(); FIXME needed?
908   }
909
910   LOG (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
911   return data_size;
912 }
913
914
915 /******************************************************************************/
916 /********************************    API    ***********************************/
917 /******************************************************************************/
918
919
920 /**
921  * Free a transmission that was already queued with all resources
922  * associated to the request.
923  *
924  * @param queue Queue handler to cancel.
925  * @param clear_cls Is it necessary to free associated cls?
926  */
927 void
928 GMP_queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
929 {
930   struct MeshPeer *peer;
931
932   peer = queue->peer;
933   GNUNET_assert (NULL != queue->c);
934
935   if (GNUNET_YES == clear_cls)
936   {
937     LOG (GNUNET_ERROR_TYPE_DEBUG, "#   queue destroy type %s\n",
938                 GM_m2s (queue->type));
939     switch (queue->type)
940     {
941       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
942         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
943         /* fall through */
944       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
945       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
946       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
947       case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
948       case GNUNET_MESSAGE_TYPE_MESH_KX:
949       case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
950       case GNUNET_MESSAGE_TYPE_MESH_ACK:
951       case GNUNET_MESSAGE_TYPE_MESH_POLL:
952         GNUNET_free_non_null (queue->cls);
953         break;
954
955       default:
956         GNUNET_break (0);
957         LOG (GNUNET_ERROR_TYPE_ERROR, "#   type %s unknown!\n",
958                     GM_m2s (queue->type));
959     }
960   }
961   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
962
963   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
964       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
965   {
966     peer->queue_n--;
967   }
968
969   if (NULL != queue->callback)
970   {
971     LOG (GNUNET_ERROR_TYPE_DEBUG, "#   Calling callback\n");
972     queue->callback (queue->callback_cls,
973                      queue->c, queue->type,
974                      queue->fwd, queue->size,
975                      GNUNET_TIME_absolute_get_duration (queue->start_waiting));
976   }
977
978   GNUNET_free (queue);
979 }
980
981
982 /**
983  * @brief Queue and pass message to core when possible.
984  *
985  * @param peer Peer towards which to queue the message.
986  * @param cls Closure (@c type dependant). It will be used by queue_send to
987  *            build the message to be sent if not already prebuilt.
988  * @param type Type of the message, 0 for a raw message.
989  * @param size Size of the message.
990  * @param c Connection this message belongs to (cannot be NULL).
991  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
992  * @param cont Continuation to be called once CORE has taken the message.
993  * @param cont_cls Closure for @c cont.
994  *
995  * @return Handle to cancel the message before it is sent. Once cont is called
996  *         message has been sent and therefore the handle is no longer valid.
997  */
998 struct MeshPeerQueue *
999 GMP_queue_add (struct MeshPeer *peer, void *cls, uint16_t type, size_t size,
1000                struct MeshConnection *c, int fwd,
1001                GMP_sent cont, void *cont_cls)
1002 {
1003   struct MeshPeerQueue *queue;
1004   int priority;
1005   int call_core;
1006
1007   LOG (GNUNET_ERROR_TYPE_DEBUG,
1008        "queue add %s %s towards %s (size %u) on c %p (%s)\n",
1009        GM_f2s (fwd),  GM_m2s (type), GMP_2s(peer),
1010        size, c, GMC_2s (c));
1011   GNUNET_assert (NULL != c);
1012
1013   if (NULL == peer->connections)
1014   {
1015     /* We are not connected to this peer, ignore request. */
1016     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING %s not a neighbor\n", GMP_2s (peer));
1017     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1018                               GNUNET_NO);
1019     return NULL;
1020   }
1021
1022   priority = 0;
1023
1024   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
1025       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
1026   {
1027     priority = 100;
1028   }
1029
1030   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1031
1032   call_core = GMC_is_sendable (c, fwd);
1033   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
1034   queue->cls = cls;
1035   queue->type = type;
1036   queue->size = size;
1037   queue->peer = peer;
1038   queue->c = c;
1039   queue->fwd = fwd;
1040   queue->callback = cont;
1041   queue->callback_cls = cont_cls;
1042   if (100 > priority)
1043   {
1044     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
1045     peer->queue_n++;
1046   }
1047   else
1048   {
1049     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
1050     call_core = GNUNET_YES;
1051   }
1052
1053   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1054   {
1055     LOG (GNUNET_ERROR_TYPE_DEBUG,
1056                 "calling core tmt rdy towards %s for %u bytes\n",
1057                 GMP_2s (peer), size);
1058     peer->core_transmit =
1059         GNUNET_CORE_notify_transmit_ready (core_handle,
1060                                            0,
1061                                            0,
1062                                            GNUNET_TIME_UNIT_FOREVER_REL,
1063                                            GNUNET_PEER_resolve2 (peer->id),
1064                                            size,
1065                                            &queue_send,
1066                                            peer);
1067     queue->start_waiting = GNUNET_TIME_absolute_get ();
1068   }
1069   else
1070   {
1071     LOG (GNUNET_ERROR_TYPE_DEBUG,
1072                 "core tmt rdy towards %s already called\n",
1073                 GMP_2s (peer));
1074
1075   }
1076   return queue;
1077 }
1078
1079
1080 /**
1081  * Cancel all queued messages to a peer that belong to a certain connection.
1082  *
1083  * @param peer Peer towards whom to cancel.
1084  * @param c Connection whose queued messages to cancel. Might be destroyed by
1085  *          the sent continuation call.
1086  */
1087 void
1088 GMP_queue_cancel (struct MeshPeer *peer, struct MeshConnection *c)
1089 {
1090   struct MeshPeerQueue *q;
1091   struct MeshPeerQueue *next;
1092   struct MeshPeerQueue *prev;
1093
1094   for (q = peer->queue_head; NULL != q; q = next)
1095   {
1096     prev = q->prev;
1097     if (q->c == c)
1098     {
1099       LOG (GNUNET_ERROR_TYPE_DEBUG, "GMP_cancel_queue %s\n", GM_m2s (q->type));
1100       GMP_queue_destroy (q, GNUNET_YES);
1101
1102       /* Get next from prev, q->next might be already freed:
1103        * queue destroy -> callback -> GMC_destroy -> cancel_queues -> here
1104        */
1105       if (NULL == prev)
1106         next = peer->queue_head;
1107       else
1108         next = prev->next;
1109     }
1110     else
1111     {
1112       next = q->next;
1113     }
1114   }
1115   if (NULL == peer->queue_head)
1116   {
1117     if (NULL != peer->core_transmit)
1118     {
1119       GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1120       peer->core_transmit = NULL;
1121     }
1122   }
1123 }
1124
1125
1126 /**
1127  * Get the first transmittable message for a connection.
1128  *
1129  * @param peer Neighboring peer.
1130  * @param c Connection.
1131  *
1132  * @return First transmittable message.
1133  */
1134 static struct MeshPeerQueue *
1135 connection_get_first_message (struct MeshPeer *peer, struct MeshConnection *c)
1136 {
1137   struct MeshPeerQueue *q;
1138
1139   for (q = peer->queue_head; NULL != q; q = q->next)
1140   {
1141     if (q->c != c)
1142       continue;
1143     if (queue_is_sendable (q))
1144     {
1145       LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
1146       return q;
1147     }
1148     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
1149   }
1150
1151   return NULL;
1152 }
1153
1154
1155 void
1156 GMP_queue_unlock (struct MeshPeer *peer, struct MeshConnection *c)
1157 {
1158   struct MeshPeerQueue *q;
1159   size_t size;
1160
1161   if (NULL != peer->core_transmit)
1162   {
1163     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
1164     return; /* Already unlocked */
1165   }
1166
1167   q = connection_get_first_message (peer, c);
1168   if (NULL == q)
1169   {
1170     LOG (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
1171     return; /* Nothing to transmit */
1172   }
1173
1174   size = q->size;
1175   peer->core_transmit =
1176       GNUNET_CORE_notify_transmit_ready (core_handle,
1177                                          GNUNET_NO,
1178                                          0,
1179                                          GNUNET_TIME_UNIT_FOREVER_REL,
1180                                          GNUNET_PEER_resolve2 (peer->id),
1181                                          size,
1182                                          &queue_send,
1183                                          peer);
1184 }
1185
1186
1187 /**
1188  * Initialize the peer subsystem.
1189  *
1190  * @param c Configuration.
1191  */
1192 void
1193 GMP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1194 {
1195   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1196   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1197   if (GNUNET_OK !=
1198       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
1199                                              &max_peers))
1200   {
1201     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1202                                "MESH", "MAX_PEERS", "USING DEFAULT");
1203     max_peers = 1000;
1204   }
1205
1206   if (GNUNET_OK !=
1207       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
1208                                              &drop_percent))
1209   {
1210     drop_percent = 0;
1211   }
1212   else
1213   {
1214     LOG (GNUNET_ERROR_TYPE_WARNING,
1215                 "\n***************************************\n"
1216                 "Mesh is running with drop mode enabled.\n"
1217                 "This is NOT a good idea!\n"
1218                 "Remove the DROP_PERCENT option from your configuration.\n"
1219                 "***************************************\n");
1220   }
1221
1222   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1223                                      NULL,      /* Closure passed to MESH functions */
1224                                      &core_init,        /* Call core_init once connected */
1225                                      &core_connect,     /* Handle connects */
1226                                      &core_disconnect,  /* remove peers on disconnects */
1227                                      NULL,      /* Don't notify about all incoming messages */
1228                                      GNUNET_NO, /* For header only in notification */
1229                                      NULL,      /* Don't notify about all outbound messages */
1230                                      GNUNET_NO, /* For header-only out notification */
1231                                      core_handlers);    /* Register these handlers */
1232   if (NULL == core_handle)
1233   {
1234     GNUNET_break (0);
1235     GNUNET_SCHEDULER_shutdown ();
1236     return;
1237   }
1238 }
1239
1240 /**
1241  * Shut down the peer subsystem.
1242  */
1243 void
1244 GMP_shutdown (void)
1245 {
1246   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
1247
1248   if (core_handle != NULL)
1249   {
1250     GNUNET_CORE_disconnect (core_handle);
1251     core_handle = NULL;
1252   }
1253   GNUNET_PEER_change_rc (myid, -1);
1254 }
1255
1256 /**
1257  * Retrieve the MeshPeer stucture associated with the peer, create one
1258  * and insert it in the appropriate structures if the peer is not known yet.
1259  *
1260  * @param peer_id Full identity of the peer.
1261  *
1262  * @return Existing or newly created peer structure.
1263  */
1264 struct MeshPeer *
1265 GMP_get (const struct GNUNET_PeerIdentity *peer_id)
1266 {
1267   struct MeshPeer *peer;
1268
1269   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1270   if (NULL == peer)
1271   {
1272     peer = GNUNET_new (struct MeshPeer);
1273     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1274     {
1275       peer_delete_oldest ();
1276     }
1277         GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1278                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1279         peer->id = GNUNET_PEER_intern (peer_id);
1280   }
1281   peer->last_contact = GNUNET_TIME_absolute_get();
1282
1283   return peer;
1284 }
1285
1286
1287 /**
1288  * Retrieve the MeshPeer stucture associated with the peer, create one
1289  * and insert it in the appropriate structures if the peer is not known yet.
1290  *
1291  * @param peer Short identity of the peer.
1292  *
1293  * @return Existing or newly created peer structure.
1294  */
1295 struct MeshPeer *
1296 GMP_get_short (const GNUNET_PEER_Id peer)
1297 {
1298   return GMP_get (GNUNET_PEER_resolve2 (peer));
1299 }
1300
1301
1302 /**
1303  * Try to establish a new connection to this peer (in its tunnel).
1304  * If the peer doesn't have any path to it yet, try to get one.
1305  * If the peer already has some path, send a CREATE CONNECTION towards it.
1306  *
1307  * @param peer Peer to connect to.
1308  */
1309 void
1310 GMP_connect (struct MeshPeer *peer)
1311 {
1312   struct MeshTunnel3 *t;
1313   struct MeshPeerPath *p;
1314   struct MeshConnection *c;
1315   int rerun_search;
1316
1317   LOG (GNUNET_ERROR_TYPE_DEBUG, "peer_connect towards %s\n", GMP_2s (peer));
1318   t = peer->tunnel;
1319   c = NULL;
1320   rerun_search = GNUNET_NO;
1321
1322   if (NULL != peer->path_head)
1323   {
1324     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1325     p = peer_get_best_path (peer);
1326     if (NULL != p)
1327     {
1328       LOG (GNUNET_ERROR_TYPE_DEBUG, "  %u hops\n", p->length);
1329       c = GMT_use_path (t, p);
1330       if (NULL == c)
1331       {
1332         /* This case can happen when the path includes a first hop that is
1333          * not yet known to be connected.
1334          *
1335          * This happens quite often during testing when running mesh
1336          * under valgrind: core connect notifications come very late and the
1337          * DHT result has already come and created a valid path.
1338          * In this case, the peer->connections hashmap will be NULL and
1339          * tunnel_use_path will not be able to create a connection from that
1340          * path.
1341          *
1342          * Re-running the DHT GET should give core time to callback.
1343          *
1344          * GMT_use_path -> GMC_new -> register_neighbors takes care of
1345          * updating statistics about this issue.
1346          */
1347         rerun_search = GNUNET_YES;
1348       }
1349       else
1350       {
1351         GMC_send_create (c);
1352         return;
1353       }
1354     }
1355     else
1356     {
1357       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1358     }
1359   }
1360
1361   if (NULL != peer->search_h && GNUNET_YES == rerun_search)
1362   {
1363     GMD_search_stop (peer->search_h);
1364     peer->search_h = NULL;
1365     LOG (GNUNET_ERROR_TYPE_DEBUG,
1366          "  Stopping DHT GET for peer %s\n",
1367          GMP_2s (peer));
1368   }
1369
1370   if (NULL == peer->search_h)
1371   {
1372     const struct GNUNET_PeerIdentity *id;
1373
1374     id = GNUNET_PEER_resolve2 (peer->id);
1375     LOG (GNUNET_ERROR_TYPE_DEBUG,
1376                 "  Starting DHT GET for peer %s\n", GMP_2s (peer));
1377     peer->search_h = GMD_search (id, &search_handler, peer);
1378     if (MESH_TUNNEL3_NEW == GMT_get_cstate (t))
1379       GMT_change_cstate (t, MESH_TUNNEL3_SEARCHING);
1380   }
1381 }
1382
1383
1384 /**
1385  * Set tunnel.
1386  *
1387  * @param peer Peer.
1388  * @param t Tunnel.
1389  */
1390 void
1391 GMP_set_tunnel (struct MeshPeer *peer, struct MeshTunnel3 *t)
1392 {
1393   peer->tunnel = t;
1394 }
1395
1396
1397 /**
1398  * Chech whether there is a direct (core level)  connection to peer.
1399  *
1400  * @param peer Peer to check.
1401  *
1402  * @return #GNUNET_YES if there is a direct connection.
1403  */
1404 int
1405 GMP_is_neighbor (const struct MeshPeer *peer)
1406 {
1407   struct MeshPeerPath *path;
1408
1409   if (NULL == peer->connections)
1410     return GNUNET_NO;
1411
1412   for (path = peer->path_head; NULL != path; path = path->next)
1413   {
1414     if (3 > path->length)
1415       return GNUNET_YES;
1416   }
1417
1418   GNUNET_break (0); /* Is not a neighbor but connections is not NULL */
1419   return GNUNET_NO;
1420 }
1421
1422
1423 /**
1424  * Create and initialize a new tunnel towards a peer, in case it has none.
1425  * In case the peer already has a tunnel, nothing is done.
1426  *
1427  * Does not generate any traffic, just creates the local data structures.
1428  *
1429  * @param peer Peer towards which to create the tunnel.
1430  */
1431 void
1432 GMP_add_tunnel (struct MeshPeer *peer)
1433 {
1434   if (NULL != peer->tunnel)
1435     return;
1436   peer->tunnel = GMT_new (peer);
1437 }
1438
1439
1440 /**
1441  * Add a connection to a neighboring peer.
1442  *
1443  * Store that the peer is the first hop of the connection in one
1444  * direction and that on peer disconnect the connection must be
1445  * notified and destroyed, for it will no longer be valid.
1446  *
1447  * @param peer Peer to add connection to.
1448  * @param c Connection to add.
1449  *
1450  * @return GNUNET_OK on success.
1451  */
1452 int
1453 GMP_add_connection (struct MeshPeer *peer,
1454                     struct MeshConnection *c)
1455 {
1456   if (NULL == peer->connections)
1457   {
1458     GNUNET_break (0);
1459     return GNUNET_SYSERR;
1460   }
1461   return GNUNET_CONTAINER_multihashmap_put (peer->connections,
1462                                             GMC_get_id (c),
1463                                             c,
1464                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1465 }
1466
1467
1468 /**
1469  * Add the path to the peer and update the path used to reach it in case this
1470  * is the shortest.
1471  *
1472  * @param peer Destination peer to add the path to.
1473  * @param path New path to add. Last peer must be the peer in arg 1.
1474  *             Path will be either used of freed if already known.
1475  * @param trusted Do we trust that this path is real?
1476  *
1477  * @return path if path was taken, pointer to existing duplicate if exists
1478  *         NULL on error.
1479  */
1480 struct MeshPeerPath *
1481 GMP_add_path (struct MeshPeer *peer, struct MeshPeerPath *path,
1482               int trusted)
1483 {
1484   struct MeshPeerPath *aux;
1485   unsigned int l;
1486   unsigned int l2;
1487
1488   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1489        path->length, GMP_2s (peer));
1490
1491   if ((NULL == peer) || (NULL == path))
1492   {
1493     GNUNET_break (0);
1494     path_destroy (path);
1495     return NULL;
1496   }
1497   if (path->peers[path->length - 1] != peer->id)
1498   {
1499     GNUNET_break (0);
1500     path_destroy (path);
1501     return NULL;
1502   }
1503   if (2 >= path->length && GNUNET_NO == trusted)
1504   {
1505     /* Only allow CORE to tell us about direct paths */
1506     path_destroy (path);
1507     return NULL;
1508   }
1509   for (l = 1; l < path->length; l++)
1510   {
1511     if (path->peers[l] == myid)
1512     {
1513       LOG (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
1514       for (l2 = 0; l2 < path->length - l; l2++)
1515       {
1516         path->peers[l2] = path->peers[l + l2];
1517       }
1518       path->length -= l;
1519       l = 1;
1520       path->peers = GNUNET_realloc (path->peers,
1521                                     path->length * sizeof (GNUNET_PEER_Id));
1522     }
1523   }
1524
1525   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u]\n", path->length);
1526
1527   l = path_get_length (path);
1528   if (0 == l)
1529   {
1530     path_destroy (path);
1531     return NULL;
1532   }
1533
1534   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1535   for (aux = peer->path_head; aux != NULL; aux = aux->next)
1536   {
1537     l2 = path_get_length (aux);
1538     if (l2 > l)
1539     {
1540       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1541       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1542                                           peer->path_tail, aux, path);
1543       return path;
1544     }
1545     else
1546     {
1547       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1548       {
1549         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1550         path_destroy (path);
1551         return aux;
1552       }
1553     }
1554   }
1555   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head, peer->path_tail,
1556                                     path);
1557   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1558   return path;
1559 }
1560
1561
1562 /**
1563  * Add the path to the origin peer and update the path used to reach it in case
1564  * this is the shortest.
1565  * The path is given in peer_info -> destination, therefore we turn the path
1566  * upside down first.
1567  *
1568  * @param peer Peer to add the path to, being the origin of the path.
1569  * @param path New path to add after being inversed.
1570  *             Path will be either used or freed.
1571  * @param trusted Do we trust that this path is real?
1572  *
1573  * @return path if path was taken, pointer to existing duplicate if exists
1574  *         NULL on error.
1575  */
1576 struct MeshPeerPath *
1577 GMP_add_path_to_origin (struct MeshPeer *peer,
1578                         struct MeshPeerPath *path,
1579                         int trusted)
1580 {
1581   if (NULL == path)
1582     return NULL;
1583   path_invert (path);
1584   return GMP_add_path (peer, path, trusted);
1585 }
1586
1587
1588 /**
1589  * Adds a path to the info of all the peers in the path
1590  *
1591  * @param p Path to process.
1592  * @param confirmed Whether we know if the path works or not.
1593  */
1594 void
1595 GMP_add_path_to_all (const struct MeshPeerPath *p, int confirmed)
1596 {
1597   unsigned int i;
1598
1599   /* TODO: invert and add */
1600   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1601   for (i++; i < p->length; i++)
1602   {
1603     struct MeshPeer *aux;
1604     struct MeshPeerPath *copy;
1605
1606     aux = GMP_get_short (p->peers[i]);
1607     copy = path_duplicate (p);
1608     copy->length = i + 1;
1609     GMP_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
1610   }
1611 }
1612
1613
1614 /**
1615  * Remove any path to the peer that has the extact same peers as the one given.
1616  *
1617  * @param peer Peer to remove the path from.
1618  * @param path Path to remove. Is always destroyed .
1619  */
1620 void
1621 GMP_remove_path (struct MeshPeer *peer, struct MeshPeerPath *path)
1622 {
1623   struct MeshPeerPath *iter;
1624   struct MeshPeerPath *next;
1625
1626   GNUNET_assert (myid == path->peers[0]);
1627   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1628
1629   for (iter = peer->path_head; NULL != iter; iter = next)
1630   {
1631     next = iter->next;
1632     if (0 == memcmp (path->peers, iter->peers,
1633                      sizeof (GNUNET_PEER_Id) * path->length))
1634     {
1635       GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
1636       path_destroy (iter);
1637       if (path == iter)
1638         return;
1639     }
1640   }
1641   path_destroy (path);
1642 }
1643
1644
1645 /**
1646  * Remove a connection from a neighboring peer.
1647  *
1648  * @param peer Peer to remove connection from.
1649  * @param c Connection to remove.
1650  *
1651  * @return GNUNET_OK on success.
1652  */
1653 int
1654 GMP_remove_connection (struct MeshPeer *peer,
1655                        const struct MeshConnection *c)
1656 {
1657   LOG (GNUNET_ERROR_TYPE_DEBUG,
1658        "removing connection %s from peer %s\n",
1659        GMC_2s (c), GMP_2s (peer));
1660   if (NULL == peer || NULL == peer->connections)
1661   {
1662     LOG (GNUNET_ERROR_TYPE_DEBUG,
1663          "Peer %s is not a neighbor!\n",
1664          GMP_2s (peer));
1665     return GNUNET_SYSERR;
1666   }
1667   return GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1668                                                GMC_get_id (c),
1669                                                c);
1670 }
1671
1672 /**
1673  * Start the DHT search for new paths towards the peer: we don't have
1674  * enough good connections.
1675  *
1676  * @param peer Destination peer.
1677  */
1678 void
1679 GMP_start_search (struct MeshPeer *peer)
1680 {
1681   if (NULL != peer->search_h)
1682   {
1683     GNUNET_break (0);
1684     return;
1685   }
1686
1687   peer->search_h = GMD_search (GMP_get_id (peer), &search_handler, peer);
1688 }
1689
1690
1691 /**
1692  * Stop the DHT search for new paths towards the peer: we already have
1693  * enough good connections.
1694  *
1695  * @param peer Destination peer.
1696  */
1697 void
1698 GMP_stop_search (struct MeshPeer *peer)
1699 {
1700   if (NULL == peer->search_h)
1701   {
1702     GNUNET_break (0);
1703     return;
1704   }
1705
1706   GMD_search_stop (peer->search_h);
1707   peer->search_h = NULL;
1708 }
1709
1710
1711 /**
1712  * Get the Full ID of a peer.
1713  *
1714  * @param peer Peer to get from.
1715  *
1716  * @return Full ID of peer.
1717  */
1718 const struct GNUNET_PeerIdentity *
1719 GMP_get_id (const struct MeshPeer *peer)
1720 {
1721   return GNUNET_PEER_resolve2 (peer->id);
1722 }
1723
1724
1725 /**
1726  * Get the Short ID of a peer.
1727  *
1728  * @param peer Peer to get from.
1729  *
1730  * @return Short ID of peer.
1731  */
1732 GNUNET_PEER_Id
1733 GMP_get_short_id (const struct MeshPeer *peer)
1734 {
1735   return peer->id;
1736 }
1737
1738
1739 /**
1740  * Get the tunnel towards a peer.
1741  *
1742  * @param peer Peer to get from.
1743  *
1744  * @return Tunnel towards peer.
1745  */
1746 struct MeshTunnel3 *
1747 GMP_get_tunnel (const struct MeshPeer *peer)
1748 {
1749   GNUNET_assert (NULL != peer->tunnel);
1750   return peer->tunnel;
1751 }
1752
1753
1754 /**
1755  * Get the static string for a peer ID.
1756  *
1757  * @param peer Peer.
1758  *
1759  * @return Static string for it's ID.
1760  */
1761 const char *
1762 GMP_2s (const struct MeshPeer *peer)
1763 {
1764   if (NULL == peer)
1765     return "(NULL)";
1766   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1767 }