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