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