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