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