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