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