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