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