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