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