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