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