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