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