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