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