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