-towards tracking paths and trails via datacache in wdht
[oweals/gnunet.git] / src / dht / gnunet-service-wdht_neighbours.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2015 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  * @file dht/gnunet-service-wdht_neighbours.c
22  * @brief GNUnet DHT service's finger and friend table management code
23  * @author Supriti Singh
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_block_lib.h"
28 #include "gnunet_hello_lib.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_ats_service.h"
32 #include "gnunet_core_service.h"
33 #include "gnunet_datacache_lib.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_dht_service.h"
36 #include "gnunet_statistics_service.h"
37 #include "gnunet-service-wdht.h"
38 #include "gnunet-service-wdht_clients.h"
39 #include "gnunet-service-wdht_datacache.h"
40 #include "gnunet-service-wdht_neighbours.h"
41 #include "gnunet-service-wdht_nse.h"
42 #include <fenv.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include "dht.h"
46
47 #define DEBUG(...)                                           \
48   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
49
50 /**
51  * Trail timeout. After what time do trails always die?
52  */
53 #define TRAIL_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 42)
54
55 /**
56  * Random walk delay. How often do we walk the overlay?
57  */
58 #define RANDOM_WALK_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 42)
59
60 /**
61  * The number of layered ID to use.
62  */
63 #define NUMBER_LAYERED_ID 8
64
65 /**
66  * The number of random walk to launch at the beginning of the initialization
67  */
68 /* FIXME: find a better value */
69 #define NUMBER_RANDOM_WALK 20
70
71
72 /******************* The db structure and related functions *******************/
73
74 /**
75  * Entry in #friends_peermap.
76  */
77 struct FriendInfo;
78
79
80 /**
81  * Information we keep per trail.
82  */
83 struct Trail
84 {
85
86   /**
87    * MDLL entry in the list of all trails with the same predecessor.
88    */
89   struct Trail *prev_succ;
90
91   /**
92    * MDLL entry in the list of all trails with the same predecessor.
93    */
94   struct Trail *next_succ;
95
96   /**
97    * MDLL entry in the list of all trails with the same predecessor.
98    */
99   struct Trail *prev_pred;
100
101   /**
102    * MDLL entry in the list of all trails with the same predecessor.
103    */
104   struct Trail *next_pred;
105
106   /**
107    * Our predecessor in the trail, NULL if we are initiator (?).
108    */
109   struct FriendInfo *pred;
110
111   /**
112    * Our successor in the trail, NULL if we are the last peer.
113    */
114   struct FriendInfo *succ;
115
116   /**
117    * Identifier of the trail with the predecessor.
118    */
119   struct GNUNET_HashCode pred_id;
120
121   /**
122    * Identifier of the trail with the successor.
123    */
124   struct GNUNET_HashCode succ_id;
125
126   /**
127    * When does this trail expire.
128    */
129   struct GNUNET_TIME_Absolute expiration_time;
130
131   /**
132    * Location of this trail in the heap.
133    */
134   struct GNUNET_CONTAINER_HeapNode *hn;
135
136   /**
137    * If this peer started the to create a Finger (and thus @e pred is
138    * NULL), this is the Finger we are trying to intialize.
139    */
140   struct Finger **finger;
141
142 };
143
144
145 /**
146  *  Entry in #friends_peermap.
147  */
148 struct FriendInfo
149 {
150   /**
151    * Friend Identity
152    */
153   struct GNUNET_PeerIdentity id;
154
155   /**
156    *
157    */
158   struct Trail *pred_head;
159
160   /**
161    *
162    */
163   struct Trail *pred_tail;
164
165   /**
166    *
167    */
168   struct Trail *succ_head;
169
170   /**
171    *
172    */
173   struct Trail *succ_tail;
174
175   /**
176    * Core handle for sending messages to this friend.
177    */
178   struct GNUNET_MQ_Handle *mq;
179
180 };
181
182
183 /**
184  *
185  */
186 struct FingerTable;
187
188
189 /**
190  *
191  */
192 struct Finger
193 {
194   /**
195    *
196    */
197   struct Trail *trail;
198
199   /**
200    *
201    */
202   struct FingerTable *ft;
203
204   /**
205    *
206    */
207   struct GNUNET_HashCode destination;
208
209   /**
210    * #GNUNET_YES if a response has been received. Otherwise #GNUNET_NO.
211    */
212   int valid;
213 };
214
215
216 struct FingerTable
217 {
218   /**
219    * Array of our fingers, unsorted.
220    */
221   struct Finger **fingers;
222
223   /**
224    * Array of sorted fingers (sorted by destination, valid fingers first).
225    */
226   struct Finger **sorted_fingers;
227
228   /**
229    * Size of the finger array.
230    */
231   unsigned int finger_array_size;
232
233   /**
234    * Number of valid entries in @e sorted_fingers (contiguous from offset 0)
235    */
236   unsigned int number_valid_fingers;
237
238   /**
239    * Which offset in @e fingers will we redo next.
240    */
241   unsigned int walk_offset;
242
243   /**
244    * Is the finger array sorted?
245    */
246   int is_sorted;
247
248 };
249
250
251 /***********************  end of the db structure part  ***********************/
252
253
254 GNUNET_NETWORK_STRUCT_BEGIN
255
256 /**
257  * Setup a finger using the underlay topology ("social network").
258  */
259 struct RandomWalkMessage
260 {
261   /**
262    * Type: #GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK
263    */
264   struct GNUNET_MessageHeader header;
265
266   /**
267    * Number of hops this message has taken so far, we stop at
268    * log(NSE), in NBO.
269    */
270   uint16_t hops_taken GNUNET_PACKED;
271
272   /**
273    * Layer for the request, in NBO.
274    */
275   uint16_t layer GNUNET_PACKED;
276
277   /**
278    * Unique (random) identifier this peer will use to
279    * identify the trail (in future messages).
280    */
281   struct GNUNET_HashCode trail_id;
282
283 };
284
285 /**
286  * Response to a `struct RandomWalkMessage`.
287  */
288 struct RandomWalkResponseMessage
289 {
290   /**
291    * Type: #GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK_RESPONSE
292    */
293   struct GNUNET_MessageHeader header;
294
295   /**
296    * Zero, for alignment.
297    */
298   uint32_t reserved GNUNET_PACKED;
299
300   /**
301    * Unique (random) identifier from the
302    * `struct RandomWalkMessage`.
303    */
304   struct GNUNET_HashCode trail_id;
305
306   /**
307    * Random location in the respective layer where the
308    * random path of the finger setup terminated.
309    */
310   struct GNUNET_HashCode location;
311
312 };
313
314 /**
315  * Response to an event that causes a trail to die.
316  */
317 struct TrailDestroyMessage
318 {
319   /**
320    * Type: #GNUNET_MESSAGE_TYPE_WDHT_TRAIL_DESTROY
321    */
322   struct GNUNET_MessageHeader header;
323
324   /**
325    * Zero, for alignment.
326    */
327   uint32_t reserved GNUNET_PACKED;
328
329   /**
330    * Unique (random) identifier this peer will use to
331    * identify the finger (in future messages).
332    */
333   struct GNUNET_HashCode trail_id;
334
335 };
336
337
338 /**
339  * Send a message along a trail.
340  */
341 struct FindSuccessorMessage
342 {
343   /**
344    * Type: #GNUNET_MESSAGE_TYPE_WDHT_FIND_SUCCESSOR
345    */
346   struct GNUNET_MessageHeader header;
347
348   /**
349    * Zero, for alignment.
350    */
351   uint32_t reserved GNUNET_PACKED;
352
353   /**
354    * Unique (random) identifier this peer will use to
355    * identify the finger (in future messages).
356    */
357   struct GNUNET_HashCode trail_id;
358
359   /**
360    * Key for which we would like close values returned.
361    * identify the finger (in future messages).
362    */
363   struct GNUNET_HashCode key;
364
365 };
366
367
368 /**
369  * Send a message along a trail.
370  */
371 struct TrailRouteMessage
372 {
373   /**
374    * Type: #GNUNET_MESSAGE_TYPE_WDHT_TRAIL_ROUTE
375    */
376   struct GNUNET_MessageHeader header;
377
378   /**
379    * #GNUNET_YES if the path should be recorded, #GNUNET_NO if not; in NBO.
380    */
381   uint16_t record_path GNUNET_PACKED;
382
383   /**
384    * Length of the recorded trail, 0 if @e record_path is #GNUNET_NO; in NBO.
385    */
386   uint16_t path_length GNUNET_PACKED;
387
388   /**
389    * Unique (random) identifier this peer will use to
390    * identify the finger (in future messages).
391    */
392   struct GNUNET_HashCode trail_id;
393
394   /**
395    * Path the message has taken so far (excluding sender).
396    */
397   /* struct GNUNET_PeerIdentity path[path_length]; */
398
399   /* followed by payload (another `struct GNUNET_MessageHeader`) to
400      send along the trail */
401 };
402
403
404 /**
405  * P2P PUT message
406  */
407 struct PeerPutMessage
408 {
409   /**
410    * Type: #GNUNET_MESSAGE_TYPE_WDHT_PUT
411    */
412   struct GNUNET_MessageHeader header;
413
414   /**
415    * Processing options
416    */
417   uint32_t options GNUNET_PACKED;
418
419   /**
420    * Content type.
421    */
422   uint32_t block_type GNUNET_PACKED;
423
424   /**
425    * Hop count
426    */
427   uint32_t hop_count GNUNET_PACKED;
428
429   /**
430    * Replication level for this message
431    * In the current implementation, this value is not used.
432    */
433   uint32_t desired_replication_level GNUNET_PACKED;
434
435   /**
436    * Length of the PUT path that follows (if tracked).
437    */
438   uint32_t put_path_length GNUNET_PACKED;
439
440   /**
441    * When does the content expire?
442    */
443   struct GNUNET_TIME_AbsoluteNBO expiration_time;
444
445   /**
446    * The key to store the value under.
447    */
448   struct GNUNET_HashCode key GNUNET_PACKED;
449
450   /* put path (if tracked) */
451
452   /* Payload */
453
454 };
455
456 /**
457  * P2P GET message
458  */
459 struct PeerGetMessage
460 {
461   /**
462    * Type: #GNUNET_MESSAGE_TYPE_WDHT_GET
463    */
464   struct GNUNET_MessageHeader header;
465
466   /**
467    * Processing options
468    */
469   uint32_t options GNUNET_PACKED;
470
471   /**
472    * Desired content type.
473    */
474   uint32_t block_type GNUNET_PACKED;
475
476   /**
477    * Hop count
478    */
479   uint32_t hop_count GNUNET_PACKED;
480
481   /**
482    * Desired replication level for this request.
483    * In the current implementation, this value is not used.
484    */
485   uint32_t desired_replication_level GNUNET_PACKED;
486
487   /**
488    * Total number of peers in get path.
489    */
490   unsigned int get_path_length;
491
492   /**
493    * The key we are looking for.
494    */
495   struct GNUNET_HashCode key;
496
497   /* Get path. */
498   /* struct GNUNET_PeerIdentity[]*/
499 };
500
501
502 /**
503  * P2P Result message
504  */
505 struct PeerGetResultMessage
506 {
507   /**
508    * Type: #GNUNET_MESSAGE_TYPE_WDHT_GET_RESULT
509    */
510   struct GNUNET_MessageHeader header;
511
512   /**
513    * The type for the data.
514    */
515   uint32_t type GNUNET_PACKED;
516
517   /**
518    * Number of peers recorded in the outgoing path from source to the
519    * stored location of this message.
520    */
521   uint32_t put_path_length GNUNET_PACKED;
522
523   /**
524    * Length of the GET path that follows (if tracked).
525    */
526   uint32_t get_path_length GNUNET_PACKED;
527
528   /**
529    * Peer which queried for get and should get the result.
530    */
531   struct GNUNET_PeerIdentity querying_peer;
532
533   /**
534    * When does the content expire?
535    */
536   struct GNUNET_TIME_Absolute expiration_time;
537
538   /**
539    * The key of the corresponding GET request.
540    */
541   struct GNUNET_HashCode key;
542
543   /* put path (if tracked) */
544
545   /* get path (if tracked) */
546
547   /* Payload */
548
549 };
550
551 GNUNET_NETWORK_STRUCT_END
552
553
554 /**
555  * Contains all the layered IDs of this peer.
556  */
557 struct GNUNET_PeerIdentity layered_id[NUMBER_LAYERED_ID];
558
559 /**
560  * Task to timeout trails that have expired.
561  */
562 static struct GNUNET_SCHEDULER_Task *trail_timeout_task;
563
564 /**
565  * Task to perform random walks.
566  */
567 static struct GNUNET_SCHEDULER_Task *random_walk_task;
568
569 /**
570  * Identity of this peer.
571  */
572 static struct GNUNET_PeerIdentity my_identity;
573
574 /**
575  * Peer map of all the friends of a peer
576  */
577 static struct GNUNET_CONTAINER_MultiPeerMap *friends_peermap;
578
579 /**
580  * Fingers per layer.
581  */
582 static struct FingerTable fingers[NUMBER_LAYERED_ID];
583
584 /**
585  * Tail map, mapping tail identifiers to `struct Trail`s
586  */
587 static struct GNUNET_CONTAINER_MultiHashMap *trail_map;
588
589 /**
590  * Tail heap, organizing trails by expiration time.
591  */
592 static struct GNUNET_CONTAINER_Heap *trail_heap;
593
594 /**
595  * Handle to CORE.
596  */
597 static struct GNUNET_CORE_Handle *core_api;
598
599
600 /**
601  * Handle the put request from the client.
602  *
603  * @param key Key for the content
604  * @param block_type Type of the block
605  * @param options Routing options
606  * @param desired_replication_level Desired replication count
607  * @param expiration_time When does the content expire
608  * @param data Content to store
609  * @param data_size Size of content @a data in bytes
610  */
611 void
612 GDS_NEIGHBOURS_handle_put (const struct GNUNET_HashCode *key,
613                            enum GNUNET_BLOCK_Type block_type,
614                            enum GNUNET_DHT_RouteOption options,
615                            uint32_t desired_replication_level,
616                            struct GNUNET_TIME_Absolute expiration_time,
617                            const void *data,
618                            size_t data_size)
619 {
620   GDS_DATACACHE_handle_put (expiration_time,
621                             key,
622                             0, NULL,
623                             0, NULL,
624                             block_type,
625                             data_size,
626                             data);
627   GDS_CLIENTS_process_put (options,
628                            block_type,
629                            0, 0,
630                            0, NULL,
631                            expiration_time,
632                            key,
633                            data,
634                            data_size);
635 }
636
637
638 /**
639  * Handle the get request from the client file. If I am destination do
640  * datacache put and return. Else find the target friend and forward message
641  * to it.
642  *
643  * @param key Key for the content
644  * @param block_type Type of the block
645  * @param options Routing options
646  * @param desired_replication_level Desired replication count
647  */
648 void
649 GDS_NEIGHBOURS_handle_get (const struct GNUNET_HashCode *key,
650                            enum GNUNET_BLOCK_Type block_type,
651                            enum GNUNET_DHT_RouteOption options,
652                            uint32_t desired_replication_level)
653 {
654   // find closest finger(s) on all layers
655   // use TrailRoute with PeerGetMessage embedded to contact peer
656 }
657
658
659 /**
660  * Delete a trail, it died (timeout, link failure, etc.).
661  *
662  * @param trail trail to delete from all data structures
663  * @param inform_pred should we notify the predecessor?
664  * @param inform_succ should we inform the successor?
665  */
666 static void
667 delete_trail (struct Trail *trail,
668               int inform_pred,
669               int inform_succ)
670 {
671   struct FriendInfo *friend;
672   struct GNUNET_MQ_Envelope *env;
673   struct TrailDestroyMessage *tdm;
674   struct Finger *finger;
675
676   friend = trail->pred;
677   if (NULL != friend)
678   {
679     if (GNUNET_YES == inform_pred)
680     {
681       env = GNUNET_MQ_msg (tdm,
682                            GNUNET_MESSAGE_TYPE_WDHT_TRAIL_DESTROY);
683       tdm->trail_id = trail->pred_id;
684       GNUNET_MQ_send (friend->mq,
685                       env);
686     }
687     GNUNET_CONTAINER_MDLL_remove (pred,
688                                   friend->pred_head,
689                                   friend->pred_tail,
690                                   trail);
691   }
692   friend = trail->succ;
693   if (NULL != friend)
694   {
695     if (GNUNET_YES == inform_succ)
696     {
697       env = GNUNET_MQ_msg (tdm,
698                            GNUNET_MESSAGE_TYPE_WDHT_TRAIL_DESTROY);
699       tdm->trail_id = trail->pred_id;
700       GNUNET_MQ_send (friend->mq,
701                       env);
702     }
703     GNUNET_CONTAINER_MDLL_remove (succ,
704                                   friend->pred_head,
705                                   friend->pred_tail,
706                                   trail);
707   }
708   GNUNET_break (trail ==
709                 GNUNET_CONTAINER_heap_remove_node (trail->hn));
710   finger = *trail->finger;
711   if (NULL != finger)
712   {
713     *trail->finger = NULL;
714     GNUNET_free (finger);
715   }
716   GNUNET_free (trail);
717 }
718
719
720 /**
721  * Send the get result to requesting client.
722  *
723  * @param trail_id trail identifying where to send the result to, NULL for us
724  * @param key Key of the requested data.
725  * @param type Block type
726  * @param put_path_length Number of peers in @a put_path
727  * @param put_path Path taken to put the data at its stored location.
728  * @param expiration When will this result expire?
729  * @param data Payload to store
730  * @param data_size Size of the @a data
731  */
732 void
733 GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *trail_id,
734                                 const struct GNUNET_HashCode *key,
735                                 enum GNUNET_BLOCK_Type type,
736                                 unsigned int put_path_length,
737                                 const struct GNUNET_PeerIdentity *put_path,
738                                 struct GNUNET_TIME_Absolute expiration,
739                                 const void *data,
740                                 size_t data_size)
741 {
742   // TRICKY: need to introduce some context to remember trail from
743   // the lookup...
744 }
745
746
747 /**
748  * Method called whenever a peer disconnects.
749  *
750  * @param cls closure
751  * @param peer peer identity this notification is about
752  */
753 static void
754 handle_core_disconnect (void *cls,
755                         const struct GNUNET_PeerIdentity *peer)
756 {
757   struct FriendInfo *remove_friend;
758   struct Trail *t;
759
760   /* If disconnected to own identity, then return. */
761   if (0 == memcmp (&my_identity,
762                    peer,
763                    sizeof (struct GNUNET_PeerIdentity)))
764     return;
765
766   if (NULL == (remove_friend =
767                GNUNET_CONTAINER_multipeermap_get (friends_peermap,
768                                                   peer)))
769   {
770     GNUNET_break (0);
771     return;
772   }
773
774   GNUNET_assert (GNUNET_YES ==
775                  GNUNET_CONTAINER_multipeermap_remove (friends_peermap,
776                                                        peer,
777                                                        remove_friend));
778   while (NULL != (t = remove_friend->succ_head))
779     delete_trail (t,
780                   GNUNET_YES,
781                   GNUNET_NO);
782   while (NULL != (t = remove_friend->pred_head))
783     delete_trail (t,
784                   GNUNET_NO,
785                   GNUNET_YES);
786   GNUNET_MQ_destroy (remove_friend->mq);
787   GNUNET_free (remove_friend);
788   if (0 ==
789       GNUNET_CONTAINER_multipeermap_size (friends_peermap))
790   {
791     GNUNET_SCHEDULER_cancel (random_walk_task);
792     random_walk_task = NULL;
793   }
794 }
795
796
797 /**
798  * Pick random friend from friends for random walk.
799  */
800 static struct FriendInfo *
801 pick_random_friend ()
802 {
803   // TODO: need to extend peermap API to return random entry...
804   // (Note: same extension exists for hashmap API).
805   return NULL; // FIXME...
806 }
807
808
809 /**
810  * Initiate a random walk.
811  *
812  * @param cls NULL
813  * @param tc unused
814  */
815 static void
816 do_random_walk (void *cls,
817                 const struct GNUNET_SCHEDULER_TaskContext *tc)
818 {
819   static unsigned int walk_layer;
820   struct FriendInfo *friend;
821   struct GNUNET_MQ_Envelope *env;
822   struct RandomWalkMessage *rwm;
823   struct FingerTable *ft;
824   struct Finger *finger;
825   struct Trail *trail;
826
827   random_walk_task = NULL;
828   friend = pick_random_friend ();
829
830   trail = GNUNET_new (struct Trail);
831   /* We create the random walk so, no predecessor */
832   trail->succ = friend;
833   GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE,
834                                     &trail->succ_id);
835   if (GNUNET_OK !=
836       GNUNET_CONTAINER_multihashmap_put (trail_map,
837                                          &trail->succ_id,
838                                          trail,
839                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
840   {
841     GNUNET_break (0);
842     GNUNET_free (trail);
843     return;
844   }
845   GNUNET_CONTAINER_MDLL_insert (succ,
846                                 friend->succ_head,
847                                 friend->succ_tail,
848                                 trail);
849   env = GNUNET_MQ_msg (rwm,
850                        GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK);
851   rwm->hops_taken = htonl (0);
852   rwm->trail_id = trail->succ_id;
853   GNUNET_MQ_send (friend->mq,
854                   env);
855   /* clean up 'old' entry (implicitly via trail cleanup) */
856   ft = &fingers[walk_layer];
857
858   if ( (NULL != ft->fingers) &&
859        (NULL != (finger = ft->fingers[ft->walk_offset])) )
860     delete_trail (finger->trail,
861                   GNUNET_NO,
862                   GNUNET_YES);
863   if (ft->finger_array_size < 42)
864   {
865     // FIXME: must have finger array of the right size here,
866     // FIXME: growing / shrinking are tricy -- with pointers
867     // from Trails!!!
868   }
869
870   GNUNET_assert (NULL == ft->fingers[ft->walk_offset]);
871
872   finger = GNUNET_new (struct Finger);
873   finger->trail = trail;
874   trail->finger = &ft->fingers[ft->walk_offset];
875   finger->ft = ft;
876   ft->fingers[ft->walk_offset] = finger;
877   ft->is_sorted = GNUNET_NO;
878   ft->walk_offset = (ft->walk_offset + 1) % ft->finger_array_size;
879
880   walk_layer = (walk_layer + 1) % NUMBER_LAYERED_ID;
881   random_walk_task = GNUNET_SCHEDULER_add_delayed (RANDOM_WALK_DELAY,
882                                                    &do_random_walk,
883                                                    NULL);
884 }
885
886
887 /**
888  * Method called whenever a peer connects.
889  *
890  * @param cls closure
891  * @param peer_identity peer identity this notification is about
892  */
893 static void
894 handle_core_connect (void *cls,
895                      const struct GNUNET_PeerIdentity *peer_identity)
896 {
897   struct FriendInfo *friend;
898
899   /* Check for connect to self message */
900   if (0 == memcmp (&my_identity,
901                    peer_identity,
902                    sizeof (struct GNUNET_PeerIdentity)))
903     return;
904
905   /* If peer already exists in our friend_peermap, then exit. */
906   if (GNUNET_YES ==
907       GNUNET_CONTAINER_multipeermap_contains (friends_peermap,
908                                               peer_identity))
909   {
910     GNUNET_break (0);
911     return;
912   }
913
914   friend = GNUNET_new (struct FriendInfo);
915   friend->id = *peer_identity;
916   friend->mq = GNUNET_CORE_mq_create (core_api,
917                                       peer_identity);
918   GNUNET_assert (GNUNET_OK ==
919                  GNUNET_CONTAINER_multipeermap_put (friends_peermap,
920                                                     peer_identity,
921                                                     friend,
922                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
923   if (NULL == random_walk_task)
924   {
925     /* random walk needs to be started -- we have a first connection */
926     random_walk_task = GNUNET_SCHEDULER_add_now (&do_random_walk,
927                                                  NULL);
928   }
929 }
930
931
932 /**
933  * To be called on core init/fail.
934  *
935  * @param cls service closure
936  * @param identity the public identity of this peer
937  */
938 static void
939 core_init (void *cls,
940            const struct GNUNET_PeerIdentity *identity)
941 {
942   my_identity = *identity;
943 }
944
945
946 /**
947  * Handle a `struct RandomWalkMessage` from a
948  * #GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK message.
949  *
950  * @param cls closure (NULL)
951  * @param peer sender identity
952  * @param message the setup message
953  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
954  */
955 static int
956 handle_dht_p2p_random_walk (void *cls,
957                             const struct GNUNET_PeerIdentity *peer,
958                             const struct GNUNET_MessageHeader *message)
959 {
960   const struct RandomWalkMessage *m;
961   struct Trail *t;
962   struct FriendInfo *pred;
963
964   m = (const struct RandomWalkMessage *) message;
965   pred = GNUNET_CONTAINER_multipeermap_get (friends_peermap,
966                                             peer);
967   t = GNUNET_new (struct Trail);
968   t->pred_id = m->trail_id;
969   t->pred = pred;
970   t->expiration_time = GNUNET_TIME_relative_to_absolute (TRAIL_TIMEOUT);
971   if (GNUNET_OK !=
972       GNUNET_CONTAINER_multihashmap_put (trail_map,
973                                          &t->pred_id,
974                                          t,
975                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
976   {
977     GNUNET_break_op (0);
978     GNUNET_free (t);
979     return GNUNET_SYSERR;
980   }
981   GNUNET_CONTAINER_MDLL_insert (pred,
982                                 pred->pred_head,
983                                 pred->pred_tail,
984                                 t);
985   if (ntohl (m->hops_taken) > GDS_NSE_get ())
986   {
987     /* We are the last hop, generate response */
988     struct GNUNET_MQ_Envelope *env;
989     struct RandomWalkResponseMessage *rwrm;
990     uint16_t layer;
991
992     env = GNUNET_MQ_msg (rwrm,
993                          GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK_RESPONSE);
994     rwrm->reserved = htonl (0);
995     rwrm->trail_id = m->trail_id;
996     layer = ntohs (m->layer);
997     if (0 == layer)
998       (void) GDS_DATACACHE_get_random_key (&rwrm->location);
999     else
1000     {
1001       struct FingerTable *ft;
1002
1003       if (layer > NUMBER_LAYERED_ID)
1004       {
1005         GNUNET_break_op (0);
1006         // FIXME: clean up 't'...
1007         return GNUNET_SYSERR;
1008       }
1009       ft = &fingers[layer-1];
1010       if (0 == ft->number_valid_fingers)
1011       {
1012         GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE,
1013                                           &rwrm->location);
1014       }
1015       else
1016       {
1017         struct Finger *f;
1018
1019         f = ft->fingers[GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
1020                                                   ft->number_valid_fingers)];
1021         rwrm->location = f->destination;
1022       }
1023     }
1024     GNUNET_MQ_send (pred->mq,
1025                     env);
1026   }
1027   else
1028   {
1029     struct GNUNET_MQ_Envelope *env;
1030     struct RandomWalkMessage *rwm;
1031     struct FriendInfo *succ;
1032
1033     /* extend the trail by another random hop */
1034     succ = pick_random_friend ();
1035     GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_NONCE,
1036                                       &t->succ_id);
1037     t->succ = succ;
1038     if (GNUNET_OK !=
1039         GNUNET_CONTAINER_multihashmap_put (trail_map,
1040                                            &t->succ_id,
1041                                            t,
1042                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1043     {
1044       GNUNET_break (0);
1045       GNUNET_CONTAINER_MDLL_remove (pred,
1046                                     pred->pred_head,
1047                                     pred->pred_tail,
1048                                     t);
1049       GNUNET_free (t);
1050       return GNUNET_OK;
1051     }
1052     GNUNET_CONTAINER_MDLL_insert (succ,
1053                                   succ->succ_head,
1054                                   succ->succ_tail,
1055                                   t);
1056     env = GNUNET_MQ_msg (rwm,
1057                          GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK);
1058     rwm->hops_taken = htons (1 + ntohs (m->hops_taken));
1059     rwm->layer = m->layer;
1060     rwm->trail_id = t->succ_id;
1061     GNUNET_MQ_send (succ->mq,
1062                     env);
1063   }
1064   return GNUNET_OK;
1065 }
1066
1067
1068 /**
1069  * Handle a `struct RandomWalkResponseMessage` from a GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK_RESPONSE
1070  * message.
1071  *
1072  * @param cls closure (NULL)
1073  * @param peer sender identity
1074  * @param message the setup response message
1075  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1076  */
1077 static int
1078 handle_dht_p2p_random_walk_response (void *cls,
1079                                      const struct GNUNET_PeerIdentity *peer,
1080                                      const struct GNUNET_MessageHeader *message)
1081 {
1082   const struct RandomWalkResponseMessage *rwrm;
1083
1084   rwrm = (const struct RandomWalkResponseMessage *) message;
1085   // 1) lookup trail => find Finger entry => fill in 'destination' and mark valid, move to end of sorted array, mark unsorted, update links from 'trails'
1086   /*
1087    * Steps :
1088    *  1 check if we are the correct layer
1089    *  1.a if true : add the returned value (finger) in the db structure
1090    *  1.b if true : do nothing
1091    */
1092   /* FIXME: add the value in db structure 1.a */
1093
1094   return GNUNET_OK;
1095 }
1096
1097
1098 /**
1099  * Handle a `struct TrailDestroyMessage`.
1100  *
1101  * @param cls closure (NULL)
1102  * @param peer sender identity
1103  * @param message the finger destroy message
1104  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1105  */
1106 static int
1107 handle_dht_p2p_trail_destroy (void *cls,
1108                              const struct GNUNET_PeerIdentity *peer,
1109                              const struct GNUNET_MessageHeader *message)
1110 {
1111   const struct TrailDestroyMessage *tdm;
1112
1113   tdm = (const struct TrailDestroyMessage *) message;
1114
1115   /*
1116    * Steps :
1117    *  1 check if message comme from a trail (that we still remember...)
1118    *  1.a.1 if true: send the destroy message to the rest trail
1119    *  1.a.2 clean the trail structure
1120    *  1.a.3 did i have to remove the trail and ID from the db structure?
1121    *  1.b if false: do nothing
1122    */
1123
1124   return GNUNET_OK;
1125 }
1126
1127
1128 /**
1129  * Handler for a message we received along some trail.
1130  *
1131  * @param cls closure
1132  * @param trail_id trail identifier
1133  * @param message the message we got
1134  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1135  */
1136 typedef int
1137 (*TrailHandlerCallback)(void *cls,
1138                         const struct GNUNET_HashCode *trail_id,
1139                         const struct GNUNET_MessageHandler *message);
1140
1141
1142 /**
1143  * Definition of a handler for a message received along some trail.
1144  */
1145 struct TrailHandler
1146 {
1147   /**
1148    * NULL for end-of-list.
1149    */
1150   TrailHandlerCallback callback;
1151
1152   /**
1153    * Closure for @e callback.
1154    */
1155   void *cls;
1156
1157   /**
1158    * Message type this handler addresses.
1159    */
1160   uint16_t message_type;
1161
1162   /**
1163    * Use 0 for variable-size.
1164    */
1165   uint16_t message_size;
1166 };
1167
1168
1169 /**
1170  * Handle a `struct TrailRouteMessage`.
1171  *
1172  * @param cls closure (NULL)
1173  * @param peer sender identity
1174  * @param message the finger destroy message
1175  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1176  */
1177 static int
1178 handle_dht_p2p_trail_route (void *cls,
1179                             const struct GNUNET_PeerIdentity *peer,
1180                             const struct GNUNET_MessageHeader *message)
1181 {
1182   const struct TrailRouteMessage *trm;
1183
1184   trm = (const struct TrailRouteMessage *) message;
1185
1186   /*
1187    * Steps :
1188    *  1 check if message comme from a trail
1189    *  1.a.1 if trail not finished with us, continue to forward
1190    *  1.a.2 otherwise handle body message embedded in trail
1191    */
1192   return GNUNET_OK;
1193 }
1194
1195
1196 /**
1197  * Handle a `struct FindSuccessorMessage` from a #GNUNET_MESSAGE_TYPE_WDHT_SUCCESSOR_FIND
1198  * message.
1199  *
1200  * @param cls closure (NULL)
1201  * @param trail_id path to the originator
1202  * @param message the finger setup message
1203  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1204  */
1205 static int
1206 handle_dht_p2p_successor_find (void *cls,
1207                                const struct GNUNET_HashCode *trail_id,
1208                                const struct GNUNET_MessageHeader *message)
1209 {
1210   const struct FindSuccessorMessage *fsm;
1211
1212   fsm = (const struct FindSuccessorMessage *) message;
1213   // locate trail (for sending reply), if not exists, fail nicely.
1214   // otherwise, go to datacache and return 'top k' elements closest to 'key'
1215   // as "PUT" messages via the trail (need to extend DB API!)
1216 #if 0
1217   GDS_DATACACHE_get_successors (trail_id,
1218                                 key);
1219 #endif
1220   return GNUNET_OK;
1221 }
1222
1223
1224 /**
1225  * Handle a `struct PeerGetMessage`.
1226  *
1227  * @param cls closure (NULL)
1228  * @param trail_id path to the originator
1229  * @param message the peer get message
1230  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1231  */
1232 static int
1233 handle_dht_p2p_peer_get (void *cls,
1234                          const struct GNUNET_HashCode *trail_id,
1235                          const struct GNUNET_MessageHeader *message)
1236 {
1237   const struct PeerGetMessage *pgm;
1238
1239   // FIXME: note: never called like this, message embedded with trail route!
1240   pgm = (const struct PeerGetMessage *) message;
1241   // -> lookup in datacache (figure out way to remember trail!)
1242      /*
1243     * steps :
1244     *   1 extract the result
1245     *   2 save the peer
1246     *   3 send it using the good trail
1247     *
1248     * What do i do when i don't have the key/value?
1249     */
1250
1251   return GNUNET_OK;
1252 }
1253
1254
1255 /**
1256  * Handle a `struct PeerGetResultMessage`.
1257  *
1258  * @param cls closure (NULL)
1259  * @param trail_id path to the originator
1260  * @param message the peer get result message
1261  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1262  */
1263 static int
1264 handle_dht_p2p_peer_get_result (void *cls,
1265                                 const struct GNUNET_HashCode *trail_id,
1266                                 const struct GNUNET_MessageHeader *message)
1267 {
1268   const struct PeerGetResultMessage *pgrm;
1269
1270   pgrm = (const struct PeerGetResultMessage *) message;
1271   // pretty much: parse, & pass to client (there is some call for that...)
1272
1273 #if 0
1274   GDS_CLIENTS_process_get (options,
1275                            type,
1276                            0, 0,
1277                            path_length, path,
1278                            key);
1279   (void) GDS_DATACACHE_handle_get (trail_id,
1280                                    key,
1281                                    type,
1282                                    xquery,
1283                                    xquery_size,
1284                                    &reply_bf,
1285                                    reply_bf_mutator);
1286 #endif
1287   return GNUNET_OK;
1288 }
1289
1290
1291 /**
1292  * Handle a `struct PeerPutMessage`.
1293  *
1294  * @param cls closure (NULL)
1295  * @param trail_id path to the originator
1296  * @param message the peer put message
1297  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1298  */
1299 static int
1300 handle_dht_p2p_peer_put (void *cls,
1301                          const struct GNUNET_HashCode *trail_id,
1302                          const struct GNUNET_MessageHeader *message)
1303 {
1304   const struct PeerGetResultMessage *pgrm;
1305
1306   pgrm = (const struct PeerGetResultMessage *) message;
1307   // parse & store in datacache, this is in response to us asking for successors.
1308   /*
1309    * steps :
1310    * 1 check the size of the message
1311    * 2 use the API to add the value in the "database". Check on the xdht file, how to do it.
1312    * 3 Did i a have to return a notification or did i have to return GNUNET_[OK|SYSERR]?
1313    */
1314 #if 0
1315   GDS_DATACACHE_handle_put (expiration_time,
1316                             key,
1317                             path_length, path,
1318                             block_type,
1319                             data_size,
1320                             data);
1321   GDS_CLIENTS_process_put (options,
1322                            block_type,
1323                            0, 0,
1324                            path_length, path,
1325                            expiration_time,
1326                            key,
1327                            data,
1328                            data_size);
1329 #endif
1330   return GNUNET_OK;
1331 }
1332
1333
1334 /**
1335  * Initialize neighbours subsystem.
1336  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1337  */
1338 int
1339 GDS_NEIGHBOURS_init (void)
1340 {
1341   static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1342     { &handle_dht_p2p_random_walk,
1343       GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK,
1344       sizeof (struct RandomWalkMessage) },
1345     { &handle_dht_p2p_random_walk_response,
1346       GNUNET_MESSAGE_TYPE_WDHT_RANDOM_WALK_RESPONSE,
1347       sizeof (struct RandomWalkResponseMessage) },
1348     { &handle_dht_p2p_trail_destroy,
1349       GNUNET_MESSAGE_TYPE_WDHT_TRAIL_DESTROY,
1350       sizeof (struct TrailDestroyMessage) },
1351     { &handle_dht_p2p_trail_route,
1352       GNUNET_MESSAGE_TYPE_WDHT_TRAIL_ROUTE,
1353       0},
1354     {NULL, 0, 0}
1355   };
1356
1357   core_api =
1358     GNUNET_CORE_connect (GDS_cfg, NULL,
1359                          &core_init,
1360                          &handle_core_connect,
1361                          &handle_core_disconnect,
1362                          NULL, GNUNET_NO,
1363                          NULL, GNUNET_NO,
1364                          core_handlers);
1365
1366   if (NULL == core_api)
1367     return GNUNET_SYSERR;
1368   friends_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
1369   trail_map = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_YES);
1370   trail_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1371   return GNUNET_OK;
1372 }
1373
1374
1375 /**
1376  * Shutdown neighbours subsystem.
1377  */
1378 void
1379 GDS_NEIGHBOURS_done (void)
1380 {
1381   if (NULL == core_api)
1382     return;
1383   GNUNET_CORE_disconnect (core_api);
1384   core_api = NULL;
1385   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (friends_peermap));
1386   GNUNET_CONTAINER_multipeermap_destroy (friends_peermap);
1387   friends_peermap = NULL;
1388   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (trail_map));
1389   GNUNET_CONTAINER_multihashmap_destroy (trail_map);
1390   trail_map = NULL;
1391   GNUNET_CONTAINER_heap_destroy (trail_heap);
1392   trail_heap = NULL;
1393 }
1394
1395
1396 /**
1397  * Get my identity
1398  *
1399  * @return my identity
1400  */
1401 struct GNUNET_PeerIdentity
1402 GDS_NEIGHBOURS_get_my_id (void)
1403 {
1404   return my_identity;
1405 }
1406
1407 /* end of gnunet-service-wdht_neighbours.c */