Cancel CORE transmit ready request when cancelling last transmittable message
[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_INFO, "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       return GNUNET_YES;
770
771     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
772       break;
773
774     default:
775       GNUNET_break (0);
776   }
777
778   return GMC_is_sendable (q->c, q->fwd);
779 }
780
781
782 /**
783  * Get first sendable message.
784  *
785  * @param peer The destination peer.
786  *
787  * @return First transmittable message, if any. Otherwise, NULL.
788  */
789 static struct MeshPeerQueue *
790 peer_get_first_message (const struct MeshPeer *peer)
791 {
792   struct MeshPeerQueue *q;
793
794   for (q = peer->queue_head; NULL != q; q = q->next)
795   {
796     LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking %p towards %s\n", q, GMC_2s (q->c));
797     if (queue_is_sendable (q))
798       return q;
799   }
800
801   return NULL;
802 }
803
804
805 /**
806  * Function to process paths received for a new peer addition. The recorded
807  * paths form the initial tunnel, which can be optimized later.
808  * Called on each result obtained for the DHT search.
809  *
810  * @param cls closure
811  * @param path
812  */
813 static void
814 search_handler (void *cls, const struct MeshPeerPath *path)
815 {
816   struct MeshPeer *peer = cls;
817   unsigned int connection_count;
818
819   GMP_add_path_to_all (path, GNUNET_NO);
820
821   /* Count connections */
822   connection_count = GMT_count_connections (peer->tunnel);
823
824   /* If we already have 3 (or more (?!)) connections, it's enough */
825   if (3 <= connection_count)
826     return;
827
828   if (MESH_TUNNEL3_SEARCHING == GMT_get_cstate (peer->tunnel))
829   {
830     LOG (GNUNET_ERROR_TYPE_DEBUG, " ... connect!\n");
831     GMP_connect (peer);
832   }
833   return;
834 }
835
836
837
838 /**
839  * Core callback to write a queued packet to core buffer
840  *
841  * @param cls Closure (peer info).
842  * @param size Number of bytes available in buf.
843  * @param buf Where the to write the message.
844  *
845  * @return number of bytes written to buf
846  */
847 static size_t
848 queue_send (void *cls, size_t size, void *buf)
849 {
850   struct MeshPeer *peer = cls;
851   struct MeshConnection *c;
852   struct MeshPeerQueue *queue;
853   const struct GNUNET_PeerIdentity *dst_id;
854   size_t data_size;
855
856   peer->core_transmit = NULL;
857   LOG (GNUNET_ERROR_TYPE_DEBUG, "* Queue send towards %s (max %u)\n",
858        GMP_2s (peer), size);
859
860   if (NULL == buf || 0 == size)
861   {
862     LOG (GNUNET_ERROR_TYPE_DEBUG, "* Buffer size 0.\n");
863     return 0;
864   }
865
866   /* Initialize */
867   queue = peer_get_first_message (peer);
868   if (NULL == queue)
869   {
870     GNUNET_assert (0); /* Core tmt_rdy should've been canceled */
871     return 0;
872   }
873   c = queue->c;
874
875   dst_id = GNUNET_PEER_resolve2 (peer->id);
876   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   on connection %s\n", GMC_2s (c));
877   /* Check if buffer size is enough for the message */
878   if (queue->size > size)
879   {
880     LOG (GNUNET_ERROR_TYPE_WARNING, "not enough room (%u vs %u), reissue\n",
881          queue->size, size);
882     peer->core_transmit =
883       GNUNET_CORE_notify_transmit_ready (core_handle,
884                                          GNUNET_NO, get_priority (queue),
885                                          GNUNET_TIME_UNIT_FOREVER_REL,
886                                          dst_id,
887                                          queue->size,
888                                          &queue_send,
889                                          peer);
890     return 0;
891   }
892   LOG (GNUNET_ERROR_TYPE_DEBUG, "*   size %u ok\n", queue->size);
893
894   /* Fill buf */
895   switch (queue->type)
896   {
897     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
898     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
899     case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
900     case GNUNET_MESSAGE_TYPE_MESH_KX:
901     case GNUNET_MESSAGE_TYPE_MESH_ACK:
902     case GNUNET_MESSAGE_TYPE_MESH_POLL:
903       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   raw: %s\n", GM_m2s (queue->type));
904       data_size = send_core_data_raw (queue->cls, size, buf);
905       break;
906     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
907       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path create\n");
908       if (GMC_is_origin (c, GNUNET_YES))
909         data_size = send_core_connection_create (queue->c, size, buf);
910       else
911         data_size = send_core_data_raw (queue->cls, size, buf);
912       break;
913     case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
914       LOG (GNUNET_ERROR_TYPE_DEBUG, "*   path ack\n");
915       if (GMC_is_origin (c, GNUNET_NO) ||
916           GMC_is_origin (c, GNUNET_YES))
917         data_size = send_core_connection_ack (queue->c, size, buf);
918       else
919         data_size = send_core_data_raw (queue->cls, size, buf);
920       break;
921     case GNUNET_MESSAGE_TYPE_MESH_DATA:
922     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_CREATE:
923     case GNUNET_MESSAGE_TYPE_MESH_CHANNEL_DESTROY:
924       /* This should be encapsulted */
925       GNUNET_break (0);
926       data_size = 0;
927       break;
928     default:
929       GNUNET_break (0);
930       LOG (GNUNET_ERROR_TYPE_WARNING, "*   type unknown: %u\n", queue->type);
931       data_size = 0;
932   }
933
934   if (0 < drop_percent &&
935       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 101) < drop_percent)
936   {
937     LOG (GNUNET_ERROR_TYPE_WARNING, "DD %s on connection\n",
938          GM_m2s (queue->type), GMC_2s (c));
939     data_size = 0;
940   }
941   else
942   {
943     LOG (GNUNET_ERROR_TYPE_INFO,
944         "ss %s on connection %s (%p) %s (size %u)\n",
945         GM_m2s (queue->type), GMC_2s (c), c, GM_f2s (queue->fwd), data_size);
946   }
947
948   /* Free queue, but cls was freed by send_core_* */
949   GMP_queue_destroy (queue, GNUNET_NO);
950
951   /* If more data in queue, send next */
952   queue = peer_get_first_message (peer);
953   if (NULL != queue)
954   {
955     LOG (GNUNET_ERROR_TYPE_DEBUG, "*   more data!\n");
956     if (NULL == peer->core_transmit)
957     {
958       peer->core_transmit =
959           GNUNET_CORE_notify_transmit_ready (core_handle,
960                                              GNUNET_NO, get_priority (queue),
961                                              GNUNET_TIME_UNIT_FOREVER_REL,
962                                              dst_id,
963                                              queue->size,
964                                              &queue_send,
965                                              peer);
966       queue->start_waiting = GNUNET_TIME_absolute_get ();
967     }
968     else
969     {
970       LOG (GNUNET_ERROR_TYPE_DEBUG,
971                   "*   tmt rdy called somewhere else\n");
972     }
973 //     GMC_start_poll (); FIXME needed?
974   }
975   else
976   {
977 //     GMC_stop_poll(); FIXME needed?
978   }
979
980   LOG (GNUNET_ERROR_TYPE_DEBUG, "*  Return %d\n", data_size);
981   return data_size;
982 }
983
984
985 /******************************************************************************/
986 /********************************    API    ***********************************/
987 /******************************************************************************/
988
989
990 /**
991  * Free a transmission that was already queued with all resources
992  * associated to the request.
993  *
994  * @param queue Queue handler to cancel.
995  * @param clear_cls Is it necessary to free associated cls?
996  */
997 void
998 GMP_queue_destroy (struct MeshPeerQueue *queue, int clear_cls)
999 {
1000   struct MeshPeer *peer;
1001
1002   peer = queue->peer;
1003
1004   if (GNUNET_YES == clear_cls)
1005   {
1006     LOG (GNUNET_ERROR_TYPE_DEBUG, "#   queue destroy type %s\n",
1007                 GM_m2s (queue->type));
1008     switch (queue->type)
1009     {
1010       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
1011         LOG (GNUNET_ERROR_TYPE_INFO, "destroying a DESTROY message\n");
1012         /* fall through */
1013       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
1014       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
1015       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
1016       case GNUNET_MESSAGE_TYPE_MESH_KEEPALIVE:
1017       case GNUNET_MESSAGE_TYPE_MESH_KX:
1018       case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
1019       case GNUNET_MESSAGE_TYPE_MESH_ACK:
1020       case GNUNET_MESSAGE_TYPE_MESH_POLL:
1021         GNUNET_free_non_null (queue->cls);
1022         break;
1023
1024       default:
1025         GNUNET_break (0);
1026         LOG (GNUNET_ERROR_TYPE_ERROR, "#   type %s unknown!\n",
1027                     GM_m2s (queue->type));
1028     }
1029   }
1030   GNUNET_CONTAINER_DLL_remove (peer->queue_head, peer->queue_tail, queue);
1031
1032   if (queue->type != GNUNET_MESSAGE_TYPE_MESH_ACK &&
1033       queue->type != GNUNET_MESSAGE_TYPE_MESH_POLL)
1034   {
1035     peer->queue_n--;
1036   }
1037
1038   if (NULL != queue->callback)
1039   {
1040     LOG (GNUNET_ERROR_TYPE_DEBUG, "#   Calling callback\n");
1041     queue->callback (queue->callback_cls,
1042                      queue->c, queue->type,
1043                      queue->fwd, queue->size,
1044                      GNUNET_TIME_absolute_get_duration (queue->start_waiting));
1045   }
1046
1047   if (NULL == peer_get_first_message (peer) && NULL != peer->core_transmit)
1048   {
1049     GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1050     peer->core_transmit = NULL;
1051   }
1052
1053   GNUNET_free (queue);
1054 }
1055
1056
1057 /**
1058  * @brief Queue and pass message to core when possible.
1059  *
1060  * @param peer Peer towards which to queue the message.
1061  * @param cls Closure (@c type dependant). It will be used by queue_send to
1062  *            build the message to be sent if not already prebuilt.
1063  * @param type Type of the message, 0 for a raw message.
1064  * @param size Size of the message.
1065  * @param c Connection this message belongs to (can be NULL).
1066  * @param fwd Is this a message going root->dest? (FWD ACK are NOT FWD!)
1067  * @param cont Continuation to be called once CORE has taken the message.
1068  * @param cont_cls Closure for @c cont.
1069  *
1070  * @return Handle to cancel the message before it is sent. Once cont is called
1071  *         message has been sent and therefore the handle is no longer valid.
1072  */
1073 struct MeshPeerQueue *
1074 GMP_queue_add (struct MeshPeer *peer, void *cls, uint16_t type, size_t size,
1075                struct MeshConnection *c, int fwd,
1076                GMP_sent cont, void *cont_cls)
1077 {
1078   struct MeshPeerQueue *queue;
1079   int priority;
1080   int call_core;
1081
1082   LOG (GNUNET_ERROR_TYPE_INFO, "qq %s on connection %s (%p) %s towards %s (size %u)\n",
1083        GM_m2s (type), GMC_2s (c), c, GM_f2s (fwd), GMP_2s(peer), size);
1084
1085   if (NULL == peer->connections)
1086   {
1087     /* We are not connected to this peer, ignore request. */
1088     LOG (GNUNET_ERROR_TYPE_DEBUG, "WARNING %s not a neighbor\n", GMP_2s (peer));
1089     GNUNET_STATISTICS_update (stats, "# messages dropped due to wrong hop", 1,
1090                               GNUNET_NO);
1091     return NULL;
1092   }
1093
1094   priority = 0;
1095
1096   if (GNUNET_MESSAGE_TYPE_MESH_POLL == type ||
1097       GNUNET_MESSAGE_TYPE_MESH_ACK == type)
1098   {
1099     priority = 100;
1100   }
1101
1102   LOG (GNUNET_ERROR_TYPE_DEBUG, "priority %d\n", priority);
1103
1104   call_core = NULL == c ? GNUNET_YES : GMC_is_sendable (c, fwd);
1105   queue = GNUNET_new (struct MeshPeerQueue);
1106   queue->cls = cls;
1107   queue->type = type;
1108   queue->size = size;
1109   queue->peer = peer;
1110   queue->c = c;
1111   queue->fwd = fwd;
1112   queue->callback = cont;
1113   queue->callback_cls = cont_cls;
1114   if (100 > priority)
1115   {
1116     GNUNET_CONTAINER_DLL_insert_tail (peer->queue_head, peer->queue_tail, queue);
1117     peer->queue_n++;
1118   }
1119   else
1120   {
1121     GNUNET_CONTAINER_DLL_insert (peer->queue_head, peer->queue_tail, queue);
1122     call_core = GNUNET_YES;
1123   }
1124
1125   if (NULL == peer->core_transmit && GNUNET_YES == call_core)
1126   {
1127     LOG (GNUNET_ERROR_TYPE_DEBUG,
1128                 "calling core tmt rdy towards %s for %u bytes\n",
1129                 GMP_2s (peer), size);
1130     peer->core_transmit =
1131         GNUNET_CORE_notify_transmit_ready (core_handle,
1132                                            GNUNET_NO, get_priority (queue),
1133                                            GNUNET_TIME_UNIT_FOREVER_REL,
1134                                            GNUNET_PEER_resolve2 (peer->id),
1135                                            size,
1136                                            &queue_send,
1137                                            peer);
1138     queue->start_waiting = GNUNET_TIME_absolute_get ();
1139   }
1140   else
1141   {
1142     LOG (GNUNET_ERROR_TYPE_DEBUG,
1143                 "core tmt rdy towards %s already called\n",
1144                 GMP_2s (peer));
1145
1146   }
1147   return queue;
1148 }
1149
1150
1151 /**
1152  * Cancel all queued messages to a peer that belong to a certain connection.
1153  *
1154  * @param peer Peer towards whom to cancel.
1155  * @param c Connection whose queued messages to cancel. Might be destroyed by
1156  *          the sent continuation call.
1157  */
1158 void
1159 GMP_queue_cancel (struct MeshPeer *peer, struct MeshConnection *c)
1160 {
1161   struct MeshPeerQueue *q;
1162   struct MeshPeerQueue *next;
1163   struct MeshPeerQueue *prev;
1164
1165   for (q = peer->queue_head; NULL != q; q = next)
1166   {
1167     prev = q->prev;
1168     if (q->c == c)
1169     {
1170       LOG (GNUNET_ERROR_TYPE_DEBUG, "GMP_cancel_queue %s\n", GM_m2s (q->type));
1171       GMP_queue_destroy (q, GNUNET_YES);
1172
1173       /* Get next from prev, q->next might be already freed:
1174        * queue destroy -> callback -> GMC_destroy -> cancel_queues -> here
1175        */
1176       if (NULL == prev)
1177         next = peer->queue_head;
1178       else
1179         next = prev->next;
1180     }
1181     else
1182     {
1183       next = q->next;
1184     }
1185   }
1186   if (NULL == peer->queue_head)
1187   {
1188     if (NULL != peer->core_transmit)
1189     {
1190       GNUNET_CORE_notify_transmit_ready_cancel (peer->core_transmit);
1191       peer->core_transmit = NULL;
1192     }
1193   }
1194 }
1195
1196
1197 /**
1198  * Get the first transmittable message for a connection.
1199  *
1200  * @param peer Neighboring peer.
1201  * @param c Connection.
1202  *
1203  * @return First transmittable message.
1204  */
1205 static struct MeshPeerQueue *
1206 connection_get_first_message (struct MeshPeer *peer, struct MeshConnection *c)
1207 {
1208   struct MeshPeerQueue *q;
1209
1210   for (q = peer->queue_head; NULL != q; q = q->next)
1211   {
1212     if (q->c != c)
1213       continue;
1214     if (queue_is_sendable (q))
1215     {
1216       LOG (GNUNET_ERROR_TYPE_DEBUG, "  sendable!!\n");
1217       return q;
1218     }
1219     LOG (GNUNET_ERROR_TYPE_DEBUG, "  not sendable\n");
1220   }
1221
1222   return NULL;
1223 }
1224
1225
1226 /**
1227  * Get the first message for a connection and unqueue it.
1228  *
1229  * @param peer Neighboring peer.
1230  * @param c Connection.
1231  *
1232  * @return First message for this connection.
1233  */
1234 struct GNUNET_MessageHeader *
1235 GMP_connection_pop (struct MeshPeer *peer, struct MeshConnection *c)
1236 {
1237   struct MeshPeerQueue *q;
1238   struct GNUNET_MessageHeader *msg;
1239
1240   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection pop on %s\n", GMC_2s (c));
1241   for (q = peer->queue_head; NULL != q; q = q->next)
1242   {
1243     if (q->c != c)
1244       continue;
1245     switch (q->type)
1246     {
1247       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_CREATE:
1248       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_ACK:
1249       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_DESTROY:
1250       case GNUNET_MESSAGE_TYPE_MESH_CONNECTION_BROKEN:
1251       case GNUNET_MESSAGE_TYPE_MESH_ACK:
1252       case GNUNET_MESSAGE_TYPE_MESH_POLL:
1253         GMP_queue_destroy (q, GNUNET_YES);
1254         continue;
1255
1256       case GNUNET_MESSAGE_TYPE_MESH_KX:
1257       case GNUNET_MESSAGE_TYPE_MESH_ENCRYPTED:
1258         msg = (struct GNUNET_MessageHeader *) q->cls;
1259         GMP_queue_destroy (q, GNUNET_NO);
1260         return msg;
1261
1262       default:
1263         GNUNET_break (0);
1264     }
1265   }
1266
1267   return NULL;
1268 }
1269
1270
1271 void
1272 GMP_queue_unlock (struct MeshPeer *peer, struct MeshConnection *c)
1273 {
1274   struct MeshPeerQueue *q;
1275   size_t size;
1276
1277   if (NULL != peer->core_transmit)
1278   {
1279     LOG (GNUNET_ERROR_TYPE_DEBUG, "  already unlocked!\n");
1280     return; /* Already unlocked */
1281   }
1282
1283   q = connection_get_first_message (peer, c);
1284   if (NULL == q)
1285   {
1286     LOG (GNUNET_ERROR_TYPE_DEBUG, "  queue empty!\n");
1287     return; /* Nothing to transmit */
1288   }
1289
1290   size = q->size;
1291   peer->core_transmit =
1292       GNUNET_CORE_notify_transmit_ready (core_handle,
1293                                          GNUNET_NO, get_priority (q),
1294                                          GNUNET_TIME_UNIT_FOREVER_REL,
1295                                          GNUNET_PEER_resolve2 (peer->id),
1296                                          size,
1297                                          &queue_send,
1298                                          peer);
1299 }
1300
1301
1302 /**
1303  * Initialize the peer subsystem.
1304  *
1305  * @param c Configuration.
1306  */
1307 void
1308 GMP_init (const struct GNUNET_CONFIGURATION_Handle *c)
1309 {
1310   LOG (GNUNET_ERROR_TYPE_DEBUG, "init\n");
1311   peers = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1312   if (GNUNET_OK !=
1313       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "MAX_PEERS",
1314                                              &max_peers))
1315   {
1316     GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_WARNING,
1317                                "MESH", "MAX_PEERS", "USING DEFAULT");
1318     max_peers = 1000;
1319   }
1320
1321   if (GNUNET_OK !=
1322       GNUNET_CONFIGURATION_get_value_number (c, "MESH", "DROP_PERCENT",
1323                                              &drop_percent))
1324   {
1325     drop_percent = 0;
1326   }
1327   else
1328   {
1329     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1330     LOG (GNUNET_ERROR_TYPE_WARNING, "Mesh is running with DROP enabled.\n");
1331     LOG (GNUNET_ERROR_TYPE_WARNING, "This is NOT a good idea!\n");
1332     LOG (GNUNET_ERROR_TYPE_WARNING, "Remove DROP_PERCENT from config file.\n");
1333     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1334   }
1335
1336   core_handle = GNUNET_CORE_connect (c, /* Main configuration */
1337                                      NULL,      /* Closure passed to MESH functions */
1338                                      &core_init,        /* Call core_init once connected */
1339                                      &core_connect,     /* Handle connects */
1340                                      &core_disconnect,  /* remove peers on disconnects */
1341                                      NULL,      /* Don't notify about all incoming messages */
1342                                      GNUNET_NO, /* For header only in notification */
1343                                      NULL,      /* Don't notify about all outbound messages */
1344                                      GNUNET_NO, /* For header-only out notification */
1345                                      core_handlers);    /* Register these handlers */
1346   if (GNUNET_YES !=
1347     GNUNET_CONFIGURATION_get_value_yesno (c, "MESH", "DISABLE_TRY_CONNECT"))
1348   {
1349     transport_handle = GNUNET_TRANSPORT_connect (c, &my_full_id, NULL, /* cls */
1350                                                  /* Notify callbacks */
1351                                                  NULL, NULL, NULL);
1352   }
1353   else
1354   {
1355     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1356     LOG (GNUNET_ERROR_TYPE_WARNING, "*  DISABLE TRYING CONNECT in config  *\n");
1357     LOG (GNUNET_ERROR_TYPE_WARNING, "*  Use this only for test purposes.  *\n");
1358     LOG (GNUNET_ERROR_TYPE_WARNING, "**************************************\n");
1359   }
1360
1361
1362
1363   if (NULL == core_handle)
1364   {
1365     GNUNET_break (0);
1366     GNUNET_SCHEDULER_shutdown ();
1367     return;
1368   }
1369
1370 }
1371
1372 /**
1373  * Shut down the peer subsystem.
1374  */
1375 void
1376 GMP_shutdown (void)
1377 {
1378   GNUNET_CONTAINER_multipeermap_iterate (peers, &shutdown_tunnel, NULL);
1379
1380   if (core_handle != NULL)
1381   {
1382     GNUNET_CORE_disconnect (core_handle);
1383     core_handle = NULL;
1384   }
1385   if (transport_handle != NULL)
1386   {
1387     GNUNET_TRANSPORT_disconnect (transport_handle);
1388     transport_handle = NULL;
1389   }
1390   GNUNET_PEER_change_rc (myid, -1);
1391 }
1392
1393 /**
1394  * Retrieve the MeshPeer stucture associated with the peer, create one
1395  * and insert it in the appropriate structures if the peer is not known yet.
1396  *
1397  * @param peer_id Full identity of the peer.
1398  *
1399  * @return Existing or newly created peer structure.
1400  */
1401 struct MeshPeer *
1402 GMP_get (const struct GNUNET_PeerIdentity *peer_id)
1403 {
1404   struct MeshPeer *peer;
1405
1406   peer = GNUNET_CONTAINER_multipeermap_get (peers, peer_id);
1407   if (NULL == peer)
1408   {
1409     peer = GNUNET_new (struct MeshPeer);
1410     if (GNUNET_CONTAINER_multipeermap_size (peers) > max_peers)
1411     {
1412       peer_delete_oldest ();
1413     }
1414         GNUNET_CONTAINER_multipeermap_put (peers, peer_id, peer,
1415                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1416         peer->id = GNUNET_PEER_intern (peer_id);
1417   }
1418   peer->last_contact = GNUNET_TIME_absolute_get();
1419
1420   return peer;
1421 }
1422
1423
1424 /**
1425  * Retrieve the MeshPeer stucture associated with the peer, create one
1426  * and insert it in the appropriate structures if the peer is not known yet.
1427  *
1428  * @param peer Short identity of the peer.
1429  *
1430  * @return Existing or newly created peer structure.
1431  */
1432 struct MeshPeer *
1433 GMP_get_short (const GNUNET_PEER_Id peer)
1434 {
1435   return GMP_get (GNUNET_PEER_resolve2 (peer));
1436 }
1437
1438
1439 /**
1440  * Try to connect to a peer on transport level.
1441  *
1442  * @param cls Closure (peer).
1443  * @param tc TaskContext.
1444  */
1445 static void
1446 try_connect (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1447 {
1448   struct MeshPeer *peer = cls;
1449
1450   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1451     return;
1452
1453   GNUNET_TRANSPORT_try_connect (transport_handle,
1454                                 GNUNET_PEER_resolve2 (peer->id), NULL, NULL);
1455 }
1456
1457
1458 /**
1459  * Try to establish a new connection to this peer (in its tunnel).
1460  * If the peer doesn't have any path to it yet, try to get one.
1461  * If the peer already has some path, send a CREATE CONNECTION towards it.
1462  *
1463  * @param peer Peer to connect to.
1464  */
1465 void
1466 GMP_connect (struct MeshPeer *peer)
1467 {
1468   struct MeshTunnel3 *t;
1469   struct MeshPeerPath *p;
1470   struct MeshConnection *c;
1471   int rerun_search;
1472
1473   LOG (GNUNET_ERROR_TYPE_DEBUG, "peer_connect towards %s\n", GMP_2s (peer));
1474
1475   /* If we have a current hello, try to connect using it. */
1476   GMP_try_connect (peer);
1477
1478   t = peer->tunnel;
1479   c = NULL;
1480   rerun_search = GNUNET_NO;
1481
1482   if (NULL != peer->path_head)
1483   {
1484     LOG (GNUNET_ERROR_TYPE_DEBUG, "  some path exists\n");
1485     p = peer_get_best_path (peer);
1486     if (NULL != p)
1487     {
1488       char *s;
1489
1490       s = path_2s (p);
1491       LOG (GNUNET_ERROR_TYPE_DEBUG, "  path to use: %s\n", s);
1492       GNUNET_free (s);
1493
1494       c = GMT_use_path (t, p);
1495       if (NULL == c)
1496       {
1497         /* This case can happen when the path includes a first hop that is
1498          * not yet known to be connected.
1499          *
1500          * This happens quite often during testing when running mesh
1501          * under valgrind: core connect notifications come very late and the
1502          * DHT result has already come and created a valid path.
1503          * In this case, the peer->connections hashmap will be NULL and
1504          * tunnel_use_path will not be able to create a connection from that
1505          * path.
1506          *
1507          * Re-running the DHT GET should give core time to callback.
1508          *
1509          * GMT_use_path -> GMC_new -> register_neighbors takes care of
1510          * updating statistics about this issue.
1511          */
1512         rerun_search = GNUNET_YES;
1513       }
1514       else
1515       {
1516         GMC_send_create (c);
1517         return;
1518       }
1519     }
1520     else
1521     {
1522       LOG (GNUNET_ERROR_TYPE_DEBUG, "  but is NULL, all paths are in use\n");
1523     }
1524   }
1525
1526   if (NULL != peer->search_h && GNUNET_YES == rerun_search)
1527   {
1528     GMD_search_stop (peer->search_h);
1529     peer->search_h = NULL;
1530     LOG (GNUNET_ERROR_TYPE_DEBUG,
1531          "  Stopping DHT GET for peer %s\n",
1532          GMP_2s (peer));
1533   }
1534
1535   if (NULL == peer->search_h)
1536   {
1537     const struct GNUNET_PeerIdentity *id;
1538
1539     id = GNUNET_PEER_resolve2 (peer->id);
1540     LOG (GNUNET_ERROR_TYPE_DEBUG,
1541                 "  Starting DHT GET for peer %s\n", GMP_2s (peer));
1542     peer->search_h = GMD_search (id, &search_handler, peer);
1543     if (MESH_TUNNEL3_NEW == GMT_get_cstate (t))
1544       GMT_change_cstate (t, MESH_TUNNEL3_SEARCHING);
1545   }
1546 }
1547
1548
1549 /**
1550  * Chech whether there is a direct (core level)  connection to peer.
1551  *
1552  * @param peer Peer to check.
1553  *
1554  * @return #GNUNET_YES if there is a direct connection.
1555  */
1556 int
1557 GMP_is_neighbor (const struct MeshPeer *peer)
1558 {
1559   struct MeshPeerPath *path;
1560
1561   if (NULL == peer->connections)
1562     return GNUNET_NO;
1563
1564   for (path = peer->path_head; NULL != path; path = path->next)
1565   {
1566     if (3 > path->length)
1567       return GNUNET_YES;
1568   }
1569
1570   /* Is not a neighbor but connections is not NULL, probably disconnecting */
1571   return GNUNET_NO;
1572 }
1573
1574
1575 /**
1576  * Create and initialize a new tunnel towards a peer, in case it has none.
1577  * In case the peer already has a tunnel, nothing is done.
1578  *
1579  * Does not generate any traffic, just creates the local data structures.
1580  *
1581  * @param peer Peer towards which to create the tunnel.
1582  */
1583 void
1584 GMP_add_tunnel (struct MeshPeer *peer)
1585 {
1586   if (NULL != peer->tunnel)
1587     return;
1588   peer->tunnel = GMT_new (peer);
1589 }
1590
1591
1592 /**
1593  * Add a connection to a neighboring peer.
1594  *
1595  * Store that the peer is the first hop of the connection in one
1596  * direction and that on peer disconnect the connection must be
1597  * notified and destroyed, for it will no longer be valid.
1598  *
1599  * @param peer Peer to add connection to.
1600  * @param c Connection to add.
1601  *
1602  * @return GNUNET_OK on success.
1603  */
1604 int
1605 GMP_add_connection (struct MeshPeer *peer,
1606                     struct MeshConnection *c)
1607 {
1608   int result;
1609   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding connection %s\n", GMC_2s (c));
1610   LOG (GNUNET_ERROR_TYPE_DEBUG, "to peer %s\n", GMP_2s (peer));
1611
1612   if (NULL == peer->connections)
1613   {
1614     GNUNET_break (0);
1615     LOG (GNUNET_ERROR_TYPE_DEBUG,
1616          "Peer %s is not a neighbor!\n",
1617          GMP_2s (peer));
1618     return GNUNET_SYSERR;
1619   }
1620   LOG (GNUNET_ERROR_TYPE_DEBUG,
1621        "peer %s ok, has %u connections.\n",
1622        GMP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
1623   result = GNUNET_CONTAINER_multihashmap_put (peer->connections,
1624                                               GMC_get_h (c),
1625                                               c,
1626                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1627   LOG (GNUNET_ERROR_TYPE_DEBUG,
1628        " now has %u connections.\n",
1629        GNUNET_CONTAINER_multihashmap_size (peer->connections));
1630   LOG (GNUNET_ERROR_TYPE_DEBUG, "result %u\n", result);
1631
1632   return result;
1633 }
1634
1635
1636 /**
1637  * Add the path to the peer and update the path used to reach it in case this
1638  * is the shortest.
1639  *
1640  * @param peer Destination peer to add the path to.
1641  * @param path New path to add. Last peer must be the peer in arg 1.
1642  *             Path will be either used of freed if already known.
1643  * @param trusted Do we trust that this path is real?
1644  *
1645  * @return path if path was taken, pointer to existing duplicate if exists
1646  *         NULL on error.
1647  */
1648 struct MeshPeerPath *
1649 GMP_add_path (struct MeshPeer *peer, struct MeshPeerPath *path,
1650               int trusted)
1651 {
1652   struct MeshPeerPath *aux;
1653   unsigned int l;
1654   unsigned int l2;
1655
1656   LOG (GNUNET_ERROR_TYPE_DEBUG, "adding path [%u] to peer %s\n",
1657        path->length, GMP_2s (peer));
1658
1659   if ((NULL == peer) || (NULL == path))
1660   {
1661     GNUNET_break (0);
1662     path_destroy (path);
1663     return NULL;
1664   }
1665   if (path->peers[path->length - 1] != peer->id)
1666   {
1667     GNUNET_break (0);
1668     path_destroy (path);
1669     return NULL;
1670   }
1671
1672   for (l = 1; l < path->length; l++)
1673   {
1674     if (path->peers[l] == myid)
1675     {
1676       LOG (GNUNET_ERROR_TYPE_DEBUG, " shortening path by %u\n", l);
1677       for (l2 = 0; l2 < path->length - l; l2++)
1678       {
1679         path->peers[l2] = path->peers[l + l2];
1680       }
1681       path->length -= l;
1682       l = 1;
1683       path->peers = GNUNET_realloc (path->peers,
1684                                     path->length * sizeof (GNUNET_PEER_Id));
1685     }
1686   }
1687
1688   LOG (GNUNET_ERROR_TYPE_DEBUG, " final length: %u\n", path->length);
1689
1690   if (2 >= path->length && GNUNET_NO == trusted)
1691   {
1692     /* Only allow CORE to tell us about direct paths */
1693     path_destroy (path);
1694     return NULL;
1695   }
1696
1697   l = path_get_length (path);
1698   if (0 == l)
1699   {
1700     path_destroy (path);
1701     return NULL;
1702   }
1703
1704   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1705   for (aux = peer->path_head; aux != NULL; aux = aux->next)
1706   {
1707     l2 = path_get_length (aux);
1708     if (l2 > l)
1709     {
1710       LOG (GNUNET_ERROR_TYPE_DEBUG, "  added\n");
1711       GNUNET_CONTAINER_DLL_insert_before (peer->path_head,
1712                                           peer->path_tail, aux, path);
1713       if (NULL != peer->tunnel && 3 < GMT_count_connections (peer->tunnel))
1714       {
1715         GMP_connect (peer);
1716       }
1717       return path;
1718     }
1719     else
1720     {
1721       if (l2 == l && memcmp (path->peers, aux->peers, l) == 0)
1722       {
1723         LOG (GNUNET_ERROR_TYPE_DEBUG, "  already known\n");
1724         path_destroy (path);
1725         return aux;
1726       }
1727     }
1728   }
1729   GNUNET_CONTAINER_DLL_insert_tail (peer->path_head, peer->path_tail,
1730                                     path);
1731   LOG (GNUNET_ERROR_TYPE_DEBUG, "  added last\n");
1732   if (NULL != peer->tunnel && 3 < GMT_count_connections (peer->tunnel))
1733   {
1734     GMP_connect (peer);
1735   }
1736   return path;
1737 }
1738
1739
1740 /**
1741  * Add the path to the origin peer and update the path used to reach it in case
1742  * this is the shortest.
1743  * The path is given in peer_info -> destination, therefore we turn the path
1744  * upside down first.
1745  *
1746  * @param peer Peer to add the path to, being the origin of the path.
1747  * @param path New path to add after being inversed.
1748  *             Path will be either used or freed.
1749  * @param trusted Do we trust that this path is real?
1750  *
1751  * @return path if path was taken, pointer to existing duplicate if exists
1752  *         NULL on error.
1753  */
1754 struct MeshPeerPath *
1755 GMP_add_path_to_origin (struct MeshPeer *peer,
1756                         struct MeshPeerPath *path,
1757                         int trusted)
1758 {
1759   if (NULL == path)
1760     return NULL;
1761   path_invert (path);
1762   return GMP_add_path (peer, path, trusted);
1763 }
1764
1765
1766 /**
1767  * Adds a path to the info of all the peers in the path
1768  *
1769  * @param p Path to process.
1770  * @param confirmed Whether we know if the path works or not.
1771  */
1772 void
1773 GMP_add_path_to_all (const struct MeshPeerPath *p, int confirmed)
1774 {
1775   unsigned int i;
1776
1777   /* TODO: invert and add */
1778   for (i = 0; i < p->length && p->peers[i] != myid; i++) /* skip'em */ ;
1779   for (i++; i < p->length; i++)
1780   {
1781     struct MeshPeer *aux;
1782     struct MeshPeerPath *copy;
1783
1784     aux = GMP_get_short (p->peers[i]);
1785     copy = path_duplicate (p);
1786     copy->length = i + 1;
1787     GMP_add_path (aux, copy, p->length < 3 ? GNUNET_NO : confirmed);
1788   }
1789 }
1790
1791
1792 /**
1793  * Remove any path to the peer that has the extact same peers as the one given.
1794  *
1795  * @param peer Peer to remove the path from.
1796  * @param path Path to remove. Is always destroyed .
1797  */
1798 void
1799 GMP_remove_path (struct MeshPeer *peer, struct MeshPeerPath *path)
1800 {
1801   struct MeshPeerPath *iter;
1802   struct MeshPeerPath *next;
1803
1804   GNUNET_assert (myid == path->peers[0]);
1805   GNUNET_assert (peer->id == path->peers[path->length - 1]);
1806
1807   for (iter = peer->path_head; NULL != iter; iter = next)
1808   {
1809     next = iter->next;
1810     if (0 == memcmp (path->peers, iter->peers,
1811                      sizeof (GNUNET_PEER_Id) * path->length))
1812     {
1813       GNUNET_CONTAINER_DLL_remove (peer->path_head, peer->path_tail, iter);
1814       if (iter != path)
1815         path_destroy (iter);
1816     }
1817   }
1818   path_destroy (path);
1819 }
1820
1821
1822 /**
1823  * Remove a connection from a neighboring peer.
1824  *
1825  * @param peer Peer to remove connection from.
1826  * @param c Connection to remove.
1827  *
1828  * @return GNUNET_OK on success.
1829  */
1830 int
1831 GMP_remove_connection (struct MeshPeer *peer,
1832                        const struct MeshConnection *c)
1833 {
1834   LOG (GNUNET_ERROR_TYPE_DEBUG, "removing connection %s\n", GMC_2s (c));
1835   LOG (GNUNET_ERROR_TYPE_DEBUG, "from peer %s\n", GMP_2s (peer));
1836
1837   if (NULL == peer || NULL == peer->connections)
1838   {
1839     LOG (GNUNET_ERROR_TYPE_DEBUG,
1840          "Peer %s is not a neighbor!\n",
1841          GMP_2s (peer));
1842     return GNUNET_SYSERR;
1843   }
1844   LOG (GNUNET_ERROR_TYPE_DEBUG,
1845        "peer %s ok, has %u connections.\n",
1846        GMP_2s (peer), GNUNET_CONTAINER_multihashmap_size (peer->connections));
1847
1848   return GNUNET_CONTAINER_multihashmap_remove (peer->connections,
1849                                                GMC_get_h (c),
1850                                                c);
1851 }
1852
1853 /**
1854  * Start the DHT search for new paths towards the peer: we don't have
1855  * enough good connections.
1856  *
1857  * @param peer Destination peer.
1858  */
1859 void
1860 GMP_start_search (struct MeshPeer *peer)
1861 {
1862   if (NULL != peer->search_h)
1863   {
1864     GNUNET_break (0);
1865     return;
1866   }
1867
1868   peer->search_h = GMD_search (GMP_get_id (peer), &search_handler, peer);
1869 }
1870
1871
1872 /**
1873  * Stop the DHT search for new paths towards the peer: we already have
1874  * enough good connections.
1875  *
1876  * @param peer Destination peer.
1877  */
1878 void
1879 GMP_stop_search (struct MeshPeer *peer)
1880 {
1881   if (NULL == peer->search_h)
1882   {
1883     GNUNET_break (0);
1884     return;
1885   }
1886
1887   GMD_search_stop (peer->search_h);
1888   peer->search_h = NULL;
1889 }
1890
1891
1892 /**
1893  * Get the Full ID of a peer.
1894  *
1895  * @param peer Peer to get from.
1896  *
1897  * @return Full ID of peer.
1898  */
1899 const struct GNUNET_PeerIdentity *
1900 GMP_get_id (const struct MeshPeer *peer)
1901 {
1902   return GNUNET_PEER_resolve2 (peer->id);
1903 }
1904
1905
1906 /**
1907  * Get the Short ID of a peer.
1908  *
1909  * @param peer Peer to get from.
1910  *
1911  * @return Short ID of peer.
1912  */
1913 GNUNET_PEER_Id
1914 GMP_get_short_id (const struct MeshPeer *peer)
1915 {
1916   return peer->id;
1917 }
1918
1919
1920 /**
1921  * Set tunnel.
1922  *
1923  * @param peer Peer.
1924  * @param t Tunnel.
1925  */
1926 void
1927 GMP_set_tunnel (struct MeshPeer *peer, struct MeshTunnel3 *t)
1928 {
1929   peer->tunnel = t;
1930   if (NULL == t && NULL != peer->search_h)
1931   {
1932     GMP_stop_search (peer);
1933   }
1934 }
1935
1936
1937 /**
1938  * Get the tunnel towards a peer.
1939  *
1940  * @param peer Peer to get from.
1941  *
1942  * @return Tunnel towards peer.
1943  */
1944 struct MeshTunnel3 *
1945 GMP_get_tunnel (const struct MeshPeer *peer)
1946 {
1947   return peer->tunnel;
1948 }
1949
1950
1951 /**
1952  * Set the hello message.
1953  *
1954  * @param peer Peer whose message to set.
1955  * @param hello Hello message.
1956  */
1957 void
1958 GMP_set_hello (struct MeshPeer *peer, const struct GNUNET_HELLO_Message *hello)
1959 {
1960   struct GNUNET_HELLO_Message *old;
1961   size_t size;
1962
1963   LOG (GNUNET_ERROR_TYPE_DEBUG, "set hello for %s\n", GMP_2s (peer));
1964   if (NULL == hello)
1965     return;
1966
1967   old = GMP_get_hello (peer);
1968   if (NULL == old)
1969   {
1970     size = GNUNET_HELLO_size (hello);
1971     LOG (GNUNET_ERROR_TYPE_DEBUG, " new (%u bytes)\n", size);
1972     peer->hello = GNUNET_malloc (size);
1973     memcpy (peer->hello, hello, size);
1974   }
1975   else
1976   {
1977     peer->hello = GNUNET_HELLO_merge (old, hello);
1978     LOG (GNUNET_ERROR_TYPE_DEBUG, " merge into %p (%u bytes)\n",
1979          peer->hello, GNUNET_HELLO_size (hello));
1980     GNUNET_free (old);
1981   }
1982 }
1983
1984
1985 /**
1986  * Get the hello message.
1987  *
1988  * @param peer Peer whose message to get.
1989  *
1990  * @return Hello message.
1991  */
1992 struct GNUNET_HELLO_Message *
1993 GMP_get_hello (struct MeshPeer *peer)
1994 {
1995   struct GNUNET_TIME_Absolute expiration;
1996   struct GNUNET_TIME_Relative remaining;
1997
1998   if (NULL == peer->hello)
1999     return NULL;
2000
2001   expiration = GNUNET_HELLO_get_last_expiration (peer->hello);
2002   remaining = GNUNET_TIME_absolute_get_remaining (expiration);
2003   if (0 == remaining.rel_value_us)
2004   {
2005     LOG (GNUNET_ERROR_TYPE_DEBUG, " get - hello expired on %s\n",
2006          GNUNET_STRINGS_absolute_time_to_string (expiration));
2007     GNUNET_free (peer->hello);
2008     peer->hello = NULL;
2009   }
2010   return peer->hello;
2011 }
2012
2013
2014 /**
2015  * Try to connect to a peer on TRANSPORT level.
2016  *
2017  * @param peer Peer to whom to connect.
2018  */
2019 void
2020 GMP_try_connect (struct MeshPeer *peer)
2021 {
2022   struct GNUNET_HELLO_Message *hello;
2023   struct GNUNET_MessageHeader *mh;
2024
2025   if (NULL == transport_handle)
2026     return;
2027
2028   hello = GMP_get_hello (peer);
2029   if (NULL == hello)
2030     return;
2031
2032   mh = GNUNET_HELLO_get_header (hello);
2033   GNUNET_TRANSPORT_offer_hello (transport_handle, mh, try_connect, peer);
2034 }
2035
2036
2037 /**
2038  * Notify a peer that a link between two other peers is broken. If any path
2039  * used that link, eliminate it.
2040  *
2041  * @param peer Peer affected by the change.
2042  * @param peer1 Peer whose link is broken.
2043  * @param peer2 Peer whose link is broken.
2044  */
2045 void
2046 GMP_notify_broken_link (struct MeshPeer *peer,
2047                         struct GNUNET_PeerIdentity *peer1,
2048                         struct GNUNET_PeerIdentity *peer2)
2049 {
2050   struct MeshPeerPath *iter;
2051   struct MeshPeerPath *next;
2052   unsigned int i;
2053   GNUNET_PEER_Id p1;
2054   GNUNET_PEER_Id p2;
2055
2056   p1 = GNUNET_PEER_search (peer1);
2057   p2 = GNUNET_PEER_search (peer2);
2058
2059   LOG (GNUNET_ERROR_TYPE_DEBUG, "Link %u-%u broken\n", p1, p2);
2060   if (0 == p1 || 0 == p2)
2061   {
2062     /* We don't even know them */
2063     return;
2064   }
2065
2066   for (iter = peer->path_head; NULL != iter; iter = next)
2067   {
2068     next = iter->next;
2069     for (i = 0; i < iter->length - 1; i++)
2070     {
2071       if ((iter->peers[i] == p1 && iter->peers[i + 1] == p2)
2072           || (iter->peers[i] == p2 && iter->peers[i + 1] == p1))
2073       {
2074         char *s;
2075
2076         s = path_2s (iter);
2077         LOG (GNUNET_ERROR_TYPE_DEBUG, " - invalidating %s\n", s);
2078         GNUNET_free (s);
2079
2080         path_invalidate (iter);
2081       }
2082     }
2083   }
2084 }
2085
2086
2087 /**
2088  * Count the number of known paths toward the peer.
2089  *
2090  * @param peer Peer to get path info.
2091  *
2092  * @return Number of known paths.
2093  */
2094 unsigned int
2095 GMP_count_paths (const struct MeshPeer *peer)
2096 {
2097   struct MeshPeerPath *iter;
2098   unsigned int i;
2099
2100   for (iter = peer->path_head, i = 0; NULL != iter; iter = iter->next)
2101     i++;
2102
2103   return i;
2104 }
2105
2106
2107 /**
2108  * Iterate all known peers.
2109  *
2110  * @param iter Iterator.
2111  * @param cls Closure for @c iter.
2112  */
2113 void
2114 GMP_iterate_all (GNUNET_CONTAINER_PeerMapIterator iter, void *cls)
2115 {
2116   GNUNET_CONTAINER_multipeermap_iterate (peers, iter, cls);
2117 }
2118
2119
2120 /**
2121  * Get the static string for a peer ID.
2122  *
2123  * @param peer Peer.
2124  *
2125  * @return Static string for it's ID.
2126  */
2127 const char *
2128 GMP_2s (const struct MeshPeer *peer)
2129 {
2130   if (NULL == peer)
2131     return "(NULL)";
2132   return GNUNET_i2s (GNUNET_PEER_resolve2 (peer->id));
2133 }