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