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