- fix LOG
[oweals/gnunet.git] / src / mesh / gnunet-service-mesh_peer.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21
22 #include "platform.h"
23 #include "gnunet_util_lib.h"
24
25 #include "gnunet_core_service.h"
26
27 #include "mesh_protocol_enc.h"
28
29 #include "gnunet-service-mesh_peer.h"
30 #include "gnunet-service-mesh_dht.h"
31 #include "gnunet-service-mesh_connection.h"
32 #include "gnunet-service-mesh_local.h"
33 #include "mesh_path.h"
34
35 #define LOG(level, ...) GNUNET_log_from (level,"mesh-p2p",__VA_ARGS__)
36
37 /******************************************************************************/
38 /********************************   STRUCTS  **********************************/
39 /******************************************************************************/
40
41 /**
42  * Struct containing all information regarding a given peer
43  */
44 struct MeshPeer
45 {
46     /**
47      * ID of the peer
48      */
49   GNUNET_PEER_Id id;
50
51     /**
52      * Last time we heard from this peer
53      */
54   struct GNUNET_TIME_Absolute last_contact;
55
56     /**
57      * Paths to reach the peer, ordered by ascending hop count
58      */
59   struct MeshPeerPath *path_head;
60
61     /**
62      * Paths to reach the peer, ordered by ascending hop count
63      */
64   struct MeshPeerPath *path_tail;
65
66     /**
67      * Handle to stop the DHT search for paths to this peer
68      */
69   struct GMD_search_handle *search_h;
70
71     /**
72      * Tunnel to this peer, if any.
73      */
74   struct MeshTunnel2 *tunnel;
75
76     /**
77      * Connections that go through this peer, indexed by tid;
78      */
79   struct GNUNET_CONTAINER_MultiHashMap *connections;
80
81     /**
82      * Handle for queued transmissions
83      */
84   struct GNUNET_CORE_TransmitHandle *core_transmit;
85
86   /**
87    * Transmission queue to core DLL head
88    */
89   struct MeshPeerQueue *queue_head;
90
91   /**
92    * Transmission queue to core DLL tail
93    */
94   struct MeshPeerQueue *queue_tail;
95
96   /**
97    * How many messages are in the queue to this peer.
98    */
99   unsigned int queue_n;
100 };
101
102
103 /******************************************************************************/
104 /*******************************   GLOBALS  ***********************************/
105 /******************************************************************************/
106
107 /**
108  * Peers known, indexed by PeerIdentity (MeshPeer).
109  */
110 static struct GNUNET_CONTAINER_MultiPeerMap *peers;
111
112 /**
113  * How many peers do we want to remember?
114  */
115 static unsigned long long max_peers;
116
117 /**
118  * Percentage of messages that will be dropped (for test purposes only).
119  */
120 static unsigned long long drop_percent;
121
122 /**
123  * Handle to communicate with core.
124  */
125 static struct GNUNET_CORE_Handle *core_handle;
126
127 /**
128  * Local peer own ID (full value).
129  */
130 const static struct GNUNET_PeerIdentity *my_full_id;
131
132 /******************************************************************************/
133 /***************************** CORE CALLBACKS *********************************/
134 /******************************************************************************/
135
136
137 /**
138  * Iterator to notify all connections of a broken link. Mark connections
139  * to destroy after all traffic has been sent.
140  *
141  * @param cls Closure (peer disconnected).
142  * @param key Current key code (peer id).
143  * @param value Value in the hash map (connection).
144  *
145  * @return GNUNET_YES if we should continue to iterate,
146  *         GNUNET_NO if not.
147  */
148 static int
149 notify_broken (void *cls,
150                const struct GNUNET_HashCode *key,
151                void *value)
152 {
153   struct MeshPeer *peer = cls;
154   struct MeshConnection *c = value;
155
156   GMC_notify_broken (c, peer, my_full_id);
157
158   return GNUNET_YES;
159 }
160
161
162 /**
163  * Method called whenever a given peer connects.
164  *
165  * @param cls closure
166  * @param peer peer identity this notification is about
167  */
168 static void
169 core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
170 {
171   struct MeshPeer *pi;
172   struct MeshPeerPath *path;
173
174   LOG ("Peer connected\n");
175   LOG ("     %s\n", GNUNET_i2s (&my_full_id));
176   pi = peer_get (peer);
177   if (myid == pi->id)
178   {
179     LOG ("     (self)\n");
180     path = path_new (1);
181   }
182   else
183   {
184     LOG ("     %s\n", GNUNET_i2s (peer));
185     path = path_new (2);
186     path->peers[1] = pi->id;
187     GNUNET_PEER_change_rc (pi->id, 1);
188     GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
189   }
190   path->peers[0] = myid;
191   GNUNET_PEER_change_rc (myid, 1);
192   peer_add_path (pi, path, GNUNET_YES);
193
194   pi->connections = GNUNET_CONTAINER_multihashmap_create (32, GNUNET_YES);
195   return;
196 }
197
198
199 /**
200  * Method called whenever a peer disconnects.
201  *
202  * @param cls closure
203  * @param peer peer identity this notification is about
204  */
205 static void
206 core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
207 {
208   struct MeshPeer *pi;
209
210   LOG ("Peer disconnected\n");
211   pi = GNUNET_CONTAINER_multipeermap_get (peers, peer);
212   if (NULL == pi)
213   {
214     GNUNET_break (0);
215     return;
216   }
217
218   GNUNET_CONTAINER_multihashmap_iterate (pi->connections, &notify_broken, pi);
219   GNUNET_CONTAINER_multihashmap_destroy (pi->connections);
220   pi->connections = NULL;
221   if (NULL != pi->core_transmit)
222     {
223       GNUNET_CORE_notify_transmit_ready_cancel (pi->core_transmit);
224       pi->core_transmit = NULL;
225     }
226   if (myid == pi->id)
227   {
228     LOG ("     (self)\n");
229   }
230   GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
231
232   return;
233 }
234
235
236 /**
237  * Functions to handle messages from core
238  */
239 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
240   {&GMC_handle_create, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE,
241     0},
242   {&GMC_handle_confirm, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK,
243     sizeof (struct GNUNET_MESH_ConnectionACK)},
244   {&GMC_handle_broken, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN,
245     sizeof (struct GNUNET_MESH_ConnectionBroken)},
246   {&GMC_handle_destroy, GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY,
247     sizeof (struct GNUNET_MESH_ConnectionDestroy)},
248   {&GMC_handle_keepalive, GNUNET_MESSAGE_TYPE_MESH_FWD_KEEPALIVE,
249     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
250   {&GMC_handle_keepalive, GNUNET_MESSAGE_TYPE_MESH_BCK_KEEPALIVE,
251     sizeof (struct GNUNET_MESH_ConnectionKeepAlive)},
252   {&GMC_handle_ack, GNUNET_MESSAGE_TYPE_MESH_ACK,
253     sizeof (struct GNUNET_MESH_ACK)},
254   {&GMC_handle_poll, GNUNET_MESSAGE_TYPE_MESH_POLL,
255     sizeof (struct GNUNET_MESH_Poll)},
256   {&GMC_handle_fwd, GNUNET_MESSAGE_TYPE_MESH_FWD, 0},
257   {&GMC_handle_bck, GNUNET_MESSAGE_TYPE_MESH_BCK, 0},
258   {NULL, 0, 0}
259 };
260
261
262 /**
263  * To be called on core init/fail.
264  *
265  * @param cls Closure (config)
266  * @param identity the public identity of this peer
267  */
268 static void
269 core_init (void *cls,
270            const struct GNUNET_PeerIdentity *identity)
271 {
272   const struct GNUNET_CONFIGURATION_Handle *c = cls;
273   static int i = 0;
274
275   LOG (GNUNET_ERROR_TYPE_DEBUG, "Core init\n");
276   if (0 != memcmp (identity, &my_full_id, sizeof (my_full_id)))
277   {
278     LOG (GNUNET_ERROR_TYPE_ERROR, _("Wrong CORE service\n"));
279     LOG (GNUNET_ERROR_TYPE_ERROR, " core id %s\n", GNUNET_i2s (identity));
280     LOG (GNUNET_ERROR_TYPE_ERROR, " my id %s\n", GNUNET_i2s (&my_full_id));
281     GNUNET_CORE_disconnect (core_handle);
282     core_handle = GNUNET_CORE_connect (c, /* Main configuration */
283                                        NULL,      /* Closure passed to MESH functions */
284                                        &core_init,        /* Call core_init once connected */
285                                        &core_connect,     /* Handle connects */
286                                        &core_disconnect,  /* remove peers on disconnects */
287                                        NULL,      /* Don't notify about all incoming messages */
288                                        GNUNET_NO, /* For header only in notification */
289                                        NULL,      /* Don't notify about all outbound messages */
290                                        GNUNET_NO, /* For header-only out notification */
291                                        core_handlers);    /* Register these handlers */
292     if (10 < i++)
293       GNUNET_abort();
294   }
295   GML_start ();
296   return;
297 }
298
299 /**
300   * Core callback to write a pre-constructed data packet to core buffer
301   *
302   * @param cls Closure (MeshTransmissionDescriptor with data in "data" member).
303   * @param size Number of bytes available in buf.
304   * @param buf Where the to write the message.
305   *
306   * @return number of bytes written to buf
307   */
308 static size_t
309 send_core_data_raw (void *cls, size_t size, void *buf)
310 {
311   struct GNUNET_MessageHeader *msg = cls;
312   size_t total_size;
313
314   GNUNET_assert (NULL != msg);
315   total_size = ntohs (msg->size);
316
317   if (total_size > size)
318   {
319     GNUNET_break (0);
320     return 0;
321   }
322   memcpy (buf, msg, total_size);
323   GNUNET_free (cls);
324   return total_size;
325 }
326
327
328 /**
329  * Function to send a create connection message to a peer.
330  *
331  * @param c Connection to create.
332  * @param size number of bytes available in buf
333  * @param buf where the callee should write the message
334  * @return number of bytes written to buf
335  */
336 static size_t
337 send_core_connection_create (struct MeshConnection *c, size_t size, void *buf)
338 {
339   struct GNUNET_MESH_ConnectionCreate *msg;
340   struct GNUNET_PeerIdentity *peer_ptr;
341   struct MeshPeerPath *p = c->path;
342   size_t size_needed;
343   int i;
344
345   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION CREATE...\n");
346   size_needed =
347       sizeof (struct GNUNET_MESH_ConnectionCreate) +
348       p->length * sizeof (struct GNUNET_PeerIdentity);
349
350   if (size < size_needed || NULL == buf)
351   {
352     GNUNET_break (0);
353     return 0;
354   }
355   msg = (struct GNUNET_MESH_ConnectionCreate *) buf;
356   msg->header.size = htons (size_needed);
357   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE);
358   msg->cid = c->id;
359
360   peer_ptr = (struct GNUNET_PeerIdentity *) &msg[1];
361   for (i = 0; i < p->length; i++)
362   {
363     GNUNET_PEER_resolve (p->peers[i], peer_ptr++);
364   }
365
366   LOG (GNUNET_ERROR_TYPE_DEBUG,
367               "CONNECTION CREATE (%u bytes long) sent!\n", size_needed);
368   return size_needed;
369 }
370
371
372 /**
373  * Creates a path ack message in buf and frees all unused resources.
374  *
375  * @param c Connection to send an ACK on.
376  * @param size number of bytes available in buf
377  * @param buf where the callee should write the message
378  *
379  * @return number of bytes written to buf
380  */
381 static size_t
382 send_core_connection_ack (struct MeshConnection *c, size_t size, void *buf)
383 {
384   struct GNUNET_MESH_ConnectionACK *msg = buf;
385   struct MeshTunnel2 *t = c->t;
386
387   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending CONNECTION ACK...\n");
388   GNUNET_assert (NULL != t);
389   if (sizeof (struct GNUNET_MESH_ConnectionACK) > size)
390   {
391     GNUNET_break (0);
392     return 0;
393   }
394   msg->header.size = htons (sizeof (struct GNUNET_MESH_ConnectionACK));
395   msg->header.type = htons (GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK);
396   msg->cid = c->id;
397   msg->reserved = 0;
398
399   /* TODO add signature */
400
401   LOG (GNUNET_ERROR_TYPE_DEBUG, "CONNECTION ACK sent!\n");
402   return sizeof (struct GNUNET_MESH_ConnectionACK);
403 }
404
405
406 /******************************************************************************/
407 /********************************   STATIC  ***********************************/
408 /******************************************************************************/
409
410 /**
411  * Iterator over tunnel hash map entries to destroy the tunnel during shutdown.
412  *
413  * @param cls closure
414  * @param key current key code
415  * @param value value in the hash map
416  * @return #GNUNET_YES if we should continue to iterate,
417  *         #GNUNET_NO if not.
418  */
419 static int
420 shutdown_tunnel (void *cls,
421                  const struct GNUNET_PeerIdentity *key,
422                  void *value)
423 {
424   struct MeshPeer *p = value;
425   struct MeshTunnel2 *t = p->tunnel;
426
427   if (NULL != t)
428     GMT_destroy (t);
429   return GNUNET_YES;
430 }
431
432
433
434 /**
435  * Destroy the peer_info and free any allocated resources linked to it
436  *
437  * @param peer The peer_info to destroy.
438  *
439  * @return GNUNET_OK on success
440  */
441 static int
442 peer_destroy (struct MeshPeer *peer)
443 {
444   struct GNUNET_PeerIdentity id;
445   struct MeshPeerPath *p;
446   struct MeshPeerPath *nextp;
447
448   GNUNET_PEER_resolve (peer->id, &id);
449   GNUNET_PEER_change_rc (peer->id, -1);
450
451   if (GNUNET_YES !=
452     GNUNET_CONTAINER_multipeermap_remove (peers, &id, peer))
453   {
454     GNUNET_break (0);
455     LOG (GNUNET_ERROR_TYPE_WARNING,
456                 "removing peer %s, not in peermap\n", GNUNET_i2s (&id));
457   }
458     if (NULL != peer->search_h)
459     {
460       GMD_search_stop (peer->search_h);
461     }
462       p = peer->path_head;
463       while (NULL != p)
464       {
465         nextp = p->next;
466         GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, p);
467         path_destroy (p);
468         p = nextp;
469       }
470         tunnel_destroy_empty (peer->tunnel);
471         GNUNET_free (peer);
472         return GNUNET_OK;
473 }
474
475
476 /**
477  * Returns if peer is used (has a tunnel, is neighbor).
478  *
479  * @peer Peer to check.
480  *
481  * @return GNUNET_YES if peer is in use.
482  */
483 static int
484 peer_is_used (struct MeshPeer *peer)
485 {
486   struct MeshPeerPath *p;
487
488   if (NULL != peer->tunnel)
489     return GNUNET_YES;
490
491   for (p = peer->path_head; NULL != p; p = p->next)
492   {
493     if (p->length < 3)
494       return GNUNET_YES;
495   }
496     return GNUNET_NO;
497 }
498
499
500 /**
501  * Iterator over all the peers to get the oldest timestamp.
502  *
503  * @param cls Closure (unsued).
504  * @param key ID of the peer.
505  * @param value Peer_Info of the peer.
506  */
507 static int
508 peer_get_oldest (void *cls,
509                  const struct GNUNET_PeerIdentity *key,
510                  void *value)
511 {
512   struct MeshPeer *p = value;
513   struct GNUNET_TIME_Absolute *abs = cls;
514
515   /* Don't count active peers */
516   if (GNUNET_YES == peer_is_used (p))
517     return GNUNET_YES;
518
519   if (abs->abs_value_us < p->last_contact.abs_value_us)
520     abs->abs_value_us = p->last_contact.abs_value_us;
521
522   return GNUNET_YES;
523 }
524
525
526 /**
527  * Iterator over all the peers to remove the oldest entry.
528  *
529  * @param cls Closure (unsued).
530  * @param key ID of the peer.
531  * @param value Peer_Info of the peer.
532  */
533 static int
534 peer_timeout (void *cls,
535               const struct GNUNET_PeerIdentity *key,
536               void *value)
537 {
538   struct MeshPeer *p = value;
539   struct GNUNET_TIME_Absolute *abs = cls;
540
541   if (p->last_contact.abs_value_us == abs->abs_value_us &&
542     GNUNET_NO == peer_is_used (p))
543   {
544     peer_destroy (p);
545     return GNUNET_NO;
546   }
547     return GNUNET_YES;
548 }
549
550
551 /**
552  * Delete oldest unused peer.
553  */
554 static void
555 peer_delete_oldest (void)
556 {
557   struct GNUNET_TIME_Absolute abs;
558
559   abs = GNUNET_TIME_UNIT_FOREVER_ABS;
560
561   GNUNET_CONTAINER_multipeermap_iterate (peers,
562                                          &peer_get_oldest,
563                                          &abs);
564   GNUNET_CONTAINER_multipeermap_iterate (peers,
565                                          &peer_timeout,
566                                          &abs);
567 }
568
569
570 /**
571  * Retrieve the MeshPeer stucture associated with the peer, create one
572  * and insert it in the appropriate structures if the peer is not known yet.
573  *
574  * @param peer Full identity of the peer.
575  *
576  * @return Existing or newly created peer info.
577  */
578 static struct MeshPeer *
579 peer_get (const struct GNUNET_PeerIdentity *peer_id)
580 {
581   struct MeshPeer *peer;
582
583   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
584   if (NULL == peer)
585   {
586     peer = GNUNET_new (struct MeshPeer);
587     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
588     {
589       peer_delete_oldest ();
590     }
591         GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
592                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
593         peer->id = GNUNET_PEER_intern (peer_id);
594   }
595     peer->last_contact = GNUNET_TIME_absolute_get();
596
597     return peer;
598 }
599
600
601 /**
602  * Retrieve the MeshPeer stucture associated with the peer, create one
603  * and insert it in the appropriate structures if the peer is not known yet.
604  *
605  * @param peer Short identity of the peer.
606  *
607  * @return Existing or newly created peer info.
608  */
609 static struct MeshPeer *
610 peer_get_short (const GNUNET_PEER_Id peer)
611 {
612   return peer_get (GNUNET_PEER_resolve2 (peer));
613 }
614
615
616 /**
617  * Get a cost of a path for a peer considering existing tunnel connections.
618  *
619  * @param peer Peer towards which the path is considered.
620  * @param path Candidate path.
621  *
622  * @return Cost of the path (path length + number of overlapping nodes)
623  */
624 static unsigned int
625 peer_get_path_cost (const struct MeshPeer *peer,
626                     const struct MeshPeerPath *path)
627 {
628   struct MeshConnection *c;
629   unsigned int overlap;
630   unsigned int i;
631   unsigned int j;
632
633   if (NULL == path)
634     return 0;
635
636   overlap = 0;
637   GNUNET_assert (NULL != peer->tunnel);
638
639   for (i = 0; i < path->length; i++)
640   {
641     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
642     {
643       for (j = 0; j < c->path->length; j++)
644       {
645         if (path->peers[i] == c->path->peers[j])
646         {
647           overlap++;
648           break;
649         }
650       }
651     }
652   }
653   return (path->length + overlap) * (path->score * -1);
654 }
655
656
657 /**
658  * Choose the best path towards a peer considering the tunnel properties.
659  *
660  * @param peer The destination peer.
661  *
662  * @return Best current known path towards the peer, if any.
663  */
664 static struct MeshPeerPath *
665 peer_get_best_path (const struct MeshPeer *peer)
666 {
667   struct MeshPeerPath *best_p;
668   struct MeshPeerPath *p;
669   struct MeshConnection *c;
670   unsigned int best_cost;
671   unsigned int cost;
672
673   best_cost = UINT_MAX;
674   best_p = NULL;
675   for (p = peer->path_head; NULL != p; p = p->next)
676   {
677     for (c = peer->tunnel->connection_head; NULL != c; c = c->next)
678       if (c->path == p)
679         break;
680       if (NULL != c)
681         continue; /* If path is in use in a connection, skip it. */
682
683             if ((cost = peer_get_path_cost (peer, p)) < best_cost)
684             {
685               best_cost = cost;
686               best_p = p;
687             }
688   }
689     return best_p;
690 }
691
692
693 /**
694  * Add the path to the peer and update the path used to reach it in case this
695  * is the shortest.
696  *
697  * @param peer_info Destination peer to add the path to.
698  * @param path New path to add. Last peer must be the peer in arg 1.
699  *             Path will be either used of freed if already known.
700  * @param trusted Do we trust that this path is real?
701  */
702 void
703 peer_add_path (struct MeshPeer *peer_info, struct MeshPeerPath *path,
704                int trusted)
705 {
706   struct MeshPeerPath *aux;
707   unsigned int l;
708   unsigned int l2;
709
710   if ((NULL == peer_info) || (NULL == path))
711   {
712     GNUNET_break (0);
713     path_destroy (path);
714     return;
715   }
716     if (path->peers[path->length - 1] != peer_info->id)
717     {
718       GNUNET_break (0);
719       path_destroy (path);
720       return;
721     }
722       if (2 >= path->length && GNUNET_NO == trusted)
723       {
724         /* Only allow CORE to tell us about direct paths */
725         path_destroy (path);
726         return;
727       }
728         for (l = 1; l < path->length; l++)
729         {
730           if (path->peers[l] == myid)
731           {
732             LOG (GNUNET_ERROR_TYPE_DEBUG, "shortening path by %u\n", l);
733             for (l2 = 0; l2 < path->length - l; l2++)
734             {
735               path->peers[l2] = path->peers[l + l2];
736             }
737                   path->length -= l;
738                   l = 1;
739                   path->peers =
740                             GNUNET_realloc (path->peers, path->length * sizeof (GNUNET_PEER_Id));
741           }
742         }
743
744           LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
745                       path->length, peer2s (peer_info));
746
747           l = path_get_length (path);
748           if (0 == l)
749           {
750             path_destroy (path);
751             return;
752           }
753
754             GNUNET_assert (peer_info->id == path->peers[path->length - 1]);
755             for (aux = peer_info->path_head; aux != NULL; aux = aux->next)
756             {
757               l2 = path_get_length (aux);
758               if (l2 > l)
759               {
760                 GNUNET_CONTAINER_DLL_insert_before (peer_info->path_head,
761                                                     peer_info->path_tail, aux, path);
762                 return;
763               }
764                   else
765                   {
766                     if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
767                     {
768                       path_destroy (path);
769                       return;
770                     }
771                   }
772             }
773               GNUNET_CONTAINER_DLL_insert_tail (peer_info->path_head, peer_info->path_tail,
774                                                 path);
775               return;
776 }
777
778
779 /**
780  * Add the path to the origin peer and update the path used to reach it in case
781  * this is the shortest.
782  * The path is given in peer_info -> destination, therefore we turn the path
783  * upside down first.
784  *
785  * @param peer_info Peer to add the path to, being the origin of the path.
786  * @param path New path to add after being inversed.
787  *             Path will be either used or freed.
788  * @param trusted Do we trust that this path is real?
789  */
790 static void
791 peer_add_path_to_origin (struct MeshPeer *peer_info,
792                          struct MeshPeerPath *path, int trusted)
793 {
794   if (NULL == path)
795     return;
796   path_invert (path);
797   peer_add_path (peer_info, path, trusted);
798 }
799
800
801 /**
802  * Adds a path to the peer_infos of all the peers in the path
803  *
804  * @param p Path to process.
805  * @param confirmed Whether we know if the path works or not.
806  */
807 static void
808 path_add_to_peers (struct MeshPeerPath *p, int confirmed)
809 {
810   unsigned int i;
811
812   /* TODO: invert and add */
813   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
814   for (i++; i < p->length; i++)
815   {
816     struct MeshPeer *aux;
817     struct MeshPeerPath *copy;
818     
819     aux = peer_get_short (p->peers[i]);
820     copy = path_duplicate (p);
821     copy->length = i + 1;
822     peer_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
823   }
824 }
825
826
827 /**
828  * Function to process paths received for a new peer addition. The recorded
829  * paths form the initial tunnel, which can be optimized later.
830  * Called on each result obtained for the DHT search.
831  *
832  * @param cls closure
833  * @param path
834  */
835 static void
836 search_handler (void *cls, struct MeshPeerPath *path)
837 {
838   struct MeshPeer *peer = cls;
839   unsigned int connection_count;
840
841   path_add_to_peers (path, GNUNET_NO);
842
843   /* Count connections */
844   connection_count = GMC_count (peer->tunnel->connection_head);
845
846   /* If we already have 3 (or more (?!)) connections, it's enough */
847   if (3 <= connection_count)
848     return;
849
850   if (peer->tunnel->state == MESH_TUNNEL_SEARCHING)
851   {
852     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
853     GMP_connect (peer);
854   }
855   return;
856 }
857
858
859 /**
860  * Core callback to write a queued packet to core buffer
861  *
862  * @param cls Closure (peer info).
863  * @param size Number of bytes available in buf.
864  * @param buf Where the to write the message.
865  *
866  * @return number of bytes written to buf
867  */
868 static size_t
869 queue_send (void *cls, size_t size, void *buf)
870 {
871   struct MeshPeer *peer = cls;
872   struct MeshFlowControl *fc;
873   struct MeshConnection *c;
874   struct GNUNET_MessageHeader *msg;
875   struct MeshPeerQueue *queue;
876   struct MeshTunnel2 *t;
877   struct MeshChannel *ch;
878   const struct GNUNET_PeerIdentity *dst_id;
879   size_t data_size;
880   uint32_t pid;
881   uint16_t type;
882   int fwd;
883
884   peer->core_transmit = NULL;
885   LOG (GNUNET_ERROR_TYPE_DEBUG, "* Queue send (max %u)\n", size);
886
887   if (NULL == buf || 0 == size)
888   {
889     LOG (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
890     return 0;
891   }
892
893   /* Initialize */
894   queue = peer_get_first_message (peer);
895   if (NULL == queue)
896   {
897     GNUNET_break (0); /* Core tmt_rdy should've been canceled */
898     return 0;
899   }
900   c = queue->c;
901   fwd = queue->fwd;
902   fc = fwd ? &c->fwd_fc : &c->bck_fc;
903
904   dst_id = GNUNET_PEER_resolve2 (peer->id);
905   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   towards %s\n", GNUNET_i2s (dst_id));
906   /* Check if buffer size is enough for the message */
907   if (queue->size > size)
908   {
909       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   not enough room, reissue\n");
910       peer->core_transmit =
911           GNUNET_CORE_notify_transmit_ready (core_handle,
912                                              GNUNET_NO,
913                                              0,
914                                              GNUNET_TIME_UNIT_FOREVER_REL,
915                                              dst_id,
916                                              queue->size,
917                                              &queue_send,
918                                              peer);
919       return 0;
920   }
921   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
922
923   t = (NULL != c) ? c->t : NULL;
924   type = 0;
925
926   /* Fill buf */
927   switch (queue->type)
928   {
929     case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
930     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
931     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
932     case GNUNET_MESSAGE_TYPE_MESH_FWD:
933     case GNUNET_MESSAGE_TYPE_MESH_BCK:
934     case GNUNET_MESSAGE_TYPE_MESH_ACK:
935     case GNUNET_MESSAGE_TYPE_MESH_POLL:
936       LOG (GNUNET_ERROR_TYPE_DEBUG,
937                   "*   raw: %s\n",
938                   GNUNET_MESH_DEBUG_M2S (queue->type));
939       data_size = send_core_data_raw (queue->cls, size, buf);
940       msg = (struct GNUNET_MessageHeader *) buf;
941       type = ntohs (msg->type);
942       break;
943     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
944       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
945       if (GMC_is_origin (c, GNUNET_YES))
946         data_size = send_core_connection_create (queue->c, size, buf);
947       else
948         data_size = send_core_data_raw (queue->cls, size, buf);
949       break;
950     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
951       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
952       if (GMC_is_origin (c, GNUNET_NO) ||
953           GMC_is_origin (c, GNUNET_YES))
954         data_size = send_core_connection_ack (queue->c, size, buf);
955       else
956         data_size = send_core_data_raw (queue->cls, size, buf);
957       break;
958     case GNUNET_MESSAGE_TYPE_MESH_DATA:
959     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
960     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
961       /* This should be encapsulted */
962       GNUNET_break (0);
963       data_size = 0;
964       break;
965     default:
966       GNUNET_break (0);
967       LOG (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n",
968                   queue->type);
969       data_size = 0;
970   }
971
972   if (0 < drop_percent &&
973       GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
974   {
975     LOG (GNUNET_ERROR_TYPE_WARNING,
976                 "Dropping message of type %s\n",
977                 GNUNET_MESH_DEBUG_M2S (queue->type));
978     data_size = 0;
979   }
980
981   /* Free queue, but cls was freed by send_core_* */
982   ch = queue->ch;
983   queue_destroy (queue, GNUNET_NO);
984
985   /* Send ACK if needed, after accounting for sent ID in fc->queue_n */
986   switch (type)
987   {
988     case GNUNET_MESSAGE_TYPE_MESH_FWD:
989     case GNUNET_MESSAGE_TYPE_MESH_BCK:
990       pid = ntohl ( ((struct GNUNET_MESH_Encrypted *) buf)->pid );
991       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   accounting pid %u\n", pid);
992       fc->last_pid_sent = pid;
993       send_ack (c, ch, fwd);
994       break;
995     default:
996       break;
997   }
998
999   /* If more data in queue, send next */
1000   queue = peer_get_first_message (peer);
1001   if (NULL != queue)
1002   {
1003     LOG (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
1004     if (NULL == peer->core_transmit) {
1005       peer->core_transmit =
1006           GNUNET_CORE_notify_transmit_ready(core_handle,
1007                                             0,
1008                                             0,
1009                                             GNUNET_TIME_UNIT_FOREVER_REL,
1010                                             dst_id,
1011                                             queue->size,
1012                                             &queue_send,
1013                                             peer);
1014     }
1015     else
1016     {
1017       LOG (GNUNET_ERROR_TYPE_DEBUG,
1018                   "*   tmt rdy called somewhere else\n");
1019     }
1020     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task)
1021     {
1022       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   starting poll timeout\n");
1023       fc->poll_task =
1024           GNUNET_SCHEDULER_add_delayed (fc->poll_time, &connection_poll, fc);
1025     }
1026   }
1027   else
1028   {
1029     if (GNUNET_SCHEDULER_NO_TASK != fc->poll_task)
1030     {
1031       GNUNET_SCHEDULER_cancel (fc->poll_task);
1032       fc->poll_task = GNUNET_SCHEDULER_NO_TASK;
1033     }
1034   }
1035   if (NULL != c)
1036   {
1037     c->pending_messages--;
1038     if (GNUNET_YES == c->destroy && 0 == c->pending_messages)
1039     {
1040       LOG (GNUNET_ERROR_TYPE_DEBUG, "*  destroying connection!\n");
1041       GMC_destroy (c);
1042     }
1043   }
1044
1045   if (NULL != t)
1046   {
1047     t->pending_messages--;
1048     if (GNUNET_YES == t->destroy && 0 == t->pending_messages)
1049     {
1050 //       LOG (GNUNET_ERROR_TYPE_DEBUG, "*  destroying tunnel!\n");
1051       tunnel_destroy (t);
1052     }
1053   }
1054   LOG (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
1055   return data_size;
1056 }
1057
1058
1059
1060 /**
1061  * Get first sendable message.
1062  *
1063  * @param peer The destination peer.
1064  *
1065  * @return Best current known path towards the peer, if any.
1066  */
1067 static struct MeshPeerQueue *
1068 peer_get_first_message (const struct MeshPeer *peer)
1069 {
1070   struct MeshPeerQueue *q;
1071
1072   for (q = peer->queue_head; NULL != q; q = q->next)
1073   {
1074     if (queue_is_sendable (q))
1075       return q;
1076   }
1077
1078   return NULL;
1079 }
1080
1081
1082 static int
1083 queue_is_sendable (struct MeshPeerQueue *q)
1084 {
1085   struct MeshFlowControl *fc;
1086
1087   /* Is PID-independent? */
1088   switch (q->type)
1089   {
1090     case GNUNET_MESSAGE_TYPE_MESH_ACK:
1091     case GNUNET_MESSAGE_TYPE_MESH_POLL:
1092       return GNUNET_YES;
1093   }
1094
1095   /* Is PID allowed? */
1096   fc = q->fwd ? &q->c->fwd_fc : &q->c->bck_fc;
1097   if (GMC_is_pid_bigger (fc->last_ack_recv, fc->last_pid_sent))
1098     return GNUNET_YES;
1099
1100   return GNUNET_NO;
1101 }
1102
1103
1104 /******************************************************************************/
1105 /********************************    API    ***********************************/
1106 /******************************************************************************/
1107
1108
1109 /**
1110  * Free a transmission that was already queued with all resources
1111  * associated to the request.
1112  *
1113  * @param queue Queue handler to cancel.
1114  * @param clear_cls Is it necessary to free associated cls?
1115  */
1116 void
1117 GMP_queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
1118 {
1119   struct MeshPeer *peer;
1120   struct MeshFlowControl *fc;
1121   int fwd;
1122
1123   fwd = queue->fwd;
1124   peer = queue->peer;
1125   GNUNET_assert (NULL != queue->c);
1126   fc = fwd ? &queue->c->fwd_fc : &queue->c->bck_fc;
1127
1128   if (GNUNET_YES == clear_cls)
1129   {
1130     LOG (GNUNET_ERROR_TYPE_DEBUG, "   queue destroy type %s\n",
1131                 GNUNET_MESH_DEBUG_M2S (queue->type));
1132     switch (queue->type)
1133     {
1134       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
1135       case GNUNET_MESSAGE_TYPE_MESH_TUNNEL_DESTROY:
1136         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
1137         GNUNET_break (GNUNET_YES == queue->c->destroy);
1138         /* fall through */
1139       case GNUNET_MESSAGE_TYPE_MESH_FWD:
1140       case GNUNET_MESSAGE_TYPE_MESH_BCK:
1141       case GNUNET_MESSAGE_TYPE_MESH_ACK:
1142       case GNUNET_MESSAGE_TYPE_MESH_POLL:
1143       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
1144       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
1145       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
1146         LOG (GNUNET_ERROR_TYPE_DEBUG, "   prebuilt message\n");;
1147         GNUNET_free_non_null (queue->cls);
1148         break;
1149
1150       default:
1151         GNUNET_break (0);
1152         LOG (GNUNET_ERROR_TYPE_ERROR, "   type %s unknown!\n",
1153                     GNUNET_MESH_DEBUG_M2S (queue->type));
1154     }
1155
1156   }
1157   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
1158
1159   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
1160       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
1161   {
1162     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N- %p %u\n", fc, fc->queue_n);
1163     fc->queue_n--;
1164     peer->queue_n--;
1165   }
1166   if (NULL != queue->c)
1167   {
1168     queue->c->pending_messages--;
1169     if (NULL != queue->c->t)
1170     {
1171       queue->c->t->pending_messages--;
1172     }
1173   }
1174
1175   GNUNET_free (queue);
1176 }
1177
1178
1179 /**
1180  * @brief Queue and pass message to core when possible.
1181  *
1182  * @param cls Closure (@c type dependant). It will be used by queue_send to
1183  *            build the message to be sent if not already prebuilt.
1184  * @param type Type of the message, 0 for a raw message.
1185  * @param size Size of the message.
1186  * @param c Connection this message belongs to (cannot be NULL).
1187  * @param ch Channel this message belongs to, if applicable (otherwise NULL).
1188  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1189  */
1190 void
1191 GMP_queue_add (void *cls, uint16_t type, size_t size, 
1192                struct MeshConnection *c,
1193                struct MeshChannel *ch,
1194                int fwd)
1195 {
1196   struct MeshPeerQueue *queue;
1197   struct MeshFlowControl *fc;
1198   struct MeshPeer *peer;
1199   int priority;
1200   int call_core;
1201
1202   LOG (GNUNET_ERROR_TYPE_DEBUG,
1203               "queue add %s %s (%u) on c %p, ch %p\n",
1204               fwd ? "FWD" : "BCK",  GNUNET_MESH_DEBUG_M2S (type), size, c, ch);
1205   GNUNET_assert (NULL != c);
1206
1207   fc   = fwd ? &c->fwd_fc : &c->bck_fc;
1208   peer = fwd ? connection_get_next_hop (c) : connection_get_prev_hop (c);
1209
1210   if (NULL == fc)
1211   {
1212     GNUNET_break (0);
1213     return;
1214   }
1215
1216   if (NULL == peer->connections)
1217   {
1218     /* We are not connected to this peer, ignore request. */
1219     GNUNET_break_op (0);
1220     return;
1221   }
1222
1223   priority = 0;
1224
1225   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
1226       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
1227   {
1228     priority = 100;
1229   }
1230
1231   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1232   LOG (GNUNET_ERROR_TYPE_DEBUG, "fc %p\n", fc);
1233   if (fc->queue_n >= fc->queue_max && 0 == priority)
1234   {
1235     GNUNET_STATISTICS_update (stats, "# messages dropped (buffer full)",
1236                               1, GNUNET_NO);
1237     GNUNET_break (0);
1238     LOG (GNUNET_ERROR_TYPE_DEBUG,
1239                 "queue full: %u/%u\n",
1240                 fc->queue_n, fc->queue_max);
1241     return; /* Drop this message */
1242   }
1243
1244   LOG (GNUNET_ERROR_TYPE_DEBUG, "last pid %u\n", fc->last_pid_sent);
1245   LOG (GNUNET_ERROR_TYPE_DEBUG, "     ack %u\n", fc->last_ack_recv);
1246   if (GMC_is_pid_bigger (fc->last_pid_sent + 1, fc->last_ack_recv))
1247   {
1248     call_core = GNUNET_NO;
1249     if (GNUNET_SCHEDULER_NO_TASK == fc->poll_task &&
1250         GNUNET_MESSAGE_TYPE_MESH_POLL != type)
1251     {
1252       LOG (GNUNET_ERROR_TYPE_DEBUG,
1253                   "no buffer space (%u > %u): starting poll\n",
1254                   fc->last_pid_sent + 1, fc->last_ack_recv);
1255       fc->poll_task = GNUNET_SCHEDULER_add_delayed (fc->poll_time,
1256                                                     &connection_poll,
1257                                                     fc);
1258     }
1259   }
1260   else
1261     call_core = GNUNET_YES;
1262   queue = GNUNET_malloc (sizeof (struct MeshPeerQueue));
1263   queue->cls = cls;
1264   queue->type = type;
1265   queue->size = size;
1266   queue->peer = peer;
1267   queue->c = c;
1268   queue->ch = ch;
1269   queue->fwd = fwd;
1270   if (100 <= priority)
1271   {
1272     struct MeshPeerQueue *copy;
1273     struct MeshPeerQueue *next;
1274
1275     for (copy = peer->queue_head; NULL != copy; copy = next)
1276     {
1277       next = copy->next;
1278       if (copy->type == type && copy->c == c && copy->fwd == fwd)
1279       {
1280         /* Example: also a FWD ACK for connection XYZ */
1281         queue_destroy (copy, GNUNET_YES);
1282       }
1283     }
1284     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
1285   }
1286   else
1287   {
1288     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
1289     LOG (GNUNET_ERROR_TYPE_DEBUG, "  Q_N+ %p %u\n", fc, fc->queue_n);
1290     fc->queue_n++;
1291     peer->queue_n++;
1292   }
1293
1294   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1295   {
1296     LOG (GNUNET_ERROR_TYPE_DEBUG,
1297                 "calling core tmt rdy towards %s for %u bytes\n",
1298                 peer2s (peer), size);
1299     peer->core_transmit =
1300         GNUNET_CORE_notify_transmit_ready (core_handle,
1301                                            0,
1302                                            0,
1303                                            GNUNET_TIME_UNIT_FOREVER_REL,
1304                                            GNUNET_PEER_resolve2 (peer->id),
1305                                            size,
1306                                            &queue_send,
1307                                            peer);
1308   }
1309   else
1310   {
1311     LOG (GNUNET_ERROR_TYPE_DEBUG,
1312                 "core tmt rdy towards %s already called\n",
1313                 peer2s (peer));
1314
1315   }
1316   c->pending_messages++;
1317   if (NULL != c->t)
1318     c->t->pending_messages++;
1319 }
1320
1321
1322
1323 /**
1324  * Initialize the peer subsystem.
1325  *
1326  * @param c Configuration.
1327  * @param id Peer identity
1328  */
1329 void
1330 GMP_init (const struct GNUNET_CONFIGURATION_Handle *c,
1331           const struct GNUNET_PeerIdentity *id)
1332 {
1333   my_full_id = id;
1334   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1335   if (GNUNET_OK !=
1336       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
1337                                              &max_peers))
1338   {
1339     LOG_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1340                                "MESH", "MAX_PEERS", "USING DEFAULT");
1341     max_peers = 1000;
1342   }
1343
1344   if (GNUNET_OK !=
1345       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
1346                                              &drop_percent))
1347   {
1348     drop_percent = 0;
1349   }
1350   else
1351   {
1352     LOG (GNUNET_ERROR_TYPE_WARNING,
1353                 "\n***************************************\n"
1354                 "Mesh is running with drop mode enabled.\n"
1355                 "This is NOT a good idea!\n"
1356                 "Remove the DROP_PERCENT option from your configuration.\n"
1357                 "***************************************\n");
1358   }
1359
1360   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1361                                      NULL,      /* Closure passed to MESH functions */
1362                                      &core_init,        /* Call core_init once connected */
1363                                      &core_connect,     /* Handle connects */
1364                                      &core_disconnect,  /* remove peers on disconnects */
1365                                      NULL,      /* Don't notify about all incoming messages */
1366                                      GNUNET_NO, /* For header only in notification */
1367                                      NULL,      /* Don't notify about all outbound messages */
1368                                      GNUNET_NO, /* For header-only out notification */
1369                                      core_handlers);    /* Register these handlers */
1370   if (NULL == core_handle)
1371   {
1372     GNUNET_break (0);
1373     GNUNET_SCHEDULER_shutdown ();
1374     return;
1375   }
1376 }
1377
1378 /**
1379  * Shut down the peer subsystem.
1380  */
1381 void
1382 GMP_shutdown (void)
1383 {
1384   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
1385 }
1386
1387
1388 /**
1389  * Try to establish a new connection to this peer in the given tunnel.
1390  * If the peer doesn't have any path to it yet, try to get one.
1391  * If the peer already has some path, send a CREATE CONNECTION towards it.
1392  *
1393  * @param peer PeerInfo of the peer.
1394  */
1395 void
1396 GMP_connect (struct MeshPeer *peer)
1397 {
1398   struct MeshTunnel2 *t;
1399   struct MeshPeerPath *p;
1400   struct MeshConnection *c;
1401   int rerun_search;
1402
1403   LOG (GNUNET_ERROR_TYPE_DEBUG,
1404               "peer_connect towards %s\n",
1405               peer2s (peer));
1406   t = peer->tunnel;
1407   c = NULL;
1408   rerun_search = GNUNET_NO;
1409
1410   if (NULL != peer->path_head)
1411   {
1412     LOG (GNUNET_ERROR_TYPE_DEBUG, "path exists\n");
1413     p = peer_get_best_path (peer);
1414     if (NULL != p)
1415     {
1416       LOG (GNUNET_ERROR_TYPE_DEBUG, "  %u hops\n", p->length);
1417       c = tunnel_use_path (t, p);
1418       if (NULL == c)
1419       {
1420         /* This case can happen when the path includes a first hop that is
1421          * not yet known to be connected.
1422          *
1423          * This happens quite often during testing when running mesh
1424          * under valgrind: core connect notifications come very late and the
1425          * DHT result has already come and created a valid path.
1426          * In this case, the peer->connections hashmap will be NULL and
1427          * tunnel_use_path will not be able to create a connection from that
1428          * path.
1429          *
1430          * Re-running the DHT GET should give core time to callback.
1431          */
1432         GNUNET_break(0);
1433                 rerun_search = GNUNET_YES;
1434       }
1435       else
1436       {
1437         send_connection_create (c);
1438         return;
1439       }
1440     }
1441   }
1442
1443   if (NULL != peer->search_h && GNUNET_YES == rerun_search)
1444   {
1445     GMD_search_stop (peer->search_h);
1446     peer->search_h = NULL;
1447     LOG (GNUNET_ERROR_TYPE_DEBUG,
1448                 "  Stopping DHT GET for peer %s\n", peer2s (peer));
1449   }
1450
1451   if (NULL == peer->search_h)
1452   {
1453     const struct GNUNET_PeerIdentity *id;
1454
1455     id = GNUNET_PEER_resolve2 (peer->id);
1456     LOG (GNUNET_ERROR_TYPE_DEBUG,
1457                 "  Starting DHT GET for peer %s\n", peer2s (peer));
1458     peer->search_h = GMD_search (id, &search_handler, peer);
1459     if (MESH_TUNNEL_NEW == t->state)
1460       tunnel_change_state (t, MESH_TUNNEL_SEARCHING);
1461   }
1462 }
1463
1464 /**
1465  * Get the static string for a peer ID.
1466  *
1467  * @param peer Peer.
1468  *
1469  * @return Static string for it's ID.
1470  */
1471 const char *
1472 GMP_2s (const struct MeshPeer *peer)
1473 {
1474   if (NULL == peer)
1475     return "(NULL)";
1476   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
1477 }