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