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