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