- debug info
[oweals/gnunet.git] / src / dht / gnunet-service-xdht_neighbours.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009-2014 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file dht/gnunet-service-xdht_neighbours.c
23  * @brief GNUnet DHT service's finger and friend table management code
24  * @author Supriti Singh
25  */
26
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_block_lib.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_ats_service.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_datacache_lib.h"
36 #include "gnunet_transport_service.h"
37 #include "gnunet_dht_service.h"
38 #include "gnunet_statistics_service.h"
39 #include "gnunet-service-xdht.h"
40 #include "gnunet-service-xdht_clients.h"
41 #include "gnunet-service-xdht_datacache.h"
42 #include "gnunet-service-xdht_neighbours.h"
43 #include "gnunet-service-xdht_routing.h"
44 #include "dht.h"
45
46 /**
47  * TODO:
48  * 1. In X-Vine paper, there is no policy defined for replicating the data to
49  * recover in case of peer failure. We can do it in Chord way. In R5N, the key
50  * is hashed and then data is stored according to the key value generated after
51  * hashing.
52  */
53
54 #define DEBUG(...)                                           \
55   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
56
57 /**
58  * Maximum possible fingers (including predecessor) of a peer
59  */
60 #define MAX_FINGERS 65
61
62 /**
63  * Maximum allowed number of pending messages per friend peer.
64  */
65 #define MAXIMUM_PENDING_PER_FRIEND 64
66
67 /**
68  * How long to wait before sending another find finger trail request
69  */
70 #define DHT_FIND_FINGER_TRAIL_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
71
72 /**
73  * How long to wait before sending another verify successor message.
74  */
75 #define DHT_SEND_VERIFY_SUCCESSOR_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
76
77 /**
78  * How long to wait before sending another verify successor message.
79  */
80 #define DHT_SEND_VERIFY_SUCCESSOR_RETRY_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
81
82 /**
83  * How long to wait before retrying notify successor.
84  */
85 #define DHT_SEND_NOTIFY_SUCCESSOR_RETRY_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
86
87 /**
88  * How long at most to wait for transmission of a request to a friend ?
89  */
90 #define PENDING_MESSAGE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
91
92 /**
93  * Duration for which I may remain congested.
94  * Note: Its a static value. In future, a peer may do some analysis and calculate
95  * congestion_timeout based on 'some' parameters.
96  */
97 #define CONGESTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
98
99 /**
100  * In case we don't hear back from the current successor, then we can start
101  * verify successor.
102  */
103 #define WAIT_NOTIFY_CONFIRMATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 200)
104
105 /**
106  * Maximum number of trails allowed to go through a friend.
107  */
108 #define TRAILS_THROUGH_FRIEND_THRESHOLD 64
109
110 /**
111  * Maximum number of trails stored per finger.
112  */
113 #define MAXIMUM_TRAILS_PER_FINGER 4
114
115 /**
116  * Finger map index for predecessor entry in finger table.
117  */
118 #define PREDECESSOR_FINGER_ID 64
119
120 /**
121  * FIXME: Its use only at 3 places check if you can remove it.
122  * To check if a finger is predecessor or not.
123  */
124 enum GDS_NEIGHBOURS_finger_type
125 {
126   GDS_FINGER_TYPE_PREDECESSOR = 1,
127   GDS_FINGER_TYPE_NON_PREDECESSOR = 0
128 };
129
130 GNUNET_NETWORK_STRUCT_BEGIN
131
132 /**
133  * P2P PUT message
134  */
135 struct PeerPutMessage
136 {
137   /**
138    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_PUT
139    */
140   struct GNUNET_MessageHeader header;
141
142   /**
143    * Processing options
144    */
145   uint32_t options GNUNET_PACKED;
146
147   /**
148    * Content type.
149    */
150   uint32_t block_type GNUNET_PACKED;
151
152   /**
153    * Hop count
154    */
155   uint32_t hop_count GNUNET_PACKED;
156
157   /**
158    * Replication level for this message
159    * In the current implementation, this value is not used.
160    */
161   uint32_t desired_replication_level GNUNET_PACKED;
162
163   /**
164    * Length of the PUT path that follows (if tracked).
165    */
166   uint32_t put_path_length GNUNET_PACKED;
167
168   /**
169    * Best known destination (could be my friend or finger) which should
170    * get this message next.
171    */
172   struct GNUNET_PeerIdentity best_known_destination;
173
174   /**
175    * In case best_known_destination is a finger, then trail to reach
176    * to that finger. Else its default value is 0.
177    */
178   struct GNUNET_HashCode intermediate_trail_id;
179
180   /**
181    * When does the content expire?
182    */
183   struct GNUNET_TIME_AbsoluteNBO expiration_time;
184
185   /**
186    * The key to store the value under.
187    */
188   struct GNUNET_HashCode key GNUNET_PACKED;
189
190   /* put path (if tracked) */
191
192   /* Payload */
193
194 };
195
196 /**
197  * P2P GET message
198  */
199 struct PeerGetMessage
200 {
201   /**
202    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_GET
203    */
204   struct GNUNET_MessageHeader header;
205
206   /**
207    * Processing options
208    */
209   uint32_t options GNUNET_PACKED;
210
211   /**
212    * Desired content type.
213    */
214   uint32_t block_type GNUNET_PACKED;
215
216   /**
217    * Hop count
218    */
219   uint32_t hop_count GNUNET_PACKED;
220
221   /**
222    * Desired replication level for this request.
223    * In the current implementation, this value is not used.
224    */
225   uint32_t desired_replication_level GNUNET_PACKED;
226
227   /**
228    * Total number of peers in get path.
229    */
230   unsigned int get_path_length;
231
232   /**
233    * Best known destination (could be my friend or finger) which should
234    * get this message next.
235    */
236   struct GNUNET_PeerIdentity best_known_destination;
237
238   /**
239    * In case best_known_destination is a finger, then trail to reach
240    * to that finger. Else its default value is 0.
241    */
242   struct GNUNET_HashCode intermediate_trail_id;
243
244   /**
245    * The key we are looking for.
246    */
247   struct GNUNET_HashCode key;
248
249   /* Get path. */
250   /* struct GNUNET_PeerIdentity[]*/
251 };
252
253 /**
254  * P2P Result message
255  */
256 struct PeerGetResultMessage
257 {
258   /**
259    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_GET_RESULT
260    */
261   struct GNUNET_MessageHeader header;
262
263   /**
264    * The type for the data.
265    */
266   uint32_t type GNUNET_PACKED;
267
268   /**
269    * Number of peers recorded in the outgoing path from source to the
270    * stored location of this message.
271    */
272   uint32_t put_path_length GNUNET_PACKED;
273
274   /**
275    * Length of the GET path that follows (if tracked).
276    */
277   uint32_t get_path_length GNUNET_PACKED;
278
279   /**
280    * Peer which queried for get and should get the result.
281    */
282   struct GNUNET_PeerIdentity querying_peer;
283
284   /**
285    * When does the content expire?
286    */
287   struct GNUNET_TIME_AbsoluteNBO expiration_time;
288
289   /**
290    * The key of the corresponding GET request.
291    */
292   struct GNUNET_HashCode key;
293
294   /* put path (if tracked) */
295
296   /* get path (if tracked) */
297
298   /* Payload */
299
300 };
301
302 /**
303  * P2P Trail setup message
304  */
305 struct PeerTrailSetupMessage
306 {
307   /**
308    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP
309    */
310   struct GNUNET_MessageHeader header;
311
312   /**
313    * Is source_peer trying to setup the trail to a predecessor or any finger.
314    */
315   uint32_t is_predecessor;
316
317   /**
318    * Peer closest to this value will be our finger.
319    */
320   uint64_t final_destination_finger_value;
321
322   /**
323    * Source peer which wants to setup the trail to one of its finger.
324    */
325   struct GNUNET_PeerIdentity source_peer;
326
327   /**
328    * Best known destination (could be my friend or finger) which should
329    * get this message next.
330    *
331    * FIXME: this could be removed if we include trail_source / trail_dest
332    * in the routing table. This way we save 32 bytes of bandwidth by using
333    * extra 8 bytes of memory (2 * sizeof (GNUNET_PEER_ID))
334    */
335   struct GNUNET_PeerIdentity best_known_destination;
336
337   /**
338    * In case best_known_destination is a finger, then trail id of trail to
339    * reach to this finger.
340    */
341   struct GNUNET_HashCode intermediate_trail_id;
342
343   /**
344    * Trail id for trail which we are trying to setup.
345    */
346   struct GNUNET_HashCode trail_id;
347
348   /* List of peers which are part of trail setup so far.
349    * Trail does NOT include source_peer and peer which will be closest to
350    * ultimate_destination_finger_value.
351    * struct GNUNET_PeerIdentity trail[]
352    */
353 };
354
355 /**
356   * P2P Trail Setup Result message
357  */
358 struct PeerTrailSetupResultMessage
359 {
360
361   /**
362    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_RESULT
363    */
364   struct GNUNET_MessageHeader header;
365
366   /**
367    * Finger to which we have found the path.
368    */
369   struct GNUNET_PeerIdentity finger_identity;
370
371   /**
372    * Peer which started trail_setup to find trail to finger_identity
373    */
374   struct GNUNET_PeerIdentity querying_peer;
375
376   /**
377    * Is the trail setup to querying_peer's predecessor or finger?
378    */
379   uint32_t is_predecessor;
380
381   /**
382    * Value to which finger_identity is the closest peer.
383    */
384   uint64_t ulitmate_destination_finger_value;
385
386   /**
387    * Identifier of the trail from querying peer to finger_identity, NOT
388    * including both endpoints.
389    */
390   struct GNUNET_HashCode trail_id;
391
392   /* List of peers which are part of the trail from querying peer to
393    * finger_identity, NOT including both endpoints.
394    * struct GNUNET_PeerIdentity trail[]
395    */
396 };
397
398 /**
399  * P2P Verify Successor Message.
400  */
401 struct PeerVerifySuccessorMessage
402 {
403   /**
404    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR
405    */
406   struct GNUNET_MessageHeader header;
407
408   /**
409    * Peer which wants to verify its successor.
410    */
411   struct GNUNET_PeerIdentity source_peer;
412
413   /**
414    * Source Peer's current successor.
415    */
416   struct GNUNET_PeerIdentity successor;
417
418   /**
419    * Identifier of trail to reach from source_peer to successor.
420    */
421   struct GNUNET_HashCode trail_id;
422
423   /* List of the peers which are part of trail to reach  from source_peer
424    * to successor, NOT including them
425    * struct GNUNET_PeerIdentity trail[]
426    */
427 };
428
429 /**
430  * P2P Verify Successor Result Message
431  */
432 struct PeerVerifySuccessorResultMessage
433 {
434   /**
435    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR_RESULT
436    */
437   struct GNUNET_MessageHeader header;
438
439   /**
440    * Peer which sent the request to verify its successor.
441    */
442   struct GNUNET_PeerIdentity querying_peer;
443
444   /**
445    * Successor to which PeerVerifySuccessorMessage was sent.
446    */
447   struct GNUNET_PeerIdentity current_successor;
448
449   /**
450    * Current Predecessor of source_successor. It can be same as querying peer
451    * or different. In case it is different then it can be querying_peer's
452    * probable successor.
453    */
454   struct GNUNET_PeerIdentity probable_successor;
455
456   /**
457    * Trail identifier of trail from querying_peer to current_successor.
458    */
459   struct GNUNET_HashCode trail_id;
460
461   /**
462    * Direction in which we are looking at the trail.
463    */
464   uint32_t trail_direction;
465
466   /* In case probable_successor != querying_peer, then trail to reach from
467    * querying_peer to probable_successor, NOT including end points.
468    * struct GNUNET_PeerIdentity trail[]
469    */
470 };
471
472 /**
473  * P2P Notify New Successor Message.
474  */
475 struct PeerNotifyNewSuccessorMessage
476 {
477   /**
478    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_NOTIFY_NEW_SUCCESSOR
479    */
480   struct GNUNET_MessageHeader header;
481
482   /**
483    * Peer which wants to notify its new successor.
484    */
485   struct GNUNET_PeerIdentity source_peer;
486
487   /**
488    * New successor of source_peer.
489    */
490   struct GNUNET_PeerIdentity new_successor;
491
492   /**
493    * Unique identifier of the trail from source_peer to new_successor,
494    * NOT including the endpoints.
495    */
496   struct GNUNET_HashCode trail_id;
497
498   /* List of peers in trail from source_peer to new_successor,
499    * NOT including the endpoints.
500    * struct GNUNET_PeerIdentity trail[]
501    */
502 };
503
504 /**
505  * P2P Notify Successor Confirmation message.
506  */
507 struct PeerNotifyConfirmationMessage
508 {
509    /**
510    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_TEARDOWN
511    */
512   struct GNUNET_MessageHeader header;
513
514   /**
515    * Unique identifier of the trail.
516    */
517   struct GNUNET_HashCode trail_id;
518
519   /**
520    * Direction of trail.
521    */
522   uint32_t trail_direction;
523 };
524
525
526 /**
527  * P2P Trail Tear Down message.
528  */
529 struct PeerTrailTearDownMessage
530 {
531   /**
532    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_TEARDOWN
533    */
534   struct GNUNET_MessageHeader header;
535
536   /**
537    * Unique identifier of the trail.
538    */
539   struct GNUNET_HashCode trail_id;
540
541   /**
542    * Direction of trail.
543    */
544   uint32_t trail_direction;
545 };
546
547
548 /**
549  * P2P Trail Rejection Message.
550  */
551 struct PeerTrailRejectionMessage
552 {
553   /**
554    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_REJECTION
555    */
556   struct GNUNET_MessageHeader header;
557
558   /**
559    * Peer which wants to set up the trail.
560    */
561   struct GNUNET_PeerIdentity source_peer;
562
563   /**
564    * Peer which sent trail rejection message as it it congested.
565    */
566   struct GNUNET_PeerIdentity congested_peer;
567
568   /**
569    * Peer identity closest to this value will be finger of
570    * source_peer.
571    */
572   uint64_t ultimate_destination_finger_value;
573
574   /**
575    * Is source_peer trying to setup the trail to its predecessor or finger.
576    */
577   uint32_t is_predecessor;
578
579   /**
580    * Identifier for the trail that source peer is trying to setup.
581    */
582   struct GNUNET_HashCode trail_id;
583
584   /**
585    * Relative time for which congested_peer will remain congested.
586    */
587   struct GNUNET_TIME_Relative congestion_time;
588
589   /* Trail_list from source_peer to peer which sent the message for trail setup
590    * to congested peer. This trail does NOT include source_peer.
591    struct GNUNET_PeerIdnetity trail[]*/
592 };
593
594 /**
595  * P2P Add Trail Message.
596  */
597 struct PeerAddTrailMessage
598 {
599   /**
600    * Type: #GNUNET_MESSAGE_TYPE_XDHT_P2P_ADD_TRAIL
601    */
602   struct GNUNET_MessageHeader header;
603
604   /**
605    * Source of the routing trail.
606    */
607   struct GNUNET_PeerIdentity source_peer;
608
609   /**
610    * Destination of the routing trail.
611    */
612   struct GNUNET_PeerIdentity destination_peer;
613
614   /**
615    * Unique identifier of the trail from source_peer to destination_peer,
616    * NOT including the endpoints.
617    */
618   struct GNUNET_HashCode trail_id;
619
620   /* Trail from source peer to destination peer, NOT including them.
621    * struct GNUNET_PeerIdentity trail[]
622    */
623 };
624
625
626 GNUNET_NETWORK_STRUCT_END
627
628 /**
629  * Linked list of messages to send to a particular other peer.
630  */
631 struct P2PPendingMessage
632 {
633   /**
634    * Pointer to next item in the list
635    */
636   struct P2PPendingMessage *next;
637
638   /**
639    * Pointer to previous item in the list
640    */
641   struct P2PPendingMessage *prev;
642
643   /**
644    * Message importance level.  FIXME: used? useful?
645    */
646   unsigned int importance;
647
648   /**
649    * When does this message time out?
650    */
651   struct GNUNET_TIME_Absolute timeout;
652
653   /**
654    * Actual message to be sent, allocated at the end of the struct:
655    * // msg = (cast) &pm[1];
656    * // memcpy (&pm[1], data, len);
657    */
658   const struct GNUNET_MessageHeader *msg;
659
660 };
661
662 /**
663  *  Entry in friend_peermap.
664  */
665 struct FriendInfo
666 {
667   /**
668    * Friend Identity
669    */
670   struct GNUNET_PeerIdentity id;
671
672   /**
673    * Number of trails for which this friend is the first hop or if the friend
674    * is finger.
675    */
676   unsigned int trails_count;
677
678   /**
679    * Count of outstanding messages for this friend.
680    */
681   unsigned int pending_count;
682
683   /**
684    * In case not 0, then amount of time for which this friend is congested.
685    */
686   struct GNUNET_TIME_Absolute congestion_timestamp;
687
688
689   // TODO : Change name of head and tail to pending_messages_list_head and so.
690   /**
691    * Head of pending messages to be sent to this friend.
692    */
693   struct P2PPendingMessage *head;
694
695   /**
696    * Tail of pending messages to be sent to this friend.
697    */
698   struct P2PPendingMessage *tail;
699
700   /**
701    * Core handle for sending messages to this friend.
702    */
703   struct GNUNET_CORE_TransmitHandle *th;
704
705 };
706
707 /**
708  * An individual element of the trail to reach to a finger.
709  */
710 struct Trail_Element
711 {
712   /**
713     * Pointer to next item in the list
714     */
715   struct Trail_Element *next;
716
717   /**
718     * Pointer to prev item in the list
719     */
720   struct Trail_Element *prev;
721
722   /**
723    * An element in this trail.
724    */
725   struct GNUNET_PeerIdentity peer;
726 };
727
728 /**
729  * Information about an individual trail.
730  */
731 struct Trail
732 {
733   /**
734    * Head of trail.
735    */
736   struct Trail_Element *trail_head;
737
738   /**
739    * Tail of trail.
740    */
741   struct Trail_Element *trail_tail;
742
743   /**
744    * Unique identifier of this trail.
745    */
746   struct GNUNET_HashCode trail_id;
747
748   /**
749    * Length of trail pointed
750    */
751   unsigned int trail_length;
752
753   /**
754    * Is there a valid trail entry.
755    */
756   unsigned int is_present;
757 };
758
759 /**
760  * An entry in finger_table
761  */
762 struct FingerInfo
763 {
764   /**
765    * Finger identity.
766    */
767   struct GNUNET_PeerIdentity finger_identity;
768
769   /**
770    * In case not 0, this amount is time to wait for notify successor message.
771    * Used ONLY for successor. NOT for any other finger.
772    */
773   struct GNUNET_TIME_Absolute wait_notify_confirmation;
774
775   /**
776    * Is any finger stored at this finger index.
777    */
778   unsigned int is_present;
779
780   /**
781    * Index in finger peer map
782    */
783   uint32_t finger_table_index;
784
785   /**
786    * Number of trails setup so far for this finger.
787    * Should not cross MAXIMUM_TRAILS_PER_FINGER.
788    */
789   uint32_t trails_count;
790
791   /**
792    * Array of trails to reach to this finger.
793    */
794   struct Trail trail_list[MAXIMUM_TRAILS_PER_FINGER];
795 };
796
797
798 /**
799  * Stores information about the peer which is closest to destination_finger_value.
800  * 'closest' can be either successor or predecessor depending on is_predecessor
801  * flag.
802  */
803 struct Closest_Peer
804 {
805   /**
806    * Destination finger value.
807    */
808   uint64_t destination_finger_value;
809
810   /**
811    * Is finger_value a predecessor or any other finger.
812    */
813   unsigned int is_predecessor;
814
815   /**
816    * Trail id to reach to peer.
817    * In case peer is my identity or friend, it is set to 0.
818    */
819   struct GNUNET_HashCode trail_id;
820
821   /**
822    * Next destination. In case of friend and my_identity , it is same as next_hop
823    * In case of finger it is finger identity.
824    */
825   struct GNUNET_PeerIdentity best_known_destination;
826
827   /**
828    * In case best_known_destination is a finger, then first friend in the trail
829    * to reach to it. In other case, same as best_known_destination.
830    */
831   struct GNUNET_PeerIdentity next_hop;
832
833   /**
834    * In case finger is the next hop, it contains a valid finger table index
835    * at which the finger is stored. Else, It contains 65, which is out of range
836    * of finger table index.
837    */
838   unsigned int finger_table_index;
839 };
840
841 /**
842  * Context for send_verify_successor_task.
843  */
844 struct VerifySuccessorContext
845 {
846   /**
847    * Number of times this has been scheduled.
848    */
849   unsigned int num_retries_scheduled;
850 };
851
852 /**
853  * Task that sends FIND FINGER TRAIL requests. This task is started when we have
854  * get our first friend.
855  */
856 static struct GNUNET_SCHEDULER_Task * find_finger_trail_task;
857
858 /**
859  * Task that sends verify successor message. This task is started when we get
860  * our successor for the first time.
861  */
862 static struct GNUNET_SCHEDULER_Task * send_verify_successor_task;
863
864 /**
865  * Task that sends verify successor message. This task is started when we get
866  * our successor for the first time.
867  */
868 static struct GNUNET_SCHEDULER_Task * send_verify_successor_retry_task;
869
870 /**
871  * Task that sends verify successor message. This task is started when we get
872  * our successor for the first time.
873  */
874 static struct GNUNET_SCHEDULER_Task * send_notify_new_successor_retry_task;
875
876 /**
877  * Identity of this peer.
878  */
879 static struct GNUNET_PeerIdentity my_identity;
880
881 /**
882  * Peer map of all the friends of a peer
883  */
884 static struct GNUNET_CONTAINER_MultiPeerMap *friend_peermap;
885
886 /**
887  * Array of all the fingers.
888  */
889 static struct FingerInfo finger_table [MAX_FINGERS];
890
891 /**
892  * Handle to CORE.
893  */
894 static struct GNUNET_CORE_Handle *core_api;
895
896 /**
897  * Handle for the statistics service.
898  */
899 //extern struct GNUNET_STATISTICS_Handle *GDS_stats;
900
901 /**
902  * The current finger index that we have want to find trail to. We start the
903  * search with value = 0, i.e. successor  and then go to PREDCESSOR_FINGER_ID
904  * and decrement it. For any index 63 <= index < 0, if finger is same as successor,
905  * we reset this index to 0.
906  */
907 static unsigned int current_search_finger_index;
908
909 /**
910  * Time duration to schedule find finger trail task.
911  */
912 static struct GNUNET_TIME_Relative find_finger_trail_task_next_send_time;
913
914 /**
915  * Time duration to schedule verify successor task.
916  */
917 static struct GNUNET_TIME_Relative verify_successor_next_send_time;
918
919 /**
920  * Time duration to send verify successor again, if result was not received in time.
921  */
922 static struct GNUNET_TIME_Relative verify_successor_retry_time;
923
924 /**
925  * Time duration to retry send_notify_successor.
926  */
927 static struct GNUNET_TIME_Relative notify_successor_retry_time;
928
929 /**
930  * Are we waiting for confirmation from our new successor that it got the
931  * message
932  */
933 //static unsigned int waiting_for_notify_confirmation;
934
935 /* Below variables are used only for testing, and statistics collection. */
936 /**
937  * Should we store our topology predecessor and successor IDs into statistics?
938  */
939 unsigned int track_topology;
940
941 /**
942  * Should I be a malicious peer and drop the PUT/GET packets?
943  * if 0 then NOT malicious.
944  */
945 unsigned int act_malicious;
946
947 /**
948  * Count of fingers found. Ideally we should have O(logn) fingers for a
949  * stable network.
950  */
951 static unsigned int total_fingers_found;
952
953 /**
954  * Number of times we found the same successor.
955  */
956 static unsigned int successor_times;
957
958 /**
959  * Number of rounds for which we should search for finger.
960  */
961 static unsigned int fingers_round_count;
962 /**
963  * Called when core is ready to send a message we asked for
964  * out to the destination.
965  *
966  * @param cls the 'struct FriendInfo' of the target friend
967  * @param size number of bytes available in buf
968  * @param buf where the callee should write the message
969  * @return number of bytes written to buf
970  */
971 static size_t
972 core_transmit_notify (void *cls, size_t size, void *buf)
973 {
974   struct FriendInfo *peer = cls;
975   char *cbuf = buf;
976   struct P2PPendingMessage *pending;
977   size_t off;
978   size_t msize;
979
980   peer->th = NULL;
981   while ( (NULL != (pending = peer->head)) &&
982           (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us) )
983   {
984     GNUNET_STATISTICS_update (GDS_stats,
985                               gettext_noop
986                               ("# Messages dropped (CORE timeout)"),
987                               1,
988                               GNUNET_NO);
989     peer->pending_count--;
990     GNUNET_CONTAINER_DLL_remove (peer->head,
991                                  peer->tail,
992                                  pending);
993     GNUNET_free (pending);
994   }
995   if (NULL == pending)
996   {
997     /* no messages pending */
998     return 0;
999   }
1000   if (NULL == buf)
1001   {
1002     peer->th =
1003         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
1004                                            GNUNET_CORE_PRIO_BEST_EFFORT,
1005                                            GNUNET_TIME_absolute_get_remaining
1006                                            (pending->timeout), &peer->id,
1007                                            ntohs (pending->msg->size),
1008                                            &core_transmit_notify, peer);
1009     GNUNET_break (NULL != peer->th);
1010     return 0;
1011   }
1012   off = 0;
1013   while ((NULL != (pending = peer->head)) &&
1014          (size - off >= (msize = ntohs (pending->msg->size))))
1015   {
1016     GNUNET_STATISTICS_update (GDS_stats,
1017                               gettext_noop
1018                               ("# Bytes transmitted to other peers"),
1019                               msize,
1020                               GNUNET_NO);
1021     memcpy (&cbuf[off], pending->msg, msize);
1022     off += msize;
1023     peer->pending_count--;
1024     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1025     GNUNET_free (pending);
1026   }
1027   if (peer->head != NULL)
1028   {
1029     peer->th =
1030         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
1031                                            GNUNET_CORE_PRIO_BEST_EFFORT,
1032                                            GNUNET_TIME_absolute_get_remaining
1033                                            (pending->timeout), &peer->id, msize,
1034                                            &core_transmit_notify, peer);
1035     GNUNET_break (NULL != peer->th);
1036   }
1037   return off;
1038 }
1039
1040
1041 /**
1042  * Transmit all messages in the friend's message queue.
1043  *
1044  * @param peer message queue to process
1045  */
1046 static void
1047 process_friend_queue (struct FriendInfo *peer)
1048 {
1049   struct P2PPendingMessage *pending;
1050
1051   if (NULL == (pending = peer->head))
1052   {
1053     return;
1054   }
1055   if (NULL != peer->th)
1056   {
1057     return;
1058   }
1059
1060   peer->th =
1061       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
1062                                          pending->importance,
1063                                          GNUNET_TIME_absolute_get_remaining
1064                                          (pending->timeout), &peer->id,
1065                                          ntohs (pending->msg->size),
1066                                          &core_transmit_notify, peer);
1067   GNUNET_break (NULL != peer->th);
1068 }
1069
1070
1071 #if ENABLE_MALICIOUS
1072 /**
1073  * Set the ENABLE_MALICIOUS value to malicious.
1074  * @param malicious
1075  */
1076 int
1077 GDS_NEIGHBOURS_act_malicious (unsigned int malicious)
1078 {
1079   act_malicious = malicious;
1080   return GNUNET_OK;
1081 }
1082 #endif
1083
1084 /**
1085  * Construct a trail setup message and forward it to target_friend
1086  * @param source_peer Peer which wants to setup the trail
1087  * @param ultimate_destination_finger_value Peer identity closest to this value
1088  *                                          will be finger to @a source_peer
1089  * @param best_known_destination Best known destination (could be finger or friend)
1090  *                               which should get this message. In case it is
1091  *                               friend, then it is same as target_friend
1092  * @param target_friend Friend to which message is forwarded now.
1093  * @param trail_length Total number of peers in trail setup so far.
1094  * @param trail_peer_list Trail setup so far
1095  * @param is_predecessor Is @a source_peer looking for trail to a predecessor or not.
1096  * @param trail_id Unique identifier for the trail we are trying to setup.
1097  * @param intermediate_trail_id Trail id of intermediate trail to reach to
1098  *                              best_known_destination when its a finger. If not
1099  *                              used then set to 0.
1100  */
1101 void
1102 GDS_NEIGHBOURS_send_trail_setup (struct GNUNET_PeerIdentity source_peer,
1103                                  uint64_t ultimate_destination_finger_value,
1104                                  struct GNUNET_PeerIdentity best_known_destination,
1105                                  struct FriendInfo *target_friend,
1106                                  unsigned int trail_length,
1107                                  const struct GNUNET_PeerIdentity *trail_peer_list,
1108                                  unsigned int is_predecessor,
1109                                  struct GNUNET_HashCode trail_id,
1110                                  struct GNUNET_HashCode intermediate_trail_id)
1111 {
1112   struct P2PPendingMessage *pending;
1113   struct PeerTrailSetupMessage *tsm;
1114   struct GNUNET_PeerIdentity *peer_list;
1115   size_t msize;
1116
1117   msize = sizeof (struct PeerTrailSetupMessage) +
1118           (trail_length * sizeof (struct GNUNET_PeerIdentity));
1119
1120   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1121   {
1122     GNUNET_break (0);
1123     return;
1124   }
1125
1126   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1127   {
1128     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1129                                 1, GNUNET_NO);
1130   }
1131   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1132   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1133   tsm = (struct PeerTrailSetupMessage *) &pending[1];
1134   pending->msg = &(tsm->header);
1135   tsm->header.size = htons (msize);
1136   tsm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP);
1137   tsm->final_destination_finger_value = GNUNET_htonll (ultimate_destination_finger_value);
1138   tsm->source_peer = source_peer;
1139   tsm->best_known_destination = best_known_destination;
1140   tsm->is_predecessor = htonl (is_predecessor);
1141   tsm->trail_id = trail_id;
1142   tsm->intermediate_trail_id = intermediate_trail_id;
1143
1144   if (trail_length > 0)
1145   {
1146     peer_list = (struct GNUNET_PeerIdentity *) &tsm[1];
1147     memcpy (peer_list, trail_peer_list, trail_length * sizeof(struct GNUNET_PeerIdentity));
1148   }
1149
1150   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1151   target_friend->pending_count++;
1152   process_friend_queue (target_friend);
1153 }
1154
1155
1156 /**
1157  * Construct a trail setup result message and forward it to target friend.
1158  * @param querying_peer Peer which sent the trail setup request and should get
1159  *                      the result back.
1160  * @param Finger Peer to which the trail has been setup to.
1161  * @param target_friend Friend to which this message should be forwarded.
1162  * @param trail_length Numbers of peers in the trail.
1163  * @param trail_peer_list Peers which are part of the trail from
1164  *                        querying_peer to Finger, NOT including them.
1165  * @param is_predecessor Is @a Finger predecessor to @a querying_peer ?
1166  * @param ultimate_destination_finger_value Value to which @a finger is the closest
1167  *                                          peer.
1168  * @param trail_id Unique identifier of the trail.
1169  */
1170 void
1171 GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity querying_peer,
1172                                         struct GNUNET_PeerIdentity finger,
1173                                         struct FriendInfo *target_friend,
1174                                         unsigned int trail_length,
1175                                         const struct GNUNET_PeerIdentity *trail_peer_list,
1176                                         unsigned int is_predecessor,
1177                                         uint64_t ultimate_destination_finger_value,
1178                                         struct GNUNET_HashCode trail_id)
1179 {
1180   struct P2PPendingMessage *pending;
1181   struct PeerTrailSetupResultMessage *tsrm;
1182   struct GNUNET_PeerIdentity *peer_list;
1183   size_t msize;
1184
1185   msize = sizeof (struct PeerTrailSetupResultMessage) +
1186           (trail_length * sizeof (struct GNUNET_PeerIdentity));
1187
1188   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1189   {
1190     GNUNET_break (0);
1191     return;
1192   }
1193
1194   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1195   {
1196     GNUNET_STATISTICS_update (GDS_stats,
1197                               gettext_noop ("# P2P messages dropped due to full queue"),
1198                               1, GNUNET_NO);
1199   }
1200
1201   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1202   pending->importance = 0;
1203   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1204   tsrm = (struct PeerTrailSetupResultMessage *) &pending[1];
1205   pending->msg = &tsrm->header;
1206   tsrm->header.size = htons (msize);
1207   tsrm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_RESULT);
1208   tsrm->querying_peer = querying_peer;
1209   tsrm->finger_identity = finger;
1210   tsrm->is_predecessor = htonl (is_predecessor);
1211   tsrm->trail_id = trail_id;
1212   tsrm->ulitmate_destination_finger_value =
1213           GNUNET_htonll (ultimate_destination_finger_value);
1214   peer_list = (struct GNUNET_PeerIdentity *) &tsrm[1];
1215   memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
1216
1217   /* Send the message to chosen friend. */
1218   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1219   target_friend->pending_count++;
1220   process_friend_queue (target_friend);
1221 }
1222
1223 /**
1224  * Send notify successor confirmation message.
1225  * @param trail_id Unique Identifier of the trail.
1226  * @param trail_direction Destination to Source.
1227  * @param target_friend Friend to get this message next.
1228  */
1229 void
1230 GDS_NEIGHBOURS_send_notify_succcessor_confirmation (struct GNUNET_HashCode trail_id,
1231                                                     unsigned int trail_direction,
1232                                                      struct FriendInfo *target_friend)
1233 {
1234   struct PeerNotifyConfirmationMessage *ncm;
1235   struct P2PPendingMessage *pending;
1236   size_t msize;
1237
1238   msize = sizeof (struct PeerNotifyConfirmationMessage);
1239   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1240   {
1241     GNUNET_break (0);
1242     return;
1243   }
1244
1245   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1246   {
1247     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1248                                 1, GNUNET_NO);
1249   }
1250
1251   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1252   pending->importance = 0;    /* FIXME */
1253   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1254   ncm = (struct PeerNotifyConfirmationMessage *) &pending[1];
1255   pending->msg = &ncm->header;
1256   ncm->header.size = htons (msize);
1257   ncm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_NOTIFY_SUCCESSOR_CONFIRMATION);
1258   ncm->trail_id = trail_id;
1259   ncm->trail_direction = htonl (trail_direction);
1260
1261   /* Send the message to chosen friend. */
1262   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1263   target_friend->pending_count++;
1264   process_friend_queue (target_friend);
1265 }
1266
1267
1268 /**
1269  * Send trail rejection message to target friend
1270  * @param source_peer Peer which is trying to setup the trail.
1271  * @param ultimate_destination_finger_value Peer closest to this value will be
1272  *                                          @a source_peer's finger
1273  * @param congested_peer Peer which sent this message as it is congested.
1274  * @param is_predecessor Is source_peer looking for trail to a predecessor or not.
1275  * @param trail_peer_list Trails seen so far in trail setup before getting rejected
1276  *                        by congested_peer. This does NOT include @a source_peer
1277  *                        and congested_peer.
1278  * @param trail_length Total number of peers in trail_peer_list, NOT including
1279  *                     @a source_peer and @a congested_peer
1280  * @param trail_id Unique identifier of this trail.
1281  * @param congestion_timeout Duration given by congested peer as an estimate of
1282  *                           how long it may remain congested.
1283  */
1284 void
1285 GDS_NEIGHBOURS_send_trail_rejection (struct GNUNET_PeerIdentity source_peer,
1286                                      uint64_t ultimate_destination_finger_value,
1287                                      struct GNUNET_PeerIdentity congested_peer,
1288                                      unsigned int is_predecessor,
1289                                      const struct GNUNET_PeerIdentity *trail_peer_list,
1290                                      unsigned int trail_length,
1291                                      struct GNUNET_HashCode trail_id,
1292                                      struct FriendInfo *target_friend,
1293                                      const struct GNUNET_TIME_Relative congestion_timeout)
1294 {
1295   struct PeerTrailRejectionMessage *trm;
1296   struct P2PPendingMessage *pending;
1297   struct GNUNET_PeerIdentity *peer_list;
1298   size_t msize;
1299
1300   msize = sizeof (struct PeerTrailRejectionMessage) +
1301           (trail_length * sizeof (struct GNUNET_PeerIdentity));
1302
1303   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1304   {
1305     GNUNET_break (0);
1306     return;
1307   }
1308
1309   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1310   {
1311     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1312                                 1, GNUNET_NO);
1313   }
1314
1315   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1316   pending->importance = 0;
1317   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1318   trm = (struct PeerTrailRejectionMessage *)&pending[1];
1319   pending->msg = &trm->header;
1320   trm->header.size = htons (msize);
1321   trm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_REJECTION);
1322   trm->source_peer = source_peer;
1323   trm->congested_peer = congested_peer;
1324   trm->congestion_time = congestion_timeout;
1325   trm->is_predecessor = htonl (is_predecessor);
1326   trm->trail_id = trail_id;
1327   trm->ultimate_destination_finger_value =
1328           GNUNET_htonll (ultimate_destination_finger_value);
1329
1330   peer_list = (struct GNUNET_PeerIdentity *) &trm[1];
1331   if (trail_length > 0)
1332   {
1333     memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
1334   }
1335
1336   /* Send the message to chosen friend. */
1337   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1338   target_friend->pending_count++;
1339   process_friend_queue (target_friend);
1340 }
1341
1342
1343 /**
1344  * Construct a verify successor message and forward it to target_friend.
1345  * @param source_peer Peer which wants to verify its successor.
1346  * @param successor Peer which is @a source_peer's current successor.
1347  * @param trail_id Unique Identifier of trail from @a source_peer to @a successor,
1348  *                 NOT including them.
1349  * @param trail List of peers which are part of trail to reach from @a source_peer
1350  *              to @a successor, NOT including them.
1351  * @param trail_length Total number of peers in @a trail.
1352  * @param target_friend Next friend to get this message.
1353  */
1354 void
1355 GDS_NEIGHBOURS_send_verify_successor_message (struct GNUNET_PeerIdentity source_peer,
1356                                               struct GNUNET_PeerIdentity successor,
1357                                               struct GNUNET_HashCode trail_id,
1358                                               struct GNUNET_PeerIdentity *trail,
1359                                               unsigned int trail_length,
1360                                               struct FriendInfo *target_friend)
1361 {
1362   struct PeerVerifySuccessorMessage *vsm;
1363   struct P2PPendingMessage *pending;
1364   struct GNUNET_PeerIdentity *peer_list;
1365   size_t msize;
1366
1367   msize = sizeof (struct PeerVerifySuccessorMessage) +
1368          (trail_length * sizeof (struct GNUNET_PeerIdentity));
1369
1370   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1371   {
1372     GNUNET_break (0);
1373     return;
1374   }
1375
1376   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1377   {
1378     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1379                                 1, GNUNET_NO);
1380   }
1381
1382   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1383   pending->importance = 0;    /* FIXME */
1384   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1385   vsm = (struct PeerVerifySuccessorMessage *) &pending[1];
1386   pending->msg = &vsm->header;
1387   vsm->header.size = htons (msize);
1388   vsm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR);
1389   vsm->source_peer = source_peer;
1390   vsm->successor = successor;
1391   vsm->trail_id = trail_id;
1392   peer_list = (struct GNUNET_PeerIdentity *) &vsm[1];
1393   memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
1394
1395   /* Send the message to chosen friend. */
1396   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1397   target_friend->pending_count++;
1398   process_friend_queue (target_friend);
1399 }
1400
1401
1402 /**
1403  * FIXME: In every function we pass target friend except for this one.
1404  * so, either change everything or this one. also, should se just store
1405  * the pointer to friend in routing table rather than gnunet_peeridentity.
1406  * if yes then we should keep friend info in.h  andmake lot of changes.
1407  * Construct a trail teardown message and forward it to target friend.
1408  *
1409  * @param trail_id Unique identifier of the trail.
1410  * @param trail_direction Direction of trail.
1411  * @param target_friend Friend to get this message.
1412  */
1413 void
1414 GDS_NEIGHBOURS_send_trail_teardown (const struct GNUNET_HashCode *trail_id,
1415                                     unsigned int trail_direction,
1416                                     const struct GNUNET_PeerIdentity *peer)
1417 {
1418   struct PeerTrailTearDownMessage *ttdm;
1419   struct P2PPendingMessage *pending;
1420   struct FriendInfo *target_friend;
1421   size_t msize;
1422
1423   msize = sizeof (struct PeerTrailTearDownMessage);
1424   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1425   {
1426     GNUNET_break (0);
1427     return;
1428   }
1429
1430   if (NULL == (target_friend =
1431                GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)))
1432   {
1433     /* FIXME: In what case friend can be null. ?*/
1434     GNUNET_break (0);
1435     return;
1436   }
1437
1438   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1439   {
1440     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1441                                 1, GNUNET_NO);
1442   }
1443
1444   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1445   pending->importance = 0;    /* FIXME */
1446   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1447   ttdm = (struct PeerTrailTearDownMessage *) &pending[1];
1448   pending->msg = &ttdm->header;
1449   ttdm->header.size = htons (msize);
1450   ttdm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_TEARDOWN);
1451   ttdm->trail_id = *trail_id;
1452   ttdm->trail_direction = htonl (trail_direction);
1453
1454   /* Send the message to chosen friend. */
1455   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1456   target_friend->pending_count++;
1457   process_friend_queue (target_friend);
1458 }
1459
1460
1461 /**
1462  * Construct a verify successor result message and send it to target_friend
1463  * @param querying_peer Peer which sent the verify successor message.
1464  * @param source_successor Current_successor of @a querying_peer.
1465  * @param current_predecessor Current predecessor of @a successor. Could be same
1466  *                            or different from @a querying_peer.
1467  * @param trail_id Unique identifier of the trail from @a querying_peer to
1468  *                 @a successor, NOT including them.
1469  * @param trail List of peers which are part of trail from @a querying_peer to
1470  *                 @a successor, NOT including them.
1471  * @param trail_length Total number of peers in @a trail
1472  * @param trail_direction Direction in which we are sending the message. In this
1473  *                        case we are sending result from @a successor to @a querying_peer.
1474  * @param target_friend Next friend to get this message.
1475  */
1476 void
1477 GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity querying_peer,
1478                                              struct GNUNET_PeerIdentity current_successor,
1479                                              struct GNUNET_PeerIdentity probable_successor,
1480                                              struct GNUNET_HashCode trail_id,
1481                                              const struct GNUNET_PeerIdentity *trail,
1482                                              unsigned int trail_length,
1483                                              enum GDS_ROUTING_trail_direction trail_direction,
1484                                              struct FriendInfo *target_friend)
1485 {
1486   struct PeerVerifySuccessorResultMessage *vsmr;
1487   struct P2PPendingMessage *pending;
1488   struct GNUNET_PeerIdentity *peer_list;
1489   size_t msize;
1490
1491   msize = sizeof (struct PeerVerifySuccessorResultMessage) +
1492           (trail_length * sizeof(struct GNUNET_PeerIdentity));
1493
1494   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1495   {
1496     GNUNET_break (0);
1497     return;
1498   }
1499
1500   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1501   {
1502     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1503                                 1, GNUNET_NO);
1504   }
1505
1506   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1507   pending->importance = 0;    /* FIXME */
1508   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1509   vsmr = (struct PeerVerifySuccessorResultMessage *) &pending[1];
1510   pending->msg = &vsmr->header;
1511   vsmr->header.size = htons (msize);
1512   vsmr->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR_RESULT);
1513   vsmr->querying_peer = querying_peer;
1514   vsmr->current_successor = current_successor;
1515   vsmr->probable_successor = probable_successor;
1516   vsmr->trail_direction = htonl (trail_direction);
1517   vsmr->trail_id = trail_id;
1518   peer_list = (struct GNUNET_PeerIdentity *) &vsmr[1];
1519   memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
1520
1521    /* Send the message to chosen friend. */
1522   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1523   target_friend->pending_count++;
1524   process_friend_queue (target_friend);
1525 }
1526
1527
1528 /**
1529  * Construct a notify new successor message and send it to target_friend
1530  * @param source_peer Peer which wants to notify to its new successor that it
1531  *                    could be its predecessor.
1532  * @param successor New successor of @a source_peer
1533  * @param successor_trail List of peers in Trail to reach from
1534  *                            @a source_peer to @a new_successor, NOT including
1535  *                            the endpoints.
1536  * @param successor_trail_length Total number of peers in @a new_successor_trail.
1537  * @param successor_trail_id Unique identifier of @a new_successor_trail.
1538  * @param target_friend Next friend to get this message.
1539  */
1540 void
1541 GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity source_peer,
1542                                           struct GNUNET_PeerIdentity successor,
1543                                           const struct GNUNET_PeerIdentity *successor_trail,
1544                                           unsigned int successor_trail_length,
1545                                           struct GNUNET_HashCode succesor_trail_id,
1546                                           struct FriendInfo *target_friend)
1547 {
1548   struct PeerNotifyNewSuccessorMessage *nsm;
1549   struct P2PPendingMessage *pending;
1550   struct GNUNET_PeerIdentity *peer_list;
1551   size_t msize;
1552
1553   msize = sizeof (struct PeerNotifyNewSuccessorMessage) +
1554           (successor_trail_length * sizeof(struct GNUNET_PeerIdentity));
1555
1556   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1557   {
1558     GNUNET_break (0);
1559     return;
1560   }
1561
1562   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1563   {
1564     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1565                                 1, GNUNET_NO);
1566   }
1567
1568   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1569   pending->importance = 0;    /* FIXME */
1570   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1571   nsm = (struct PeerNotifyNewSuccessorMessage *) &pending[1];
1572   pending->msg = &nsm->header;
1573   nsm->header.size = htons (msize);
1574   nsm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_NOTIFY_NEW_SUCCESSOR);
1575   nsm->new_successor = successor;
1576   nsm->source_peer = source_peer;
1577   nsm->trail_id = succesor_trail_id;
1578   peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
1579   memcpy (peer_list, successor_trail,
1580           successor_trail_length * sizeof (struct GNUNET_PeerIdentity));
1581
1582    /* Send the message to chosen friend. */
1583   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1584   target_friend->pending_count++;
1585   process_friend_queue (target_friend);
1586 }
1587
1588
1589 /**
1590  * Construct an add_trail message and send it to target_friend
1591  * @param source_peer Source of the trail.
1592  * @param destination_peer Destination of the trail.
1593  * @param trail_id Unique identifier of the trail from
1594  *                 @a source_peer to @a destination_peer, NOT including the endpoints.
1595  * @param trail List of peers in Trail from @a source_peer to @a destination_peer,
1596  *              NOT including the endpoints.
1597  * @param trail_length Total number of peers in @a trail.
1598  * @param target_friend Next friend to get this message.
1599  */
1600 void
1601 GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
1602                                struct GNUNET_PeerIdentity destination_peer,
1603                                struct GNUNET_HashCode trail_id,
1604                                const struct GNUNET_PeerIdentity *trail,
1605                                unsigned int trail_length,
1606                                struct FriendInfo *target_friend)
1607 {
1608   struct PeerAddTrailMessage *adm;
1609   struct GNUNET_PeerIdentity *peer_list;
1610   struct P2PPendingMessage *pending;
1611   size_t msize;
1612
1613   msize = sizeof (struct PeerAddTrailMessage) +
1614           (trail_length * sizeof(struct GNUNET_PeerIdentity));
1615
1616   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1617   {
1618     GNUNET_break (0);
1619     return;
1620   }
1621
1622   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
1623   {
1624     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1625                                 1, GNUNET_NO);
1626   }
1627
1628   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1629   pending->importance = 0;    /* FIXME */
1630   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
1631   adm = (struct PeerAddTrailMessage *) &pending[1];
1632   pending->msg = &adm->header;
1633   adm->header.size = htons (msize);
1634   adm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_ADD_TRAIL);
1635   adm->source_peer = source_peer;
1636   adm->destination_peer = destination_peer;
1637   adm->trail_id = trail_id;
1638   peer_list = (struct GNUNET_PeerIdentity *)&adm[1];
1639   memcpy (peer_list, trail, sizeof (struct GNUNET_PeerIdentity) * trail_length);
1640
1641   /* Send the message to chosen friend. */
1642   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
1643   target_friend->pending_count++;
1644   process_friend_queue (target_friend);
1645
1646 }
1647
1648
1649 /**
1650  * Search my location in trail. In case I am present more than once in the
1651  * trail (can happen during trail setup), then return my lowest index.
1652  * @param trail List of peers
1653  * @return my_index if found
1654  *         trail_length + 1 if an entry is present twice, It is an error.
1655  *         -1 if no entry found.
1656  */
1657 static int
1658 search_my_index (const struct GNUNET_PeerIdentity *trail,
1659                  int trail_length)
1660 {
1661   int i;
1662   int index_seen = trail_length + 1;
1663   int flag = 0;
1664
1665   for (i = 0; i < trail_length; i++)
1666   {
1667     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &trail[i]))
1668     {
1669       flag = 1;
1670       if(index_seen == (trail_length + 1))
1671         index_seen = i;
1672       else
1673       {
1674         DEBUG("Entry is present twice in trail. Its not allowed\n");
1675       }
1676       break;
1677     }
1678   }
1679
1680   if (1 == flag)
1681     return index_seen;
1682   else
1683     return -1;
1684 }
1685
1686
1687 /**
1688  * Check if the friend is congested or have reached maximum number of trails
1689  * it can be part of of.
1690  * @param friend Friend to be checked.
1691  * @return #GNUNET_NO if friend is not congested or have not crossed threshold.
1692  *         #GNUNET_YES if friend is either congested or have crossed threshold
1693  */
1694 static int
1695 is_friend_congested (struct FriendInfo *friend)
1696 {
1697   if (( friend->trails_count < TRAILS_THROUGH_FRIEND_THRESHOLD) &&
1698       ((0 == GNUNET_TIME_absolute_get_remaining
1699              (friend->congestion_timestamp).rel_value_us)))
1700     return GNUNET_NO;
1701   else
1702     return GNUNET_YES;
1703 }
1704
1705
1706 /**
1707  * Select closest finger to value.
1708  * @param peer1 First peer
1709  * @param peer2 Second peer
1710  * @param value Value to be compare
1711  * @return Closest peer
1712  */
1713 static struct GNUNET_PeerIdentity
1714 select_closest_finger (const struct GNUNET_PeerIdentity *peer1,
1715                        const struct GNUNET_PeerIdentity *peer2,
1716                        uint64_t value)
1717 {
1718   uint64_t peer1_value;
1719   uint64_t peer2_value;
1720
1721   memcpy (&peer1_value, peer1, sizeof (uint64_t));
1722   memcpy (&peer2_value, peer2, sizeof (uint64_t));
1723   peer1_value = GNUNET_ntohll (peer1_value);
1724   peer2_value = GNUNET_ntohll (peer2_value);
1725
1726   if (peer1_value == value)
1727   {
1728     return *peer1;
1729   }
1730
1731   if (peer2_value == value)
1732   {
1733     return *peer2;
1734   }
1735
1736   if (value < peer1_value && peer1_value < peer2_value)
1737   {
1738     return *peer1;
1739   }
1740   else if (value < peer2_value && peer2_value < peer1_value)
1741   {
1742     return *peer2;
1743   }
1744   else if (peer1_value < value && value < peer2_value)
1745   {
1746     return *peer2;
1747   }
1748   else if (peer2_value < value && value < peer1_value)
1749   {
1750     return *peer1;
1751   }
1752   else if (peer1_value < peer2_value && peer2_value < value)
1753   {
1754     return *peer1;
1755   }
1756   else  // if (peer2_value < peer1_value && peer1_value < value)
1757   {
1758     return *peer2;
1759   }
1760 }
1761
1762
1763 /**
1764  * Select closest predecessor to value.
1765  * @param peer1 First peer
1766  * @param peer2 Second peer
1767  * @param value Value to be compare
1768  * @return Peer which precedes value in the network.
1769  */
1770 static struct GNUNET_PeerIdentity
1771 select_closest_predecessor (const struct GNUNET_PeerIdentity *peer1,
1772                             const struct GNUNET_PeerIdentity *peer2,
1773                             uint64_t value)
1774 {
1775   uint64_t peer1_value;
1776   uint64_t peer2_value;
1777
1778   memcpy (&peer1_value, peer1, sizeof (uint64_t));
1779   memcpy (&peer2_value, peer2, sizeof (uint64_t));
1780   peer1_value = GNUNET_ntohll (peer1_value);
1781   peer2_value = GNUNET_ntohll (peer2_value);
1782
1783    if (peer1_value == value)
1784   {
1785     return *peer1;
1786   }
1787
1788   if (peer2_value == value)
1789   {
1790     return *peer2;
1791   }
1792
1793   if (value < peer1_value && peer1_value < peer2_value)
1794   {
1795     return *peer2;
1796   }
1797   else if (value < peer2_value && peer2_value < peer1_value)
1798   {
1799     return *peer1;
1800   }
1801   else if (peer1_value < value && value < peer2_value)
1802   {
1803     return *peer1;
1804   }
1805   else if (peer2_value < value && value < peer1_value)
1806   {
1807     return *peer2;
1808   }
1809   else if (peer1_value < peer2_value && peer2_value < value)
1810   {
1811     return *peer2;
1812   }
1813   else  // if (peer2_value < peer1_value && peer1_value < value)
1814   {
1815     return *peer1;
1816   }
1817 }
1818
1819 #if 0
1820 /**
1821  *
1822  *
1823  */
1824 void
1825 test_print_trail (struct GNUNET_PeerIdentity *trail,
1826                   unsigned int trail_length)
1827 {
1828   struct GNUNET_PeerIdentity print_peer;
1829   int i;
1830
1831   FPRINTF (stderr,_("\nSUPU %s, %s, %d,trail_length = %d"),
1832   __FILE__, __func__,__LINE__,trail_length);
1833   for (i =0 ; i< trail_length; i++)
1834   {
1835     print_peer = trail[i];
1836     FPRINTF (stderr,_("\nSUPU %s, %s, %d,trail[%d]=%s"),
1837             __FILE__, __func__,__LINE__,i,GNUNET_i2s(&print_peer));
1838   }
1839 }
1840 #endif
1841
1842 #if 0
1843 /**
1844  * This is a test function to print all the entries of friend table.
1845  */
1846 static void
1847 test_friend_peermap_print ()
1848 {
1849   struct FriendInfo *friend;
1850   struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
1851   struct GNUNET_PeerIdentity print_peer;
1852   struct GNUNET_PeerIdentity key_ret;
1853   int i;
1854
1855   print_peer = my_identity;
1856   FPRINTF (stderr,_("\nSUPU************  FRIEND_PEERMAP of %s"),GNUNET_i2s(&print_peer));
1857   friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
1858
1859   for (i = 0; i < GNUNET_CONTAINER_multipeermap_size (friend_peermap); i++)
1860   {
1861     if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (friend_iter,
1862                                                                   &key_ret,
1863                                                                   (const void **)&friend))
1864     {
1865       memcpy (&print_peer, &key_ret, sizeof (struct GNUNET_PeerIdentity));
1866       FPRINTF (stderr,_("\nSUPU %s, %s, %d, friend = %s, friend->trails_count = %d"),
1867               __FILE__, __func__,__LINE__, GNUNET_i2s(&print_peer), friend->trails_count);
1868     }
1869   }
1870 }
1871 #endif
1872
1873 #if 0
1874 /**
1875  * This is a test function, to print all the entries of finger table.
1876  */
1877 static void
1878 test_finger_table_print()
1879 {
1880   struct FingerInfo *finger;
1881   struct GNUNET_PeerIdentity print_peer;
1882   //struct Trail *trail;
1883   int i;
1884   //int j;
1885   //int k;
1886   print_peer = my_identity;
1887   FPRINTF (stderr,_("\nSUPU************  FINGER_TABLE of %s"),GNUNET_i2s(&print_peer));
1888   for (i = 0; i < MAX_FINGERS; i++)
1889   {
1890     finger = &finger_table[i];
1891
1892     if (GNUNET_NO == finger->is_present)
1893       continue;
1894
1895     print_peer = finger->finger_identity;
1896     FPRINTF (stderr,_("\nSUPU %s, %s, %d, finger_table[%d] = %s, trails_count = %d"),
1897             __FILE__, __func__,__LINE__,i,GNUNET_i2s (&print_peer), finger->trails_count);
1898
1899 #if 0
1900     for (j = 0; j < finger->trails_count; j++)
1901     {
1902       trail = &finger->trail_list[j];
1903       FPRINTF (stderr,_("\nSUPU %s, %s, %d, trail_id[%d]=%s"),__FILE__, __func__,__LINE__,j, GNUNET_h2s(&trail->trail_id));
1904       struct Trail_Element *element;
1905       element = trail->trail_head;
1906       for (k = 0; k < trail->trail_length; k++)
1907       {
1908         print_peer = element->peer;
1909         FPRINTF (stderr,_("\nSUPU %s, %s, %d,trail[%d] = %s "),__FILE__, __func__,__LINE__,k, GNUNET_i2s(&print_peer));
1910         element = element->next;
1911       }
1912     }
1913     #endif
1914   }
1915 }
1916 #endif
1917
1918 /**
1919  * Select the closest peer among two peers (which should not be same)
1920  * with respect to value and finger_table_index
1921  * NOTE: peer1 != peer2
1922  * @param peer1 First peer
1923  * @param peer2 Second peer
1924  * @param value Value relative to which we find the closest
1925  * @param is_predecessor Is value a predecessor or any other finger.
1926  * @return Closest peer among two peers.
1927  */
1928 static struct GNUNET_PeerIdentity
1929 select_closest_peer (const struct GNUNET_PeerIdentity *peer1,
1930                      const struct GNUNET_PeerIdentity *peer2,
1931                      uint64_t value,
1932                      unsigned int is_predecessor)
1933 {
1934   /* This check is here to ensure that calling function never sends
1935       same peer value in peer1 and peer2. Remove it later. */
1936   GNUNET_assert(0 != GNUNET_CRYPTO_cmp_peer_identity (peer1, peer2));
1937   if (1 == is_predecessor)
1938     return select_closest_predecessor (peer1, peer2, value);
1939
1940   // TODO: Change name to something like select_closest_successor!!
1941   return select_closest_finger (peer1, peer2, value);
1942 }
1943
1944
1945 /**
1946  * Iterate over the list of all the trails of a finger. In case the first
1947  * friend to reach the finger has reached trail threshold or is congested,
1948  * then don't select it. In case there multiple available good trails to reach
1949  * to Finger, choose the one with shortest trail length.
1950  * Note: We use length as parameter. But we can use any other suitable parameter
1951  * also.
1952  * @param finger Finger Finger whose trail we have to select.
1953  * @return Trail Selected Trail.
1954  */
1955 static struct Trail *
1956 select_finger_trail (struct FingerInfo *finger)
1957 {
1958   struct FriendInfo *friend;
1959   struct Trail *current_finger_trail;
1960   struct Trail *best_trail = NULL;
1961   unsigned int i;
1962
1963   GNUNET_assert (finger->trails_count > 0);
1964   for (i = 0; i < finger->trails_count; i++)
1965   {
1966     current_finger_trail = &finger->trail_list[i];
1967
1968     /* No trail stored at this index. */
1969     if (GNUNET_NO == current_finger_trail->is_present)
1970       continue;
1971
1972     GNUNET_assert (NULL !=
1973                   (friend =
1974                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
1975                                                       &current_finger_trail->trail_head->peer)));
1976
1977     /* First friend to reach trail is not free. */
1978     if (GNUNET_YES == is_friend_congested (friend))
1979       continue;
1980
1981     if (NULL == best_trail ||
1982         best_trail->trail_length > current_finger_trail->trail_length)
1983     {
1984       best_trail = current_finger_trail;
1985     }
1986   }
1987
1988   return best_trail;
1989 }
1990
1991
1992 /**
1993  * Compare FINGER entry with current successor. If finger's first friend of all
1994  * its trail is not congested and  has not crossed trail threshold, then check
1995  * if finger peer identity is closer to final_destination_finger_value than
1996  * current_successor. If yes then update current_successor.
1997  * @param current_successor[in/out]
1998  * @return
1999  */
2000 static void
2001 compare_finger_and_current_closest_peer (struct Closest_Peer *current_closest_peer)
2002 {
2003   struct FingerInfo *finger;
2004   struct GNUNET_PeerIdentity closest_peer;
2005   struct Trail *finger_trail;
2006   int i;
2007
2008   /* Iterate over finger table. */
2009   for (i = 0; i < MAX_FINGERS; i++)
2010   {
2011     finger = &finger_table[i];
2012
2013     if (GNUNET_NO == finger->is_present)
2014       continue;
2015
2016     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
2017                                               &current_closest_peer->best_known_destination))
2018       continue;
2019
2020     /* If I am my own finger, then ignore this finger. */
2021     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
2022                                               &my_identity))
2023       continue;
2024
2025    /* If finger is a friend, we have already checked it in previous function. */
2026     if (NULL != (GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2027                                                     &finger->finger_identity)))
2028     {
2029       continue;
2030     }
2031
2032     closest_peer = select_closest_peer (&finger->finger_identity,
2033                                         &current_closest_peer->best_known_destination,
2034                                         current_closest_peer->destination_finger_value,
2035                                         current_closest_peer->is_predecessor);
2036
2037     if (0 == GNUNET_CRYPTO_cmp_peer_identity(&finger->finger_identity, &closest_peer))
2038     {
2039       /* Choose one of the trail to reach to finger. */
2040       finger_trail = select_finger_trail (finger);
2041
2042       /* In case no trail found, ignore this finger. */
2043       if (NULL == finger_trail)
2044         continue;
2045
2046       current_closest_peer->best_known_destination = closest_peer;
2047       current_closest_peer->next_hop = finger_trail->trail_head->peer;
2048       current_closest_peer->trail_id = finger_trail->trail_id;
2049       current_closest_peer->finger_table_index = i;
2050     }
2051     continue;
2052   }
2053 }
2054
2055
2056 /**
2057  * Compare friend entry with current successor.
2058  * If friend identity and current_successor is same, then do nothing.
2059  * If friend is not congested and has not crossed trail threshold, then check
2060  * if friend peer identity is closer to final_destination_finger_value than
2061  * current_successor. If yes then update current_successor.
2062  * @param cls closure
2063  * @param key current public key
2064  * @param value struct Closest_Peer
2065  * @return #GNUNET_YES if we should continue to iterate,
2066  *         #GNUNET_NO if not.
2067  */
2068 static int
2069 compare_friend_and_current_closest_peer (void *cls,
2070                                          const struct GNUNET_PeerIdentity *key,
2071                                          void *value)
2072 {
2073   struct FriendInfo *friend = value;
2074   struct Closest_Peer *current_closest_peer = cls;
2075   struct GNUNET_PeerIdentity closest_peer;
2076
2077   /* Friend is either congested or has crossed threshold. */
2078   if (GNUNET_YES == is_friend_congested (friend))
2079     return GNUNET_YES;
2080
2081   /* If current_closest_peer and friend identity are same, then do nothing.*/
2082   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&friend->id,
2083                                             &current_closest_peer->best_known_destination))
2084   {
2085     GNUNET_break (0);
2086     return GNUNET_YES;
2087   }
2088
2089   closest_peer = select_closest_peer (&friend->id,
2090                                       &current_closest_peer->best_known_destination,
2091                                       current_closest_peer->destination_finger_value,
2092                                       current_closest_peer->is_predecessor);
2093
2094   /* Is friend the closest successor? */
2095   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&friend->id, &closest_peer))
2096   {
2097     current_closest_peer->best_known_destination = friend->id;
2098     current_closest_peer->next_hop = friend->id;
2099   }
2100
2101   return GNUNET_YES;
2102 }
2103
2104
2105 /**
2106  * Initialize current_successor to my_identity.
2107  * @param my_identity My peer identity
2108  * @return Updated closest_peer
2109  */
2110 static struct Closest_Peer
2111 init_closest_peer (struct GNUNET_PeerIdentity my_identity,
2112                         uint64_t destination_finger_value,
2113                         unsigned int is_predecessor)
2114 {
2115   struct Closest_Peer current_closest_peer;
2116
2117   memset (&current_closest_peer.trail_id, 0, sizeof(struct GNUNET_HashCode));
2118   current_closest_peer.destination_finger_value = destination_finger_value;
2119   current_closest_peer.is_predecessor = is_predecessor;
2120   current_closest_peer.next_hop = my_identity;
2121   current_closest_peer.best_known_destination = my_identity;
2122   current_closest_peer.finger_table_index = 65; //65 is a for non valid finger table index.
2123   return current_closest_peer;
2124 }
2125
2126
2127 /**
2128  * Find locally best known peer, among your own identity, friend and finger list,
2129  * which is closest to given destination_finger_value.
2130  *
2131  * NOTE: In case a friend is also a finger, then it is always chosen as friend
2132  * not a finger.
2133  * @param destination_finger_value Peer closest to this value will be the next destination.
2134  * @param is_predecessor Are we looking for predecessor or finger?
2135  * @return Closest_Peer that contains all the relevant field to reach to
2136  *                      @a destination_finger_value
2137  */
2138 static struct Closest_Peer
2139 find_local_best_known_next_hop (uint64_t destination_finger_value,
2140                                 unsigned int is_predecessor)
2141 {
2142   struct Closest_Peer current_closest_peer;
2143
2144    /* Initialize current_successor to my_identity. */
2145   current_closest_peer = init_closest_peer (my_identity,
2146                                             destination_finger_value,
2147                                             is_predecessor);
2148
2149   /* Compare each friend entry with current_successor and update current_successor
2150    * with friend if its closest. */
2151   GNUNET_assert
2152           (GNUNET_SYSERR !=
2153            GNUNET_CONTAINER_multipeermap_iterate (friend_peermap,
2154                                                   &compare_friend_and_current_closest_peer,
2155                                                   &current_closest_peer));
2156
2157   /* Compare each finger entry with current_successor and update current_successor
2158    * with finger if its closest. */
2159   compare_finger_and_current_closest_peer (&current_closest_peer);
2160   return current_closest_peer;
2161 }
2162
2163
2164 /**
2165  * Construct a Put message and send it to target_peer.
2166  * @param key Key for the content
2167  * @param block_type Type of the block
2168  * @param options Routing options
2169  * @param desired_replication_level Desired replication count
2170  * @param best_known_dest Peer to which this message should reach eventually,
2171  *                        as it is best known destination to me.
2172  * @param intermediate_trail_id Trail id in case
2173  * @param target_peer Peer to which this message will be forwarded.
2174  * @param hop_count Number of hops traversed so far.
2175  * @param put_path_length Total number of peers in @a put_path
2176  * @param put_path Number of peers traversed so far
2177  * @param expiration_time When does the content expire
2178  * @param data Content to store
2179  * @param data_size Size of content @a data in bytes
2180  */
2181 void
2182 GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
2183                          enum GNUNET_BLOCK_Type block_type,
2184                          enum GNUNET_DHT_RouteOption options,
2185                          uint32_t desired_replication_level,
2186                          struct GNUNET_PeerIdentity best_known_dest,
2187                          struct GNUNET_HashCode intermediate_trail_id,
2188                          struct GNUNET_PeerIdentity *target_peer,
2189                          uint32_t hop_count,
2190                          uint32_t put_path_length,
2191                          struct GNUNET_PeerIdentity *put_path,
2192                          struct GNUNET_TIME_Absolute expiration_time,
2193                          const void *data, size_t data_size)
2194 {
2195   struct PeerPutMessage *ppm;
2196   struct P2PPendingMessage *pending;
2197   struct FriendInfo *target_friend;
2198   struct GNUNET_PeerIdentity *pp;
2199   size_t msize;
2200
2201   msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
2202           sizeof (struct PeerPutMessage);
2203   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
2204   {
2205     put_path_length = 0;
2206     msize = data_size + sizeof (struct PeerPutMessage);
2207   }
2208
2209   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
2210   {
2211     DEBUG("msize = %lu\n",msize);
2212     GNUNET_break (0);
2213     return;
2214   }
2215
2216   GNUNET_assert (NULL !=
2217                  (target_friend =
2218                   GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer)));
2219   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2220   pending->timeout = expiration_time;
2221   ppm = (struct PeerPutMessage *) &pending[1];
2222   pending->msg = &ppm->header;
2223   ppm->header.size = htons (msize);
2224   ppm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_PUT);
2225   ppm->options = htonl (options);
2226   ppm->block_type = htonl (block_type);
2227   ppm->hop_count = htonl (hop_count + 1);
2228   ppm->desired_replication_level = htonl (desired_replication_level);
2229   ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
2230   ppm->best_known_destination = best_known_dest;
2231   ppm->intermediate_trail_id = intermediate_trail_id;
2232   ppm->key = *key;
2233   pp = (struct GNUNET_PeerIdentity *) &ppm[1];
2234   ppm->put_path_length = htonl (put_path_length);
2235   if(put_path_length > 0)
2236   {
2237     memcpy (pp, put_path,
2238             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
2239   }
2240   memcpy (&pp[put_path_length], data, data_size);
2241   GNUNET_assert (NULL != target_friend);
2242   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2243   target_friend->pending_count++;
2244   process_friend_queue (target_friend);
2245 }
2246
2247
2248 /**
2249  * Handle the put request from the client.
2250  * @param key Key for the content
2251  * @param block_type Type of the block
2252  * @param options Routing options
2253  * @param desired_replication_level Desired replication count
2254  * @param expiration_time When does the content expire
2255  * @param data Content to store
2256  * @param data_size Size of content @a data in bytes
2257  */
2258 void
2259 GDS_NEIGHBOURS_handle_put (const struct GNUNET_HashCode *key,
2260                            enum GNUNET_BLOCK_Type block_type,
2261                            enum GNUNET_DHT_RouteOption options,
2262                            uint32_t desired_replication_level,
2263                            struct GNUNET_TIME_Absolute expiration_time,
2264                            const void *data, size_t data_size)
2265 {
2266   struct GNUNET_PeerIdentity best_known_dest;
2267   struct GNUNET_HashCode intermediate_trail_id;
2268   struct GNUNET_PeerIdentity next_hop;
2269   uint64_t key_value;
2270   struct Closest_Peer successor;
2271
2272   memcpy (&key_value, key, sizeof (uint64_t));
2273   key_value = GNUNET_ntohll (key_value);
2274   successor = find_local_best_known_next_hop (key_value,
2275                                               GDS_FINGER_TYPE_NON_PREDECESSOR);
2276   best_known_dest = successor.best_known_destination;
2277   next_hop = successor.next_hop;
2278   intermediate_trail_id = successor.trail_id;
2279
2280   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&best_known_dest, &my_identity))
2281   {
2282     DEBUG("\n PUT_REQUEST_SUCCESSFUL for key = %s",GNUNET_h2s(key));
2283     /* I am the destination. */
2284     GDS_DATACACHE_handle_put (expiration_time, key, 0, NULL,
2285                               block_type,data_size,data);
2286     GDS_CLIENTS_process_put (options, block_type, 0,
2287                              ntohl (desired_replication_level),
2288                              1, &my_identity, expiration_time, //FIXME: GNUNETnthoh something on expiration time.
2289                              key, data, data_size);
2290     return;
2291   }
2292   /* In case we are sending the request to  a finger, then send across all of its
2293    trail.*/
2294 #if ENABLE_MALICIOUS
2295   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&successor.best_known_destination,
2296                                             &successor.next_hop))
2297   {
2298     struct FingerInfo *next_hop_finger;
2299     unsigned int i;
2300
2301     next_hop_finger = &finger_table[successor.finger_table_index];
2302     for (i = 0; i < next_hop_finger->trails_count; i++)
2303     {
2304       if (GNUNET_YES == next_hop_finger->trail_list[i].is_present)
2305       {
2306         if(0 == next_hop_finger->trail_list[i].trail_length)
2307         {
2308            GDS_NEIGHBOURS_send_put (key, block_type, options, desired_replication_level,
2309                                     best_known_dest, intermediate_trail_id, &next_hop,
2310                                     0, 1, &my_identity, expiration_time,
2311                                     data, data_size);
2312            return;
2313         }
2314         next_hop = next_hop_finger->trail_list[i].trail_head->peer;
2315         GDS_NEIGHBOURS_send_put (key, block_type, options, desired_replication_level,
2316                                  best_known_dest,
2317                                  next_hop_finger->trail_list[i].trail_id,
2318                                  &next_hop, 0, 1, &my_identity,
2319                                  expiration_time,
2320                                  data, data_size);
2321        }
2322     }
2323     return;
2324   }
2325 #endif
2326  GDS_NEIGHBOURS_send_put (key, block_type, options, desired_replication_level,
2327                           best_known_dest, intermediate_trail_id, &next_hop,
2328                           0, 1, &my_identity, expiration_time,
2329                           data, data_size);
2330 }
2331
2332 /**
2333  * Construct a Get message and send it to target_peer.
2334  * @param key Key for the content
2335  * @param block_type Type of the block
2336  * @param options Routing options
2337  * @param desired_replication_level Desired replication count
2338  * @param best_known_dest Peer which should get this message. Same as target peer
2339  *                        if best_known_dest is a friend else its a finger.
2340  * @param intermediate_trail_id  Trail id to reach to @a best_known_dest
2341  *                              in case it is a finger else set to 0.
2342  * @param target_peer Peer to which this message will be forwarded.
2343  * @param hop_count Number of hops traversed so far.
2344  * @param data Content to store
2345  * @param data_size Size of content @a data in bytes
2346  * @param get_path_length Total number of peers in @a get_path
2347  * @param get_path Number of peers traversed so far
2348  */
2349 void
2350 GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
2351                          enum GNUNET_BLOCK_Type block_type,
2352                          enum GNUNET_DHT_RouteOption options,
2353                          uint32_t desired_replication_level,
2354                          struct GNUNET_PeerIdentity best_known_dest,
2355                          struct GNUNET_HashCode intermediate_trail_id,
2356                          struct GNUNET_PeerIdentity *target_peer,
2357                          uint32_t hop_count,
2358                          uint32_t get_path_length,
2359                          struct GNUNET_PeerIdentity *get_path)
2360 {
2361   struct PeerGetMessage *pgm;
2362   struct P2PPendingMessage *pending;
2363   struct FriendInfo *target_friend;
2364   struct GNUNET_PeerIdentity *gp;
2365   size_t msize;
2366
2367   msize = sizeof (struct PeerGetMessage) +
2368           (get_path_length * sizeof (struct GNUNET_PeerIdentity));
2369
2370   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
2371   {
2372     GNUNET_break (0);
2373     return;
2374   }
2375   GNUNET_assert (NULL !=
2376                  (target_friend =
2377                   GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer)));
2378
2379   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2380   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
2381   pending->importance = 0;    /* FIXME */
2382   pgm = (struct PeerGetMessage *) &pending[1];
2383   pending->msg = &pgm->header;
2384   pgm->header.size = htons (msize);
2385   pgm->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_GET);
2386   pgm->get_path_length = htonl (get_path_length);
2387   pgm->best_known_destination = best_known_dest;
2388   pgm->key = *key;
2389   pgm->intermediate_trail_id = intermediate_trail_id;
2390   pgm->hop_count = htonl (hop_count + 1);
2391   pgm->get_path_length = htonl (get_path_length);
2392   gp = (struct GNUNET_PeerIdentity *) &pgm[1];
2393   memcpy (gp, get_path,
2394           sizeof (struct GNUNET_PeerIdentity) * get_path_length);
2395   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2396   target_friend->pending_count++;
2397   process_friend_queue (target_friend);
2398 }
2399
2400
2401 /**
2402  * Handle the get request from the client file. If I am destination do
2403  * datacache put and return. Else find the target friend and forward message
2404  * to it.
2405  * @param key Key for the content
2406  * @param block_type Type of the block
2407  * @param options Routing options
2408  * @param desired_replication_level Desired replication count
2409  */
2410 void
2411 GDS_NEIGHBOURS_handle_get(const struct GNUNET_HashCode *key,
2412                           enum GNUNET_BLOCK_Type block_type,
2413                           enum GNUNET_DHT_RouteOption options,
2414                           uint32_t desired_replication_level)
2415 {
2416   struct Closest_Peer successor;
2417   struct GNUNET_PeerIdentity best_known_dest;
2418   struct GNUNET_HashCode intermediate_trail_id;
2419   uint64_t key_value;
2420
2421   memcpy (&key_value, key, sizeof (uint64_t));
2422   key_value = GNUNET_ntohll (key_value);
2423
2424   successor = find_local_best_known_next_hop (key_value,
2425                                               GDS_FINGER_TYPE_NON_PREDECESSOR);
2426
2427   best_known_dest = successor.best_known_destination;
2428   intermediate_trail_id = successor.trail_id;
2429
2430   /* I am the destination. I have the data. */
2431   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
2432                                             &best_known_dest))
2433   {
2434     GDS_DATACACHE_handle_get (key,block_type, NULL, 0,
2435                               NULL, 0, 1, &my_identity, NULL,&my_identity);
2436     return;
2437   }
2438
2439 #if ENABLE_MALICIOUS
2440   struct GNUNET_PeerIdentity next_hop;
2441   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&successor.best_known_destination,
2442                                             &successor.next_hop))
2443   {
2444     struct FingerInfo *next_hop_finger;
2445     unsigned int i;
2446
2447     next_hop_finger = &finger_table[successor.finger_table_index];
2448     for (i = 0; i < next_hop_finger->trails_count; i++)
2449     {
2450       if (GNUNET_YES == next_hop_finger->trail_list[i].is_present)
2451       {
2452         if(0 == next_hop_finger->trail_list[i].trail_length)
2453         {
2454            GDS_NEIGHBOURS_send_get (key, block_type, options,
2455                                     desired_replication_level,
2456                                     best_known_dest,intermediate_trail_id,
2457                                     &successor.next_hop,
2458                                     0, 1, &my_identity);
2459            return;
2460         }
2461         next_hop = next_hop_finger->trail_list[i].trail_head->peer;
2462         GDS_NEIGHBOURS_send_get (key, block_type, options, desired_replication_level,
2463                                  best_known_dest,
2464                                  next_hop_finger->trail_list[i].trail_id,
2465                                  &next_hop, 0, 1, &my_identity);
2466        }
2467     }
2468     return;
2469   }
2470 #endif
2471   GDS_NEIGHBOURS_send_get (key, block_type, options, desired_replication_level,
2472                            best_known_dest,intermediate_trail_id, &successor.next_hop,
2473                            0, 1, &my_identity);
2474 }
2475
2476
2477 /**
2478  * Send the get result to requesting client.
2479  *
2480  * @param key Key of the requested data.
2481  * @param type Block type
2482  * @param target_peer Next peer to forward the message to.
2483  * @param source_peer Peer which has the data for the key.
2484  * @param put_path_length Number of peers in @a put_path
2485  * @param put_path Path taken to put the data at its stored location.
2486  * @param get_path_length Number of peers in @a get_path
2487  * @param get_path Path taken to reach to the location of the key.
2488  * @param expiration When will this result expire?
2489  * @param data Payload to store
2490  * @param data_size Size of the @a data
2491  */
2492 void
2493 GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
2494                                 enum GNUNET_BLOCK_Type type,
2495                                 const struct GNUNET_PeerIdentity *target_peer,
2496                                 const struct GNUNET_PeerIdentity *source_peer,
2497                                 unsigned int put_path_length,
2498                                 const struct GNUNET_PeerIdentity *put_path,
2499                                 unsigned int get_path_length,
2500                                 const struct GNUNET_PeerIdentity *get_path,
2501                                 struct GNUNET_TIME_Absolute expiration,
2502                                 const void *data, size_t data_size)
2503 {
2504   struct PeerGetResultMessage *get_result;
2505   struct GNUNET_PeerIdentity *paths;
2506   struct P2PPendingMessage *pending;
2507   struct FriendInfo *target_friend;
2508   int current_path_index;
2509   size_t msize;
2510
2511   msize = (put_path_length + get_path_length )* sizeof (struct GNUNET_PeerIdentity) +
2512           data_size +
2513           sizeof (struct PeerGetResultMessage);
2514
2515   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
2516   {
2517     put_path_length = 0;
2518     msize = msize - put_path_length * sizeof (struct GNUNET_PeerIdentity);
2519   }
2520
2521   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
2522   {
2523     GNUNET_break(0);
2524     return;
2525   }
2526   current_path_index = 0;
2527   if(get_path_length > 0)
2528   {
2529     current_path_index = search_my_index(get_path, get_path_length);
2530     if (-1 == current_path_index)
2531     {
2532       GNUNET_break (0);
2533       return;
2534     }
2535     if ((get_path_length + 1) == current_path_index)
2536     {
2537       DEBUG ("Peer found twice in get path. Not allowed \n");
2538       GNUNET_break (0);
2539       return;
2540     }
2541   }
2542   if (0 == current_path_index)
2543   {
2544     DEBUG ("GET_RESULT TO CLIENT KEY = %s, Peer = %s",GNUNET_h2s(key),GNUNET_i2s(&my_identity));
2545     GDS_CLIENTS_handle_reply (expiration, key, get_path_length,
2546                               get_path, put_path_length,
2547                               put_path, type, data_size, data);
2548     return;
2549   }
2550
2551   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2552   pending->timeout = GNUNET_TIME_relative_to_absolute (PENDING_MESSAGE_TIMEOUT);
2553   pending->importance = 0;
2554   get_result = (struct PeerGetResultMessage *)&pending[1];
2555   pending->msg = &get_result->header;
2556   get_result->header.size = htons (msize);
2557   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_XDHT_P2P_GET_RESULT);
2558   get_result->key = *key;
2559   get_result->querying_peer = *source_peer;
2560   get_result->expiration_time = GNUNET_TIME_absolute_hton (expiration);
2561   get_result->get_path_length = htonl (get_path_length);
2562   get_result->put_path_length = htonl (put_path_length);
2563   paths = (struct GNUNET_PeerIdentity *)&get_result[1];
2564   memcpy (paths, put_path,
2565           put_path_length * sizeof (struct GNUNET_PeerIdentity));
2566   memcpy (&paths[put_path_length], get_path,
2567           get_path_length * sizeof (struct GNUNET_PeerIdentity));
2568   memcpy (&paths[put_path_length + get_path_length], data, data_size);
2569
2570   GNUNET_assert (NULL !=
2571                 (target_friend =
2572                  GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2573                                                     &get_path[current_path_index - 1])));
2574   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2575   target_friend->pending_count++;
2576   process_friend_queue (target_friend);
2577 }
2578
2579
2580 /**
2581  * Randomly choose one of your friends (which is not congested and have not crossed
2582  * trail threshold) from the friend_peermap
2583  * @return Friend Randomly chosen friend.
2584  *         NULL in case friend peermap is empty, or all the friends are either
2585  *              congested or have crossed trail threshold.
2586  */
2587 static struct FriendInfo *
2588 select_random_friend ()
2589 {
2590   unsigned int current_size;
2591   uint32_t index;
2592   unsigned int j = 0;
2593   struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
2594   struct GNUNET_PeerIdentity key_ret;
2595   struct FriendInfo *friend;
2596
2597   current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
2598
2599   /* No friends.*/
2600   if (0 == current_size)
2601     return NULL;
2602
2603   index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
2604   iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
2605
2606   /* Iterate till you don't reach to index. */
2607   for (j = 0; j < index ; j++)
2608     GNUNET_assert (GNUNET_YES ==
2609                    GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL));
2610
2611   do
2612   {
2613     /* Reset the index in friend peermap to 0 as we reached to the end. */
2614     if (j == current_size)
2615     {
2616       j = 0;
2617       GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
2618       iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
2619
2620     }
2621
2622     /* Get the friend stored at the index, j*/
2623     GNUNET_assert (GNUNET_YES ==
2624                    GNUNET_CONTAINER_multipeermap_iterator_next (iter,
2625                                                                 &key_ret,
2626                                                                 (const void **)&friend));
2627
2628     /* This friend is not congested and has not crossed trail threshold. */
2629     if ((friend->trails_count < TRAILS_THROUGH_FRIEND_THRESHOLD) &&
2630         (0 == GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us))
2631     {
2632       break;
2633     }
2634     friend = NULL;
2635     j++;
2636   } while (j != index);
2637
2638   GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
2639   return friend;
2640 }
2641
2642
2643 /**
2644  * Compute 64 bit value of finger_identity corresponding to a finger index using
2645  * chord formula.
2646  * For all fingers, n.finger[i] = n + pow (2,i),
2647  * For predecessor, n.finger[PREDECESSOR_FINGER_ID] = n - 1, where
2648  * n = my_identity, i = finger_index, n.finger[i] = 64 bit finger value
2649  * @param finger_index Index corresponding to which we calculate 64 bit value.
2650  * @return 64 bit value.
2651  */
2652 static uint64_t
2653 compute_finger_identity_value (unsigned int finger_index)
2654 {
2655   uint64_t my_id64;
2656
2657   memcpy (&my_id64, &my_identity, sizeof (uint64_t));
2658   my_id64 = GNUNET_ntohll (my_id64);
2659
2660   /* Are we looking for immediate predecessor? */
2661   if (PREDECESSOR_FINGER_ID == finger_index)
2662     return (my_id64 - 1);
2663   else
2664   {
2665     uint64_t add = (uint64_t)1 << finger_index;
2666     return (my_id64 + add);
2667   }
2668 }
2669
2670
2671 /*
2672  * Choose a random friend. Calculate the next finger identity to search,from
2673  * current_search_finger_index. Start looking for the trail to reach to
2674  * finger identity through this random friend.
2675  *
2676  * @param cls closure for this task
2677  * @param tc the context under which the task is running
2678  */
2679 static void
2680 send_find_finger_trail_message (void *cls,
2681                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
2682 {
2683   struct FriendInfo *target_friend;
2684   struct GNUNET_HashCode trail_id;
2685   struct GNUNET_HashCode intermediate_trail_id;
2686   unsigned int is_predecessor = 0;
2687   uint64_t finger_id_value;
2688
2689   /* Schedule another send_find_finger_trail_message task. After one round of
2690    * finger search, this time is exponentially backoff. */
2691   find_finger_trail_task_next_send_time.rel_value_us =
2692       find_finger_trail_task_next_send_time.rel_value_us +
2693       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2694                                 DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
2695   find_finger_trail_task =
2696       GNUNET_SCHEDULER_add_delayed (find_finger_trail_task_next_send_time,
2697                                     &send_find_finger_trail_message,
2698                                     NULL);
2699
2700   /* No space in my routing table. (Source and destination peers also store entries
2701    * in their routing table).  */
2702   if (GNUNET_YES == GDS_ROUTING_threshold_reached())
2703     return;
2704
2705   target_friend = select_random_friend ();
2706   if (NULL == target_friend)
2707   {
2708     return;
2709   }
2710
2711   finger_id_value = compute_finger_identity_value (current_search_finger_index);
2712   if (PREDECESSOR_FINGER_ID == current_search_finger_index)
2713     is_predecessor = 1;
2714
2715   /* Generate a unique trail id for trail we are trying to setup. */
2716   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
2717                               &trail_id, sizeof (trail_id));
2718   memset(&intermediate_trail_id, 0, sizeof (struct GNUNET_HashCode));
2719   GDS_NEIGHBOURS_send_trail_setup (my_identity, finger_id_value,
2720                                    target_friend->id, target_friend, 0, NULL,
2721                                    is_predecessor, trail_id,
2722                                    intermediate_trail_id);
2723 }
2724
2725
2726 /**
2727  * In case there are already maximum number of possible trails to reach to a
2728  * finger, then check if the new trail's length is lesser than any of the
2729  * existing trails.
2730  * If yes then replace that old trail by new trail.
2731  *
2732  * Note: Here we are taking length as a parameter to choose the best possible
2733  * trail, but there could be other parameters also like:
2734  * 1. duration of existence of a trail - older the better.
2735  * 2. if the new trail is completely disjoint than the
2736  *    other trails, then may be choosing it is better.
2737  *
2738  * @param finger Finger
2739  * @param new_finger_trail List of peers to reach from me to @a finger, NOT
2740  *                         including the endpoints.
2741  * @param new_finger_trail_length Total number of peers in @a new_finger_trail
2742  * @param new_finger_trail_id Unique identifier of @a new_finger_trail.
2743  */
2744 static void
2745 select_and_replace_trail (struct FingerInfo *finger,
2746                           const struct GNUNET_PeerIdentity *new_trail,
2747                           unsigned int new_trail_length,
2748                           struct GNUNET_HashCode new_trail_id)
2749 {
2750   struct Trail *current_trail;
2751   unsigned int largest_trail_length;
2752   unsigned int largest_trail_index;
2753   struct Trail_Element *trail_element;
2754   struct GNUNET_PeerIdentity *next_hop;
2755   unsigned int i;
2756
2757   largest_trail_length = new_trail_length;
2758   largest_trail_index = MAXIMUM_TRAILS_PER_FINGER + 1;
2759
2760   GNUNET_assert (MAXIMUM_TRAILS_PER_FINGER == finger->trails_count);
2761
2762   for (i = 0; i < finger->trails_count; i++)
2763   {
2764     current_trail = &finger->trail_list[i];
2765     GNUNET_assert (GNUNET_YES == current_trail->is_present);
2766     if (current_trail->trail_length > largest_trail_length)
2767     {
2768       largest_trail_length = current_trail->trail_length;
2769       largest_trail_index = i;
2770     }
2771   }
2772
2773   /* New trail is not better than existing ones. Send trail teardown. */
2774   if (largest_trail_index == (MAXIMUM_TRAILS_PER_FINGER + 1))
2775   {
2776     next_hop = GDS_ROUTING_get_next_hop (new_trail_id, GDS_ROUTING_SRC_TO_DEST);
2777     GDS_ROUTING_remove_trail (new_trail_id);
2778     GDS_NEIGHBOURS_send_trail_teardown (&new_trail_id,
2779                                         GDS_ROUTING_SRC_TO_DEST,
2780                                         next_hop);
2781     return;
2782   }
2783
2784   /* Send trail teardown message across the replaced trail. */
2785   struct Trail *replace_trail = &finger->trail_list[largest_trail_index];
2786   next_hop = GDS_ROUTING_get_next_hop (replace_trail->trail_id, GDS_ROUTING_SRC_TO_DEST);
2787   GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (replace_trail->trail_id));
2788   GDS_NEIGHBOURS_send_trail_teardown (&replace_trail->trail_id,
2789                                       GDS_ROUTING_SRC_TO_DEST,
2790                                       next_hop);
2791
2792   /* Free the trail. */
2793   while (NULL != (trail_element = replace_trail->trail_head))
2794   {
2795     GNUNET_CONTAINER_DLL_remove (replace_trail->trail_head,
2796                                  replace_trail->trail_tail, trail_element);
2797     GNUNET_free_non_null (trail_element);
2798   }
2799
2800   /* Add new trial at that location. */
2801   replace_trail->is_present = GNUNET_YES;
2802   replace_trail->trail_length = new_trail_length;
2803   replace_trail->trail_id = new_trail_id;
2804
2805   for (i = 0; i < new_trail_length; i++)
2806   {
2807     struct Trail_Element *element = GNUNET_new (struct Trail_Element);
2808     element->peer = new_trail[i];
2809
2810     GNUNET_CONTAINER_DLL_insert_tail (replace_trail->trail_head,
2811                                       replace_trail->trail_tail,
2812                                       element);
2813   }
2814   /* FIXME: URGENT Are we adding the trail back to the list. */
2815 }
2816
2817
2818 /**
2819  * Check if the new trail to reach to finger is unique or do we already have
2820  * such a trail present for finger.
2821  * @param existing_finger Finger identity
2822  * @param new_trail New trail to reach @a existing_finger
2823  * @param trail_length Total number of peers in new_trail.
2824  * @return #GNUNET_YES if the new trail is unique
2825  *         #GNUNET_NO if same trail is already present.
2826  */
2827 static int
2828 is_new_trail_unique (struct FingerInfo *existing_finger,
2829                      const struct GNUNET_PeerIdentity *new_trail,
2830                      unsigned int trail_length)
2831 {
2832   struct Trail *current_trail;
2833   struct Trail_Element *trail_element;
2834   int i;
2835   int j;
2836
2837   GNUNET_assert (existing_finger->trails_count > 0);
2838
2839   /* Iterate over list of trails. */
2840   for (i = 0; i < existing_finger->trails_count; i++)
2841   {
2842     current_trail = &(existing_finger->trail_list[i]);
2843     if(GNUNET_NO == current_trail->is_present)
2844       continue;
2845
2846     /* New trail and existing trail length are not same. */
2847     if (current_trail->trail_length != trail_length)
2848     {
2849       return GNUNET_YES;
2850     }
2851
2852     trail_element = current_trail->trail_head;
2853     for (j = 0; j < current_trail->trail_length; j++)
2854     {
2855       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&new_trail[j],
2856                                                 &trail_element->peer))
2857       {
2858         return GNUNET_YES;
2859       }
2860       trail_element = trail_element->next;
2861     }
2862   }
2863   return GNUNET_NO;
2864 }
2865
2866 /**
2867  * FIXME; In case of multiple trails, we may have a case where a trail from in
2868  * between has been removed, then we should try to find a free slot , not simply
2869  * add a trail at then end of the list.
2870  * Add a new trail at a free slot in trail array of existing finger.
2871  * @param existing_finger Finger
2872  * @param new_finger_trail New trail from me to finger, NOT including endpoints
2873  * @param new_finger_trail_length Total number of peers in @a new_finger_trail
2874  * @param new_finger_trail_id Unique identifier of the trail.
2875  */
2876 static void
2877 add_new_trail (struct FingerInfo *existing_finger,
2878                const struct GNUNET_PeerIdentity *new_trail,
2879                unsigned int new_trail_length,
2880                struct GNUNET_HashCode new_trail_id)
2881 {
2882   struct FriendInfo *friend;
2883   struct Trail *trail;
2884   unsigned int i;
2885   int free_slot = -1;
2886
2887   if (GNUNET_NO == is_new_trail_unique (existing_finger, new_trail,
2888                                         new_trail_length))
2889     return;
2890
2891   for (i = 0; i < existing_finger->trails_count; i++)
2892   {
2893     if (GNUNET_NO == existing_finger->trail_list[i].is_present)
2894     {
2895       free_slot = i;
2896       break;
2897     }
2898   }
2899
2900   if (-1 == free_slot)
2901     free_slot = i;
2902
2903   trail = &existing_finger->trail_list[free_slot];
2904   GNUNET_assert (GNUNET_NO == trail->is_present);
2905   trail->trail_id = new_trail_id;
2906   trail->trail_length = new_trail_length;
2907   existing_finger->trails_count++;
2908   trail->is_present = GNUNET_YES;
2909   if (0 == new_trail_length)
2910   {
2911     friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2912                                                 &existing_finger->finger_identity);
2913   }
2914   else
2915   {
2916     friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2917                                                 &new_trail[0]);
2918   }
2919   GNUNET_assert (NULL != friend);
2920   friend->trails_count++;
2921   for (i = 0; i < new_trail_length; i++)
2922   {
2923     struct Trail_Element *element;
2924
2925     element = GNUNET_new (struct Trail_Element);
2926     element->peer = new_trail[i];
2927     GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
2928                                       trail->trail_tail,
2929                                       element);
2930   }
2931
2932   existing_finger->trail_list[free_slot].trail_head = trail->trail_head;
2933   existing_finger->trail_list[free_slot].trail_tail = trail->trail_tail;
2934   existing_finger->trail_list[free_slot].trail_length = new_trail_length;
2935   existing_finger->trail_list[free_slot].trail_id = new_trail_id;
2936   existing_finger->trail_list[free_slot].is_present = GNUNET_YES;
2937 }
2938
2939
2940 #if 0
2941 /**
2942  * FIXME; In case of multiple trails, we may have a case where a trail from in
2943  * between has been removed, then we should try to find a free slot , not simply
2944  * add a trail at then end of the list.
2945  * Add a new trail at a free slot in trail array of existing finger.
2946  * @param existing_finger Finger
2947  * @param new_finger_trail New trail from me to finger, NOT including endpoints
2948  * @param new_finger_trail_length Total number of peers in @a new_finger_trail
2949  * @param new_finger_trail_id Unique identifier of the trail.
2950  */
2951 static void
2952 add_new_trail (struct FingerInfo *existing_finger,
2953                const struct GNUNET_PeerIdentity *new_trail,
2954                unsigned int new_trail_length,
2955                struct GNUNET_HashCode new_trail_id)
2956 {
2957   struct Trail *trail;
2958   struct FriendInfo *first_friend;
2959   int i;
2960   int index;
2961
2962   if (GNUNET_NO == is_new_trail_unique (existing_finger, new_trail,
2963                                         new_trail_length))
2964     return;
2965
2966   index = existing_finger->trails_count;
2967   trail = &existing_finger->trail_list[index];
2968   GNUNET_assert (GNUNET_NO == trail->is_present);
2969   trail->trail_id = new_trail_id;
2970   trail->trail_length = new_trail_length;
2971   existing_finger->trails_count++;
2972   trail->is_present = GNUNET_YES;
2973
2974   GNUNET_assert (NULL == (GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2975                                                              &existing_finger->finger_identity)));
2976   /* If finger is a friend then we never call this function. */
2977   GNUNET_assert (new_trail_length > 0);
2978
2979   first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2980                                                     &new_trail[0]);
2981   first_friend->trails_count++;
2982
2983   for (i = 0; i < new_trail_length; i++)
2984   {
2985     struct Trail_Element *element;
2986
2987     element = GNUNET_new (struct Trail_Element);
2988     element->peer = new_trail[i];
2989     GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
2990                                       trail->trail_tail,
2991                                       element);
2992   }
2993   /* Do we need to add trail head and trail tail in the trail list itearator.*/
2994   existing_finger->trail_list[index].trail_head = trail->trail_head;
2995   existing_finger->trail_list[index].trail_tail = trail->trail_tail;
2996   existing_finger->trail_list[index].trail_length = new_trail_length;
2997   existing_finger->trail_list[index].trail_id = new_trail_id;
2998   existing_finger->trail_list[index].is_present = GNUNET_YES;
2999 }
3000 #endif
3001
3002 /**
3003  * Get the next hop to send trail teardown message from routing table and
3004  * then delete the entry from routing table. Send trail teardown message for a
3005  * specific trail of a finger.
3006  * @param finger Finger whose trail is to be removed.
3007  * @param trail List of peers in trail from me to a finger, NOT including
3008  *              endpoints.
3009  */
3010 static void
3011 send_trail_teardown (struct FingerInfo *finger,
3012                      struct Trail *trail)
3013 {
3014   struct FriendInfo *friend;
3015   struct GNUNET_PeerIdentity *next_hop;
3016
3017   next_hop = GDS_ROUTING_get_next_hop (trail->trail_id,
3018                                        GDS_ROUTING_SRC_TO_DEST);
3019   if (NULL == next_hop)
3020   {
3021 //    DEBUG(" NO ENTRY FOUND IN %s ROUTING TABLE for trail id %s, line=%d,traillength = %d",
3022 //            GNUNET_i2s(&my_identity), GNUNET_h2s(&trail->trail_id), __LINE__,trail->trail_length);
3023     return;
3024   }
3025   GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
3026                                                        &my_identity));
3027
3028   GNUNET_assert(GNUNET_YES == trail->is_present);
3029   if (trail->trail_length > 0)
3030   {
3031     friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3032                                                 &trail->trail_head->peer);
3033   }
3034   else
3035   {
3036     friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3037                                                 &finger->finger_identity);
3038   }
3039
3040   if(NULL == friend)
3041   {
3042     DEBUG ("\n LINE NO: = %d, Friend not found for trail id  %s of peer %s trail length = %d",
3043            __LINE__,GNUNET_h2s(&trail->trail_id), GNUNET_i2s(&my_identity),trail->trail_length);
3044     return;
3045   }
3046   if (0 != GNUNET_CRYPTO_cmp_peer_identity (next_hop, &friend->id)
3047       && (0 == trail->trail_length))
3048   {
3049      DEBUG ("\n LINE NO: = %d, Friend not found for trail id  %s of peer %s trail length = %d",
3050            __LINE__,GNUNET_h2s(&trail->trail_id), GNUNET_i2s(&my_identity),trail->trail_length);
3051     return;
3052   }
3053   GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail->trail_id));
3054   friend->trails_count--;
3055   GDS_NEIGHBOURS_send_trail_teardown (&trail->trail_id,
3056                                       GDS_ROUTING_SRC_TO_DEST,
3057                                       &friend->id);
3058 }
3059
3060
3061 /**
3062  * Send trail teardown message across all the trails to reach to finger.
3063  * @param finger Finger whose all the trail should be freed.
3064  */
3065 static void
3066 send_all_finger_trails_teardown (struct FingerInfo *finger)
3067 {
3068   unsigned int i;
3069
3070   for (i = 0; i < finger->trails_count; i++)
3071   {
3072     struct Trail *trail;
3073
3074     trail = &finger->trail_list[i];
3075     if (GNUNET_YES == trail->is_present)
3076     {
3077       send_trail_teardown (finger, trail);
3078       trail->is_present = GNUNET_NO;
3079     }
3080   }
3081 }
3082
3083
3084 /**
3085  * Free a specific trail
3086  * @param trail List of peers to be freed.
3087  */
3088 static void
3089 free_trail (struct Trail *trail)
3090 {
3091   struct Trail_Element *trail_element;
3092
3093   while (NULL != (trail_element = trail->trail_head))
3094   {
3095     GNUNET_CONTAINER_DLL_remove (trail->trail_head,
3096                                  trail->trail_tail,
3097                                  trail_element);
3098     GNUNET_free_non_null (trail_element);
3099   }
3100   trail->trail_head = NULL;
3101   trail->trail_tail = NULL;
3102 }
3103
3104
3105 /**
3106  * Free finger and its trail.
3107  * @param finger Finger to be freed.
3108  * @param finger_table_index Index at which finger is stored.
3109  */
3110 static void
3111 free_finger (struct FingerInfo *finger, unsigned int finger_table_index)
3112 {
3113   struct Trail *trail;
3114   unsigned int i;
3115   for (i = 0; i < finger->trails_count; i++)
3116   {
3117     trail = &finger->trail_list[i];
3118     if (GNUNET_NO == trail->is_present)
3119       continue;
3120
3121     if (trail->trail_length > 0)
3122       free_trail (trail);
3123     trail->is_present = GNUNET_NO;
3124   }
3125
3126   finger->is_present = GNUNET_NO;
3127   memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
3128 }
3129
3130
3131 /**
3132  * Add a new entry in finger table at finger_table_index.
3133  * In case I am my own finger, then we don't have a trail. In case of a friend,
3134  * we have a trail with unique id and '0' trail length.
3135  * In case a finger is a friend, then increment the trails count of the friend.
3136  * @param finger_identity Peer Identity of new finger
3137  * @param finger_trail Trail to reach from me to finger (excluding both end points).
3138  * @param finger_trail_length Total number of peers in @a finger_trail.
3139  * @param trail_id Unique identifier of the trail.
3140  * @param finger_table_index Index in finger table.
3141  */
3142 static void
3143 add_new_finger (struct GNUNET_PeerIdentity finger_identity,
3144                 const struct GNUNET_PeerIdentity *finger_trail,
3145                 unsigned int finger_trail_length,
3146                 struct GNUNET_HashCode trail_id,
3147                 unsigned int finger_table_index)
3148 {
3149   struct FingerInfo *new_entry;
3150   struct FriendInfo *first_trail_hop;
3151   struct Trail *trail;
3152   unsigned int i;
3153
3154   new_entry = GNUNET_new (struct FingerInfo);
3155   new_entry->finger_identity = finger_identity;
3156   new_entry->finger_table_index = finger_table_index;
3157   new_entry->is_present = GNUNET_YES;
3158
3159   /* If the new entry is my own identity. */
3160   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
3161                                             &finger_identity))
3162   {
3163     new_entry->trails_count = 0;
3164     finger_table[finger_table_index] = *new_entry;
3165     GNUNET_free (new_entry);
3166     return;
3167   }
3168
3169   /* Finger is a friend. */
3170   if (0 == finger_trail_length)
3171   {
3172     new_entry->trail_list[0].trail_id = trail_id;
3173     new_entry->trails_count = 1;
3174     new_entry->trail_list[0].is_present = GNUNET_YES;
3175     new_entry->trail_list[0].trail_length = 0;
3176     new_entry->trail_list[0].trail_head = NULL;
3177     new_entry->trail_list[0].trail_tail = NULL;
3178     finger_table[finger_table_index] = *new_entry;
3179     GNUNET_assert (NULL !=
3180                   (first_trail_hop =
3181                        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3182                                                           &finger_identity)));
3183
3184     first_trail_hop->trails_count++;
3185     GNUNET_free (new_entry);
3186     return;
3187   }
3188
3189   GNUNET_assert (NULL !=
3190                 (first_trail_hop =
3191                        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3192                                                           &finger_trail[0])));
3193   new_entry->trails_count = 1;
3194   first_trail_hop->trails_count++;
3195   /* Copy the finger trail into trail. */
3196   trail = &new_entry->trail_list[0];
3197   for(i = 0; i < finger_trail_length; i++)
3198   {
3199     struct Trail_Element *element = GNUNET_new (struct Trail_Element);
3200
3201     element->next = NULL;
3202     element->prev = NULL;
3203     element->peer = finger_trail[i];
3204     GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
3205                                       trail->trail_tail,
3206                                       element);
3207   }
3208
3209   /* Add trail to trail list. */
3210   trail->trail_length = finger_trail_length;
3211   trail->trail_id = trail_id;
3212   trail->is_present = GNUNET_YES;
3213   finger_table[finger_table_index] = *new_entry;
3214   GNUNET_free (new_entry);
3215 }
3216
3217
3218 /**
3219  * Periodic task to verify current successor. There can be multiple trails to reach
3220  * to successor, choose the shortest one and send verify successor message
3221  * across that trail.
3222  * @param cls closure for this task
3223  * @param tc the context under which the task is running
3224  */
3225 static void
3226 send_verify_successor_message (void *cls,
3227                                const struct GNUNET_SCHEDULER_TaskContext *tc)
3228 {
3229   struct FriendInfo *target_friend;
3230   struct GNUNET_HashCode trail_id;
3231   struct Trail *trail;
3232   struct Trail_Element *element;
3233   unsigned int trail_length;
3234   unsigned int i = 0;
3235   struct FingerInfo *successor;
3236
3237   successor = &finger_table[0];
3238
3239   /* This task will be scheduled when the result for Verify Successor is received. */
3240   send_verify_successor_task = NULL;
3241
3242   /* When verify successor is being called for first time *for current context*
3243    * cls will be NULL. If send_verify_successor_retry_task is not NO_TASK, we
3244    * must cancel the retry task scheduled for verify_successor of previous
3245    * context.
3246    */
3247   if (NULL == cls)
3248   {
3249     /* FIXME: Here we are scheduling a new verify successor task, as we
3250      got a new successor. But a send verify successor task may be in progress.
3251      1. We need to be sure that this is indeed a new successor. As this function
3252      is called even if we add a new trail to reach t old successor.
3253      2. Assuming the new successor is different, then verify successor message
3254      * to old successor may be following stages.
3255      * --> Waiting for verify successor result. Don't wait anymore. there is
3256      *     no trail to reach from old successor to me, hence, routing
3257      *     lookup will fail.
3258      * --> Waiting for notify confirmation. again don't wait for it. notify
3259      *    confirmation will not succeded.
3260      */
3261     if (send_verify_successor_retry_task != NULL)
3262     {
3263       /* FIXME: Are we scheduling retry task as soon as we send verify message.
3264        If yes then here before making this task, first check if the message
3265        is for the same peer again. */
3266       struct VerifySuccessorContext *old_ctx =
3267           GNUNET_SCHEDULER_cancel(send_verify_successor_retry_task);
3268       /* old_ctx must not be NULL, as the retry task had been scheduled */
3269       GNUNET_assert(NULL != old_ctx);
3270       GNUNET_free(old_ctx);
3271       /* FIXME: Why don't we reset the task to NO_TASK here? */
3272     }
3273
3274     struct VerifySuccessorContext *ctx;
3275     ctx = GNUNET_new(struct VerifySuccessorContext);
3276
3277     ctx->num_retries_scheduled++;
3278     send_verify_successor_retry_task =
3279         GNUNET_SCHEDULER_add_delayed (verify_successor_retry_time,
3280                                       &send_verify_successor_message,
3281                                       ctx);
3282   }
3283   else
3284   {
3285     /* This is a retry attempt for verify_successor for a previous context */
3286     struct VerifySuccessorContext *ctx;
3287
3288     ctx = cls;
3289     ctx->num_retries_scheduled++;
3290     send_verify_successor_retry_task =
3291         GNUNET_SCHEDULER_add_delayed (verify_successor_retry_time,
3292                                       &send_verify_successor_message,
3293                                       ctx);
3294   }
3295
3296   /* Among all the trails to reach to successor, select first one which is present.*/
3297   for (i = 0; i < successor->trails_count; i++)
3298   {
3299     trail = &successor->trail_list[i];
3300     if(GNUNET_YES == trail->is_present)
3301       break;
3302   }
3303
3304   /* No valid trail found to reach to successor. */
3305   if (i == successor->trails_count)
3306     return;
3307
3308   GNUNET_assert(0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
3309                                                       &successor->finger_identity));
3310   /* Trail stored at this index. */
3311   GNUNET_assert (GNUNET_YES == trail->is_present);
3312   trail_id = trail->trail_id;
3313   if (NULL == GDS_ROUTING_get_next_hop(trail_id,GDS_ROUTING_SRC_TO_DEST))
3314   {
3315     DEBUG(" NO ENTRY FOUND IN %s ROUTING TABLE for trail id %s, line",
3316             GNUNET_i2s(&my_identity), GNUNET_h2s(&trail->trail_id), __LINE__);
3317     GNUNET_break(0);
3318     return;
3319   }
3320   trail_length = trail->trail_length;
3321   if (trail_length > 0)
3322   {
3323      /* Copy the trail into peer list. */
3324     struct GNUNET_PeerIdentity peer_list[trail_length];
3325     element = trail->trail_head;
3326     for(i = 0; i < trail_length; i++)
3327     {
3328       peer_list[i] = element->peer;
3329       element = element->next;
3330     }
3331     GNUNET_assert (NULL != (target_friend =
3332                             GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3333                                                                &peer_list[0])));
3334     GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
3335                                                   successor->finger_identity,
3336                                                   trail_id, peer_list, trail_length,
3337                                                   target_friend);
3338   }
3339   else
3340   {
3341     GNUNET_assert (NULL != (target_friend =
3342                             GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3343                                                                &successor->finger_identity)));
3344     GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
3345                                                   successor->finger_identity,
3346                                                   trail_id, NULL, 0,
3347                                                   target_friend);
3348   }
3349 }
3350
3351
3352 /**
3353  * FIXME: should this be a periodic task, incrementing the search finger index?
3354  * Update the current search finger index.
3355  * @a finger_identity
3356  * @a finger_table_index
3357  */
3358 static void
3359 update_current_search_finger_index (unsigned int finger_table_index)
3360 {
3361   struct FingerInfo *successor;
3362
3363   /* FIXME correct this: only move current index periodically */
3364   if (finger_table_index != current_search_finger_index)
3365     return;
3366
3367   successor = &finger_table[0];
3368   GNUNET_assert (GNUNET_YES == successor->is_present);
3369
3370   /* We were looking for immediate successor.  */
3371   if (0 == current_search_finger_index)
3372   {
3373     current_search_finger_index = PREDECESSOR_FINGER_ID;
3374     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &successor->finger_identity))
3375     {
3376       if (NULL == send_verify_successor_task)
3377       {
3378         send_verify_successor_task =
3379                 GNUNET_SCHEDULER_add_now (&send_verify_successor_message, NULL);
3380       }
3381     }
3382     return;
3383   }
3384
3385   current_search_finger_index = current_search_finger_index - 1;
3386   return;
3387 }
3388
3389
3390 /**
3391  * Get the least significant bit set in val.
3392  *
3393  * @param val Value
3394  * @return Position of first bit set, 65 in case of error.
3395  */
3396 static unsigned int
3397 find_set_bit (uint64_t val)
3398 {
3399   uint64_t i;
3400   unsigned int pos;
3401
3402   i = 1;
3403   pos = 0;
3404
3405   while (!(i & val))
3406   {
3407     i = i << 1;
3408     pos++;
3409     if (pos > 63)
3410     {
3411       GNUNET_break (0);
3412       return 65;
3413     }
3414   }
3415
3416   if (val/i != 1)
3417     return 65; /* Some other bit was set to 1 as well. */
3418
3419   return pos;
3420 }
3421
3422
3423 /**
3424  * Calculate finger_table_index from initial 64 bit finger identity value that
3425  * we send in trail setup message.
3426  * @param ultimate_destination_finger_value Value that we calculated from our
3427  *                                          identity and finger_table_index.
3428  * @param is_predecessor Is the entry for predecessor or not?
3429  * @return finger_table_index Value between 0 <= finger_table_index <= 64
3430  *         finger_table_index > PREDECESSOR_FINGER_ID, if error occurs.
3431  */
3432 static unsigned int
3433 get_finger_table_index (uint64_t ultimate_destination_finger_value,
3434                         unsigned int is_predecessor)
3435 {
3436   uint64_t my_id64;
3437   uint64_t diff;
3438   unsigned int finger_table_index;
3439
3440   memcpy (&my_id64, &my_identity, sizeof (uint64_t));
3441   my_id64 = GNUNET_ntohll (my_id64);
3442
3443   /* Is this a predecessor finger? */
3444   if (1 == is_predecessor)
3445   {
3446     diff =  my_id64 - ultimate_destination_finger_value;
3447     if (1 == diff)
3448       finger_table_index = PREDECESSOR_FINGER_ID;
3449     else
3450       finger_table_index = PREDECESSOR_FINGER_ID + 1; //error value
3451
3452   }
3453   else
3454   {
3455     diff = ultimate_destination_finger_value - my_id64;
3456     finger_table_index = find_set_bit (diff);
3457   }
3458   return finger_table_index;
3459 }
3460
3461
3462 /**
3463  * Remove finger and its associated data structures from finger table.
3464  * @param existing_finger Finger to be removed which is in finger table.
3465  * @param finger_table_index Index in finger table where @a existing_finger
3466  *                           is stored.
3467  */
3468 static void
3469 remove_existing_finger (struct FingerInfo *existing_finger,
3470                         unsigned int finger_table_index)
3471 {
3472   GNUNET_assert (GNUNET_YES == existing_finger->is_present);
3473
3474   /* If I am my own finger, then we have no trails. */
3475   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&existing_finger->finger_identity,
3476                                             &my_identity))
3477   {
3478     existing_finger->is_present = GNUNET_NO;
3479     memset ((void *)&finger_table[finger_table_index], 0,
3480             sizeof (finger_table[finger_table_index]));
3481     return;
3482   }
3483
3484   /* For all other fingers, send trail teardown across all the trails to reach
3485    finger, and free the finger. */
3486   send_all_finger_trails_teardown (existing_finger);
3487   free_finger (existing_finger, finger_table_index);
3488 }
3489
3490
3491 /**
3492  * Check if there is already an entry in finger_table at finger_table_index.
3493  * We get the finger_table_index from 64bit finger value we got from the network.
3494  * -- If yes, then select the closest finger.
3495  *   -- If new and existing finger are same, then check if you can store more
3496  *      trails.
3497  *      -- If yes then add trail, else keep the best trails to reach to the
3498  *         finger.
3499  *   -- If the new finger is closest, remove the existing entry, send trail
3500  *      teardown message across all the trails to reach the existing entry.
3501  *      Add the new finger.
3502  *  -- If new and existing finger are different, and existing finger is closest
3503  *     then do nothing.
3504  * -- Update current_search_finger_index.
3505  * @param finger_identity Peer Identity of new finger
3506  * @param finger_trail Trail to reach the new finger
3507  * @param finger_trail_length Total number of peers in @a new_finger_trail.
3508  * @param is_predecessor Is this entry for predecessor in finger_table?
3509  * @param finger_value 64 bit value of finger identity that we got from network.
3510  * @param finger_trail_id Unique identifier of @finger_trail.
3511  */
3512 static void
3513 finger_table_add (struct GNUNET_PeerIdentity finger_identity,
3514                   const struct GNUNET_PeerIdentity *finger_trail,
3515                   unsigned int finger_trail_length,
3516                   unsigned int is_predecessor,
3517                   uint64_t finger_value,
3518                   struct GNUNET_HashCode finger_trail_id)
3519 {
3520   struct FingerInfo *existing_finger;
3521   struct GNUNET_PeerIdentity closest_peer;
3522   struct FingerInfo *successor;
3523   unsigned int finger_table_index;
3524
3525   /* Get the finger_table_index corresponding to finger_value we got from network.*/
3526   finger_table_index = get_finger_table_index (finger_value, is_predecessor);
3527
3528   /* Invalid finger_table_index. */
3529   if ((finger_table_index > PREDECESSOR_FINGER_ID))
3530   {
3531     GNUNET_break_op (0);
3532     return;
3533   }
3534
3535   /* Check if  new entry is same as successor. */
3536   if ((0 != finger_table_index) &&
3537       (PREDECESSOR_FINGER_ID != finger_table_index))
3538   {
3539     successor = &finger_table[0];
3540     if (GNUNET_NO == successor->is_present)
3541     {
3542       GNUNET_break (0); //ASSERTION FAILS HERE. FIXME
3543       return;
3544     }
3545     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
3546                                               &successor->finger_identity))
3547     {
3548       if (0 == fingers_round_count)
3549       {
3550          find_finger_trail_task_next_send_time =
3551               GNUNET_TIME_STD_BACKOFF(find_finger_trail_task_next_send_time);
3552       }
3553       else
3554         fingers_round_count--;
3555       current_search_finger_index = 0;
3556       GNUNET_STATISTICS_update (GDS_stats,
3557                                 gettext_noop
3558                                 ("# FINGERS_COUNT"), (int64_t) total_fingers_found,
3559                                 GNUNET_NO);
3560       total_fingers_found  = 0;
3561       return;
3562     }
3563
3564     struct FingerInfo prev_finger;
3565     prev_finger = finger_table[finger_table_index - 1];
3566     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
3567                                               &prev_finger.finger_identity))
3568     {
3569        current_search_finger_index--;
3570        return;
3571     }
3572   }
3573
3574   total_fingers_found++;
3575   existing_finger = &finger_table[finger_table_index];
3576
3577   /* No entry present in finger_table for given finger map index. */
3578   if (GNUNET_NO == existing_finger->is_present)
3579   {
3580      /* Shorten the trail if possible. */
3581     add_new_finger (finger_identity, finger_trail,
3582                     finger_trail_length,
3583                     finger_trail_id, finger_table_index);
3584     update_current_search_finger_index (finger_table_index);
3585     return;
3586   }
3587
3588   /* If existing entry and finger identity are not same. */
3589   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
3590                                             &finger_identity))
3591   {
3592     closest_peer = select_closest_peer (&existing_finger->finger_identity,
3593                                         &finger_identity,
3594                                         finger_value,
3595                                         is_predecessor);
3596
3597     /* If the new finger is the closest peer. */
3598     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, &closest_peer))
3599     {
3600       remove_existing_finger (existing_finger, finger_table_index);
3601       add_new_finger (finger_identity, finger_trail, finger_trail_length,
3602                       finger_trail_id, finger_table_index);
3603     }
3604     else
3605     {
3606       /* Existing finger is the closest one. We need to send trail teardown
3607          across the trail setup in routing table of all the peers. */
3608       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, &my_identity))
3609       {
3610         if (finger_trail_length > 0)
3611           GDS_NEIGHBOURS_send_trail_teardown (&finger_trail_id,
3612                                               GDS_ROUTING_SRC_TO_DEST,
3613                                               &finger_trail[0]);
3614         else
3615           GDS_NEIGHBOURS_send_trail_teardown (&finger_trail_id,
3616                                               GDS_ROUTING_SRC_TO_DEST,
3617                                               &finger_identity);
3618       }
3619     }
3620   }
3621   else
3622   {
3623     /* If both new and existing entry are same as my_identity, then do nothing. */
3624     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
3625                                               &my_identity))
3626     {
3627       return;
3628     }
3629
3630     /* If there is space to store more trails. */
3631     if (existing_finger->trails_count < MAXIMUM_TRAILS_PER_FINGER)
3632         add_new_trail (existing_finger, finger_trail,
3633                        finger_trail_length, finger_trail_id);
3634     else
3635         select_and_replace_trail (existing_finger, finger_trail,
3636                                   finger_trail_length, finger_trail_id);
3637   }
3638   update_current_search_finger_index (finger_table_index);
3639   return;
3640 }
3641
3642
3643 /**
3644  * Core handler for P2P put messages.
3645  * @param cls closure
3646  * @param peer sender of the request
3647  * @param message message
3648  * @return #GNUNET_OK to keep the connection open,
3649  *         #GNUNET_SYSERR to close it (signal serious error)
3650  */
3651 static int
3652 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
3653                     const struct GNUNET_MessageHeader *message)
3654 {
3655   struct PeerPutMessage *put;
3656   struct GNUNET_PeerIdentity *put_path;
3657   struct GNUNET_PeerIdentity current_best_known_dest;
3658   struct GNUNET_PeerIdentity best_known_dest;
3659   struct GNUNET_HashCode received_intermediate_trail_id;
3660   struct GNUNET_HashCode intermediate_trail_id;
3661   struct GNUNET_PeerIdentity next_hop;
3662   struct GNUNET_PeerIdentity *next_routing_hop;
3663   enum GNUNET_DHT_RouteOption options;
3664   struct GNUNET_HashCode test_key;
3665   void *payload;
3666   size_t msize;
3667   uint32_t putlen;
3668   uint32_t hop_count;
3669   size_t payload_size;
3670   uint64_t key_value;
3671
3672   msize = ntohs (message->size);
3673   if (msize < sizeof (struct PeerPutMessage))
3674   {
3675     GNUNET_break_op (0);
3676     return GNUNET_OK;
3677   }
3678
3679   put = (struct PeerPutMessage *) message;
3680   putlen = ntohl (put->put_path_length);
3681   if ((msize <
3682        sizeof (struct PeerPutMessage) +
3683        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
3684       (putlen >
3685        GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
3686   {
3687     GNUNET_break_op (0);
3688     return GNUNET_OK;
3689   }
3690 #if ENABLE_MALICIOUS
3691   if(1 == act_malicious)
3692   {
3693     DEBUG("\n I AM MALICIOUS PUT_REQUEST_DROPPED for key = %ss",GNUNET_h2s(&put->key));
3694     return GNUNET_OK;
3695   }
3696 #endif
3697   GNUNET_STATISTICS_update (GDS_stats,
3698                             gettext_noop
3699                             ("# Bytes received from other peers"), (int64_t) msize,
3700                             GNUNET_NO);
3701
3702   current_best_known_dest = put->best_known_destination;
3703   put_path = (struct GNUNET_PeerIdentity *) &put[1];
3704   payload = &put_path[putlen];
3705   options = ntohl (put->options);
3706   received_intermediate_trail_id = put->intermediate_trail_id;
3707   hop_count = ntohl(put->hop_count);
3708   payload_size = msize - (sizeof (struct PeerPutMessage) +
3709                           putlen * sizeof (struct GNUNET_PeerIdentity));
3710   hop_count++;
3711   switch (GNUNET_BLOCK_get_key (GDS_block_context, ntohl (put->block_type),
3712                                 payload, payload_size, &test_key))
3713   {
3714     case GNUNET_YES:
3715       if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
3716       {
3717         char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
3718         GNUNET_break_op (0);
3719         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3720                     "PUT with key `%s' for block with key %s\n",
3721                      put_s, GNUNET_h2s_full (&test_key));
3722         GNUNET_free (put_s);
3723         return GNUNET_OK;
3724       }
3725     break;
3726     case GNUNET_NO:
3727       GNUNET_break_op (0);
3728       return GNUNET_OK;
3729     case GNUNET_SYSERR:
3730       /* cannot verify, good luck */
3731       break;
3732   }
3733
3734    if (ntohl (put->block_type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
3735   {
3736     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
3737                                    ntohl (put->block_type),
3738                                    GNUNET_BLOCK_EO_NONE,
3739                                    NULL,    /* query */
3740                                    NULL, 0, /* bloom filer */
3741                                    NULL, 0, /* xquery */
3742                                    payload, payload_size))
3743     {
3744     case GNUNET_BLOCK_EVALUATION_OK_MORE:
3745     case GNUNET_BLOCK_EVALUATION_OK_LAST:
3746       break;
3747
3748     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3749     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3750     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
3751     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3752     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3753     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3754     default:
3755       GNUNET_break_op (0);
3756       return GNUNET_OK;
3757     }
3758   }
3759
3760   /* Check if you are already a part of put path. */
3761   unsigned int i;
3762   for (i = 0; i < putlen; i++)
3763   {
3764     if(0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &put_path[i]))
3765     {
3766       putlen = i;
3767       break;
3768     }
3769   }
3770
3771   /* Add yourself to the list. */
3772   struct GNUNET_PeerIdentity pp[putlen + 1];
3773   //if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
3774   if (1)
3775   {
3776     memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
3777     pp[putlen] = my_identity;
3778     putlen++;
3779   }
3780   else
3781     putlen = 0;
3782
3783   memcpy (&key_value, &(put->key), sizeof (uint64_t));
3784   struct Closest_Peer successor;
3785   key_value = GNUNET_ntohll (key_value);
3786   successor = find_local_best_known_next_hop (key_value,
3787                                               GDS_FINGER_TYPE_NON_PREDECESSOR);
3788   next_hop = successor.next_hop;
3789   intermediate_trail_id = successor.trail_id;
3790   best_known_dest = successor.best_known_destination;
3791
3792   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_best_known_dest, &my_identity)))
3793   {
3794     next_routing_hop = GDS_ROUTING_get_next_hop (received_intermediate_trail_id,
3795                                                  GDS_ROUTING_SRC_TO_DEST);
3796     if (NULL != next_routing_hop)
3797     {
3798       next_hop = *next_routing_hop;
3799       intermediate_trail_id = received_intermediate_trail_id;
3800       best_known_dest = current_best_known_dest;
3801     }
3802   }
3803
3804   GDS_CLIENTS_process_put (options,
3805                            ntohl (put->block_type),
3806                            hop_count,
3807                            ntohl (put->desired_replication_level),
3808                            putlen, pp,
3809                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
3810                            &put->key,
3811                            payload,
3812                            payload_size);
3813
3814   /* I am the final destination */
3815   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &best_known_dest))
3816   {
3817     DEBUG("\n PUT_REQUEST_SUCCESSFUL for key = %s",GNUNET_h2s(&put->key));
3818     GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
3819                               &(put->key),putlen, pp, ntohl (put->block_type),
3820                               payload_size, payload);
3821   }
3822   else
3823   {
3824 #if ENABLE_MALICIOUS
3825   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&successor.best_known_destination,
3826                                             &successor.next_hop))
3827   {
3828     struct FingerInfo *next_hop_finger;
3829     unsigned int i;
3830
3831     next_hop_finger = &finger_table[successor.finger_table_index];
3832     for (i = 0; i < next_hop_finger->trails_count; i++)
3833     {
3834       if (GNUNET_YES == next_hop_finger->trail_list[i].is_present)
3835       {
3836         if(0 == next_hop_finger->trail_list[i].trail_length)
3837         {
3838           GDS_NEIGHBOURS_send_put (&put->key,
3839                                   ntohl (put->block_type),ntohl (put->options),
3840                                   ntohl (put->desired_replication_level),
3841                                   best_known_dest, intermediate_trail_id, &next_hop,
3842                                   hop_count, putlen, pp,
3843                                   GNUNET_TIME_absolute_ntoh (put->expiration_time),
3844                                   payload, payload_size);
3845           return GNUNET_OK;
3846         }
3847         next_hop = next_hop_finger->trail_list[i].trail_head->peer;
3848         GDS_NEIGHBOURS_send_put (&put->key,
3849                                  ntohl (put->block_type),ntohl (put->options),
3850                                  ntohl (put->desired_replication_level),
3851                                  best_known_dest,
3852                                  next_hop_finger->trail_list[i].trail_id,
3853                                  &next_hop, hop_count, putlen, pp,
3854                                  GNUNET_TIME_absolute_ntoh (put->expiration_time),
3855                                  payload, payload_size);
3856        }
3857     }
3858     return GNUNET_OK;
3859   }
3860 #endif
3861   GDS_NEIGHBOURS_send_put (&put->key,
3862                            ntohl (put->block_type),ntohl (put->options),
3863                            ntohl (put->desired_replication_level),
3864                            best_known_dest, intermediate_trail_id, &next_hop,
3865                            hop_count, putlen, pp,
3866                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
3867                            payload, payload_size);
3868    }
3869   return GNUNET_OK;
3870 }
3871
3872
3873 /**
3874  * FIXME: Check for loop in the request. If you already are part of get path,
3875  * then you need to reset the get path length.
3876  * Core handler for p2p get requests.
3877  *
3878  * @param cls closure
3879  * @param peer sender of the request
3880  * @param message message
3881  * @return #GNUNET_OK to keep the connection open,
3882  *         #GNUNET_SYSERR to close it (signal serious error)
3883  */
3884 static int
3885 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
3886                     const struct GNUNET_MessageHeader *message)
3887 {
3888   const struct PeerGetMessage *get;
3889   const struct GNUNET_PeerIdentity *get_path;
3890   struct GNUNET_PeerIdentity best_known_dest;
3891   struct GNUNET_PeerIdentity current_best_known_dest;
3892   struct GNUNET_HashCode intermediate_trail_id;
3893   struct GNUNET_HashCode received_intermediate_trail_id;
3894   struct Closest_Peer successor;
3895   struct GNUNET_PeerIdentity next_hop;
3896   struct GNUNET_PeerIdentity *next_routing_hop;
3897   uint32_t get_length;
3898   uint64_t key_value;
3899   uint32_t hop_count;
3900   size_t msize;
3901
3902   msize = ntohs (message->size);
3903   if (msize < sizeof (struct PeerGetMessage))
3904   {
3905     GNUNET_break_op (0);
3906     return GNUNET_YES;
3907   }
3908
3909   get = (const struct PeerGetMessage *)message;
3910   get_length = ntohl (get->get_path_length);
3911   if ((msize <
3912        sizeof (struct PeerGetMessage) +
3913        get_length * sizeof (struct GNUNET_PeerIdentity)) ||
3914        (get_length >
3915         GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
3916   {
3917     GNUNET_break_op (0);
3918     return GNUNET_YES;
3919   }
3920
3921 #if ENABLE_MALICIOUS
3922   if(1 == act_malicious)
3923   {
3924     DEBUG("I am malicious,GET_REQUEST_DROPPED for key = %s. \n",GNUNET_h2s(&get->key));
3925     return GNUNET_OK;
3926   }
3927 #endif
3928   current_best_known_dest = get->best_known_destination;
3929   received_intermediate_trail_id = get->intermediate_trail_id;
3930   get_path = (const struct GNUNET_PeerIdentity *)&get[1];
3931   hop_count = get->hop_count;
3932   hop_count++;
3933
3934
3935   GNUNET_STATISTICS_update (GDS_stats,
3936                             gettext_noop
3937                             ("# Bytes received from other peers"), msize,
3938                             GNUNET_NO);
3939
3940   memcpy (&key_value, &(get->key), sizeof (uint64_t));
3941   key_value = GNUNET_ntohll (key_value);
3942
3943   /* Check if you are already a part of get path. */
3944   unsigned int i;
3945   for (i = 0; i < get_length; i++)
3946   {
3947     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &get_path[i]))
3948     {
3949       get_length = i;
3950       break;
3951     }
3952   }
3953
3954   /* Add yourself in the get path. */
3955   struct GNUNET_PeerIdentity gp[get_length + 1];
3956   memcpy (gp, get_path, get_length * sizeof (struct GNUNET_PeerIdentity));
3957   gp[get_length] = my_identity;
3958   get_length = get_length + 1;
3959   GDS_CLIENTS_process_get (get->options, get->block_type, hop_count,
3960                            get->desired_replication_level, get->get_path_length,
3961                            gp, &get->key);
3962
3963
3964   successor = find_local_best_known_next_hop (key_value,
3965                                                 GDS_FINGER_TYPE_NON_PREDECESSOR);
3966   next_hop = successor.next_hop;
3967   best_known_dest = successor.best_known_destination;
3968   intermediate_trail_id = successor.trail_id;
3969   /* I am not the final destination. I am part of trail to reach final dest. */
3970   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_best_known_dest, &my_identity)))
3971   {
3972     next_routing_hop = GDS_ROUTING_get_next_hop (received_intermediate_trail_id,
3973                                                   GDS_ROUTING_SRC_TO_DEST);
3974     if (NULL != next_routing_hop)
3975     {
3976       next_hop = *next_routing_hop;
3977       best_known_dest = current_best_known_dest;
3978       intermediate_trail_id = received_intermediate_trail_id;
3979     }
3980   }
3981
3982   /* I am the final destination. */
3983   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &best_known_dest))
3984   {
3985     if (1 == get_length)
3986     {
3987       DEBUG("\n GET_REQUEST DONE for key = %s",GNUNET_h2s(&get->key));
3988       GDS_DATACACHE_handle_get (&(get->key),(get->block_type), NULL, 0,
3989                                 NULL, 0, 1, &my_identity, NULL,&my_identity);
3990     }
3991     else
3992     {
3993       GDS_DATACACHE_handle_get (&(get->key),(get->block_type), NULL, 0, NULL, 0,
3994                                 get_length, gp, &gp[get_length - 2],
3995                                 &my_identity);
3996     }
3997   }
3998   else
3999   {
4000
4001 #if ENABLE_MALICIOUS
4002   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&successor.best_known_destination,
4003                                             &successor.next_hop))
4004   {
4005     struct FingerInfo *next_hop_finger;
4006     unsigned int i;
4007
4008     next_hop_finger = &finger_table[successor.finger_table_index];
4009     for (i = 0; i < next_hop_finger->trails_count; i++)
4010     {
4011       if(0 == next_hop_finger->trail_list[i].trail_length)
4012       {
4013         GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options,
4014                                 get->desired_replication_level, best_known_dest,
4015                                 intermediate_trail_id, &next_hop, hop_count,
4016                                 get_length, gp);
4017         return GNUNET_OK;
4018       }
4019       if (GNUNET_YES == next_hop_finger->trail_list[i].is_present)
4020       {
4021         next_hop = next_hop_finger->trail_list[i].trail_head->peer;
4022         GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options,
4023                                  get->desired_replication_level, best_known_dest,
4024                                  next_hop_finger->trail_list[i].trail_id,
4025                                  &next_hop, hop_count,
4026                                  get_length, gp);
4027        }
4028     }
4029     return GNUNET_OK;
4030   }
4031 #endif
4032     GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options,
4033                              get->desired_replication_level, best_known_dest,
4034                              intermediate_trail_id, &next_hop, hop_count,
4035                              get_length, gp);
4036   }
4037   return GNUNET_YES;
4038 }
4039
4040
4041 /**
4042  * Core handler for get result
4043  * @param cls closure
4044  * @param peer sender of the request
4045  * @param message message
4046  * @return #GNUNET_OK to keep the connection open,
4047  *         #GNUNET_SYSERR to close it (signal serious error)
4048  */
4049 static int
4050 handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4051                            const struct GNUNET_MessageHeader *message)
4052 {
4053   const struct PeerGetResultMessage *get_result;
4054   const struct GNUNET_PeerIdentity *get_path;
4055   const struct GNUNET_PeerIdentity *put_path;
4056   const void *payload;
4057   size_t payload_size;
4058   size_t msize;
4059   unsigned int getlen;
4060   unsigned int putlen;
4061   int current_path_index;
4062
4063   msize = ntohs (message->size);
4064   if (msize < sizeof (struct PeerGetResultMessage))
4065   {
4066     GNUNET_break_op (0);
4067     return GNUNET_YES;
4068   }
4069
4070   get_result = (const struct PeerGetResultMessage *)message;
4071   getlen = ntohl (get_result->get_path_length);
4072   putlen = ntohl (get_result->put_path_length);
4073
4074   if ((msize <
4075        sizeof (struct PeerGetResultMessage) +
4076        getlen * sizeof (struct GNUNET_PeerIdentity) +
4077        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
4078       (getlen >
4079        GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity) ||
4080       (putlen >
4081          GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity))))
4082   {
4083     GNUNET_break_op (0);
4084     return GNUNET_YES;
4085   }
4086   DEBUG("GET_RESULT  FOR DATA_SIZE = %lu\n",msize);
4087   GNUNET_STATISTICS_update (GDS_stats,
4088                             gettext_noop
4089                             ("# Bytes received from other peers"), msize,
4090                             GNUNET_NO);
4091
4092   put_path = (const struct GNUNET_PeerIdentity *) &get_result[1];
4093   get_path = &put_path[putlen];
4094   payload = (const void *) &get_path[getlen];
4095   payload_size = msize - (sizeof (struct PeerGetResultMessage) +
4096                          (getlen + putlen) * sizeof (struct GNUNET_PeerIdentity));
4097
4098   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &(get_path[0]))))
4099   {
4100     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (get_result->expiration_time),
4101                               &(get_result->key),
4102                               getlen, get_path, putlen,
4103                               put_path, get_result->type, payload_size, payload);
4104     return GNUNET_YES;
4105   }
4106   else
4107   {
4108     current_path_index = search_my_index (get_path, getlen);
4109     if (-1 == current_path_index )
4110     {
4111       DEBUG ("No entry found in get path.\n");
4112       GNUNET_break (0);
4113       return GNUNET_SYSERR;
4114     }
4115     if((getlen + 1) == current_path_index)
4116     {
4117       DEBUG("Present twice in get path. Not allowed. \n");
4118       GNUNET_break (0);
4119       return GNUNET_SYSERR;
4120     }
4121     GDS_NEIGHBOURS_send_get_result (&(get_result->key), get_result->type,
4122                                     &get_path[current_path_index - 1],
4123                                     &(get_result->querying_peer), putlen, put_path,
4124                                     getlen, get_path,
4125                                     GNUNET_TIME_absolute_ntoh (get_result->expiration_time),
4126                                     payload, payload_size);
4127     return GNUNET_YES;
4128   }
4129   return GNUNET_SYSERR;
4130 }
4131
4132
4133 /**
4134  * Find the next hop to pass trail setup message. First find the local best known
4135  * hop from your own identity, friends and finger. If you were part of trail,
4136  * then get the next hop from routing table. Compare next_hop from routing table
4137  * and local best known hop, and return the closest one to final_dest_finger_val
4138  * @param final_dest_finger_val 64 bit value of finger identity
4139  * @param intermediate_trail_id If you are part of trail to reach to some other
4140  *                              finger, then it is the trail id to reach to
4141  *                              that finger, else set to 0.
4142  * @param is_predecessor Are we looking for closest successor or predecessor.
4143  * @param source Source of trail setup message.
4144  * @param current_dest In case you are part of trail, then finger to which
4145  *                     we should forward the message. Else my own identity
4146  * @return Closest Peer for @a final_dest_finger_val
4147  */
4148 static struct Closest_Peer
4149 get_local_best_known_next_hop (uint64_t final_dest_finger_val,
4150                                struct GNUNET_HashCode intermediate_trail_id,
4151                                unsigned int is_predecessor,
4152                                struct GNUNET_PeerIdentity source,
4153                                struct GNUNET_PeerIdentity *current_dest)
4154 {
4155   struct Closest_Peer peer;
4156
4157   peer = find_local_best_known_next_hop (final_dest_finger_val, is_predecessor);
4158
4159   /* Am I just a part of a trail towards a finger (current_destination)? */
4160   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, current_dest) &&
4161       0 != GNUNET_CRYPTO_cmp_peer_identity (&peer.best_known_destination,
4162                                             current_dest))
4163   {
4164     struct GNUNET_PeerIdentity closest_peer;
4165
4166     /* Select best successor among one found locally and current_destination
4167      * that we got from network.*/
4168     closest_peer = select_closest_peer (&peer.best_known_destination,
4169                                         current_dest,
4170                                         final_dest_finger_val,
4171                                         is_predecessor);
4172
4173     /* Is current dest (end point of the trail of which I am a part) closest_peer? */
4174     if (0 == GNUNET_CRYPTO_cmp_peer_identity (current_dest, &closest_peer))
4175     {
4176       struct GNUNET_PeerIdentity *next_hop;
4177
4178       next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id,
4179                                            GDS_ROUTING_SRC_TO_DEST);
4180       /* next_hop NULL is a valid case. This intermediate trail id is set by
4181        some other finger, and while this trail setup is in progress, that other
4182        peer might have found a better trail ,and send trail teardown message
4183        across the network. In case we got the trail teardown message first,
4184        then next_hop will be NULL. A possible solution could be to keep track
4185        * of all removed trail id, and be sure that there is no other reason . */
4186       if(NULL != next_hop)
4187       {
4188          peer.next_hop = *next_hop;
4189          peer.best_known_destination =  *current_dest;
4190          peer.trail_id = intermediate_trail_id;
4191       }
4192     }
4193   }
4194   return peer;
4195 }
4196
4197
4198 /*
4199  * Core handle for PeerTrailSetupMessage.
4200  * @param cls closure
4201  * @param message message
4202  * @param peer peer identity this notification is about
4203  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4204  */
4205 static int
4206 handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
4207                             const struct GNUNET_MessageHeader *message)
4208 {
4209   const struct PeerTrailSetupMessage *trail_setup;
4210   const struct GNUNET_PeerIdentity *trail_peer_list;
4211   struct GNUNET_PeerIdentity current_dest;
4212   struct FriendInfo *target_friend;
4213   struct GNUNET_PeerIdentity source;
4214   struct GNUNET_HashCode intermediate_trail_id;
4215   struct GNUNET_HashCode trail_id;
4216   unsigned int is_predecessor;
4217   uint32_t trail_length;
4218   uint64_t final_dest_finger_val;
4219   int i;
4220   size_t msize;
4221
4222   msize = ntohs (message->size);
4223   if (msize < sizeof (struct PeerTrailSetupMessage))
4224   {
4225     GNUNET_break_op (0);
4226     return GNUNET_SYSERR;
4227   }
4228
4229   trail_setup = (const struct PeerTrailSetupMessage *) message;
4230   if ((msize - sizeof (struct PeerTrailSetupMessage)) %
4231       sizeof (struct GNUNET_PeerIdentity) != 0)
4232   {
4233     GNUNET_break_op (0);
4234     return GNUNET_OK;
4235   }
4236   trail_length = (msize - sizeof (struct PeerTrailSetupMessage))/
4237                   sizeof (struct GNUNET_PeerIdentity);
4238
4239   GNUNET_STATISTICS_update (GDS_stats,
4240                             gettext_noop
4241                             ("# Bytes received from other peers"), msize,
4242                             GNUNET_NO);
4243
4244   trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_setup[1];
4245   current_dest = trail_setup->best_known_destination;
4246   trail_id = trail_setup->trail_id;
4247   final_dest_finger_val =
4248           GNUNET_ntohll (trail_setup->final_destination_finger_value);
4249   source = trail_setup->source_peer;
4250   is_predecessor = ntohl (trail_setup->is_predecessor);
4251   intermediate_trail_id = trail_setup->intermediate_trail_id;
4252
4253   /* Did the friend insert its ID in the trail list? */
4254   if (trail_length > 0 &&
4255       0 != memcmp (&trail_peer_list[trail_length-1], peer, sizeof (struct GNUNET_PeerIdentity)))
4256   {
4257     GNUNET_break_op (0);
4258     return GNUNET_SYSERR;
4259   }
4260
4261    /* If I was the source and got the message back, then set trail length to 0.*/
4262   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &source))
4263   {
4264     trail_length = 0;
4265   }
4266
4267   /* Check if you are present in the trail seen so far? */
4268   for (i = 0; i < trail_length ; i++)
4269   {
4270     if(0 == GNUNET_CRYPTO_cmp_peer_identity(&trail_peer_list[i],&my_identity))
4271     {
4272       /* We will add ourself later in code, if NOT destination. */
4273       trail_length = i;
4274       break;
4275     }
4276   }
4277
4278   /* Is my routing table full?  */
4279   if (GNUNET_YES == GDS_ROUTING_threshold_reached())
4280   {
4281     if (trail_length > 0)
4282       target_friend =
4283                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
4284                                                       &trail_peer_list[trail_length - 1]);
4285     else
4286       target_friend =
4287                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
4288                                                       &source);
4289     if(NULL == target_friend)
4290     {
4291       DEBUG ("\n friend not found");
4292       GNUNET_break(0);
4293       return GNUNET_OK;
4294     }
4295     GDS_NEIGHBOURS_send_trail_rejection (source, final_dest_finger_val,
4296                                          my_identity, is_predecessor,
4297                                          trail_peer_list, trail_length,
4298                                          trail_id, target_friend,
4299                                          CONGESTION_TIMEOUT);
4300     return GNUNET_OK;
4301   }
4302
4303   /* Get the next hop to forward the trail setup request. */
4304   struct Closest_Peer next_peer =
4305           get_local_best_known_next_hop (final_dest_finger_val,
4306                                          intermediate_trail_id,
4307                                          is_predecessor,
4308                                          source,
4309                                          &current_dest);
4310
4311   /* Am I the final destination? */
4312   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&next_peer.best_known_destination,
4313                                              &my_identity)))
4314   {
4315     if(0 == GNUNET_CRYPTO_cmp_peer_identity (&source, &my_identity))
4316     {
4317       finger_table_add (my_identity, NULL, 0, is_predecessor,
4318                         final_dest_finger_val, trail_id);
4319       return GNUNET_OK;
4320     }
4321
4322     if (trail_length > 0)
4323       target_friend =
4324               GNUNET_CONTAINER_multipeermap_get (friend_peermap,
4325                                                  &trail_peer_list[trail_length-1]);
4326     else
4327       target_friend =
4328               GNUNET_CONTAINER_multipeermap_get (friend_peermap, &source);
4329     if (NULL == target_friend)
4330     {
4331       GNUNET_break_op (0);
4332       return GNUNET_SYSERR;
4333     }
4334     GDS_ROUTING_add (trail_id, target_friend->id, my_identity);
4335     GDS_NEIGHBOURS_send_trail_setup_result (source,
4336                                             my_identity,
4337                                             target_friend, trail_length,
4338                                             trail_peer_list,
4339                                             is_predecessor,
4340                                             final_dest_finger_val,trail_id);
4341   }
4342   else /* I'm not the final destination. */
4343   {
4344     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
4345                                                        &next_peer.next_hop);
4346     if(NULL == target_friend)
4347     {
4348       DEBUG ("\n target friend not found for peer = %s", GNUNET_i2s(&next_peer.next_hop));
4349       GNUNET_break (0);
4350       return GNUNET_OK;
4351     }
4352     if (0 != GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &source))
4353     {
4354       /* Add yourself to list of peers. */
4355       struct GNUNET_PeerIdentity peer_list[trail_length + 1];
4356
4357       memcpy (peer_list, trail_peer_list,
4358               trail_length * sizeof (struct GNUNET_PeerIdentity));
4359       peer_list[trail_length] = my_identity;
4360       GDS_NEIGHBOURS_send_trail_setup (source,
4361                                        final_dest_finger_val,
4362                                        next_peer.best_known_destination,
4363                                        target_friend, trail_length + 1, peer_list,
4364                                        is_predecessor, trail_id,
4365                                        next_peer.trail_id);
4366     }
4367     else
4368         GDS_NEIGHBOURS_send_trail_setup (source,
4369                                          final_dest_finger_val,
4370                                          next_peer.best_known_destination,
4371                                          target_friend, 0, NULL,
4372                                          is_predecessor, trail_id,
4373                                          next_peer.trail_id);
4374   }
4375   return GNUNET_OK;
4376 }
4377
4378
4379 /**
4380  * Core handle for p2p trail setup result messages.
4381  * @param closure
4382  * @param message message
4383  * @param peer sender of this message.
4384  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4385  */
4386 static int
4387 handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
4388                                   const struct GNUNET_MessageHeader *message)
4389 {
4390   const struct PeerTrailSetupResultMessage *trail_result;
4391   const struct GNUNET_PeerIdentity *trail_peer_list;
4392   struct GNUNET_PeerIdentity next_hop;
4393   struct FriendInfo *target_friend;
4394   struct GNUNET_PeerIdentity querying_peer;
4395   struct GNUNET_PeerIdentity finger_identity;
4396   uint32_t trail_length;
4397   uint64_t ulitmate_destination_finger_value;
4398   uint32_t is_predecessor;
4399   struct GNUNET_HashCode trail_id;
4400   int my_index;
4401   size_t msize;
4402
4403   msize = ntohs (message->size);
4404   if (msize < sizeof (struct PeerTrailSetupResultMessage))
4405   {
4406     GNUNET_break_op (0);
4407     return GNUNET_YES;
4408   }
4409
4410   trail_result = (const struct PeerTrailSetupResultMessage *) message;
4411   if ((msize - sizeof (struct PeerTrailSetupResultMessage)) %
4412       sizeof (struct GNUNET_PeerIdentity) != 0)
4413   {
4414     GNUNET_break_op (0);
4415     return GNUNET_OK;
4416   }
4417   trail_length = (msize - sizeof (struct PeerTrailSetupResultMessage))/
4418                   sizeof (struct GNUNET_PeerIdentity);
4419
4420   GNUNET_STATISTICS_update (GDS_stats,
4421                             gettext_noop
4422                             ("# Bytes received from other peers"), msize,
4423                             GNUNET_NO);
4424
4425   is_predecessor = ntohl (trail_result->is_predecessor);
4426   querying_peer = trail_result->querying_peer;
4427   finger_identity = trail_result->finger_identity;
4428   trail_id = trail_result->trail_id;
4429   trail_peer_list = (const struct GNUNET_PeerIdentity *) &trail_result[1];
4430   ulitmate_destination_finger_value =
4431           GNUNET_ntohll (trail_result->ulitmate_destination_finger_value);
4432
4433   /* Am I the one who initiated the query? */
4434   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer, &my_identity)))
4435   {
4436     /* Check that you got the message from the correct peer. */
4437     if (trail_length > 0)
4438     {
4439       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[0],
4440                                                           peer));
4441     }
4442     else
4443     {
4444       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
4445                                                           peer));
4446     }
4447     GDS_ROUTING_add (trail_id, my_identity, *peer);
4448     finger_table_add (finger_identity, trail_peer_list, trail_length,
4449                       is_predecessor, ulitmate_destination_finger_value, trail_id);
4450     return GNUNET_YES;
4451   }
4452
4453   /* Get my location in the trail. */
4454   my_index = search_my_index (trail_peer_list, trail_length);
4455   if (-1 == my_index)
4456   {
4457     DEBUG ("Not found in trail\n");
4458     GNUNET_break_op(0);
4459     return GNUNET_SYSERR;
4460   }
4461   //TODO; return -2.
4462   if ((trail_length + 1) == my_index)
4463   {
4464     DEBUG ("Found twice in trail.\n");
4465     GNUNET_break_op(0);
4466     return GNUNET_SYSERR;
4467   }
4468
4469   //TODO; Refactor code here and above to check if sender peer is correct
4470   if (my_index == 0)
4471   {
4472     if(trail_length > 1)
4473       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[1],
4474                                                           peer));
4475     else
4476       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
4477                                                           peer));
4478     next_hop = trail_result->querying_peer;
4479   }
4480   else
4481   {
4482     if(my_index == trail_length - 1)
4483     {
4484       GNUNET_assert(0 ==
4485                     GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
4486                                                      peer));
4487     }
4488     else
4489       GNUNET_assert(0 ==
4490                     GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[my_index + 1],
4491                                                       peer));
4492     next_hop = trail_peer_list[my_index - 1];
4493   }
4494
4495   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
4496   if (NULL == target_friend)
4497   {
4498     GNUNET_break_op (0);
4499     return GNUNET_SYSERR;
4500   }
4501   GDS_ROUTING_add (trail_id, next_hop, *peer);
4502   GDS_NEIGHBOURS_send_trail_setup_result (querying_peer, finger_identity,
4503                                           target_friend, trail_length, trail_peer_list,
4504                                           is_predecessor,
4505                                           ulitmate_destination_finger_value,
4506                                           trail_id);
4507   return GNUNET_OK;
4508 }
4509
4510
4511 /**
4512  * Invert the trail.
4513  * @param trail Trail to be inverted
4514  * @param trail_length Total number of peers in the trail.
4515  * @return Updated trail
4516  */
4517 static struct GNUNET_PeerIdentity *
4518 invert_trail (const struct GNUNET_PeerIdentity *trail,
4519               unsigned int trail_length)
4520 {
4521   int i;
4522   int j;
4523   struct GNUNET_PeerIdentity *inverted_trail;
4524
4525   inverted_trail = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity) *
4526                                   trail_length);
4527   i = 0;
4528   j = trail_length - 1;
4529   while (i < trail_length)
4530   {
4531     inverted_trail[i] = trail[j];
4532     i++;
4533     j--;
4534   }
4535
4536   GNUNET_assert(NULL != GNUNET_CONTAINER_multipeermap_get(friend_peermap,
4537                                                           &inverted_trail[0]));
4538   return inverted_trail;
4539 }
4540
4541
4542 /**
4543  * Return the shortest trail among all the trails to reach to finger from me.
4544  * @param finger Finger
4545  * @param shortest_trail_length[out] Trail length of shortest trail from me
4546  *                                   to @a finger
4547  * @return Shortest trail.
4548  */
4549 static struct GNUNET_PeerIdentity *
4550 get_shortest_trail (struct FingerInfo *finger,
4551                     unsigned int *trail_length)
4552 {
4553   struct Trail *trail;
4554   unsigned int flag = 0;
4555   unsigned int shortest_trail_index = 0;
4556   int shortest_trail_length = -1;
4557   struct Trail_Element *trail_element;
4558   struct GNUNET_PeerIdentity *trail_list;
4559   unsigned int i;
4560
4561   /* Get the shortest trail to reach to current successor. */
4562   for (i = 0; i < finger->trails_count; i++)
4563   {
4564     trail = &finger->trail_list[i];
4565
4566     if (0 == flag)
4567     {
4568       shortest_trail_index = i;
4569       shortest_trail_length = trail->trail_length;
4570       flag = 1;
4571       continue;
4572     }
4573
4574     if (shortest_trail_length > trail->trail_length)
4575     {
4576       shortest_trail_index = i;
4577       shortest_trail_length = trail->trail_length;
4578     }
4579     continue;
4580   }
4581
4582   /* Copy the shortest trail and return. */
4583   trail = &finger->trail_list[shortest_trail_index];
4584   trail_element = trail->trail_head;
4585
4586   trail_list = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity)*
4587                               shortest_trail_length);
4588
4589   for(i = 0; i < shortest_trail_length; i++,trail_element = trail_element->next)
4590   {
4591     trail_list[i] = trail_element->peer;
4592   }
4593
4594   GNUNET_assert(shortest_trail_length != -1);
4595
4596   *trail_length = shortest_trail_length;
4597   return trail_list;
4598 }
4599
4600
4601 /**
4602  * Check if trail_1 and trail_2 have any common element. If yes then join
4603  * them at common element. trail_1 always preceeds trail_2 in joined trail.
4604  * @param trail_1 Trail from source to me, NOT including endpoints.
4605  * @param trail_1_len Total number of peers @a trail_1
4606  * @param trail_2 Trail from me to current predecessor, NOT including endpoints.
4607  * @param trail_2_len Total number of peers @a trail_2
4608  * @param joined_trail_len Total number of peers in combined trail of trail_1
4609  *                          trail_2.
4610  * @return Joined trail.
4611  */
4612 static struct GNUNET_PeerIdentity *
4613 check_for_duplicate_entries (const struct GNUNET_PeerIdentity *trail_1,
4614                              unsigned int trail_1_len,
4615                              struct GNUNET_PeerIdentity *trail_2,
4616                              unsigned int trail_2_len,
4617                              unsigned int *joined_trail_len)
4618 {
4619   struct GNUNET_PeerIdentity *joined_trail;
4620   unsigned int i;
4621   unsigned int j;
4622   unsigned int k;
4623
4624   for (i = 0; i < trail_1_len; i++)
4625   {
4626     for (j = 0; j < trail_2_len; j++)
4627     {
4628       if(0 != GNUNET_CRYPTO_cmp_peer_identity (&trail_1[i],&trail_2[j]))
4629         continue;
4630
4631       *joined_trail_len = i + (trail_2_len - j);
4632       joined_trail = GNUNET_malloc (*joined_trail_len *
4633                                     sizeof(struct GNUNET_PeerIdentity));
4634
4635
4636       /* Copy all the elements from 0 to i into joined_trail. */
4637       for(k = 0; k < ( i+1); k++)
4638       {
4639         joined_trail[k] = trail_1[k];
4640       }
4641
4642       /* Increment j as entry stored is same as entry stored at i*/
4643       j = j+1;
4644
4645       /* Copy all the elements from j to trail_2_len-1 to joined trail.*/
4646       while(k <= (*joined_trail_len - 1))
4647       {
4648         joined_trail[k] = trail_2[j];
4649         j++;
4650         k++;
4651       }
4652
4653       return joined_trail;
4654     }
4655   }
4656
4657   /* Here you should join the  trails. */
4658   *joined_trail_len = trail_1_len + trail_2_len + 1;
4659   joined_trail = GNUNET_malloc (*joined_trail_len *
4660                                 sizeof(struct GNUNET_PeerIdentity));
4661
4662
4663   for(i = 0; i < trail_1_len;i++)
4664   {
4665     joined_trail[i] = trail_1[i];
4666   }
4667
4668   joined_trail[i] = my_identity;
4669   i++;
4670
4671   for (j = 0; i < *joined_trail_len; i++,j++)
4672   {
4673     joined_trail[i] = trail_2[j];
4674   }
4675
4676   return joined_trail;
4677 }
4678
4679
4680 /**
4681  * Return the trail from source to my current predecessor. Check if source
4682  * is already part of the this trail, if yes then return the shorten trail.
4683  * @param current_trail Trail from source to me, NOT including the endpoints.
4684  * @param current_trail_length Number of peers in @a current_trail.
4685  * @param trail_src_to_curr_pred_length[out] Number of peers in trail from
4686  *                                           source to my predecessor, NOT including
4687  *                                           the endpoints.
4688  * @return Trail from source to my predecessor.
4689  */
4690 static struct GNUNET_PeerIdentity *
4691 get_trail_src_to_curr_pred (struct GNUNET_PeerIdentity source_peer,
4692                             const struct GNUNET_PeerIdentity *trail_src_to_me,
4693                             unsigned int trail_src_to_me_len,
4694                             unsigned int *trail_src_to_curr_pred_length)
4695 {
4696   struct GNUNET_PeerIdentity *trail_me_to_curr_pred;
4697   struct GNUNET_PeerIdentity *trail_src_to_curr_pred;
4698   unsigned int trail_me_to_curr_pred_length;
4699   struct FingerInfo *current_predecessor;
4700   int i;
4701   unsigned int j;
4702   unsigned int len;
4703
4704   current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
4705
4706   /* Check if trail_src_to_me contains current_predecessor. */
4707   for (i = 0; i < trail_src_to_me_len; i++)
4708   {
4709     if (0 != GNUNET_CRYPTO_cmp_peer_identity(&trail_src_to_me[i],
4710                                              &current_predecessor->finger_identity))
4711       continue;
4712
4713
4714     *trail_src_to_curr_pred_length = i;
4715
4716     if(0 == i)
4717       return NULL;
4718
4719      trail_src_to_curr_pred = GNUNET_malloc (*trail_src_to_curr_pred_length *
4720                                               sizeof(struct GNUNET_PeerIdentity));
4721      for (j = 0; j < i; j++)
4722        trail_src_to_curr_pred[j] = trail_src_to_me[j];
4723      return trail_src_to_curr_pred;
4724   }
4725
4726
4727   trail_me_to_curr_pred = get_shortest_trail (current_predecessor,
4728                                               &trail_me_to_curr_pred_length);
4729
4730   /* Check if trail contains the source_peer. */
4731   for (i = trail_me_to_curr_pred_length - 1; i >= 0; i--)
4732   {
4733     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&source_peer,
4734                                               &trail_me_to_curr_pred[i]))
4735       continue;
4736
4737     /* Source is NOT part of trail. */
4738     i++;
4739
4740     /* Source is the last element in the trail to reach to my pred.
4741        Source is direct friend of the pred. */
4742     if (trail_me_to_curr_pred_length == i)
4743     {
4744       *trail_src_to_curr_pred_length = 0;
4745       GNUNET_free_non_null (trail_me_to_curr_pred);
4746       return NULL;
4747     }
4748
4749     *trail_src_to_curr_pred_length = trail_me_to_curr_pred_length - i;
4750     trail_src_to_curr_pred = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity)*
4751                                             *trail_src_to_curr_pred_length);
4752
4753     for (j = 0; j < *trail_src_to_curr_pred_length; i++,j++)
4754       trail_src_to_curr_pred[j] = trail_me_to_curr_pred[i];
4755     GNUNET_free_non_null (trail_me_to_curr_pred);
4756     return trail_src_to_curr_pred;
4757   }
4758
4759   trail_src_to_curr_pred = check_for_duplicate_entries (trail_src_to_me,
4760                                                         trail_src_to_me_len,
4761                                                         trail_me_to_curr_pred,
4762                                                         trail_me_to_curr_pred_length,
4763                                                         &len);
4764   *trail_src_to_curr_pred_length = len;
4765   GNUNET_free_non_null(trail_me_to_curr_pred);
4766   return trail_src_to_curr_pred;
4767 }
4768
4769
4770 /**
4771  * Add finger as your predecessor. To add, first generate a new trail id, invert
4772  * the trail to get the trail from me to finger, add an entry in your routing
4773  * table, send add trail message to peers which are part of trail from me to
4774  * finger and add finger in finger table.
4775  * @param finger
4776  * @param trail
4777  * @param trail_length
4778  */
4779 static void
4780 update_predecessor (struct GNUNET_PeerIdentity finger,
4781                     struct GNUNET_PeerIdentity *trail,
4782                     unsigned int trail_length)
4783 {
4784   struct GNUNET_HashCode trail_to_new_predecessor_id;
4785   struct GNUNET_PeerIdentity *trail_to_new_predecessor;
4786   struct FriendInfo *target_friend;
4787
4788   /* Generate trail id for trail from me to new predecessor = finger. */
4789   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
4790                               &trail_to_new_predecessor_id,
4791                               sizeof (trail_to_new_predecessor_id));
4792
4793   if (0 == trail_length)
4794   {
4795     trail_to_new_predecessor = NULL;
4796     GDS_ROUTING_add (trail_to_new_predecessor_id, my_identity, finger);
4797     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger);
4798     if (NULL == target_friend)
4799     {
4800       GNUNET_break (0);
4801       return;
4802     }
4803   }
4804   else
4805   {
4806     /* Invert the trail to get the trail from me to finger, NOT including the
4807        endpoints.*/
4808     GNUNET_assert(NULL != GNUNET_CONTAINER_multipeermap_get(friend_peermap,
4809                                                             &trail[trail_length-1]));
4810     trail_to_new_predecessor = invert_trail (trail, trail_length);
4811
4812     /* Add an entry in your routing table. */
4813     GDS_ROUTING_add (trail_to_new_predecessor_id,
4814                      my_identity,
4815                      trail_to_new_predecessor[0]);
4816
4817     GNUNET_assert (NULL != (target_friend =
4818                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
4819                                                       &trail_to_new_predecessor[0])));
4820   }
4821
4822   /* Add entry in routing table of all peers that are part of trail from me
4823      to finger, including finger. */
4824   GDS_NEIGHBOURS_send_add_trail (my_identity,
4825                                  finger,
4826                                  trail_to_new_predecessor_id,
4827                                  trail_to_new_predecessor,
4828                                  trail_length,
4829                                  target_friend);
4830
4831   add_new_finger (finger, trail_to_new_predecessor, trail_length,
4832                   trail_to_new_predecessor_id, PREDECESSOR_FINGER_ID);
4833   GNUNET_free_non_null(trail_to_new_predecessor);
4834 }
4835
4836
4837 /*
4838  * Check if you already have a predecessor. If not then add finger as your
4839  * predecessor. If you have predecessor, then compare two peer identites.
4840  * If finger is correct predecessor, then remove the old entry, add finger in
4841  * finger table and send add_trail message to add the trail in the routing
4842  * table of all peers which are part of trail to reach from me to finger.
4843  * @param finger New peer which may be our predecessor.
4844  * @param trail List of peers to reach from @finger to me.
4845  * @param trail_length Total number of peer in @a trail.
4846  */
4847 static void
4848 compare_and_update_predecessor (struct GNUNET_PeerIdentity finger,
4849                                 struct GNUNET_PeerIdentity *trail,
4850                                 unsigned int trail_length)
4851 {
4852   struct FingerInfo *current_predecessor;
4853   struct GNUNET_PeerIdentity closest_peer;
4854   uint64_t predecessor_value;
4855   unsigned int is_predecessor = 1;
4856
4857   current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
4858   GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&finger, &my_identity));
4859
4860   /* No predecessor. Add finger as your predecessor. */
4861   if (GNUNET_NO == current_predecessor->is_present)
4862   {
4863     update_predecessor (finger, trail, trail_length);
4864     return;
4865   }
4866
4867   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&current_predecessor->finger_identity,
4868                                             &finger))
4869   {
4870     return;
4871   }
4872
4873   predecessor_value = compute_finger_identity_value (PREDECESSOR_FINGER_ID);
4874   closest_peer = select_closest_peer (&finger,
4875                                       &current_predecessor->finger_identity,
4876                                       predecessor_value, is_predecessor);
4877
4878   /* Finger is the closest predecessor. Remove the existing one and add the new
4879      one. */
4880   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&closest_peer, &finger))
4881   {
4882     remove_existing_finger (current_predecessor, PREDECESSOR_FINGER_ID);
4883     update_predecessor (finger, trail, trail_length);
4884     return;
4885   }
4886   return;
4887 }
4888
4889
4890 /*
4891  * Core handle for p2p verify successor messages.
4892  * @param cls closure
4893  * @param message message
4894  * @param peer peer identity this notification is about
4895  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4896  */
4897 static int
4898 handle_dht_p2p_verify_successor(void *cls,
4899                                 const struct GNUNET_PeerIdentity *peer,
4900                                 const struct GNUNET_MessageHeader *message)
4901 {
4902   const struct PeerVerifySuccessorMessage *vsm;
4903   struct GNUNET_HashCode trail_id;
4904   struct GNUNET_PeerIdentity successor;
4905   struct GNUNET_PeerIdentity source_peer;
4906   struct GNUNET_PeerIdentity *trail;
4907   struct GNUNET_PeerIdentity *next_hop;
4908   struct FingerInfo current_predecessor;
4909   struct FriendInfo *target_friend;
4910   unsigned int trail_src_to_curr_pred_len = 0;
4911   struct GNUNET_PeerIdentity *trail_src_to_curr_pred;
4912   unsigned int trail_length;
4913   size_t msize;
4914
4915   msize = ntohs (message->size);
4916
4917   if (msize < sizeof (struct PeerVerifySuccessorMessage))
4918   {
4919     GNUNET_break_op (0);
4920     return GNUNET_YES;
4921   }
4922
4923   vsm = (const struct PeerVerifySuccessorMessage *) message;
4924   trail_length = (msize - sizeof (struct PeerVerifySuccessorMessage))/
4925                   sizeof (struct GNUNET_PeerIdentity);
4926   if ((msize - sizeof (struct PeerVerifySuccessorMessage)) %
4927       sizeof (struct GNUNET_PeerIdentity) != 0)
4928   {
4929     GNUNET_break_op (0);
4930     return GNUNET_OK;
4931   }
4932
4933   GNUNET_STATISTICS_update (GDS_stats,
4934                             gettext_noop
4935                             ("# Bytes received from other peers"), msize,
4936                             GNUNET_NO);
4937
4938   trail_id = vsm->trail_id;
4939   source_peer = vsm->source_peer;
4940   successor = vsm->successor;
4941   trail = (struct GNUNET_PeerIdentity *)&vsm[1];
4942
4943   /* I am NOT the successor of source_peer. Pass the message to next_hop on
4944    * the trail. */
4945   if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&successor, &my_identity)))
4946   {
4947     next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
4948     if (NULL == next_hop)
4949     {
4950       return GNUNET_OK;
4951     }
4952
4953     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
4954
4955     if(NULL == target_friend)
4956     {
4957       GNUNET_break_op(0);
4958       return GNUNET_OK;
4959     }
4960     GDS_NEIGHBOURS_send_verify_successor_message (source_peer, successor,
4961                                                   trail_id, trail, trail_length,
4962                                                   target_friend);
4963     return GNUNET_OK;
4964   }
4965
4966   /* I am the destination of this message. */
4967
4968   /* Check if the source_peer could be our predecessor and if yes then update
4969    * it.  */
4970   compare_and_update_predecessor (source_peer, trail, trail_length);
4971   current_predecessor = finger_table[PREDECESSOR_FINGER_ID];
4972
4973   /* Is source of this message NOT my predecessor. */
4974   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_predecessor.finger_identity,
4975                                              &source_peer)))
4976   {
4977     trail_src_to_curr_pred =
4978               get_trail_src_to_curr_pred (source_peer,
4979                                           trail,
4980                                           trail_length,
4981                                           &trail_src_to_curr_pred_len);
4982   }
4983   else
4984   {
4985     trail_src_to_curr_pred_len = trail_length;
4986     unsigned int i;
4987
4988     trail_src_to_curr_pred =
4989             GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity)
4990                            *trail_src_to_curr_pred_len);
4991     for(i = 0; i < trail_src_to_curr_pred_len; i++)
4992     {
4993       trail_src_to_curr_pred[i] = trail[i];
4994     }
4995   }
4996
4997   GNUNET_assert (NULL !=
4998                 (target_friend =
4999                  GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)));
5000   GDS_NEIGHBOURS_send_verify_successor_result (source_peer, my_identity,
5001                                                current_predecessor.finger_identity,
5002                                                trail_id, trail_src_to_curr_pred,
5003                                                trail_src_to_curr_pred_len,
5004                                                GDS_ROUTING_DEST_TO_SRC,
5005                                                target_friend);
5006   GNUNET_free_non_null(trail_src_to_curr_pred);
5007   return GNUNET_OK;
5008 }
5009
5010
5011 /**
5012  * If the trail from me to my probable successor contains a friend not
5013  * at index 0, then we can shorten the trail.
5014  * @param probable_successor Peer which is our probable successor
5015  * @param trail_me_to_probable_successor Peers in path from me to my probable
5016  *                                       successor, NOT including the endpoints.
5017  * @param trail_me_to_probable_successor_len Total number of peers in
5018  *                                           @a trail_me_to_probable_succesor.
5019  * @return Updated trail, if any friend found.
5020  *         Else the trail_me_to_probable_successor.
5021  */
5022 struct GNUNET_PeerIdentity *
5023 check_trail_me_to_probable_succ (struct GNUNET_PeerIdentity probable_successor,
5024                                  const struct GNUNET_PeerIdentity *trail_me_to_probable_successor,
5025                                  unsigned int trail_me_to_probable_successor_len,
5026                                  unsigned int *trail_to_new_successor_length)
5027 {
5028   unsigned int i;
5029   unsigned int j;
5030   struct GNUNET_PeerIdentity *trail_to_new_successor;
5031
5032   /* Probable successor is  a friend */
5033   if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5034                                                  &probable_successor))
5035   {
5036     trail_to_new_successor = NULL;
5037     *trail_to_new_successor_length = 0;
5038     return trail_to_new_successor;
5039   }
5040
5041   /* Is there any friend of yours in this trail. */
5042   if(trail_me_to_probable_successor_len > 1)
5043   {
5044     for (i = trail_me_to_probable_successor_len - 1; i > 0; i--)
5045     {
5046       if (NULL == GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5047                                                      &trail_me_to_probable_successor[i]))
5048         continue;
5049
5050       *trail_to_new_successor_length = (trail_me_to_probable_successor_len - i);
5051       trail_to_new_successor = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity)*
5052                                                 *trail_to_new_successor_length);
5053
5054
5055       for(j = 0; j < *trail_to_new_successor_length; i++,j++)
5056       {
5057         trail_to_new_successor[j] = trail_me_to_probable_successor[i];
5058       }
5059
5060       return trail_to_new_successor;
5061     }
5062   }
5063
5064   *trail_to_new_successor_length = trail_me_to_probable_successor_len;
5065   return (struct GNUNET_PeerIdentity*)trail_me_to_probable_successor;
5066 }
5067
5068 // TODO: Move up
5069 struct SendNotifyContext
5070 {
5071   struct GNUNET_PeerIdentity source_peer;
5072   struct GNUNET_PeerIdentity successor;
5073   struct GNUNET_PeerIdentity *successor_trail;
5074   unsigned int successor_trail_length;
5075   struct GNUNET_HashCode succesor_trail_id;
5076   struct FriendInfo *target_friend;
5077   unsigned int num_retries_scheduled;
5078 };
5079
5080 void
5081 send_notify_new_successor (void *cls,
5082                            const struct GNUNET_SCHEDULER_TaskContext
5083                            * tc);
5084
5085 /**
5086  * Check if the peer which sent us verify successor result message is still ours
5087  * successor or not. If not, then compare existing successor and probable successor.
5088  * In case probable successor is the correct successor, remove the existing
5089  * successor. Add probable successor as new successor. Send notify new successor
5090  * message to new successor.
5091  * @param curr_succ Peer to which we sent the verify successor message. It may
5092  * or may not be our real current successor, as we may have few iterations of
5093  * find finger trail task.
5094  * @param probable_successor Peer which should be our successor accroding to @a
5095  *                           curr_succ
5096  * @param trail List of peers to reach from me to @a probable successor, NOT including
5097  *              endpoints.
5098  * @param trail_length Total number of peers in @a trail.
5099  */
5100 static void
5101 compare_and_update_successor (struct GNUNET_PeerIdentity curr_succ,
5102                               struct GNUNET_PeerIdentity probable_successor,
5103                               const struct GNUNET_PeerIdentity *trail,
5104                               unsigned int trail_length)
5105 {
5106   struct FingerInfo *current_successor;
5107   struct GNUNET_PeerIdentity closest_peer;
5108   struct GNUNET_HashCode trail_id;
5109   struct GNUNET_PeerIdentity *trail_me_to_probable_succ;
5110   struct FriendInfo *target_friend;
5111   unsigned int trail_me_to_probable_succ_len;
5112   unsigned int is_predecessor = 0;
5113   uint64_t successor_value;
5114
5115   current_successor = &finger_table[0];
5116   successor_value = compute_finger_identity_value(0);
5117
5118   /* If probable successor is same as current_successor, do nothing. */
5119   if(0 == GNUNET_CRYPTO_cmp_peer_identity (&probable_successor,
5120                                            &current_successor->finger_identity))
5121   {
5122     if ((NULL != GDS_stats))
5123     {
5124       char *my_id_str;
5125       uint64_t succ;
5126       char *key;
5127       uint64_t my_id;
5128       memcpy (&my_id, &my_identity, sizeof(uint64_t));
5129       my_id_str = GNUNET_strdup (GNUNET_i2s_full (&my_identity));
5130       memcpy(&succ, &current_successor->finger_identity, sizeof(uint64_t));
5131       succ = GNUNET_ntohll(succ);
5132       GNUNET_asprintf (&key, "XDHT:%s:", my_id_str);
5133       GNUNET_free (my_id_str);
5134
5135       GNUNET_STATISTICS_set (GDS_stats, key, succ, 0);
5136       GNUNET_free (key);
5137     }
5138     if (send_verify_successor_task == NULL)
5139       send_verify_successor_task =
5140               GNUNET_SCHEDULER_add_delayed(verify_successor_next_send_time,
5141                                            &send_verify_successor_message,
5142                                            NULL);
5143     return;
5144   }
5145   closest_peer = select_closest_peer (&probable_successor,
5146                                       &current_successor->finger_identity,
5147                                       successor_value, is_predecessor);
5148
5149   /* If the current_successor in the finger table is closest, then do nothing. */
5150   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&closest_peer ,
5151                                             &current_successor->finger_identity))
5152   {
5153     //FIXME: Is this a good place to return the stats.
5154     if ((NULL != GDS_stats))
5155     {
5156       char *my_id_str;
5157       uint64_t succ;
5158       char *key;
5159
5160       my_id_str = GNUNET_strdup (GNUNET_i2s_full (&my_identity));
5161       memcpy(&succ, &current_successor->finger_identity, sizeof(uint64_t));
5162       GNUNET_asprintf (&key, "XDHT:%s:", my_id_str);
5163       GNUNET_free (my_id_str);
5164       GNUNET_STATISTICS_set (GDS_stats, key, succ, 0);
5165       GNUNET_free (key);
5166     }
5167
5168     if(0 == successor_times)
5169     {
5170 //      successor_times = 3;
5171       verify_successor_next_send_time =
5172               GNUNET_TIME_STD_BACKOFF (verify_successor_next_send_time);
5173     }
5174     else
5175       successor_times--;
5176
5177
5178     if (send_verify_successor_task == NULL)
5179       send_verify_successor_task =
5180               GNUNET_SCHEDULER_add_delayed(verify_successor_next_send_time,
5181                                            &send_verify_successor_message,
5182                                            NULL);
5183     return;
5184   }
5185
5186   /* Probable successor is the closest peer.*/
5187   if(trail_length > 0)
5188   {
5189     GNUNET_assert(NULL != GNUNET_CONTAINER_multipeermap_get(friend_peermap,
5190                                                             &trail[0]));
5191   }
5192   else
5193   {
5194     GNUNET_assert(NULL != GNUNET_CONTAINER_multipeermap_get(friend_peermap,
5195                                                             &probable_successor));
5196   }
5197
5198   trail_me_to_probable_succ_len = 0;
5199   trail_me_to_probable_succ =
5200           check_trail_me_to_probable_succ (probable_successor,
5201                                            trail, trail_length,
5202                                            &trail_me_to_probable_succ_len);
5203
5204   /* Remove the existing successor. */
5205   remove_existing_finger (current_successor, 0);
5206    /* Generate a new trail id to reach to your new successor. */
5207   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
5208                               &trail_id, sizeof (trail_id));
5209
5210   if (trail_me_to_probable_succ_len > 0)
5211   {
5212     GDS_ROUTING_add (trail_id, my_identity, trail_me_to_probable_succ[0]);
5213     GNUNET_assert (NULL !=
5214                   (target_friend =
5215                       GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5216                                                         &trail_me_to_probable_succ[0])));
5217   }
5218   else
5219   {
5220     GDS_ROUTING_add (trail_id, my_identity, probable_successor);
5221     GNUNET_assert (NULL !=
5222                   (target_friend =
5223                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5224                                                       &probable_successor)));
5225   }
5226
5227   add_new_finger (probable_successor, trail_me_to_probable_succ,
5228                   trail_me_to_probable_succ_len, trail_id, 0);
5229
5230   struct SendNotifyContext *notify_ctx;
5231
5232   notify_ctx = GNUNET_new(struct SendNotifyContext);
5233
5234   notify_ctx->source_peer = my_identity;
5235   notify_ctx->successor = probable_successor;
5236   notify_ctx->successor_trail =
5237           GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity) * trail_me_to_probable_succ_len);
5238   memcpy(notify_ctx->successor_trail, trail_me_to_probable_succ,
5239          sizeof(struct GNUNET_PeerIdentity) * trail_me_to_probable_succ_len);
5240   notify_ctx->successor_trail_length = trail_me_to_probable_succ_len;
5241   notify_ctx->succesor_trail_id = trail_id;
5242   notify_ctx->target_friend = target_friend;
5243   notify_ctx->num_retries_scheduled = 0;
5244   GNUNET_free_non_null (trail_me_to_probable_succ);
5245
5246   // TODO: Check if we should verify before schedule if already scheduled.
5247   GNUNET_SCHEDULER_add_now(&send_notify_new_successor, (void*)notify_ctx);
5248 }
5249
5250
5251
5252 void
5253 send_notify_new_successor (void *cls,
5254                            const struct GNUNET_SCHEDULER_TaskContext
5255                            * tc)
5256 {
5257   struct SendNotifyContext *ctx = (struct SendNotifyContext *) cls;
5258
5259   GDS_NEIGHBOURS_send_notify_new_successor (ctx->source_peer,
5260                                             ctx->successor,
5261                                             ctx->successor_trail,
5262                                             ctx->successor_trail_length,
5263                                             ctx->succesor_trail_id,
5264                                             ctx->target_friend);
5265
5266   if (0 == ctx->num_retries_scheduled &&
5267           send_notify_new_successor_retry_task != NULL)
5268   {
5269     // Result from previous notify successos hasn't arrived, so the retry task
5270     // hasn't been cancelled! Already a new notify successor must be called.
5271     // We will cancel the retry request.
5272     struct SendNotifyContext *old_notify_ctx;
5273     old_notify_ctx = GNUNET_SCHEDULER_cancel(send_notify_new_successor_retry_task);
5274     GNUNET_free (old_notify_ctx->successor_trail);
5275     GNUNET_free (old_notify_ctx);
5276     send_notify_new_successor_retry_task = NULL;
5277   }
5278
5279   ctx->num_retries_scheduled++;
5280   send_notify_new_successor_retry_task = GNUNET_SCHEDULER_add_delayed(notify_successor_retry_time,
5281                                                                       &send_notify_new_successor,
5282                                                                       cls);
5283 }
5284
5285 /*
5286  * Core handle for p2p verify successor result messages.
5287  * @param cls closure
5288  * @param message message
5289  * @param peer peer identity this notification is about
5290  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5291  */
5292 static int
5293 handle_dht_p2p_verify_successor_result(void *cls,
5294                                        const struct GNUNET_PeerIdentity *peer,
5295                                        const struct GNUNET_MessageHeader *message)
5296 {
5297   const struct PeerVerifySuccessorResultMessage *vsrm;
5298   enum GDS_ROUTING_trail_direction trail_direction;
5299   struct GNUNET_PeerIdentity querying_peer;
5300   struct GNUNET_HashCode trail_id;
5301   struct GNUNET_PeerIdentity *next_hop;
5302   struct FriendInfo *target_friend;
5303   struct GNUNET_PeerIdentity probable_successor;
5304   struct GNUNET_PeerIdentity current_successor;
5305   const struct GNUNET_PeerIdentity *trail;
5306   unsigned int trail_length;
5307   size_t msize;
5308
5309   msize = ntohs (message->size);
5310   if (msize < sizeof (struct PeerVerifySuccessorResultMessage))
5311   {
5312     GNUNET_break_op (0);
5313     return GNUNET_YES;
5314   }
5315
5316   vsrm = (const struct PeerVerifySuccessorResultMessage *) message;
5317   if ((msize - sizeof (struct PeerVerifySuccessorResultMessage)) %
5318       sizeof (struct GNUNET_PeerIdentity) != 0)
5319   {
5320     GNUNET_break_op (0);
5321     return GNUNET_OK;
5322   }
5323   trail_length = (msize - sizeof (struct PeerVerifySuccessorResultMessage))/
5324                       sizeof (struct GNUNET_PeerIdentity);
5325
5326   GNUNET_STATISTICS_update (GDS_stats,
5327                             gettext_noop
5328                             ("# Bytes received from other peers"), msize,
5329                             GNUNET_NO);
5330
5331   trail = (const struct GNUNET_PeerIdentity *) &vsrm[1];
5332   querying_peer = vsrm->querying_peer;
5333   trail_direction = ntohl (vsrm->trail_direction);
5334   trail_id = vsrm->trail_id;
5335   probable_successor = vsrm->probable_successor;
5336   current_successor = vsrm->current_successor;
5337
5338   /* I am the querying_peer. */
5339   if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer, &my_identity)))
5340   {
5341     /* Cancel Retry Task */
5342     if (NULL != send_verify_successor_retry_task)
5343     {
5344       struct VerifySuccessorContext *ctx;
5345       ctx = GNUNET_SCHEDULER_cancel(send_verify_successor_retry_task);
5346       GNUNET_free(ctx);
5347       send_verify_successor_retry_task = NULL;
5348     }
5349     compare_and_update_successor (current_successor,
5350                                   probable_successor, trail, trail_length);
5351     return GNUNET_OK;
5352   }
5353
5354   /*If you are not the querying peer then pass on the message */
5355   if(NULL == (next_hop =
5356               GDS_ROUTING_get_next_hop (trail_id, trail_direction)))
5357   {
5358     /* Here it may happen that source peer has found a new successor, and removed
5359      the trail, Hence no entry found in the routing table. Fail silently.*/
5360     DEBUG(" NO ENTRY FOUND IN %s ROUTING TABLE for trail id %s, line",
5361             GNUNET_i2s(&my_identity), GNUNET_h2s(&trail_id), __LINE__);
5362     GNUNET_break_op(0);
5363     return GNUNET_OK;
5364   }
5365   if (NULL == (target_friend =
5366                  GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop)))
5367   {
5368     GNUNET_break_op(0);
5369     return GNUNET_OK;
5370   }
5371   GDS_NEIGHBOURS_send_verify_successor_result (querying_peer,
5372                                                vsrm->current_successor,
5373                                                probable_successor, trail_id,
5374                                                trail,
5375                                                trail_length,
5376                                                trail_direction, target_friend);
5377   return GNUNET_OK;
5378 }
5379
5380
5381 /*
5382  * Core handle for p2p notify new successor messages.
5383  * @param cls closure
5384  * @param message message
5385  * @param peer peer identity this notification is about
5386  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5387  */
5388 static int
5389 handle_dht_p2p_notify_new_successor(void *cls,
5390                                     const struct GNUNET_PeerIdentity *peer,
5391                                     const struct GNUNET_MessageHeader *message)
5392 {
5393   const struct PeerNotifyNewSuccessorMessage *nsm;
5394   struct GNUNET_PeerIdentity *trail;
5395   struct GNUNET_PeerIdentity source;
5396   struct GNUNET_PeerIdentity new_successor;
5397   struct GNUNET_HashCode trail_id;
5398   struct GNUNET_PeerIdentity next_hop;
5399   struct FriendInfo *target_friend;
5400   int my_index;
5401   size_t msize;
5402   uint32_t trail_length;
5403
5404   msize = ntohs (message->size);
5405   if (msize < sizeof (struct PeerNotifyNewSuccessorMessage))
5406   {
5407     GNUNET_break_op (0);
5408     return GNUNET_YES;
5409   }
5410   nsm = (const struct PeerNotifyNewSuccessorMessage *) message;
5411   if ((msize - sizeof (struct PeerNotifyNewSuccessorMessage)) %
5412       sizeof (struct GNUNET_PeerIdentity) != 0)
5413   {
5414     GNUNET_break_op (0);
5415     return GNUNET_OK;
5416   }
5417   trail_length = (msize - sizeof (struct PeerNotifyNewSuccessorMessage))/
5418                   sizeof (struct GNUNET_PeerIdentity);
5419   GNUNET_STATISTICS_update (GDS_stats,
5420                             gettext_noop
5421                             ("# Bytes received from other peers"), msize,
5422                             GNUNET_NO);
5423
5424   trail = (struct GNUNET_PeerIdentity *) &nsm[1];
5425   source  = nsm->source_peer;
5426   new_successor = nsm->new_successor;
5427   trail_id = nsm->trail_id;
5428
5429   /* I am the new_successor to source_peer. */
5430   if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &new_successor))
5431   {
5432     if(trail_length > 0)
5433       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity(&trail[trail_length - 1],
5434                                                           peer));
5435     else
5436       GNUNET_assert(0 == GNUNET_CRYPTO_cmp_peer_identity(&source, peer));
5437
5438     compare_and_update_predecessor (source, trail, trail_length);
5439     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
5440     GNUNET_assert (NULL != target_friend);
5441     GDS_NEIGHBOURS_send_notify_succcessor_confirmation (trail_id,
5442                                                         GDS_ROUTING_DEST_TO_SRC,
5443                                                         target_friend);
5444     return GNUNET_OK;
5445   }
5446
5447   GNUNET_assert(trail_length > 0);
5448   /* I am part of trail to reach to successor. */
5449   my_index = search_my_index (trail, trail_length);
5450   if (-1 == my_index)
5451   {
5452     DEBUG ("No entry found in trail\n");
5453     GNUNET_break_op (0);
5454     return GNUNET_SYSERR;
5455   }
5456   if((trail_length + 1) == my_index)
5457   {
5458     DEBUG ("Found twice in trail.\n");
5459     GNUNET_break_op (0);
5460     return GNUNET_SYSERR;
5461   }
5462   if ((trail_length-1) == my_index)
5463     next_hop = new_successor;
5464   else
5465     next_hop = trail[my_index + 1];
5466
5467   GDS_ROUTING_add(trail_id, *peer, next_hop);
5468   target_friend =
5469                  GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
5470   if (NULL == target_friend)
5471   {
5472     GNUNET_break(0);
5473     return GNUNET_OK;
5474   }
5475   GDS_NEIGHBOURS_send_notify_new_successor (source, new_successor, trail,
5476                                             trail_length,
5477                                             trail_id, target_friend);
5478   return GNUNET_OK;
5479
5480 }
5481
5482
5483 /**
5484  * Core handler for P2P notify successor message
5485  * @param cls closure
5486  * @param message message
5487  * @param peer peer identity this notification is about
5488  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5489  */
5490 static int
5491 handle_dht_p2p_notify_succ_confirmation (void *cls,
5492                                          const struct GNUNET_PeerIdentity *peer,
5493                                          const struct GNUNET_MessageHeader *message)
5494 {
5495   const struct PeerNotifyConfirmationMessage *notify_confirmation;
5496   enum GDS_ROUTING_trail_direction trail_direction;
5497   struct GNUNET_HashCode trail_id;
5498   struct FriendInfo *target_friend;
5499   struct GNUNET_PeerIdentity *next_hop;
5500   size_t msize;
5501
5502   msize = ntohs (message->size);
5503
5504   if (msize != sizeof (struct PeerNotifyConfirmationMessage))
5505   {
5506     GNUNET_break_op (0);
5507     return GNUNET_OK;
5508   }
5509   GNUNET_STATISTICS_update (GDS_stats,
5510                             gettext_noop
5511                             ("# Bytes received from other peers"), msize,
5512                             GNUNET_NO);
5513
5514   notify_confirmation = (const struct PeerNotifyConfirmationMessage *) message;
5515   trail_direction = ntohl (notify_confirmation->trail_direction);
5516   trail_id = notify_confirmation->trail_id;
5517
5518   next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
5519   if (NULL == next_hop)
5520   {
5521     /* The source of notify new successor, might have found even a better
5522      successor. In that case it send a trail teardown message, and hence,
5523      the next hop is NULL. */
5524     //Fixme: Add some print to confirm the above theory.
5525     return GNUNET_OK;
5526   }
5527
5528   /* I peer which sent the notify successor message to the successor. */
5529   if (0 == GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity))
5530   {
5531    /*
5532     * Schedule another round of verify sucessor with your current successor
5533     * which may or may not be source of this message. This message is used
5534     * only to ensure that we have a path setup to reach to our successor.
5535     */
5536
5537     // TODO: cancel schedule of notify_successor_retry_task
5538     if (send_notify_new_successor_retry_task != NULL)
5539     {
5540       struct SendNotifyContext *notify_ctx;
5541       notify_ctx = GNUNET_SCHEDULER_cancel(send_notify_new_successor_retry_task);
5542       GNUNET_free (notify_ctx->successor_trail);
5543       GNUNET_free (notify_ctx);
5544       send_notify_new_successor_retry_task = NULL;
5545     }
5546     if (send_verify_successor_task == NULL)
5547     {
5548       verify_successor_next_send_time.rel_value_us =
5549       DHT_SEND_VERIFY_SUCCESSOR_INTERVAL.rel_value_us +
5550       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
5551                                 DHT_SEND_VERIFY_SUCCESSOR_INTERVAL.rel_value_us);
5552       send_verify_successor_task =
5553               GNUNET_SCHEDULER_add_delayed(verify_successor_next_send_time,
5554                                            &send_verify_successor_message,
5555                                            NULL);
5556     }
5557   }
5558   else
5559   {
5560     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
5561     if (NULL == target_friend)
5562     {
5563       DEBUG ("\n friend not found, line number = %d",__LINE__);
5564       return GNUNET_SYSERR;
5565     }
5566     GDS_NEIGHBOURS_send_notify_succcessor_confirmation  (trail_id,
5567                                                         GDS_ROUTING_DEST_TO_SRC,
5568                                                         target_friend);
5569   }
5570   return GNUNET_OK;
5571 }
5572
5573
5574 /**
5575  * Core handler for P2P trail rejection message
5576  * @param cls closure
5577  * @param message message
5578  * @param peer peer identity this notification is about
5579  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5580  */
5581 static int
5582 handle_dht_p2p_trail_setup_rejection (void *cls,
5583                                       const struct GNUNET_PeerIdentity *peer,
5584                                       const struct GNUNET_MessageHeader *message)
5585 {
5586   const struct PeerTrailRejectionMessage *trail_rejection;
5587   unsigned int trail_length;
5588   const struct GNUNET_PeerIdentity *trail_peer_list;
5589   struct FriendInfo *target_friend;
5590   struct GNUNET_TIME_Relative congestion_timeout;
5591   struct GNUNET_HashCode trail_id;
5592   struct GNUNET_PeerIdentity next_peer;
5593   struct GNUNET_PeerIdentity source;
5594   uint64_t ultimate_destination_finger_value;
5595   unsigned int is_predecessor;
5596   size_t msize;
5597
5598   msize = ntohs (message->size);
5599   if (msize < sizeof (struct PeerTrailRejectionMessage))
5600   {
5601     GNUNET_break_op (0);
5602     return GNUNET_YES;
5603   }
5604   trail_rejection = (const struct PeerTrailRejectionMessage *) message;
5605   if ((msize - sizeof (struct PeerTrailRejectionMessage)) %
5606       sizeof (struct GNUNET_PeerIdentity) != 0)
5607   {
5608     GNUNET_break_op (0);
5609     return GNUNET_OK;
5610   }
5611   trail_length = (msize - sizeof (struct PeerTrailRejectionMessage))/
5612                   sizeof (struct GNUNET_PeerIdentity);
5613   GNUNET_STATISTICS_update (GDS_stats,
5614                             gettext_noop
5615                             ("# Bytes received from other peers"), msize,
5616                             GNUNET_NO);
5617
5618   trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_rejection[1];
5619   is_predecessor = ntohl (trail_rejection->is_predecessor);
5620   congestion_timeout = trail_rejection->congestion_time;
5621   source = trail_rejection->source_peer;
5622   trail_id = trail_rejection->trail_id;
5623   ultimate_destination_finger_value =
5624           GNUNET_ntohll (trail_rejection->ultimate_destination_finger_value);
5625   /* First set the congestion time of the friend that sent you this message. */
5626   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
5627   if (NULL == target_friend)
5628   {
5629     DEBUG ("\nLINE = %d ,No friend found.",__LINE__);
5630     GNUNET_break(0);
5631     return GNUNET_OK;
5632   }
5633   target_friend->congestion_timestamp =
5634           GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
5635                                     congestion_timeout);
5636
5637   /* I am the source peer which wants to setup the trail. Do nothing.
5638    * send_find_finger_trail_task is scheduled periodically.*/
5639   if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &source)))
5640     return GNUNET_OK;
5641
5642   /* If I am congested then pass this message to peer before me in trail. */
5643   if(GNUNET_YES == GDS_ROUTING_threshold_reached())
5644   {
5645     /* First remove yourself from the trail. */
5646     unsigned int new_trail_length = trail_length - 1;
5647     struct GNUNET_PeerIdentity trail[new_trail_length];
5648
5649     memcpy (trail, trail_peer_list, new_trail_length * sizeof(struct GNUNET_PeerIdentity));
5650     if (0 == trail_length)
5651       next_peer = source;
5652     else
5653       next_peer = trail[new_trail_length-1];
5654
5655     target_friend =
5656                    GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
5657     if (NULL == target_friend)
5658     {
5659       DEBUG ("\nLINE = %d ,No friend found.",__LINE__);
5660       GNUNET_break(0);
5661       return GNUNET_OK;
5662     }
5663     GDS_NEIGHBOURS_send_trail_rejection (source,
5664                                          ultimate_destination_finger_value,
5665                                          my_identity, is_predecessor,
5666                                          trail, new_trail_length, trail_id,
5667                                          target_friend, CONGESTION_TIMEOUT);
5668     return GNUNET_OK;
5669   }
5670
5671   struct Closest_Peer successor;
5672   successor = find_local_best_known_next_hop (ultimate_destination_finger_value, is_predecessor);
5673
5674   /* Am I the final destination? */
5675   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&successor.best_known_destination,
5676                                              &my_identity)))
5677   {
5678      /*Here you are already part of trail. Copy the trail removing yourself. */
5679     unsigned int new_trail_length = trail_length - 1;
5680     struct GNUNET_PeerIdentity trail[new_trail_length];
5681
5682     memcpy (trail, trail_peer_list, new_trail_length * sizeof(struct GNUNET_PeerIdentity));
5683
5684     if (0 == new_trail_length)
5685       next_peer = source;
5686     else
5687     {
5688       next_peer = trail[new_trail_length-1];
5689     }
5690     target_friend =
5691                    GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
5692
5693     if (NULL == target_friend)
5694     {
5695       DEBUG ("\nLINE = %d ,No friend found.",__LINE__);
5696       GNUNET_break(0);
5697       return GNUNET_OK;
5698     }
5699     GDS_NEIGHBOURS_send_trail_setup_result (source,
5700                                             my_identity,
5701                                             target_friend, new_trail_length,
5702                                             trail,
5703                                             is_predecessor,
5704                                             ultimate_destination_finger_value,
5705                                             trail_id);
5706   }
5707   else
5708   {
5709     /* Here I was already part of trail. So no need to add. */
5710     target_friend =
5711                    GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5712                                                       &successor.next_hop);
5713     if (NULL == target_friend)
5714     {
5715       DEBUG ("\nLINE = %d ,No friend found.",__LINE__);
5716       GNUNET_break(0);
5717       return GNUNET_OK;
5718     }
5719
5720     GDS_NEIGHBOURS_send_trail_setup (source,
5721                                      ultimate_destination_finger_value,
5722                                      successor.best_known_destination,
5723                                      target_friend, trail_length, trail_peer_list,
5724                                      is_predecessor, trail_id,
5725                                      successor.trail_id);
5726   }
5727   return GNUNET_OK;
5728 }
5729
5730
5731 /**
5732  * Core handler for trail teardown message.
5733  * @param cls closure
5734  * @param message message
5735  * @param peer sender of this messsage.
5736  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5737  */
5738 static int
5739 handle_dht_p2p_trail_teardown (void *cls, const struct GNUNET_PeerIdentity *peer,
5740                                const struct GNUNET_MessageHeader *message)
5741 {
5742   const struct PeerTrailTearDownMessage *trail_teardown;
5743   enum GDS_ROUTING_trail_direction trail_direction;
5744   struct GNUNET_HashCode trail_id;
5745   struct GNUNET_PeerIdentity *next_hop;
5746   size_t msize;
5747
5748   msize = ntohs (message->size);
5749
5750   /* Here we pass only the trail id. */
5751   if (msize != sizeof (struct PeerTrailTearDownMessage))
5752   {
5753     GNUNET_break_op (0);
5754     return GNUNET_OK;
5755   }
5756
5757   GNUNET_STATISTICS_update (GDS_stats,
5758                             gettext_noop
5759                             ("# Bytes received from other peers"), msize,
5760                             GNUNET_NO);
5761
5762   trail_teardown = (const struct PeerTrailTearDownMessage *) message;
5763   trail_direction = ntohl (trail_teardown->trail_direction);
5764   trail_id = trail_teardown->trail_id;
5765
5766   /* Check if peer is the real peer from which we should get this message.*/
5767   /* Get the prev_hop for this trail by getting the next hop in opposite direction. */
5768 #if 0
5769   GNUNET_assert (NULL != (prev_hop =
5770                  GDS_ROUTING_get_next_hop (trail_id, !trail_direction)));
5771   if (0 != GNUNET_CRYPTO_cmp_peer_identity (prev_hop, peer))
5772   {
5773     GNUNET_break (0);
5774     return GNUNET_SYSERR;
5775   }
5776 #endif
5777
5778   next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
5779   if (NULL == next_hop)
5780   {
5781     DEBUG(" NO ENTRY FOUND IN %s ROUTING TABLE for trail id %s, line",
5782             GNUNET_i2s(&my_identity), GNUNET_h2s(&trail_id), __LINE__);
5783     GNUNET_break (0);
5784     return GNUNET_SYSERR;
5785   }
5786
5787   /* I am the next hop, which means I am the final destination. */
5788   if (0 == GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity))
5789   {
5790     GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
5791     return GNUNET_OK;
5792   }
5793   else
5794   {
5795     /* If not final destination, then send a trail teardown message to next hop.*/
5796     GNUNET_assert (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop));
5797     GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
5798     GDS_NEIGHBOURS_send_trail_teardown (&trail_id, trail_direction, next_hop);
5799   }
5800
5801   return GNUNET_OK;
5802 }
5803
5804
5805 /**
5806  * Core handle for p2p add trail message.
5807  * @param cls closure
5808  * @param message message
5809  * @param peer peer identity this notification is about
5810  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5811  */
5812 static int
5813 handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
5814                           const struct GNUNET_MessageHeader *message)
5815 {
5816   const struct PeerAddTrailMessage *add_trail;
5817   const struct GNUNET_PeerIdentity *trail;
5818   struct GNUNET_HashCode trail_id;
5819   struct GNUNET_PeerIdentity destination_peer;
5820   struct GNUNET_PeerIdentity source_peer;
5821   struct GNUNET_PeerIdentity next_hop;
5822   unsigned int trail_length;
5823   unsigned int my_index;
5824   size_t msize;
5825
5826   msize = ntohs (message->size);
5827   /* In this message we pass the whole trail from source to destination as we
5828    * are adding that trail.*/
5829   //FIXME: failed when run with 1000 pears. check why.
5830   if (msize < sizeof (struct PeerAddTrailMessage))
5831   {
5832     GNUNET_break_op (0);
5833     return GNUNET_OK;
5834   }
5835
5836   add_trail = (const struct PeerAddTrailMessage *) message;
5837   trail_length = (msize - sizeof (struct PeerAddTrailMessage))/
5838                   sizeof (struct GNUNET_PeerIdentity);
5839   if ((msize - sizeof (struct PeerAddTrailMessage)) %
5840       sizeof (struct GNUNET_PeerIdentity) != 0)
5841   {
5842     GNUNET_break_op (0);
5843     return GNUNET_OK;
5844   }
5845
5846   GNUNET_STATISTICS_update (GDS_stats,
5847                             gettext_noop
5848                             ("# Bytes received from other peers"), msize,
5849                             GNUNET_NO);
5850
5851   trail = (const struct GNUNET_PeerIdentity *)&add_trail[1];
5852   destination_peer = add_trail->destination_peer;
5853   source_peer = add_trail->source_peer;
5854   trail_id = add_trail->trail_id;
5855
5856   /* I am not the destination of the trail. */
5857   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &destination_peer))
5858   {
5859     struct FriendInfo *target_friend;
5860
5861     /* Get my location in the trail. */
5862     my_index = search_my_index (trail, trail_length);
5863     if (-1 == my_index)
5864     {
5865       GNUNET_break_op (0);
5866       return GNUNET_SYSERR;
5867     }
5868     if((trail_length + 1) == my_index)
5869     {
5870       DEBUG ("Found twice in trail.\n");
5871       GNUNET_break_op (0);
5872       return GNUNET_SYSERR;
5873     }
5874     if ((trail_length - 1) == my_index)
5875     {
5876       next_hop = destination_peer;
5877     }
5878     else
5879     {
5880       next_hop = trail[my_index + 1];
5881     }
5882     /* Add in your routing table. */
5883     GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, next_hop));
5884     //GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, next_hop, *peer));
5885     GNUNET_assert (NULL !=
5886                   (target_friend =
5887                    GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop)));
5888     GDS_NEIGHBOURS_send_add_trail (source_peer, destination_peer, trail_id,
5889                                    trail, trail_length, target_friend);
5890     return GNUNET_OK;
5891   }
5892   /* I am the destination. Add an entry in routing table. */
5893   GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, my_identity));
5894   return GNUNET_OK;
5895 }
5896
5897
5898 /**
5899  * Free the finger trail in which the first friend to reach to a finger is
5900  * disconnected_friend. Also remove entry from routing table for that particular
5901  * trail id.
5902  * @param disconnected_friend PeerIdentity of friend which got disconnected
5903  * @param remove_finger Finger whose trail we need to check if it has
5904  *                      disconnected_friend as the first hop.
5905  * @return Total number of trails in which disconnected_friend was the first
5906  *         hop.
5907  */
5908 static int
5909 remove_matching_trails (const struct GNUNET_PeerIdentity *disconnected_friend,
5910                         struct FingerInfo *finger)
5911 {
5912   struct GNUNET_PeerIdentity *next_hop;
5913   struct FriendInfo *remove_friend;
5914   struct Trail *current_trail;
5915   unsigned int matching_trails_count = 0;
5916   int i;
5917
5918   /* Iterate over all the trails of finger. */
5919   for (i = 0; i < finger->trails_count; i++)
5920   {
5921     current_trail = &finger->trail_list[i];
5922     if (GNUNET_NO == current_trail->is_present)
5923       continue;
5924
5925     /* First friend to reach to finger is disconnected_peer. */
5926     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&current_trail->trail_head->peer,
5927                                               disconnected_friend))
5928     {
5929       remove_friend =
5930                      GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5931                                                         disconnected_friend);
5932       GNUNET_assert (NULL != remove_friend);
5933       next_hop = GDS_ROUTING_get_next_hop (current_trail->trail_id,
5934                                            GDS_ROUTING_SRC_TO_DEST);
5935
5936       /* Here it may happen that as all the peers got disconnected, the entry in
5937        routing table for that particular trail has been removed, because the
5938        previously disconnected peer was either a next hop or prev hop of that
5939        peer. */
5940       if (NULL != next_hop)
5941       {
5942         GNUNET_assert (0 == (GNUNET_CRYPTO_cmp_peer_identity (disconnected_friend,
5943                                                               next_hop)));
5944         GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (current_trail->trail_id));
5945       }
5946       matching_trails_count++;
5947       free_trail (current_trail);
5948       current_trail->is_present = GNUNET_NO;
5949     }
5950   }
5951   return matching_trails_count;
5952 }
5953
5954
5955 /**
5956  * Iterate over finger_table entries.
5957  * 0. Ignore finger which is my_identity or if no valid entry present at
5958  *    that finger index.
5959  * 1. If disconnected_friend is a finger, then remove the routing entry from
5960       your own table. Free the trail.
5961  * 2. Check if disconnected_friend is the first friend in the trail to reach to a finger.
5962  *   2.1 Remove all the trails and entry from routing table in which disconnected
5963  *       friend is the first friend in the trail. If disconnected_friend is the
5964  *       first friend in all the trails to reach finger, then remove the finger.
5965  * @param disconnected_friend Peer identity of friend which got disconnected.
5966  */
5967 static void
5968 remove_matching_fingers (const struct GNUNET_PeerIdentity *disconnected_peer)
5969 {
5970   struct FingerInfo *current_finger;
5971   int removed_trails_count;
5972   int i;
5973
5974   /* Iterate over finger table entries. */
5975   for (i = 0; i < MAX_FINGERS; i++)
5976   {
5977     current_finger = &finger_table[i];
5978
5979     /* No finger stored at this trail index or I am the finger. */
5980     if ((GNUNET_NO == current_finger->is_present) ||
5981         (0 == GNUNET_CRYPTO_cmp_peer_identity (&current_finger->finger_identity,
5982                                                &my_identity)))
5983       continue;
5984
5985     /* Is disconnected_peer a finger? */
5986     if (0 == GNUNET_CRYPTO_cmp_peer_identity (disconnected_peer,
5987                                               &current_finger->finger_identity))
5988     {
5989       remove_existing_finger (current_finger, i);
5990     }
5991
5992     /* If finger is a friend but not disconnected_friend, then continue. */
5993     if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap,
5994                                                    &current_finger->finger_identity))
5995       continue;
5996
5997     /* Iterate over the list of trails to reach remove_finger. Check if
5998      * disconnected_friend is the first friend in any of the trail. */
5999     removed_trails_count = remove_matching_trails (disconnected_peer,
6000                                                    current_finger);
6001     current_finger->trails_count =
6002             current_finger->trails_count - removed_trails_count;
6003     if (0 == current_finger->trails_count)
6004     {
6005       current_finger->is_present = GNUNET_NO;
6006       memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
6007     }
6008   }
6009 }
6010
6011
6012 /**
6013  * Method called whenever a peer disconnects.
6014  *
6015  * @param cls closure
6016  * @param peer peer identity this notification is about
6017  */
6018 static void
6019 handle_core_disconnect (void *cls,
6020                                           const struct GNUNET_PeerIdentity *peer)
6021 {
6022   struct FriendInfo *remove_friend;
6023   struct P2PPendingMessage *pos;
6024   unsigned int discarded;
6025
6026   /* If disconnected to own identity, then return. */
6027   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
6028     return;
6029
6030   if(NULL == (remove_friend =
6031                  GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)))
6032   {
6033     DEBUG("\n friend already disconnected.");
6034     return;
6035   }
6036
6037   remove_matching_fingers (peer);
6038   GNUNET_assert (GNUNET_SYSERR != GDS_ROUTING_remove_trail_by_peer (peer));
6039   GNUNET_assert (GNUNET_YES ==
6040                  GNUNET_CONTAINER_multipeermap_remove (friend_peermap,
6041                                                        peer,
6042                                                        remove_friend));
6043
6044   /* Remove all the messages queued in pending list of this peer is discarded.*/
6045   if (remove_friend->th != NULL)
6046   {
6047     GNUNET_CORE_notify_transmit_ready_cancel(remove_friend->th);
6048     remove_friend->th = NULL;
6049   }
6050
6051   discarded = 0;
6052   while (NULL != (pos = remove_friend->head))
6053   {
6054     GNUNET_CONTAINER_DLL_remove (remove_friend->head, remove_friend->tail, pos);
6055     discarded++;
6056     GNUNET_free (pos);
6057   }
6058
6059   GNUNET_STATISTICS_update (GDS_stats,
6060                             gettext_noop
6061                             ("# Queued messages discarded (peer disconnected)"),
6062                             discarded, GNUNET_NO);
6063   //GNUNET_free (remove_friend);
6064
6065   if (0 != GNUNET_CONTAINER_multipeermap_size (friend_peermap))
6066     return;
6067
6068   if (NULL != find_finger_trail_task)
6069   {
6070       GNUNET_SCHEDULER_cancel (find_finger_trail_task);
6071       find_finger_trail_task = NULL;
6072   }
6073   else
6074     GNUNET_break (0);
6075 }
6076
6077
6078 /**
6079  * Method called whenever a peer connects.
6080  *
6081  * @param cls closure
6082  * @param peer_identity peer identity this notification is about
6083  */
6084 static void
6085 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
6086 {
6087   struct FriendInfo *friend;
6088
6089   /* Check for connect to self message */
6090   if (0 == memcmp (&my_identity, peer_identity, sizeof (struct GNUNET_PeerIdentity)))
6091     return;
6092
6093   /* If peer already exists in our friend_peermap, then exit. */
6094   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (friend_peermap,
6095                                                             peer_identity))
6096   {
6097     GNUNET_break (0);
6098     return;
6099   }
6100
6101   friend = GNUNET_new (struct FriendInfo);
6102   friend->id = *peer_identity;
6103
6104   GNUNET_assert (GNUNET_OK ==
6105                  GNUNET_CONTAINER_multipeermap_put (friend_peermap,
6106                                                     peer_identity, friend,
6107                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
6108
6109   /* FIXME: now we are not making a distinction between fingers which are friends
6110    * also.But later, we should add a congestion timestamp on the friend, so that it is
6111    * selected after some time out. This is to ensure that both peers have added
6112    * each other as their friend. */
6113   /* Got a first connection, good time to start with FIND FINGER TRAIL requests...*/
6114   if (NULL == find_finger_trail_task)
6115   {
6116     find_finger_trail_task = GNUNET_SCHEDULER_add_now (&send_find_finger_trail_message, NULL);
6117   }
6118 }
6119
6120
6121 /**
6122  * To be called on core init/fail.
6123  *
6124  * @param cls service closure
6125  * @param identity the public identity of this peer
6126  */
6127 static void
6128 core_init (void *cls,
6129            const struct GNUNET_PeerIdentity *identity)
6130 {
6131   my_identity = *identity;
6132 }
6133
6134
6135 /**
6136  * Initialize finger table entries.
6137  */
6138 static void
6139 finger_table_init ()
6140 {
6141   memset (&finger_table, 0, sizeof (finger_table));
6142 }
6143
6144
6145 /**
6146  * Initialize neighbours subsystem.
6147  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
6148  */
6149 int
6150 GDS_NEIGHBOURS_init (void)
6151 {
6152   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
6153     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_XDHT_P2P_PUT, 0},
6154     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_XDHT_P2P_GET, 0},
6155     {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_XDHT_P2P_GET_RESULT, 0},
6156     {&handle_dht_p2p_trail_setup, GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP, 0},
6157     {&handle_dht_p2p_trail_setup_result, GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_RESULT, 0},
6158     {&handle_dht_p2p_verify_successor, GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR, 0},
6159     {&handle_dht_p2p_verify_successor_result, GNUNET_MESSAGE_TYPE_XDHT_P2P_VERIFY_SUCCESSOR_RESULT, 0},
6160     {&handle_dht_p2p_notify_new_successor, GNUNET_MESSAGE_TYPE_XDHT_P2P_NOTIFY_NEW_SUCCESSOR, 0},
6161     {&handle_dht_p2p_trail_setup_rejection, GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_SETUP_REJECTION, 0},
6162     {&handle_dht_p2p_trail_teardown, GNUNET_MESSAGE_TYPE_XDHT_P2P_TRAIL_TEARDOWN,
6163                                      sizeof (struct PeerTrailTearDownMessage)},
6164     {&handle_dht_p2p_add_trail, GNUNET_MESSAGE_TYPE_XDHT_P2P_ADD_TRAIL, 0},
6165     {&handle_dht_p2p_notify_succ_confirmation, GNUNET_MESSAGE_TYPE_XDHT_P2P_NOTIFY_SUCCESSOR_CONFIRMATION,
6166                                       sizeof (struct PeerNotifyConfirmationMessage)},
6167     {NULL, 0, 0}
6168   };
6169
6170 #if ENABLE_MALICIOUS
6171   act_malicious = 0;
6172 #endif
6173
6174   core_api =
6175     GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
6176                          &handle_core_disconnect, NULL, GNUNET_NO, NULL,
6177                          GNUNET_NO, core_handlers);
6178
6179   if (NULL == core_api)
6180     return GNUNET_SYSERR;
6181
6182   //TODO: check size of this peer map?
6183   friend_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
6184   finger_table_init ();
6185   successor_times = 10;
6186   fingers_round_count = 5;
6187   find_finger_trail_task_next_send_time.rel_value_us =
6188       DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
6189       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
6190                                 DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
6191
6192   verify_successor_next_send_time.rel_value_us =
6193       DHT_SEND_VERIFY_SUCCESSOR_INTERVAL.rel_value_us +
6194       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
6195                                 DHT_SEND_VERIFY_SUCCESSOR_INTERVAL.rel_value_us);
6196
6197   verify_successor_retry_time.rel_value_us =
6198       DHT_SEND_VERIFY_SUCCESSOR_RETRY_INTERVAL.rel_value_us +
6199       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
6200                                 DHT_SEND_VERIFY_SUCCESSOR_RETRY_INTERVAL.rel_value_us);
6201
6202   notify_successor_retry_time.rel_value_us =
6203       DHT_SEND_NOTIFY_SUCCESSOR_RETRY_INTERVAL.rel_value_us +
6204       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
6205                                 DHT_SEND_NOTIFY_SUCCESSOR_RETRY_INTERVAL.rel_value_us);
6206
6207
6208   return GNUNET_OK;
6209 }
6210
6211
6212 /**
6213  * Free the memory held up by trails of a finger.
6214  */
6215 static void
6216 delete_finger_table_entries()
6217 {
6218   unsigned int i;
6219   unsigned int j;
6220
6221   for(i = 0; i < MAX_FINGERS; i++)
6222   {
6223     if(GNUNET_YES == finger_table[i].is_present)
6224     {
6225       for(j = 0; j < finger_table[i].trails_count; j++)
6226         free_trail(&finger_table[i].trail_list[j]);
6227     }
6228   }
6229 }
6230
6231
6232 /**
6233  * Shutdown neighbours subsystem.
6234  */
6235 void
6236 GDS_NEIGHBOURS_done (void)
6237 {
6238   if (NULL == core_api)
6239     return;
6240
6241   GNUNET_CORE_disconnect (core_api);
6242   core_api = NULL;
6243
6244   delete_finger_table_entries();
6245   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (friend_peermap));
6246   GNUNET_CONTAINER_multipeermap_destroy (friend_peermap);
6247   friend_peermap = NULL;
6248
6249   if (NULL != find_finger_trail_task)
6250   {
6251     GNUNET_SCHEDULER_cancel (find_finger_trail_task);
6252     find_finger_trail_task = NULL;
6253   }
6254
6255   if (NULL != send_verify_successor_task)
6256   {
6257     GNUNET_SCHEDULER_cancel (send_verify_successor_task);
6258     send_verify_successor_task = NULL;
6259   }
6260
6261   if (NULL != send_verify_successor_retry_task)
6262   {
6263     struct VerifySuccessorContext *ctx;
6264     ctx = GNUNET_SCHEDULER_cancel (send_verify_successor_retry_task);
6265     GNUNET_free(ctx);
6266     send_verify_successor_retry_task = NULL;
6267   }
6268
6269   if (send_notify_new_successor_retry_task != NULL)
6270   {
6271     struct SendNotifyContext *notify_ctx;
6272     notify_ctx = GNUNET_SCHEDULER_cancel(send_notify_new_successor_retry_task);
6273     GNUNET_free (notify_ctx->successor_trail);
6274     GNUNET_free (notify_ctx);
6275     send_notify_new_successor_retry_task = NULL;
6276   }
6277 }
6278
6279
6280 /**
6281  * Get my identity
6282  *
6283  * @return my identity
6284  */
6285 struct GNUNET_PeerIdentity
6286 GDS_NEIGHBOURS_get_my_id (void)
6287 {
6288   return my_identity;
6289 }
6290
6291 /* end of gnunet-service-xdht_neighbours.c */