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