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