xvine: minor fixes
[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   peer1_value = GNUNET_ntohll (peer1_value);
1678   peer2_value = GNUNET_ntohll (peer2_value);
1679   value = GNUNET_ntohll (value); //FIXME: Is it correct to do it here?
1680   // we do it when we get from the network. 
1681   
1682   if (peer1_value == value)
1683   {
1684     return peer1;
1685   }
1686   
1687   if (peer2_value == value)
1688   {
1689     return peer2;
1690   }
1691    
1692   if (peer2_value < peer1_value)
1693   {
1694     if ((peer2_value < value) && (value < peer1_value))
1695     {
1696       return peer1;
1697     }
1698     else if (((peer1_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
1699              ((0 < value) && (value < peer2_value)))
1700     {
1701       return peer2;
1702     }
1703   }  
1704    
1705   if (peer1_value < peer2_value)
1706   {
1707     if ((peer1_value < value) && (value < peer2_value))
1708     {
1709       return peer2;
1710     }
1711     else if (((peer2_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
1712              ((0 < value) && (value < peer1_value)))
1713     {
1714       return peer1;
1715     }
1716   }
1717   return NULL;
1718 }
1719
1720
1721 /**
1722  * FIMXE: COMPLETE THE LOGIC.
1723  * my_id = 0
1724  * finger = 5
1725  * key = 3
1726  * [0,5) â†’ my_id
1727  * [5,0) â†’ finger
1728  *
1729  * 0 <= key < 5, so my_id 0 is the predecessor. 
1730  * peer1 != peer2 ever.
1731  * Select closest predecessor to value.
1732  * @param peer1 First peer
1733  * @param peer2 Second peer
1734  * @param value Value to be compare
1735  * @return Closest peer
1736  */
1737 static struct GNUNET_PeerIdentity *
1738 select_closest_predecessor (struct GNUNET_PeerIdentity *peer1,
1739                             struct GNUNET_PeerIdentity *peer2,
1740                             uint64_t value)
1741 {
1742   uint64_t peer1_value;
1743   uint64_t peer2_value;
1744   
1745   memcpy (&peer1_value, peer1, sizeof (uint64_t));
1746   memcpy (&peer2_value, peer2, sizeof (uint64_t));
1747   peer1_value = GNUNET_ntohll (peer1_value);
1748   peer2_value = GNUNET_ntohll (peer2_value);
1749   
1750   if (peer1_value == value)
1751     return peer1;
1752   
1753   if (peer2_value == value)
1754     return peer2;
1755   
1756   if (peer1_value < peer2_value)
1757   {
1758     if ((peer1_value < value) && (value < peer2_value))
1759       return peer1;
1760     else if (((peer2_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
1761              ((PEER_IDENTITES_WRAP_AROUND > value) && (value < peer1_value)))
1762       return peer2;
1763   }
1764   
1765   if (peer2_value < peer1_value)
1766   {
1767     if ((peer2_value < value) && (value < peer1_value))
1768       return peer2;
1769     else if (((peer1_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
1770              ((PEER_IDENTITES_WRAP_AROUND > value) && (value < peer2_value)))
1771       return peer1;
1772   }
1773   return NULL;
1774 }
1775
1776
1777 /* FIXME: select closest peer w.r.t. value. [finger->friend_id, current_successor->id)
1778      and [current_successor->id, finger->friend_id). Check in which range value lies.
1779      Also, check for wrap around. But this will give you the immediate predecessor
1780      For example. if we have 0,1,6 and I am 0 and one of my finger is 6. Then
1781      for 1, we will have ranges like [0,6) and [6,0) 1 lies in range from [0,6)
1782      but successor is 6 not 0 as 6 is > than 1. If you are the closest one, 
1783      then set the values
1784      in current_successor. Want to write a generic code so that it is used in 
1785      * finger_table_add also while choosing the closest one among new and existing
1786      * one. */
1787 /**
1788  * my_id = 0
1789  * finger = 5
1790  * key = 3
1791  * [0,5) â†’ my_id
1792  * [5,0) â†’ finger
1793
1794  * 0 <= key < 5, so key should go to 5. 
1795
1796  */
1797 /**
1798  * Select the closest peer among two peers (which should not be same)
1799  * with respect to value and finger_table_index
1800  * @param peer1 First peer
1801  * @param peer2 Second peer
1802  * @param value Value relative to which we find the closest
1803  * @param finger_table_index Index in finger map. If equal to PREDECESSOR_FINGER_ID,
1804  *                         then we use different logic than other
1805  *                         finger_table_index
1806  * @return Closest peer among two peers.
1807  */
1808 static struct GNUNET_PeerIdentity *
1809 select_closest_peer (struct GNUNET_PeerIdentity *peer1,
1810                      struct GNUNET_PeerIdentity *peer2,
1811                      uint64_t value,
1812                      unsigned int finger_table_index)
1813 {
1814   struct GNUNET_PeerIdentity *closest_peer;
1815
1816   /* FIXME: select closest peer w.r.t. value. [friend_id, current_successor->id)
1817      and [current_successor->id, friend_id). Check in which range value lies.
1818      Also, check for wrap around. Set the value of current_successor accordingly.*/
1819   if (PREDECESSOR_FINGER_ID == finger_table_index)
1820     closest_peer = select_closest_predecessor (peer1, peer2, value);
1821   else
1822     closest_peer = select_closest_finger (peer1, peer2, value);
1823
1824   return closest_peer;
1825 }
1826
1827
1828 /**
1829  * FIXME: free every memory allocated using malloc before the function ends
1830  * i.e. trail.
1831  * FIXME: better names and more refactoring. 
1832  * Compare FINGER entry with current successor. If finger's first friend of all
1833  * its trail is not congested and  has not crossed trail threshold, then check 
1834  * if finger peer identity is closer to final_destination_finger_value than
1835  * current_successor. If yes then update current_successor. 
1836  * @param current_successor[in/out]
1837  * @return 
1838  */
1839 static struct Closest_Peer *
1840 compare_finger_and_current_successor (struct Closest_Peer *current_closest_peer)
1841 {
1842   struct FingerInfo *finger;
1843   struct FriendInfo *friend;
1844   struct GNUNET_PeerIdentity *closest_peer;
1845   int i;
1846   
1847   for (i = 0; i < MAX_FINGERS; i++)
1848   {
1849     struct Selected_Finger_Trail *finger_trail;
1850     finger = &finger_table[i];
1851     
1852     if (GNUNET_NO == finger->is_present)
1853       continue;
1854
1855     /* If my identity is same as current closest peer then don't consider me*/
1856     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
1857                                               &current_closest_peer->best_known_destination))
1858       continue;
1859     
1860     /* If I am my own finger, then ignore this finger. */
1861     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
1862                                               &my_identity))
1863       continue;
1864     
1865     /* If finger is friend. */
1866     if (NULL != (friend = GNUNET_CONTAINER_multipeermap_get 
1867                 (friend_peermap, &finger->finger_identity)))
1868     {
1869       if (GNUNET_YES == is_friend_congested (friend))
1870         continue;
1871       
1872        /* If not congested then compare it with current_successor. */
1873       if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
1874                                                  &current_closest_peer->best_known_destination))
1875         continue;
1876       
1877       closest_peer = select_closest_peer (&finger->finger_identity, 
1878                                           &current_closest_peer->best_known_destination,
1879                                           current_closest_peer->destination_finger_value,
1880                                           current_closest_peer->is_predecessor);
1881       if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
1882                                                 closest_peer))
1883       {
1884         current_closest_peer->best_known_destination = finger->finger_identity;
1885         current_closest_peer->next_hop = finger->finger_identity;
1886       }
1887       continue;
1888     }
1889     
1890     /* Choose one of the trail to reach to finger. */
1891     finger_trail = select_finger_trail (finger);
1892     
1893     /* In case no trail found, ignore this finger. */
1894     if (NULL == finger_trail)
1895       continue;
1896     
1897      closest_peer = select_closest_peer (&finger->finger_identity, 
1898                                          &current_closest_peer->best_known_destination,
1899                                           current_closest_peer->destination_finger_value,
1900                                           current_closest_peer->is_predecessor);
1901      if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
1902                                                closest_peer))
1903      {
1904        current_closest_peer->best_known_destination = finger->finger_identity;
1905        current_closest_peer->next_hop = finger_trail->friend.id;
1906        current_closest_peer->trail_id = finger_trail->trail_id;
1907      }
1908       continue;
1909   }
1910   return current_closest_peer;
1911 }
1912
1913
1914 /**
1915  * Compare friend entry with current successor. If friend is not congested and
1916  * has not crossed trail threshold, then check if friend peer identity is
1917  * closer to final_destination_finger_value than current_successor. If yes
1918  * then update current_successor. 
1919  * @param cls closure
1920  * @param key current public key
1921  * @param value struct Closest_Peer
1922  * @return #GNUNET_YES if we should continue to iterate,
1923  *         #GNUNET_NO if not.
1924  */
1925 static int
1926 compare_friend_and_current_closest_peer (void *cls,
1927                                          const struct GNUNET_PeerIdentity *key,
1928                                          void *value)
1929 {
1930   struct FriendInfo *friend = value;
1931   struct Closest_Peer *current_closest_peer = cls;
1932   struct GNUNET_PeerIdentity *closest_peer;
1933   
1934   if (GNUNET_YES == is_friend_congested (friend))
1935     return GNUNET_YES;
1936  
1937   if (0 == 
1938           GNUNET_CRYPTO_cmp_peer_identity (&friend->id,
1939                                            &current_closest_peer->best_known_destination))
1940     return GNUNET_YES;
1941   
1942   closest_peer = select_closest_peer (&friend->id, 
1943                                       &current_closest_peer->best_known_destination,
1944                                       current_closest_peer->destination_finger_value,
1945                                       current_closest_peer->is_predecessor);
1946
1947   /* If friend is the closest successor. */
1948   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&friend->id, closest_peer))
1949   {
1950     current_closest_peer->best_known_destination = friend->id;
1951     current_closest_peer->next_hop = friend->id;
1952   }
1953   
1954   return GNUNET_YES;
1955 }
1956
1957 /**
1958  * Initialize current_successor to my_identity.
1959  * @param my_identity My peer identity
1960  * @return current_successor
1961  */
1962 static struct Closest_Peer *
1963 init_current_successor (struct GNUNET_PeerIdentity my_identity,
1964                         uint64_t destination_finger_value,
1965                         unsigned int is_predecessor)
1966 {
1967   struct Closest_Peer *current_closest_peer;
1968   
1969   current_closest_peer = GNUNET_new (struct Closest_Peer);
1970   memset (&current_closest_peer->trail_id, 0, sizeof (current_closest_peer->trail_id)); 
1971   current_closest_peer->destination_finger_value = destination_finger_value;
1972   current_closest_peer->is_predecessor = is_predecessor;
1973   current_closest_peer->next_hop = my_identity;
1974   current_closest_peer->best_known_destination = my_identity;
1975   
1976   return current_closest_peer;
1977 }
1978
1979
1980 /**
1981  * FIXME: first check if the finger == closest_peer then don't do anything. 
1982  * Find the successor for destination_finger_value among my_identity, all my
1983  * friend and all my fingers. Don't consider friends or fingers
1984  * which are congested or have crossed the threshold.
1985  * @param destination_finger_value Peer closest to this value will be the next successor.
1986  * @param local_best_known_destination [out] Updated to my_identity if I am the 
1987  *                                     final destination. Updated to friend 
1988  *                                     identity in case a friend is successor,
1989  *                                     updated to first friend to reach to finger
1990  *                                     in case finger is the destination.
1991  * @param new_intermediate_trail_id [out] In case a finger is the
1992  *                                  @a local_best_known_destination,
1993  *                                  then it is the trail to reach it. Else
1994  *                                  default set to 0.
1995  * @param is_predecessor Are we looking for predecessor or finger?
1996  * @return Next hop to reach to local_best_known_destination. In case my_identity
1997  *         or a friend is a local_best_known_destination, then 
1998  *         next_hop = local_best_known_destination. Else
1999  *         next_hop is the first friend to reach to finger (local_best_known_destination)
2000  */
2001 static struct GNUNET_PeerIdentity *
2002 find_successor (uint64_t destination_finger_value,
2003                 struct GNUNET_PeerIdentity *local_best_known_destination,
2004                 struct GNUNET_HashCode *new_intermediate_trail_id,
2005                 unsigned int is_predecessor)
2006 {
2007   struct Closest_Peer *current_closest_peer;
2008   struct GNUNET_PeerIdentity *next_hop;
2009
2010    /* Initialize current_successor to my_identity. */
2011   current_closest_peer = init_current_successor (my_identity,
2012                                                  destination_finger_value,
2013                                                  is_predecessor);
2014
2015   /* Compare each friend entry with current_successor and update current_successor
2016    * with friend if its closest. */
2017   GNUNET_assert (GNUNET_SYSERR != 
2018                  GNUNET_CONTAINER_multipeermap_iterate (friend_peermap, 
2019                                                         &compare_friend_and_current_closest_peer,
2020                                                         current_closest_peer));
2021   
2022   /* Compare each finger entry with current_successor and update current_successor
2023    * with finger if its closest. */
2024   compare_finger_and_current_successor (current_closest_peer);
2025   
2026   *local_best_known_destination = current_closest_peer->best_known_destination;
2027   new_intermediate_trail_id = &current_closest_peer->trail_id;
2028   next_hop = GNUNET_new (struct GNUNET_PeerIdentity);
2029   *next_hop = current_closest_peer->next_hop;
2030   
2031   return next_hop;
2032 }
2033
2034
2035 /**
2036  * Construct a Put message and send it to target_peer.
2037  * @param key Key for the content
2038  * @param block_type Type of the block
2039  * @param options Routing options
2040  * @param desired_replication_level Desired replication count
2041  * @param best_known_dest Peer to which this message should reach eventually,
2042  *                        as it is best known destination to me. 
2043  * @param intermediate_trail_id Trail id in case 
2044  * @param target_peer Peer to which this message will be forwarded.
2045  * @param hop_count Number of hops traversed so far.
2046  * @param put_path_length Total number of peers in @a put_path
2047  * @param put_path Number of peers traversed so far
2048  * @param expiration_time When does the content expire
2049  * @param data Content to store
2050  * @param data_size Size of content @a data in bytes
2051  */
2052 void
2053 GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
2054                          enum GNUNET_BLOCK_Type block_type,
2055                                            enum GNUNET_DHT_RouteOption options,
2056                                            uint32_t desired_replication_level,
2057                                            struct GNUNET_PeerIdentity *best_known_dest,
2058                                            struct GNUNET_HashCode *intermediate_trail_id,
2059                                            struct GNUNET_PeerIdentity *target_peer,
2060                          uint32_t hop_count,
2061                          uint32_t put_path_length,
2062                          struct GNUNET_PeerIdentity *put_path,
2063                          struct GNUNET_TIME_Absolute expiration_time,
2064                          const void *data, size_t data_size)
2065 {
2066   struct PeerPutMessage *ppm;
2067   struct P2PPendingMessage *pending;
2068   struct FriendInfo *target_friend;
2069   struct GNUNET_PeerIdentity *pp;
2070   struct GNUNET_PeerIdentity local_best_known_dest;
2071   size_t msize;
2072   
2073   msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
2074           sizeof (struct PeerPutMessage);
2075   
2076   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2077   {
2078     put_path_length = 0;
2079     msize = data_size + sizeof (struct PeerPutMessage);
2080   }
2081   
2082   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2083   {
2084     GNUNET_break (0);
2085     return;
2086   }
2087   
2088    /* This is the first call made from clients file. So, we should search for the
2089      target_friend. */
2090   if (NULL == target_peer)
2091   {
2092     uint64_t key_value;
2093     struct GNUNET_PeerIdentity *next_hop;
2094    
2095     memcpy (&key_value, key, sizeof (uint64_t));    
2096     next_hop = find_successor (key_value, &local_best_known_dest, 
2097                                intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);
2098     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&local_best_known_dest, &my_identity)) 
2099     {
2100       /* I am the destination but we have already done datacache_put in client file.  */
2101       return;
2102     }
2103     else
2104       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);   
2105   }
2106   else
2107   {
2108     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer); 
2109   }
2110   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2111   pending->timeout = expiration_time;
2112   ppm = (struct PeerPutMessage *) &pending[1];
2113   pending->msg = &ppm->header;
2114   ppm->header.size = htons (msize);
2115   ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
2116   ppm->options = htonl (options);
2117   ppm->block_type = htonl (block_type);
2118   ppm->hop_count = htonl (hop_count + 1);
2119   ppm->desired_replication_level = htonl (desired_replication_level);
2120   ppm->put_path_length = htonl (put_path_length);
2121   ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
2122   if (NULL == best_known_dest)
2123     ppm->best_known_destination = local_best_known_dest;
2124   else
2125     ppm->best_known_destination = *best_known_dest;
2126   ppm->key = *key;
2127   if (NULL == intermediate_trail_id)
2128     memset (&ppm->intermediate_trail_id, 0, sizeof (ppm->intermediate_trail_id));
2129   else
2130     ppm->intermediate_trail_id = *intermediate_trail_id;
2131   pp = (struct GNUNET_PeerIdentity *) &ppm[1];
2132   if (put_path_length != 0)
2133   {
2134     memcpy (pp, put_path,
2135             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
2136   }
2137   memcpy (&pp[put_path_length], data, data_size);
2138   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2139   target_friend->pending_count++;
2140   process_friend_queue (target_friend);
2141 }
2142
2143
2144 /**
2145  * Construct a Get message and send it to target_peer.
2146  * @param key Key for the content
2147  * @param block_type Type of the block
2148  * @param options Routing options
2149  * @param desired_replication_level Desired replication count
2150  * @param best_known_dest Peer which should get this message. Same as target peer
2151  *                        if best_known_dest is a friend else its a finger.
2152  * @param intermediate_trail_id  Trail id to reach to @a best_known_dest
2153  *                              in case it is a finger else set to 0.
2154  * @param target_peer Peer to which this message will be forwarded.
2155  * @param hop_count Number of hops traversed so far.
2156  * @param data Content to store
2157  * @param data_size Size of content @a data in bytes
2158  * @param get_path_length Total number of peers in @a get_path
2159  * @param get_path Number of peers traversed so far
2160  */
2161 void
2162 GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
2163                          enum GNUNET_BLOCK_Type block_type,
2164                          enum GNUNET_DHT_RouteOption options,
2165                          uint32_t desired_replication_level,
2166                          const struct GNUNET_PeerIdentity *best_known_dest,
2167                          struct GNUNET_HashCode *intermediate_trail_id,
2168                          struct GNUNET_PeerIdentity *target_peer,
2169                          uint32_t hop_count,
2170                          uint32_t get_path_length,
2171                          struct GNUNET_PeerIdentity *get_path)
2172 {
2173   struct PeerGetMessage *pgm;
2174   struct P2PPendingMessage *pending;
2175   struct FriendInfo *target_friend;
2176   struct GNUNET_PeerIdentity local_best_known_dest;
2177   struct GNUNET_PeerIdentity *gp;
2178   size_t msize;
2179   
2180   msize = sizeof (struct PeerGetMessage) + 
2181           (get_path_length * sizeof (struct GNUNET_PeerIdentity));
2182   
2183   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2184   {
2185     get_path_length = 0;
2186     msize = sizeof (struct PeerPutMessage);
2187   }
2188   
2189   if (msize > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2190   {
2191     GNUNET_break (0);
2192     return;
2193   }
2194   
2195   /* This is the first time we got request from our own client file. */
2196   if (NULL == target_peer)
2197   {
2198     struct GNUNET_PeerIdentity *next_hop;
2199     uint64_t key_value;
2200     
2201     memcpy (&key_value, key, sizeof (uint64_t)); //FIXME: endianess of key?
2202     
2203     /* Find the next destination to forward the packet. */
2204     next_hop = find_successor (key_value, &local_best_known_dest,
2205                                intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);
2206
2207     /* I am the destination. I have the data. */
2208     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
2209                                               &local_best_known_dest)) 
2210     {
2211       GDS_DATACACHE_handle_get (key,block_type, NULL, 0, 
2212                                 NULL, 0, 1, &my_identity, NULL,&my_identity);
2213       return;
2214     }
2215     else
2216     {
2217       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
2218     }
2219   }
2220   else
2221   {
2222     local_best_known_dest = *best_known_dest;
2223     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer); 
2224   }
2225   
2226   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2227   pending->importance = 0;    /* FIXME */
2228   pgm = (struct PeerGetMessage *) &pending[1];
2229   pending->msg = &pgm->header;
2230   pgm->header.size = htons (msize);
2231   pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
2232   pgm->get_path_length = htonl (get_path_length);
2233   pgm->best_known_destination = local_best_known_dest;
2234   
2235   if (NULL == intermediate_trail_id)
2236     memset (&pgm->intermediate_trail_id, 0, sizeof (pgm->intermediate_trail_id));
2237   else
2238     pgm->intermediate_trail_id = *intermediate_trail_id;
2239   pgm->hop_count = htonl (hop_count + 1);
2240   
2241   if (get_path_length != 0)
2242   {
2243     gp = (struct GNUNET_PeerIdentity *) &pgm[1];
2244     memcpy (gp, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
2245   }
2246   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2247   target_friend->pending_count++;
2248   process_friend_queue (target_friend);
2249 }
2250
2251
2252 /**
2253  * Send the get result to requesting client.
2254  * @param key Key of the requested data.
2255  * @param type Block type
2256  * @param target_peer Next peer to forward the message to.
2257  * @param source_peer Peer which has the data for the key.
2258  * @param put_path_length Number of peers in @a put_path
2259  * @param put_path Path taken to put the data at its stored location.
2260  * @param get_path_length Number of peers in @a get_path
2261  * @param get_path Path taken to reach to the location of the key.
2262  * @param expiration When will this result expire?
2263  * @param data Payload to store
2264  * @param data_size Size of the @a data
2265  */
2266 void
2267 GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
2268                                 enum GNUNET_BLOCK_Type type,
2269                                 struct GNUNET_PeerIdentity *target_peer,
2270                                 struct GNUNET_PeerIdentity *source_peer,
2271                                 unsigned int put_path_length,
2272                                 const struct GNUNET_PeerIdentity *put_path,
2273                                 unsigned int get_path_length,
2274                                 struct GNUNET_PeerIdentity *get_path,
2275                                 struct GNUNET_TIME_Absolute expiration,
2276                                 const void *data, size_t data_size)
2277 {
2278   struct PeerGetResultMessage *get_result;
2279   struct GNUNET_PeerIdentity *get_result_path;
2280   struct GNUNET_PeerIdentity *pp;
2281   struct P2PPendingMessage *pending;
2282   struct FriendInfo *target_friend;
2283   int current_path_index;
2284   size_t msize;
2285
2286   msize = get_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
2287           sizeof (struct PeerPutMessage);
2288  
2289   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2290   {
2291     GNUNET_break (0);
2292     return;
2293   }
2294   
2295   if(get_path_length > 0)
2296   {
2297     current_path_index = search_my_index(get_path, get_path_length);
2298     if (GNUNET_SYSERR == current_path_index)
2299     {
2300       GNUNET_break (0);
2301       return;
2302     }
2303   }
2304   if (0 == current_path_index)
2305   {
2306     GDS_CLIENTS_handle_reply (expiration, key, get_path_length, 
2307                               get_path, put_path_length,
2308                               put_path, type, data_size, data);
2309     return;
2310   }
2311   
2312   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
2313   pending->importance = 0;   
2314   get_result = (struct PeerGetResultMessage *)&pending[1];
2315   pending->msg = &get_result->header;
2316   get_result->header.size = htons (msize);
2317   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT);
2318   get_result->key = *key;
2319   /* FIXME: check if you are passing the correct querying_peer as described in
2320    the get_result documentation. */
2321   memcpy (&(get_result->querying_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
2322   get_result->expiration_time = expiration;
2323   get_result_path = (struct GNUNET_PeerIdentity *)&get_result[1];
2324   if (get_path_length != 0)
2325   memcpy (get_result_path, get_path,
2326             sizeof (struct GNUNET_PeerIdentity) * get_path_length);
2327   memcpy (&get_result_path[get_path_length], data, data_size);
2328   
2329   /* FIXME: Is this correct? */
2330   if (put_path_length != 0)
2331   {
2332     pp = (struct GNUNET_PeerIdentity *)&get_result_path[1];
2333     memcpy (pp, put_path,sizeof (struct GNUNET_PeerIdentity) * put_path_length);
2334   }
2335   
2336   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
2337                                                      &get_result_path[current_path_index - 1]);
2338   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
2339   target_friend->pending_count++;
2340   process_friend_queue (target_friend);
2341 }
2342
2343
2344 /**
2345  * Randomly choose one of your friends (which is not congested and have not crossed
2346  * trail threshold) from the friends_peer map
2347  * @return Friend Randomly chosen friend.
2348  *         NULL in case friend peermap is empty, or all the friends are either
2349  *              congested or have crossed trail threshold.
2350  */
2351 static struct FriendInfo *
2352 select_random_friend ()
2353 {
2354   unsigned int current_size;
2355   uint32_t index;
2356   unsigned int j = 0;
2357   struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
2358   struct GNUNET_PeerIdentity key_ret;
2359   struct FriendInfo *friend;
2360
2361   current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
2362   if (0 == current_size)
2363     return NULL;
2364
2365   index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
2366   iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
2367
2368   for (j = 0; j < index ; j++)
2369     GNUNET_assert (GNUNET_YES ==
2370                    GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL));
2371   do
2372   {
2373     if (j == current_size)
2374     {
2375       j = 0;
2376       GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
2377       iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
2378
2379     }
2380     GNUNET_assert (GNUNET_YES ==
2381                 GNUNET_CONTAINER_multipeermap_iterator_next (iter,
2382                                                              &key_ret,
2383                                                              (const void **)&friend));
2384
2385     /* This friend is not congested and has not crossed trail threshold. */
2386     if ((TRAILS_THROUGH_FRIEND_THRESHOLD > friend->trails_count) &&
2387         (0 == GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us))
2388     {
2389       break;
2390     }
2391     friend = NULL;
2392     j++;
2393   } while (j != index);
2394
2395   GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
2396   return friend;
2397 }
2398
2399
2400 /**
2401  * Compute 64 bit value of finger_identity corresponding to a finger index using 
2402  * chord formula. 
2403  * For all fingers:
2404  * n.finger[i] = n + pow (2,i),
2405  * For predecessor
2406  * n.finger[i] = n - 1, where
2407  * n = my_identity
2408  * i = finger_index.
2409  * n.finger[i] = 64 bit finger value
2410  * @param finger_index Index corresponding to which we calculate 64 bit value.
2411  * @return 64 bit value.
2412  */
2413 static uint64_t
2414 compute_finger_identity_value (unsigned int finger_index)
2415 {
2416   uint64_t my_id64;
2417
2418   memcpy (&my_id64, &my_identity, sizeof (uint64_t));
2419   my_id64 = GNUNET_ntohll (my_id64);
2420   
2421   /* Are we looking for immediate predecessor? */
2422   if (PREDECESSOR_FINGER_ID == finger_index)
2423     return (my_id64 -1);
2424   else
2425     return (my_id64 + (unsigned long) pow (2, finger_index));
2426 }
2427
2428
2429 /*
2430  * Choose a random friend. Start looking for the trail to reach to
2431  * finger identity corresponding to current_search_finger_index through 
2432  * this random friend.
2433  *
2434  * @param cls closure for this task
2435  * @param tc the context under which the task is running
2436  */
2437 static void
2438 send_find_finger_trail_message (void *cls,
2439                                 const struct GNUNET_SCHEDULER_TaskContext *tc)
2440 {
2441   struct FriendInfo *target_friend;
2442   struct GNUNET_TIME_Relative next_send_time;
2443   struct GNUNET_HashCode trail_id;
2444   unsigned int is_predecessor;
2445   uint64_t finger_id_value;
2446
2447   /* Schedule another send_find_finger_trail_message task. */
2448   next_send_time.rel_value_us =
2449       DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
2450       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
2451                                 DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
2452   find_finger_trail_task =
2453       GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_finger_trail_message,
2454                                     NULL);
2455
2456   /* My own routing table is all full. I can not store any more trails for which 
2457      I am source. */
2458   if (GNUNET_YES == GDS_ROUTING_threshold_reached())
2459     return;
2460   
2461   target_friend = select_random_friend ();
2462   if (NULL == target_friend)
2463   {
2464     return;
2465   }
2466
2467   finger_id_value = compute_finger_identity_value (current_search_finger_index);
2468   if (PREDECESSOR_FINGER_ID == current_search_finger_index)
2469     is_predecessor = 1;
2470   else
2471     is_predecessor = 0;
2472
2473   /* Generate a unique trail id for trail we are trying to setup. */
2474   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
2475                               &trail_id, sizeof (trail_id));
2476   GDS_NEIGHBOURS_send_trail_setup (my_identity, finger_id_value,
2477                                    target_friend->id, target_friend, 0, NULL,
2478                                    is_predecessor, trail_id, NULL);
2479 }
2480
2481
2482 /**
2483  * In case there are already maximum number of possible trails to reach to a
2484  * finger, then check if the new trail's length is lesser than any of the
2485  * existing trails.
2486  * If yes then replace that old trail by new trail.
2487  *
2488  * Note: Here we are taking length as a parameter to choose the best possible
2489  * trail, but there could be other parameters also like:
2490  * 1. duration of existence of a trail - older the better.
2491  * 2. if the new trail is completely disjoint than the
2492  *    other trails, then may be choosing it is better.
2493  *
2494  * @param existing_finger
2495  * @param new_finger_trail
2496  * @param new_finger_trail_length
2497  * @param new_finger_trail_id
2498  */
2499 static void
2500 select_and_replace_trail (struct FingerInfo *existing_finger,
2501                           const struct GNUNET_PeerIdentity *new_trail,
2502                           unsigned int new_trail_length,
2503                           struct GNUNET_HashCode new_trail_id)
2504 {
2505   struct Trail *trail_list_iterator;
2506   unsigned int largest_trail_length;
2507   unsigned int largest_trail_index;
2508   struct Trail_Element *trail_element;
2509   unsigned int i;
2510
2511   largest_trail_length = new_trail_length;
2512   largest_trail_index = MAXIMUM_TRAILS_PER_FINGER + 1;
2513
2514   GNUNET_assert (MAXIMUM_TRAILS_PER_FINGER == existing_finger->trails_count);
2515
2516   for (i = 0; i < existing_finger->trails_count; i++)
2517   {
2518     trail_list_iterator = &existing_finger->trail_list[i];
2519     if (trail_list_iterator->trail_length > largest_trail_length)
2520     {
2521       largest_trail_length = trail_list_iterator->trail_length;
2522       largest_trail_index = i;
2523     }
2524   }
2525
2526   if (largest_trail_index == (MAXIMUM_TRAILS_PER_FINGER + 1))
2527   {
2528     // tear down new trail: it's not better than the existing ones
2529     return;
2530   }
2531
2532   /* Send trail teardown message across the replaced trail. */
2533   struct Trail *replace_trail = &existing_finger->trail_list[largest_trail_index];
2534
2535   GDS_NEIGHBOURS_send_trail_teardown (replace_trail->trail_id,
2536                                       GDS_ROUTING_SRC_TO_DEST,
2537                                       &replace_trail->trail_head->peer);
2538   /* Free the trail. */
2539   while (NULL != (trail_element = replace_trail->trail_head))
2540   {
2541     GNUNET_CONTAINER_DLL_remove (replace_trail->trail_head,
2542                                  replace_trail->trail_tail, trail_element);
2543     GNUNET_free_non_null (trail_element);
2544   }
2545
2546   /* Add new trial at that location. */
2547   i = 0;
2548   while (i < new_trail_length)
2549   {
2550     struct Trail_Element *element = GNUNET_new (struct Trail_Element);
2551     element->peer = new_trail[i];
2552
2553     GNUNET_CONTAINER_DLL_insert_tail (replace_trail->trail_head,
2554                                       replace_trail->trail_tail,
2555                                       element);
2556   }
2557 }
2558
2559
2560 /**
2561  * Check if the new trail to reach to finger is unique or do we already have
2562  * such a trail present for finger.
2563  * @param existing_finger Finger identity
2564  * @param new_trail New trail to reach @a existing_finger
2565  * @param trail_length Total number of peers in new_trail.
2566  * @return #GNUNET_YES if the new trail is unique
2567  *         #GNUNET_NO if same trail is already present.
2568  */
2569 static int
2570 is_new_trail_unique (struct FingerInfo *existing_finger,
2571                      const struct GNUNET_PeerIdentity *new_trail,
2572                      unsigned int trail_length)
2573 {
2574   struct Trail *trail_list_iterator;
2575   struct Trail_Element *trail_element;
2576   int i;
2577   int j;
2578   int trail_unique = GNUNET_NO;
2579
2580   for (i = 0; i < existing_finger->trails_count; i++)
2581   {
2582     trail_list_iterator = &existing_finger->trail_list[i];
2583     if (trail_list_iterator->trail_length != trail_length)
2584       continue;
2585     trail_element = trail_list_iterator->trail_head;
2586     for (j = 0; j < trail_list_iterator->trail_length; j++)
2587     {
2588       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&new_trail[j],
2589                                                 &trail_element->peer))
2590       {
2591         trail_unique = GNUNET_YES;
2592         break;
2593       }
2594     }
2595   }
2596   return trail_unique;
2597 }
2598
2599
2600 /**
2601  * Add a new trail to existing finger.
2602  * @param existing_finger
2603  * @param new_finger_trail
2604  * @param new_finger_trail_length
2605  * @param new_finger_trail_id
2606  */
2607 static void
2608 add_new_trail (struct FingerInfo *existing_finger,
2609                const struct GNUNET_PeerIdentity *new_trail,
2610                unsigned int new_trail_length,
2611                struct GNUNET_HashCode new_trail_id)
2612 {
2613   struct Trail *trail_list_iterator;
2614   struct FriendInfo *first_friend;
2615   int i;
2616
2617   if (GNUNET_NO == is_new_trail_unique (existing_finger, new_trail,
2618                                         new_trail_length))
2619   {
2620     return;
2621   }
2622
2623   // FIXME checking trail_head is NOT a valid way to verify an open slot
2624   for (i = 0; existing_finger->trail_list[i].trail_head != NULL; i++)
2625     GNUNET_assert (i < MAXIMUM_TRAILS_PER_FINGER);
2626
2627   trail_list_iterator = &existing_finger->trail_list[i];
2628
2629   if (new_trail_length > 0)
2630     first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2631                                                       &new_trail[0]);
2632   else
2633     first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2634                                                       &(existing_finger->finger_identity));
2635   first_friend->trails_count++;
2636   /* FIXME; we removed this field but read fixme. */
2637   //trail_list_iterator->first_friend_trail_count = first_friend->trails_count;
2638   trail_list_iterator->trail_length = new_trail_length;
2639
2640   for (i = 0; i < new_trail_length; i++)
2641   {
2642     struct Trail_Element *element;
2643     element = GNUNET_new (struct Trail_Element);
2644
2645     element->peer = new_trail[i];
2646     GNUNET_CONTAINER_DLL_insert_tail (trail_list_iterator->trail_head,
2647                                       trail_list_iterator->trail_tail,
2648                                       element);
2649   }
2650   existing_finger->trails_count++;
2651 }
2652
2653
2654 /**
2655  * Send trail teardown message for a specific trail of a finger.
2656  * @param finger Finger whose trail is to be removed. 
2657  * @param trail List of peers in trail from me to a finger, NOT including 
2658  *              endpoints. 
2659  */
2660 static void
2661 send_trail_teardown (struct FingerInfo *finger,
2662                      struct Trail *trail)
2663 {
2664   /* FIXME: Now source also stores a trail entry in its routing table. before
2665    sending the trail teardown, you should get next_hop from routing table.
2666    If it is NULL, it means that path is broken, then remove the trail. 
2667    return a value to calling function so that if all trails are removed,
2668    then remove finger. */
2669   /* We should decerement the friend trail count here. */
2670   struct FriendInfo *friend;
2671   
2672   GNUNET_assert (NULL != (friend = 
2673           GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2674                                              &trail->trail_head->peer)));
2675   
2676   friend->trails_count--;
2677   GDS_NEIGHBOURS_send_trail_teardown (trail->trail_id,
2678                                       GDS_ROUTING_SRC_TO_DEST,
2679                                       &trail->trail_head->peer);
2680 }
2681
2682
2683 /**
2684  * Send trail teardown message across all the trails to reach to finger. 
2685  * @param finger Finger whose all the trail should be freed. 
2686  */
2687 static void
2688 send_all_finger_trails_teardown (struct FingerInfo *finger)
2689 {
2690   struct Trail *trail;
2691   int i;
2692
2693   for (i = 0; i < finger->trails_count; i++)
2694   {
2695     trail = &finger->trail_list[i];
2696     if (trail->trail_length > 0)
2697     {
2698      /* decerement the friend trails count. */
2699      send_trail_teardown (finger, trail);
2700     }
2701   }
2702 }
2703
2704
2705 /**
2706  * Free a specific trail
2707  * @param trail List of peers to be freed. 
2708  */
2709 static void
2710 free_trail (struct Trail *trail)
2711 {
2712   struct Trail_Element *trail_element;
2713
2714   while (NULL != (trail_element = trail->trail_head))
2715   {
2716     GNUNET_CONTAINER_DLL_remove (trail->trail_head, 
2717                                  trail->trail_tail,
2718                                  trail_element);
2719     GNUNET_free_non_null (trail_element);
2720   }  
2721   trail->trail_head = NULL;
2722   trail->trail_tail = NULL;
2723 }
2724
2725
2726 /**
2727  * Free finger and its trail.
2728  * @param finger Finger to be freed.
2729  */
2730 static void
2731 free_finger (struct FingerInfo *finger, unsigned int finger_table_index)
2732 {
2733   struct Trail *trail;
2734   unsigned int i;
2735
2736   for (i = 0; i < finger->trails_count; i++)
2737   {
2738     trail = &finger->trail_list[i];
2739     if (GNUNET_NO == trail->is_present)
2740       continue;
2741     
2742     if (trail->trail_length > 0)
2743       free_trail (trail);
2744   }
2745   
2746   finger->is_present = GNUNET_NO;
2747   memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
2748 }
2749
2750
2751 /**
2752  * FIXME: ensure that you are not adding any trail to reach to a friend which
2753  * is a finger. Also decide on should you increment trails count of a friend
2754  * which is also a finger. 
2755  * Add a new entry in finger table at finger_table_index. 
2756  * In case finger identity is me or a friend, then don't add a trail. NOTE
2757  * trail length to reach to a finger can be 0 only if the finger is a friend
2758  * or my identity.
2759  * In case a finger is a friend, then increment the trails count of the friend.
2760  * @param finger_identity Peer Identity of new finger
2761  * @param finger_trail Trail to reach from me to finger (excluding both end points).
2762  * @param finger_trail_length Total number of peers in @a finger_trail.
2763  * @param trail_id Unique identifier of the trail.
2764  * @param finger_table_index Index in finger table.
2765  */
2766 static void
2767 add_new_finger (struct GNUNET_PeerIdentity finger_identity,
2768                 const struct GNUNET_PeerIdentity *finger_trail,
2769                 unsigned int finger_trail_length,
2770                 struct GNUNET_HashCode trail_id,
2771                 unsigned int finger_table_index)
2772 {
2773   struct FingerInfo *new_entry;
2774   struct FriendInfo *first_trail_hop;
2775   struct Trail *trail;
2776   int i = 0;
2777   
2778   new_entry = GNUNET_new (struct FingerInfo);
2779   new_entry->finger_identity = finger_identity;
2780   new_entry->finger_table_index = finger_table_index;
2781   new_entry->is_present = GNUNET_YES;
2782   
2783   /* If the new entry is my own identity or a friend. */
2784   if ((0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity)) ||
2785      (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_identity)))
2786   {
2787     new_entry->trails_count = 0;
2788     finger_table[finger_table_index] = *new_entry;
2789     return;
2790   }
2791   
2792   /* finger trail length can be 0 only in case if finger is my identity or
2793    finger is friend. We should never reach here. */
2794   GNUNET_assert (finger_trail_length > 0);
2795   
2796   GNUNET_assert (NULL != 
2797                 (first_trail_hop = 
2798                        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2799                                                           &finger_trail[0])));
2800   new_entry->trails_count = 1;
2801   first_trail_hop->trails_count++;
2802    
2803   /* Copy the finger trail into trail. */
2804   trail = GNUNET_new (struct Trail);
2805   while (i < finger_trail_length)
2806   {
2807     struct Trail_Element *element = GNUNET_new (struct Trail_Element);
2808
2809     element->next = NULL;
2810     element->prev = NULL;
2811     element->peer = finger_trail[i];
2812     GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
2813                                       trail->trail_tail,
2814                                       element);
2815     i++;
2816   }
2817   
2818   /* Add trail to trail list. */
2819   new_entry->trail_list[0].trail_head = trail->trail_head;
2820   new_entry->trail_list[0].trail_tail = trail->trail_tail;
2821   new_entry->trail_list[0].trail_length = finger_trail_length;
2822   new_entry->trail_list[0].trail_id = trail_id;
2823   new_entry->trail_list[0].is_present = GNUNET_YES;
2824   finger_table[finger_table_index] = *new_entry;
2825   GNUNET_free (new_entry);
2826   return;
2827 }
2828
2829
2830 /**
2831  * Scan the trail to check if there is any other friend in the trail other than
2832  * first hop. If yes then shortcut the trail, send trail compression message to
2833  * peers which are no longer part of trail and send back the updated trail
2834  * and trail_length to calling function.
2835  * @param finger_identity Finger whose trail we will scan.
2836  * @param finger_trail [in, out] Trail to reach from source to finger,
2837  * @param finger_trail_length  Total number of peers in original finger_trail.
2838  * @param finger_trail_id Unique identifier of the finger trail.
2839  * @return updated trail length in case we shortcut the trail, else original
2840  *         trail length.
2841  */
2842 static struct GNUNET_PeerIdentity *
2843 scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
2844                          const struct GNUNET_PeerIdentity *trail,
2845                          unsigned int trail_length,
2846                          struct GNUNET_HashCode trail_id,
2847                          int *new_trail_length)
2848 {
2849   struct FriendInfo *target_friend;
2850   struct GNUNET_PeerIdentity *new_trail;
2851   int i;
2852   
2853   /* If I am my own finger identity, then we set trail_length = 0.
2854    Note: Here we don't send trail compression message, as no peer in its
2855    trail added an entry in its routing table.*/
2856   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
2857   {
2858     *new_trail_length = 0;
2859     return NULL;
2860   }
2861
2862   /* If finger identity is a friend. */
2863   if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_identity))
2864   {
2865     *new_trail_length = 0;
2866     
2867     /* If there is trail to reach this finger/friend */
2868     if (trail_length > 0)
2869     {
2870       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2871                                                          &trail[0]);
2872       /* FIXME: In case its finger == friend, then may be we send a trail 
2873        teardown message as it does not make any sense to have any routing e
2874        entry in your own routing table.*/
2875       GDS_NEIGHBOURS_send_trail_compression (my_identity, 
2876                                              trail_id, finger_identity,
2877                                              target_friend);
2878     }
2879     return NULL;
2880   }
2881
2882   /*  For other cases, when its neither a friend nor my own identity.*/
2883   for (i = trail_length - 1; i > 0; i--)
2884   {
2885     /* If the element at this index in trail is a friend. */
2886     if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &trail[i]))
2887     {
2888       struct FriendInfo *target_friend;
2889       int j = 0;
2890
2891       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2892                                                          &trail[0]);
2893       GDS_NEIGHBOURS_send_trail_compression (my_identity, 
2894                                              trail_id, trail[i],
2895                                              target_friend);
2896
2897     
2898       /* Copy the trail from index i to index (trail_length -1) into a new trail
2899        *  and update new trail length */
2900       new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * i);
2901       while (i < trail_length)
2902       {
2903         memcpy (&new_trail[j], &trail[i], sizeof(struct GNUNET_PeerIdentity));
2904         j++;
2905         i++;
2906       }
2907       *new_trail_length = j+1;
2908       return new_trail;
2909     }
2910   }
2911   
2912   /* If we found no other friend except the first hop, return the original
2913      trail back.*/
2914   new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * trail_length); 
2915   *new_trail_length = trail_length;
2916   memcpy (new_trail, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
2917   return new_trail;
2918 }
2919
2920
2921 /**
2922  * Send verify successor message to your current successor over the shortest
2923  * trail. 
2924  * @param successor Current successor.
2925  */
2926 static void
2927 send_verify_successor_message (struct FingerInfo *successor)
2928 {
2929   /*
2930    * FIXME: should we send a verify successor message across all the trails
2931    * in case we send through all friends. It complicates the logic, don't
2932    * do it at the moment. Write it as optimization and do it later. 
2933    * 1. Here we can have 3 types of fingers
2934    * --> my own identity
2935    *     Assumption that the calling function will not send request for
2936    *     such successor. Move the logic here. 
2937    * --> friend is a finger
2938    *     Need to verify if we keep the trails count for a friend. In case of
2939    *     friend there is no trail to reach to that friend, so
2940    *     1. no entry in routing table
2941    *     2. no trail id
2942    *     3. no trails count
2943    *     4. but do we increment the count of trails through the friend? 
2944    *        Trails count is used only to keep a limit on number of trails
2945    *        that a friend should be part of. No need to increment the trails
2946    *        count for a friend which is a finegr also. so, if finger = friend
2947    *        then don't increment the trails count. But if the same friend 
2948    *        is the first friend to reach to some other finger then increment
2949    *        the trails count. Not sure if this design is correct need to verify
2950    *        again. 
2951    * --> real finger
2952    */
2953   struct FriendInfo *target_friend;
2954   struct GNUNET_HashCode trail_id;
2955   int i;
2956   
2957   /* If successor is a friend. */
2958   if (successor->trails_count == 0)
2959   {
2960     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
2961                                                        &successor->finger_identity);
2962     memset ((void *)&trail_id, 0 , sizeof (trail_id));
2963     GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
2964                                                   successor->finger_identity,
2965                                                   trail_id, NULL, 0,
2966                                                   target_friend);
2967     return;
2968   }
2969   
2970   for (i = 0; i < successor->trails_count; i++)
2971   {
2972     struct Trail *trail;
2973     struct Trail_Element *element;
2974     unsigned int trail_length;
2975     int j = 0;
2976     
2977     trail = &successor->trail_list[i];
2978     
2979     /* No trail stored at this index. */
2980     if (GNUNET_YES == trail->is_present)
2981       continue;
2982     
2983     /* Only in case of a friend we can have no trail. We have already handled
2984      * that case. So, now we should never have any such trail. */
2985     GNUNET_assert (trail->trail_length > 0);
2986     trail_id = trail->trail_id;
2987     trail_length = trail->trail_length;
2988     
2989     /* Copy the trail into peer list. */
2990     element = trail->trail_head;
2991     struct GNUNET_PeerIdentity peer_list[trail_length];
2992     while (j < trail_length)
2993     {
2994       peer_list[j] = element->peer;
2995       element = element->next;
2996       j++;
2997     }
2998    
2999     GNUNET_assert (NULL != (target_friend = 
3000                            GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
3001                                                               &peer_list[0])));
3002     GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
3003                                                   successor->finger_identity,
3004                                                   trail_id, peer_list, trail_length,
3005                                                   target_friend);
3006     
3007   }
3008 }
3009
3010
3011 /**
3012  * FIXME" clear abstraction of current search finger index and finger map index.
3013  * it never goes to 63. I don't know why
3014  * Update the current search finger index. 
3015  */
3016 static void
3017 update_current_search_finger_index (struct GNUNET_PeerIdentity finger_identity,
3018                                     unsigned int finger_table_index)
3019 {
3020   struct FingerInfo *successor;
3021
3022   if (finger_table_index != current_search_finger_index)
3023     return;
3024   
3025   successor = &finger_table[0];
3026   if (GNUNET_NO == successor->is_present)
3027     GNUNET_break(0);
3028  
3029   /* We were looking for immediate successor.  */
3030   if (0 == current_search_finger_index)
3031   {
3032     /* Start looking for immediate predecessor. */
3033     current_search_finger_index = PREDECESSOR_FINGER_ID;
3034
3035     /* If I am not my own successor, then send a verify successor message. */
3036     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
3037     {
3038       send_verify_successor_message (successor);
3039     }
3040     return;
3041   }
3042   
3043   current_search_finger_index = current_search_finger_index - 1;
3044   return;
3045 }
3046
3047
3048 /**
3049  * Calculate finger_table_index from initial 64 bit finger identity value that 
3050  * we send in trail setup message. 
3051  * @param ultimate_destination_finger_value Value that we calculated from our
3052  *                                          identity and finger_table_index.
3053  * @param is_predecessor Is the entry for predecessor or not?
3054  * @return finger_table_index Value between 0 <= finger_table_index <= 64
3055  *                            -1, if no valid finger_table_index is found. 
3056  */
3057 static unsigned int
3058 get_finger_table_index (uint64_t ultimate_destination_finger_value,
3059                         unsigned int is_predecessor)
3060 {
3061   uint64_t my_id64;
3062   int diff;
3063   unsigned int finger_table_index;
3064
3065   memcpy (&my_id64, &my_identity, sizeof (uint64_t));
3066   my_id64 = GNUNET_ntohll (my_id64);
3067   
3068   /* Is this a predecessor finger? */
3069   if (1 == is_predecessor)
3070   {
3071     diff =  my_id64 - ultimate_destination_finger_value;
3072     if (1 == diff)
3073       finger_table_index = PREDECESSOR_FINGER_ID;
3074     else
3075       finger_table_index = PREDECESSOR_FINGER_ID + 1; //error value
3076     
3077   }
3078   else 
3079   {
3080     diff = ultimate_destination_finger_value - my_id64;
3081     finger_table_index = (log10 (diff))/(log10 (2));
3082   }
3083   
3084   return finger_table_index;
3085 }
3086
3087
3088 /**
3089  * Remove finger and its associated data structures from finger table. 
3090  * @param finger Finger to be removed.
3091  */
3092 static void
3093 remove_existing_finger (struct FingerInfo *existing_finger, unsigned int finger_table_index)
3094 {
3095   struct FriendInfo *friend;
3096   struct FingerInfo *finger;
3097   
3098   finger = &finger_table[finger_table_index];
3099   GNUNET_assert (GNUNET_YES == finger->is_present);
3100   
3101   /* If I am my own finger, then we have no trails. */
3102   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
3103                                             &my_identity))
3104   {
3105     finger->is_present = GNUNET_NO;
3106     memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
3107     return;
3108   }
3109   
3110   /* If finger is a friend, then decrement the trail count and free the finger. */
3111   friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3112                                               &finger->finger_identity);
3113   if (NULL != friend)
3114   {
3115     friend->trails_count--;
3116     finger->is_present = GNUNET_NO;
3117     memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
3118     return;
3119   }
3120   
3121   /* For all other fingers, send trail teardown across all the trails to reach
3122    finger, and free the finger. */
3123   send_all_finger_trails_teardown (finger);
3124   free_finger (finger, finger_table_index);
3125   return;
3126 }
3127
3128 #if 0
3129 /**
3130  * This is a test function to print all the entries of friend table.
3131  */
3132 static void
3133 test_friend_peermap_print ()
3134 {
3135   struct FriendInfo *friend;
3136   struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
3137   struct GNUNET_PeerIdentity print_peer;
3138   struct GNUNET_PeerIdentity key_ret;
3139   int i;
3140   
3141   friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
3142   
3143   for (i = 0; i < GNUNET_CONTAINER_multipeermap_size (friend_peermap); i++)
3144   {
3145     if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (friend_iter,
3146                                                                   &key_ret,
3147                                                                   (const void **)&friend))
3148     {
3149       memcpy (&print_peer, &key_ret, sizeof (struct GNUNET_PeerIdentity));
3150       FPRINTF (stderr,_("\nSUPU %s, %s, %d, friend = %s, friend->trails_count = %d"),
3151               __FILE__, __func__,__LINE__, GNUNET_i2s(&print_peer), friend->trails_count);
3152     }
3153   }
3154 }
3155
3156
3157 /**
3158  * This is a test function, to print all the entries of finger table.
3159  */
3160 static void
3161 test_finger_table_print()
3162 {
3163   struct FingerInfo *finger;
3164   struct GNUNET_PeerIdentity print_peer;
3165   struct Trail *trail;
3166   int i;
3167   int j;
3168   int k;
3169   
3170   FPRINTF (stderr,_("\nSUPU************  FINGER_TABLE"));
3171   for (i = 0; i < MAX_FINGERS; i++)
3172   {
3173     finger = &finger_table[i];
3174     
3175     if (GNUNET_NO == finger->is_present)
3176       continue;
3177     
3178     print_peer = finger->finger_identity;
3179     FPRINTF (stderr,_("\nSUPU %s, %s, %d, finger_table[%d] = %s, trails_count = %d"),
3180             __FILE__, __func__,__LINE__,i,GNUNET_i2s (&print_peer), finger->trails_count);
3181     
3182     
3183     for (j = 0; j < finger->trails_count; j++)
3184     {
3185       trail = &finger->trail_list[j];
3186       FPRINTF (stderr,_("\nSUPU %s, %s, %d, trail_id[%d]=%s"),__FILE__, __func__,__LINE__,j, GNUNET_h2s(&trail->trail_id));
3187       struct Trail_Element *element;
3188       element = trail->trail_head;
3189       for (k = 0; k < trail->trail_length; k++)
3190       {  
3191         print_peer = element->peer;
3192         FPRINTF (stderr,_("\nSUPU %s, %s, %d,trail[%d] = %s "),__FILE__, __func__,__LINE__,k, GNUNET_i2s(&print_peer));
3193         element = element->next;
3194       }
3195     }
3196   }
3197 }
3198 #endif
3199
3200 /**
3201  * Check if there is already an entry in finger_table at finger_table_index.
3202  * We get the finger_table_index from 64bit finger value we got from the network.
3203  * -- If yes, then select the closest finger.
3204  *   -- If new and existing finger are same, then check if you can store more 
3205  *      trails. 
3206  *      -- If yes then add trail, else keep the best trails to reach to the 
3207  *         finger. 
3208  *   -- If the new finger is closest, remove the existing entry, send trail
3209  *      teardown message across all the trails to reach the existing entry.
3210  *      Add the new finger.
3211  *  -- If new and existing finger are different, and existing finger is closest
3212  *     then do nothing.  
3213  * -- Update current_search_finger_index.
3214  * @param finger_identity Peer Identity of new finger
3215  * @param finger_trail Trail to reach the new finger
3216  * @param finger_length Total number of peers in @a new_finger_trail.
3217  * @param is_predecessor Is this entry for predecessor in finger_table?
3218  * @param finger_value 64 bit value of finger identity that we got from network.
3219  * @param finger_trail_id Unique identifier of @finger_trail.
3220  */
3221 static void
3222 finger_table_add (struct GNUNET_PeerIdentity finger_identity, 
3223                   const struct GNUNET_PeerIdentity *finger_trail, 
3224                   unsigned int finger_trail_length,
3225                   unsigned int is_predecessor,
3226                   uint64_t finger_value,
3227                   struct GNUNET_HashCode finger_trail_id)
3228 {
3229   struct FingerInfo *existing_finger;
3230   struct GNUNET_PeerIdentity *closest_peer;
3231   struct GNUNET_PeerIdentity *updated_trail;
3232   struct FingerInfo *successor;
3233   int updated_finger_trail_length; 
3234   unsigned int finger_table_index;
3235   
3236 #if 0
3237   test_friend_peermap_print();
3238   test_finger_table_print();
3239 #endif
3240   
3241   /* Get the finger_table_index corresponding to finger_value we got from network.*/
3242   finger_table_index = get_finger_table_index (finger_value, is_predecessor);
3243
3244   /* Invalid finger_table_index. */
3245   if ((finger_table_index > PREDECESSOR_FINGER_ID))
3246   {
3247     GNUNET_break_op (0);
3248     return;
3249   }
3250  
3251   updated_finger_trail_length = finger_trail_length;
3252   updated_trail =
3253        scan_and_compress_trail (finger_identity, finger_trail,
3254                                 finger_trail_length, finger_trail_id, 
3255                                 &updated_finger_trail_length);
3256    
3257   /* If the new entry is same as successor then don't add it in finger table,
3258    reset the current search finger index and exit. */
3259   if ((0 != finger_table_index) && 
3260       (PREDECESSOR_FINGER_ID != finger_table_index) &&
3261       (finger_table_index == current_search_finger_index))
3262   {
3263     successor = &finger_table[0];
3264     GNUNET_assert (GNUNET_YES == successor->is_present);
3265     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
3266                                               &successor->finger_identity))
3267     {
3268       current_search_finger_index = 0;
3269       return;
3270     }
3271   }
3272   
3273   existing_finger = &finger_table[finger_table_index];
3274   
3275   /* No entry present in finger_table for given finger map index. */
3276   if (GNUNET_NO == existing_finger->is_present)
3277   {
3278     add_new_finger (finger_identity, updated_trail, updated_finger_trail_length,
3279                     finger_trail_id, finger_table_index);
3280     update_current_search_finger_index (finger_identity, finger_table_index);
3281     return;
3282   }
3283   
3284   /* If existing entry and finger identity are not same. */
3285   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
3286                                             &finger_identity))
3287   {
3288     closest_peer = select_closest_peer (&existing_finger->finger_identity,
3289                                         &finger_identity,
3290                                         finger_value, finger_table_index);
3291     
3292     /* If the new finger is the closest peer. */
3293     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, closest_peer))
3294     {
3295       remove_existing_finger (existing_finger, finger_table_index);
3296       add_new_finger (finger_identity, updated_trail, updated_finger_trail_length,
3297                       finger_trail_id, finger_table_index);
3298     }
3299   }
3300   else
3301   {
3302     /* If both new and existing entry are same as my_identity, then do nothing. */
3303     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
3304                                               &my_identity))
3305       return;
3306     
3307     /* If the existing finger is not a friend. */
3308     if (NULL ==
3309         GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3310                                            &existing_finger->finger_identity))
3311     {
3312       /* If there is space to store more trails. */
3313       if (existing_finger->trails_count < MAXIMUM_TRAILS_PER_FINGER)
3314         add_new_trail (existing_finger, updated_trail,
3315                        finger_trail_length, finger_trail_id);
3316       else
3317         select_and_replace_trail (existing_finger, updated_trail,
3318                                   finger_trail_length, finger_trail_id);
3319     }
3320   }
3321   update_current_search_finger_index (finger_identity, finger_table_index);
3322   return;
3323 }
3324
3325
3326 /**
3327  * Core handler for P2P put messages.
3328  * @param cls closure
3329  * @param peer sender of the request
3330  * @param message message
3331  * @return #GNUNET_OK to keep the connection open,
3332  *         #GNUNET_SYSERR to close it (signal serious error)
3333  */
3334 static int
3335 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
3336                     const struct GNUNET_MessageHeader *message)
3337 {
3338   struct PeerPutMessage *put;
3339   struct GNUNET_PeerIdentity *put_path;
3340   struct GNUNET_HashCode test_key;
3341   enum GNUNET_DHT_RouteOption options;
3342   struct GNUNET_PeerIdentity best_known_dest;
3343   struct GNUNET_HashCode intermediate_trail_id;
3344   struct GNUNET_PeerIdentity *next_hop;
3345   void *payload;
3346   size_t msize;
3347   uint32_t putlen;
3348   size_t payload_size;
3349   uint64_t key_value;
3350   
3351   msize = ntohs (message->size);
3352   if (msize < sizeof (struct PeerPutMessage))
3353   {
3354     GNUNET_break_op (0);
3355     return GNUNET_YES;
3356   }
3357   
3358   put = (struct PeerPutMessage *) message;
3359   putlen = ntohl (put->put_path_length);
3360    
3361   if ((msize <
3362        sizeof (struct PeerPutMessage) +
3363        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
3364       (putlen >
3365        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
3366   {
3367     GNUNET_break_op (0);
3368     return GNUNET_YES;
3369   }
3370
3371   best_known_dest = put->best_known_destination;
3372   put_path = (struct GNUNET_PeerIdentity *) &put[1];
3373   payload = &put_path[putlen];
3374   options = ntohl (put->options);
3375   intermediate_trail_id = put->intermediate_trail_id;
3376   
3377   payload_size = msize - (sizeof (struct PeerPutMessage) + 
3378                           putlen * sizeof (struct GNUNET_PeerIdentity));
3379   
3380   switch (GNUNET_BLOCK_get_key (GDS_block_context, ntohl (put->block_type),
3381                                 payload, payload_size, &test_key))
3382   {
3383     case GNUNET_YES:
3384       if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
3385       {
3386         char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
3387         GNUNET_break_op (0);
3388         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3389                     "PUT with key `%s' for block with key %s\n",
3390                      put_s, GNUNET_h2s_full (&test_key));
3391         GNUNET_free (put_s);
3392         return GNUNET_YES;
3393       }
3394     break;
3395     case GNUNET_NO:
3396       GNUNET_break_op (0);
3397       return GNUNET_YES;
3398     case GNUNET_SYSERR:
3399       /* cannot verify, good luck */
3400       break;
3401   }
3402   
3403    if (ntohl (put->block_type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
3404   {
3405     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
3406                                    ntohl (put->block_type),
3407                                    NULL,    /* query */
3408                                    NULL, 0, /* bloom filer */
3409                                    NULL, 0, /* xquery */
3410                                    payload, payload_size))
3411     {
3412     case GNUNET_BLOCK_EVALUATION_OK_MORE:
3413     case GNUNET_BLOCK_EVALUATION_OK_LAST:
3414       break;
3415
3416     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3417     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3418     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
3419     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3420     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3421     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3422     default:
3423       GNUNET_break_op (0);
3424       return GNUNET_OK;
3425     }
3426   }
3427   
3428   /* extend 'put path' by sender */
3429   struct GNUNET_PeerIdentity pp[putlen + 1];
3430   if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
3431   {
3432     memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
3433     pp[putlen] = *peer;
3434     putlen++;
3435   }
3436   else
3437     putlen = 0;
3438   
3439   memcpy (&key_value, &(put->key), sizeof (uint64_t));
3440   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&best_known_dest, &my_identity)))
3441   {
3442     next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id, 
3443                                          GDS_ROUTING_SRC_TO_DEST);
3444   }
3445   else
3446   {
3447     next_hop = find_successor (key_value, &best_known_dest, 
3448                                &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR); 
3449   }
3450   
3451   if (NULL == next_hop)
3452   {
3453     GNUNET_STATISTICS_update (GDS_stats,
3454                               gettext_noop ("# Next hop to forward the packet not found "
3455                               "trail setup request, packet dropped."),
3456                               1, GNUNET_NO);
3457     return GNUNET_SYSERR;
3458   }
3459   
3460   GDS_CLIENTS_process_put (options,
3461                            ntohl (put->block_type),
3462                            ntohl (put->hop_count),
3463                            ntohl (put->desired_replication_level),
3464                            putlen, pp,
3465                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
3466                            &put->key,
3467                            payload,
3468                            payload_size);
3469   
3470   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &best_known_dest)) /* I am the final destination */
3471   {
3472     GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
3473                               &(put->key),putlen, pp, ntohl (put->block_type), 
3474                               payload_size, payload);
3475     return GNUNET_YES;
3476   }
3477   else
3478   {
3479     GDS_NEIGHBOURS_send_put (&put->key,  
3480                              ntohl (put->block_type),ntohl (put->options),
3481                              ntohl (put->desired_replication_level),
3482                              &best_known_dest, &intermediate_trail_id, next_hop,
3483                              ntohl (put->hop_count), putlen, pp,
3484                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
3485                              payload, payload_size);
3486  
3487      return GNUNET_YES;
3488   }
3489   return GNUNET_SYSERR;
3490 }
3491
3492
3493 /**
3494  * Core handler for p2p get requests.
3495  *
3496  * @param cls closure
3497  * @param peer sender of the request
3498  * @param message message
3499  * @return #GNUNET_OK to keep the connection open,
3500  *         #GNUNET_SYSERR to close it (signal serious error)
3501  */
3502 static int
3503 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
3504                     const struct GNUNET_MessageHeader *message)
3505 {
3506   const struct PeerGetMessage *get;
3507   const struct GNUNET_PeerIdentity *get_path;
3508   struct GNUNET_PeerIdentity best_known_dest;
3509   struct GNUNET_HashCode intermediate_trail_id;
3510   struct GNUNET_PeerIdentity *next_hop;
3511   uint32_t get_length;
3512   uint64_t key_value;
3513   size_t msize;
3514   
3515   msize = ntohs (message->size);
3516   if (msize < sizeof (struct PeerGetMessage))
3517   {
3518     GNUNET_break_op (0);
3519     return GNUNET_YES;
3520   }
3521
3522   get = (const struct PeerGetMessage *)message;
3523   get_length = ntohl (get->get_path_length);
3524   best_known_dest = get->best_known_destination;
3525   intermediate_trail_id = get->intermediate_trail_id;
3526   get_path = (const struct GNUNET_PeerIdentity *)&get[1];
3527
3528   if ((msize <
3529        sizeof (struct PeerGetMessage) +
3530        get_length * sizeof (struct GNUNET_PeerIdentity)) ||
3531        (get_length >
3532         GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
3533   {
3534     GNUNET_break_op (0);
3535     return GNUNET_YES; 
3536   }
3537   
3538   /* Add sender to get path */
3539   struct GNUNET_PeerIdentity gp[get_length + 1];
3540   if (get_length > 0)
3541     memcpy (gp, get_path, get_length * sizeof (struct GNUNET_PeerIdentity));
3542   gp[get_length + 1] = *peer;
3543   get_length = get_length + 1;
3544   
3545   memcpy (&key_value, &(get->key), sizeof (uint64_t));
3546   
3547   /* I am not the final destination. I am part of trail to reach final dest. */
3548   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&best_known_dest, &my_identity)))
3549   {
3550     next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id, 
3551                                          GDS_ROUTING_SRC_TO_DEST);
3552   }
3553   else
3554   {
3555     /* Get the next hop to pass the message to. */
3556     next_hop = find_successor (key_value, &best_known_dest, 
3557                                &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);  
3558   }
3559   
3560   if (NULL == next_hop)
3561   {
3562     GNUNET_STATISTICS_update (GDS_stats,
3563                               gettext_noop ("# Next hop to forward the packet not found "
3564                               "trail setup request, packet dropped."),
3565                               1, GNUNET_NO);
3566     return GNUNET_SYSERR;
3567   }
3568   
3569   /* I am the final destination. */
3570   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &best_known_dest))
3571   {
3572     struct GNUNET_PeerIdentity final_get_path[get_length+1];
3573     struct GNUNET_PeerIdentity next_hop;
3574
3575     memcpy (final_get_path, gp, get_length * sizeof (struct GNUNET_PeerIdentity));
3576     memcpy (&final_get_path[get_length+1], &my_identity, sizeof (struct GNUNET_PeerIdentity));
3577     get_length = get_length + 1;
3578     
3579     /* Get the next hop to pass the get result message. */
3580     memcpy (&next_hop, &final_get_path[get_length-2], sizeof (struct GNUNET_PeerIdentity));
3581     GDS_DATACACHE_handle_get (&(get->key),(get->block_type), NULL, 0, NULL, 0,
3582                               get_length, final_get_path,&next_hop, &my_identity);
3583     
3584     return GNUNET_YES;
3585   }
3586   else
3587   {
3588     GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options, 
3589                              get->desired_replication_level, &best_known_dest,
3590                              &intermediate_trail_id, next_hop, 0,
3591                              get_length, gp);  
3592   }
3593   return GNUNET_SYSERR;
3594 }
3595
3596
3597 /**
3598  * Core handler for get result
3599  * @param cls closure
3600  * @param peer sender of the request
3601  * @param message message
3602  * @return #GNUNET_OK to keep the connection open,
3603  *         #GNUNET_SYSERR to close it (signal serious error)
3604  */
3605 static int
3606 handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
3607                            const struct GNUNET_MessageHeader *message)
3608 {
3609   struct PeerGetResultMessage *get_result;
3610   struct GNUNET_PeerIdentity *get_path;
3611   struct GNUNET_PeerIdentity *put_path;
3612   void *payload;
3613   size_t payload_size;
3614   size_t msize;
3615   unsigned int getlen;
3616   unsigned int putlen;
3617   int current_path_index;
3618   
3619   msize = ntohs (message->size);
3620   if (msize < sizeof (struct PeerGetResultMessage))
3621   {
3622     GNUNET_break_op (0);
3623     return GNUNET_YES;
3624   }
3625   
3626   get_result = (struct PeerGetResultMessage *)message;
3627   getlen = ntohl (get_result->get_path_length);
3628   putlen = ntohl (get_result->put_path_length);
3629   
3630   if ((msize <
3631        sizeof (struct PeerGetResultMessage) +
3632        getlen * sizeof (struct GNUNET_PeerIdentity) + 
3633        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
3634       (getlen >
3635        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity) ||
3636       (putlen >
3637          GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity))))
3638   {
3639     GNUNET_break_op (0);
3640     return GNUNET_YES;
3641   }
3642   
3643   if (getlen > 0)
3644    get_path = (struct GNUNET_PeerIdentity *) &get_result[1];
3645   payload = &get_path[getlen];
3646   payload_size = msize - (sizeof (struct PeerGetResultMessage) + 
3647                           getlen * sizeof (struct GNUNET_PeerIdentity));
3648   
3649   if (putlen > 0)
3650     put_path = &get_path[1];
3651   else
3652     put_path = NULL;
3653   
3654   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &(get_path[0]))))
3655   {
3656     GDS_CLIENTS_handle_reply (get_result->expiration_time, &(get_result->key), 
3657                               getlen, get_path, putlen,
3658                               put_path, get_result->type, payload_size, payload);
3659     return GNUNET_YES;
3660   }
3661   else
3662   {
3663     current_path_index = search_my_index (get_path, getlen);
3664     if (GNUNET_SYSERR == current_path_index )
3665     {
3666       GNUNET_break (0);
3667       return GNUNET_SYSERR;
3668     }
3669     GDS_NEIGHBOURS_send_get_result (&(get_result->key), get_result->type,
3670                                     &get_path[current_path_index - 1],
3671                                     &(get_result->querying_peer), putlen, put_path,
3672                                     getlen, get_path, get_result->expiration_time,
3673                                     payload, payload_size);
3674     return GNUNET_YES;
3675   }  
3676   return GNUNET_SYSERR;
3677 }
3678
3679
3680 /**
3681  * Get the best known next destination (local_dest) among your fingers, friends 
3682  * and my identity. If @a current_dest is some other peer and not me, then 
3683  * compare curent_dest and local_dest. 
3684  * @param final_dest_finger_value Peer closest to this value will be
3685  *                                @a local_best_known_dest
3686  * @param local_best_known_dest[out] Updated to peer identity which is closest to
3687  *                                   @a final_dest_finger_value.
3688  * @param new_intermediate_trail_id In case @a local_best_known_dest is a finger,
3689  *                                  then the trail id to reach to the finger
3690  * @param is_predecessor Is source peer trying to setup trail to its predecessor
3691  *                       or not.
3692  * @param current_dest Peer which should get this message ultimately according
3693  *                     to the peer which sent me this message. It could be me
3694  *                     or some other peer. In case it is not me, then I am a part
3695  *                     of trail to reach to that peer.
3696  * @return 
3697  */
3698 static struct GNUNET_PeerIdentity *
3699 get_local_best_known_next_hop (uint64_t final_dest_finger_value,
3700                                struct GNUNET_PeerIdentity *local_best_known_dest,
3701                                struct GNUNET_HashCode *new_intermediate_trail_id,
3702                                struct GNUNET_HashCode intermediate_trail_id,
3703                                unsigned int is_predecessor,
3704                                struct GNUNET_PeerIdentity *current_dest)
3705 {
3706   struct GNUNET_PeerIdentity *next_hop_to_local_best_known_dest;
3707   
3708  /* Choose a local best known hop among your fingers, friends and you.  */
3709   next_hop_to_local_best_known_dest = find_successor (final_dest_finger_value,
3710                                                       local_best_known_dest,
3711                                                       new_intermediate_trail_id,
3712                                                       is_predecessor);
3713
3714   /* Are we just a part of a trail towards a finger (current_destination)? */
3715   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, current_dest)))
3716   {
3717     struct GNUNET_PeerIdentity *closest_peer;
3718     
3719     /* Select best successor among one found locally and current_destination 
3720      * that we got from network.*/
3721     closest_peer = select_closest_peer (local_best_known_dest,
3722                                         current_dest,
3723                                         final_dest_finger_value,
3724                                         is_predecessor);
3725     
3726     /* Is current dest (end point of the trail of which I am a part) closest_peer? */
3727     if (0 == GNUNET_CRYPTO_cmp_peer_identity (current_dest, closest_peer))
3728     {
3729       next_hop_to_local_best_known_dest = 
3730               GDS_ROUTING_get_next_hop (intermediate_trail_id,
3731                                         GDS_ROUTING_SRC_TO_DEST);
3732       /* FIXME: Here we found next_hop NULL from routing table, but we still 
3733        * have a next_hop from find_successor should we not break and choose that
3734        * next_hop. */
3735       if (NULL == next_hop_to_local_best_known_dest) 
3736       {
3737         GNUNET_break_op (0);
3738         return NULL;
3739       }
3740       
3741       local_best_known_dest =  current_dest;
3742       *new_intermediate_trail_id = intermediate_trail_id;
3743     }
3744   }
3745   
3746   GNUNET_assert (NULL != next_hop_to_local_best_known_dest);
3747   return next_hop_to_local_best_known_dest;
3748 }
3749
3750
3751 /* Core handle for PeerTrailSetupMessage.
3752  * @param cls closure
3753  * @param message message
3754  * @param peer peer identity this notification is about
3755  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
3756  */
3757 static int
3758 handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
3759                             const struct GNUNET_MessageHeader *message)
3760 {
3761   const struct PeerTrailSetupMessage *trail_setup;
3762   const struct GNUNET_PeerIdentity *trail_peer_list;
3763   struct GNUNET_PeerIdentity *local_best_known_dest; 
3764   struct GNUNET_PeerIdentity current_dest;
3765   struct GNUNET_PeerIdentity *next_hop_towards_local_best_known_dest;
3766   struct GNUNET_PeerIdentity next_peer;
3767   struct FriendInfo *target_friend;
3768   struct GNUNET_PeerIdentity source;
3769   uint64_t final_dest_finger_val;
3770   struct GNUNET_HashCode new_intermediate_trail_id;
3771   struct GNUNET_HashCode intermediate_trail_id;
3772   struct GNUNET_HashCode trail_id;
3773   unsigned int is_predecessor;
3774   uint32_t trail_length;
3775   size_t msize;
3776
3777   msize = ntohs (message->size);
3778   if (msize < sizeof (struct PeerTrailSetupMessage))
3779   {
3780     GNUNET_break_op (0);
3781     return GNUNET_YES;
3782   }
3783
3784   trail_setup = (const struct PeerTrailSetupMessage *) message;
3785   trail_length = (msize - sizeof (struct PeerTrailSetupMessage))/
3786                   sizeof (struct GNUNET_PeerIdentity);
3787   if ((msize - sizeof (struct PeerTrailSetupMessage)) % 
3788       sizeof (struct GNUNET_PeerIdentity) != 0)
3789   {
3790     GNUNET_break_op (0);
3791     return GNUNET_OK;      
3792   }           
3793   
3794   trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_setup[1];
3795   current_dest = trail_setup->best_known_destination;
3796   trail_id = trail_setup->trail_id;
3797   final_dest_finger_val = 
3798           GNUNET_ntohll (trail_setup->final_destination_finger_value);
3799   source = trail_setup->source_peer;
3800   is_predecessor = ntohl (trail_setup->is_predecessor);
3801   intermediate_trail_id = trail_setup->intermediate_trail_id;
3802   
3803   /* Is my routing table full?  */
3804   if (GNUNET_YES == GDS_ROUTING_threshold_reached())
3805   {
3806     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
3807     GDS_NEIGHBOURS_send_trail_rejection (source, final_dest_finger_val,
3808                                          my_identity, is_predecessor,
3809                                          trail_peer_list, trail_length,
3810                                          trail_id, target_friend,
3811                                          CONGESTION_TIMEOUT);
3812     return GNUNET_OK;
3813   }
3814
3815   local_best_known_dest = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
3816   
3817   /* Get the next hop to forward the trail setup request. */
3818   next_hop_towards_local_best_known_dest = 
3819           get_local_best_known_next_hop (final_dest_finger_val, 
3820                                          local_best_known_dest,
3821                                          &new_intermediate_trail_id,
3822                                          intermediate_trail_id,
3823                                          is_predecessor,
3824                                          &current_dest);
3825  
3826   /* Am I the final destination? */
3827   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (local_best_known_dest,
3828                                              &my_identity)))
3829   {
3830     /* If I was not the source of this message for which now I am destination */
3831     if ((0 != GNUNET_CRYPTO_cmp_peer_identity (&source, &my_identity)) ||
3832         (trail_length > 0))
3833     {
3834       GDS_ROUTING_add (trail_id, *peer, my_identity);
3835     }
3836     if (0 == trail_length)
3837       memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
3838     else
3839       memcpy (&next_peer, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
3840
3841     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
3842     GDS_NEIGHBOURS_send_trail_setup_result (source,
3843                                             my_identity,
3844                                             target_friend, trail_length,
3845                                             trail_peer_list,
3846                                             final_dest_finger_val,
3847                                             is_predecessor, trail_id);
3848   }
3849   else
3850   {
3851     /* Add yourself to list of peers. */
3852     struct GNUNET_PeerIdentity peer_list[trail_length + 1];
3853
3854     memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
3855     peer_list[trail_length] = my_identity;
3856     target_friend = 
3857             GNUNET_CONTAINER_multipeermap_get (friend_peermap,
3858                                                next_hop_towards_local_best_known_dest);
3859     GDS_NEIGHBOURS_send_trail_setup (source,
3860                                      final_dest_finger_val,
3861                                      *local_best_known_dest,
3862                                      target_friend, trail_length + 1, peer_list,
3863                                      is_predecessor, trail_id,
3864                                      &new_intermediate_trail_id);
3865   }
3866   GNUNET_free (local_best_known_dest);
3867   GNUNET_free (next_hop_towards_local_best_known_dest);
3868   return GNUNET_OK;
3869 }
3870
3871
3872 /* FIXME: here we are calculating my_index and comparing also in this function.
3873    And we are doing it again here in this function. Re factor the code. */
3874 /**
3875  * FIXME: Should we call this function everywhere in all the handle functions
3876  * where we have a trail to verify from or a trail id. something like
3877  * if prev hop is not same then drop the message. 
3878  * Check if sender_peer and peer from which we should receive the message are
3879  * same or different.
3880  * @param trail_peer_list List of peers in trail
3881  * @param trail_length Total number of peers in @a trail_peer_list
3882  * @param sender_peer Peer from which we got the message. 
3883  * @param finger_identity Finger to which trail is setup. It is not part of trail.
3884  * @return #GNUNET_YES if sender_peer and peer from which we should receive the
3885  *                    message are different.
3886  *         #GNUNET_NO if sender_peer and peer from which we should receive the
3887  *                    message are different. 
3888  */
3889 static int
3890 is_sender_peer_correct (const struct GNUNET_PeerIdentity *trail_peer_list,
3891                         unsigned int trail_length,
3892                         const struct GNUNET_PeerIdentity *sender_peer,
3893                         struct GNUNET_PeerIdentity finger_identity,
3894                         struct GNUNET_PeerIdentity source_peer)
3895 {
3896   int my_index;
3897   
3898   /* I am the source peer. */
3899   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&source_peer,
3900                                              &my_identity)))
3901   {
3902     /* Is the first element of the trail is sender_peer.*/
3903     if (trail_length > 0)
3904     {
3905       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[0],
3906                                                 sender_peer))
3907         return GNUNET_NO;
3908     }
3909     else
3910     {
3911       /* Is finger the sender peer? */
3912       if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
3913                                                 &finger_identity))
3914         return GNUNET_NO;
3915     }
3916   }
3917   else
3918   {
3919     /* Get my current location in the trail. */
3920     my_index = search_my_index (trail_peer_list, trail_length);
3921     if (-1 == my_index)
3922       return GNUNET_NO;
3923     
3924     /* I am the last element in the trail. */
3925     if ((trail_length - 1) == my_index)
3926     {
3927       /* Is finger the sender_peer? */
3928       if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
3929                                                 &finger_identity))
3930         return GNUNET_NO;
3931     }
3932     else
3933     {
3934       /* Is peer after me in trail the sender peer? */
3935       if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
3936                                                 &trail_peer_list[my_index + 1]))
3937         return GNUNET_NO;
3938     }
3939   }
3940   return GNUNET_YES;
3941 }
3942
3943
3944 /**
3945  * FIXME: we should also add a case where we search if we are present in the trail
3946  * twice.
3947  * Core handle for p2p trail setup result messages.
3948  * @param closure
3949  * @param message message
3950  * @param peer sender of this message. 
3951  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
3952  */
3953 static int
3954 handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
3955                                   const struct GNUNET_MessageHeader *message)
3956 {
3957   const struct PeerTrailSetupResultMessage *trail_result;
3958   const struct GNUNET_PeerIdentity *trail_peer_list;
3959   struct GNUNET_PeerIdentity next_hop;
3960   struct FriendInfo *target_friend;
3961   struct GNUNET_PeerIdentity querying_peer;
3962   struct GNUNET_PeerIdentity finger_identity;
3963   uint32_t trail_length;
3964   uint64_t ulitmate_destination_finger_value;
3965   uint32_t is_predecessor;
3966   struct GNUNET_HashCode trail_id;
3967   int my_index;
3968   size_t msize;
3969
3970   msize = ntohs (message->size);
3971   if (msize < sizeof (struct PeerTrailSetupResultMessage))
3972   {
3973     GNUNET_break_op (0);
3974     return GNUNET_YES;
3975   }
3976
3977   trail_result = (const struct PeerTrailSetupResultMessage *) message;
3978   trail_length = (msize - sizeof (struct PeerTrailSetupResultMessage))/
3979                   sizeof (struct GNUNET_PeerIdentity);
3980   if ((msize - sizeof (struct PeerTrailSetupResultMessage)) % 
3981       sizeof (struct GNUNET_PeerIdentity) != 0)
3982   {
3983     GNUNET_break_op (0);
3984     return GNUNET_OK;      
3985   }       
3986   
3987   is_predecessor = htonl (trail_result->is_predecessor);
3988   querying_peer = trail_result->querying_peer;
3989   finger_identity = trail_result->finger_identity;
3990   trail_id = trail_result->trail_id;
3991   trail_peer_list = (const struct GNUNET_PeerIdentity *) &trail_result[1];
3992   ulitmate_destination_finger_value = 
3993           GNUNET_ntohll (trail_result->ulitmate_destination_finger_value);
3994
3995   /* FIXME: here we are calculating my_index and comparing also in this function.
3996    And we are doing it again here in this function. Re factor the code. */
3997   /* Ensure that sender peer is the peer from which we were expecting the message. */
3998   if (GNUNET_NO == is_sender_peer_correct (trail_peer_list,
3999                                            trail_length,
4000                                            peer, finger_identity, querying_peer))
4001   {
4002     GNUNET_break_op (0);
4003     return GNUNET_SYSERR;
4004   }
4005   
4006   /* Am I the one who initiated the query? */
4007   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer,
4008                                              &my_identity)))
4009   {
4010     /* If I am not my own finger identity, then add routing table entry. */
4011     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
4012     {
4013       GDS_ROUTING_add (trail_id, my_identity, *peer);
4014     }
4015     
4016     finger_table_add (finger_identity, trail_peer_list,
4017                       trail_length, ulitmate_destination_finger_value,
4018                       is_predecessor, trail_id);
4019     return GNUNET_YES;
4020   }
4021   
4022   /* Get my location in the trail. */
4023   my_index = search_my_index(trail_peer_list, trail_length);
4024   if (-1 == my_index)
4025   {
4026     GNUNET_break_op(0);
4027     return GNUNET_SYSERR;
4028   }
4029   
4030   if (my_index == 0)
4031     next_hop = trail_result->querying_peer;
4032   else
4033     next_hop = trail_peer_list[my_index - 1];
4034
4035   /* If the querying_peer is its own finger, then don't add an entry in routing
4036    * table as querying peer will discard the trail. */
4037   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->querying_peer),
4038                                              &(trail_result->finger_identity))))
4039   {
4040     GDS_ROUTING_add (trail_id, next_hop, *peer);
4041   }
4042
4043   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
4044   GDS_NEIGHBOURS_send_trail_setup_result (querying_peer, finger_identity,
4045                                           target_friend, trail_length, trail_peer_list,
4046                                           is_predecessor, 
4047                                           ulitmate_destination_finger_value,
4048                                           trail_id);
4049   return GNUNET_OK;
4050 }
4051
4052
4053 /**
4054  * Invert the trail.
4055  * @param trail Trail to be inverted
4056  * @param trail_length Total number of peers in the trail.
4057  * @return Updated trail
4058  */
4059 static struct GNUNET_PeerIdentity *
4060 invert_trail (const struct GNUNET_PeerIdentity *trail,
4061               unsigned int trail_length)
4062 {
4063   int i;
4064   int j;
4065   struct GNUNET_PeerIdentity *inverted_trail;
4066  
4067   inverted_trail = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity) *
4068                                   trail_length);
4069   i = 0;
4070   j = trail_length - 1;
4071   while (i < trail_length)
4072   {
4073     inverted_trail[i] = trail[j];
4074     i++;
4075     j--;
4076   }
4077   return inverted_trail;
4078 }
4079
4080
4081 /**
4082  * Return the shortest trail to reach from me to my_predecessor. 
4083  * @param my_predecessor my current predecessor.
4084  * @param current_trail Trail from source to me.
4085  * @param current_trail_length Total number of peers in @a current_trail
4086  * @param trail_length [out] Total number of peers in selected trail.
4087  * @return Updated trail from source peer to my_predecessor.
4088  */
4089 static struct GNUNET_PeerIdentity *
4090 trail_source_to_my_predecessor (const struct GNUNET_PeerIdentity *current_trail,
4091                                 unsigned int current_trail_length,
4092                                 unsigned int *trail_length)
4093 {
4094   struct GNUNET_PeerIdentity *trail_me_to_predecessor;
4095   struct Trail *trail;
4096   struct Trail_Element *trail_element;
4097   struct FingerInfo *my_predecessor;
4098   unsigned int i;
4099   unsigned int shortest_trail_length = 0;
4100   unsigned int trail_index = 0;
4101  
4102   my_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
4103   
4104   GNUNET_assert (GNUNET_YES == my_predecessor->is_present);
4105   
4106   //if my_predecessor is a friend then don't send back any trail. as
4107   // there is no trail. 
4108   *trail_length = 0;
4109   
4110   /* Choose the shortest path from me to my predecessor. */
4111   for (i = 0; i < my_predecessor->trails_count; i++)
4112   {
4113     trail = &my_predecessor->trail_list[i];
4114     if (trail->trail_length > shortest_trail_length)
4115       continue;
4116     shortest_trail_length = trail->trail_length;
4117     trail_index = i;
4118   }
4119
4120   *trail_length = shortest_trail_length;
4121   trail_me_to_predecessor = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity)
4122                                           * *trail_length);
4123   
4124   /* Copy the selected trail and send this trail to calling function. */
4125   i = 0;
4126   trail = &my_predecessor->trail_list[trail_index];
4127   trail_element = trail->trail_head;
4128   while ( i < shortest_trail_length)
4129   {
4130     trail_me_to_predecessor[i] = trail_element->peer;
4131     i++;
4132     trail_element = trail_element->next;
4133   }
4134
4135   return trail_me_to_predecessor;
4136 }
4137
4138
4139 /**
4140  * FIXME In case predecessor is a friend then do we add it in routing table.
4141  * if not then check the logic of trail teardown in case we compress the trail
4142  * such that friend is finger. then do we remove the entry from end points or
4143  * not. Ideally we should remove the entries from end point. 
4144  * Add finger as your predecessor. To add, first generate a new trail id, invert
4145  * the trail to get the trail from me to finger, add an entry in your routing 
4146  * table, send add trail message to peers which are part of trail from me to 
4147  * finger and add finger in finger table.
4148  * @param finger
4149  * @param trail
4150  * @param trail_length
4151  */
4152 static void
4153 update_predecessor (struct GNUNET_PeerIdentity finger, 
4154                     struct GNUNET_PeerIdentity *trail, 
4155                     unsigned int trail_length)
4156 {
4157   struct GNUNET_HashCode trail_to_new_predecessor_id;
4158   struct GNUNET_PeerIdentity *trail_to_new_predecessor;
4159   struct FriendInfo *target_friend;
4160   
4161   /* Generate trail id for trail from me to new predecessor = finger. */
4162   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
4163                               &trail_to_new_predecessor_id, 
4164                               sizeof (trail_to_new_predecessor_id));
4165     
4166   /* Invert the trail from finger to me to get the trail from me to finger. */
4167   if (trail_length == 0)
4168     trail_to_new_predecessor = NULL;
4169
4170   if (trail_length > 0)
4171   {
4172     trail_to_new_predecessor = invert_trail (trail, trail_length);
4173     /* Add an entry in your routing table. */
4174     GDS_ROUTING_add (trail_to_new_predecessor_id, 
4175                      trail_to_new_predecessor[trail_length - 1],
4176                      my_identity);
4177    
4178     target_friend = 
4179             GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
4180                                                &trail_to_new_predecessor[trail_length - 1]);
4181       
4182     // Before sending the trail may be you need to compress it. And in case
4183     // it was a friend how did we got the trail. ?? 
4184     
4185     /* Add entry in routing table of all peers that are part of trail from me
4186        to finger. */
4187
4188     GDS_NEIGHBOURS_send_add_trail (my_identity, 
4189                                    finger,
4190                                    trail_to_new_predecessor_id,
4191                                    trail_to_new_predecessor,
4192                                    trail_length,
4193                                    target_friend);
4194     }
4195   
4196     add_new_finger (finger, trail_to_new_predecessor, trail_length,
4197                     trail_to_new_predecessor_id, PREDECESSOR_FINGER_ID);
4198 }
4199
4200
4201 /* 3. In case you are successor, then 
4202    *   3.1 check if you have a predecessor
4203    *   3.2 if no predecessor, then add the source of this message as your
4204    *       predecessor. To add, first you should generate a new trail id,
4205    *       invert the trail, send add trail message across new trail, add
4206    *       an entry in finger table. Now, destination also have routing
4207    *       table entry so add in your routing table also.
4208    *   3.3 If its closer than existing one, then do everything in step 1 and
4209    *       free existing finger. 
4210    *   3.3 If its same as the old one, then do nothing.
4211    *   3.4 if its not same as old one, and between source and old one, old one
4212    *       is the correct predecessor, then construct a trail from source 
4213    *       to your old successor. scan the trail to remove duplicate entries.
4214    * 4. send verify successor result, with trail id of trail from source to
4215    * me. And also send the new trail from source to reach to its probable
4216    * predecessor. */
4217  /*
4218    * 1. this function is called from both verify and notify.
4219    * 2. so write in a way that it is used in both.
4220    */
4221 /**
4222  * Check if you have a predecessor.
4223  * 1. if no predecessor, then add finger as your predecessor. To add, first 
4224  *    generate a new trail id, invert the trail to get the trail from me to finger,
4225  *    add an entry in your routing table, send add trail message to peers which 
4226  *    are part of trail from me to finger and add finger in finger table.
4227  * 2. If there is a predecessor, then compare existing one and finger.
4228  *    2.1 If finger is correct predecessor, then remove current_predecessor. And 
4229  *        do everything in step 1 to add finger into finger table.
4230  *    2.2 If current_predecessor is correct predecessor, the construct a trail from
4231  *        finger to current_predecessor. 
4232  * @param finger
4233  * @param trail
4234  * @param trail_length
4235  * @return 
4236  */
4237 static void
4238 compare_and_update_predecessor (struct GNUNET_PeerIdentity finger, 
4239                                 struct GNUNET_PeerIdentity *trail, 
4240                                 unsigned int trail_length)
4241 {
4242   struct FingerInfo *current_predecessor;
4243   struct GNUNET_PeerIdentity *closest_peer;
4244   uint64_t predecessor_value;
4245   
4246   current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
4247
4248   GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&finger, &my_identity));
4249   
4250   /* No predecessor. Add finger as your predecessor. */
4251   if (GNUNET_NO == current_predecessor->is_present) 
4252   {
4253     update_predecessor (finger, trail, trail_length);
4254     return;
4255   }
4256   
4257   predecessor_value = compute_finger_identity_value (PREDECESSOR_FINGER_ID);
4258   closest_peer = select_closest_peer (&finger, 
4259                                       &current_predecessor->finger_identity,
4260                                       predecessor_value, PREDECESSOR_FINGER_ID);
4261   
4262   /* Finger is the closest predecessor. Remove the existing one and add the new
4263      one. */
4264   if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer, &finger))
4265   {
4266     remove_existing_finger (current_predecessor, PREDECESSOR_FINGER_ID);
4267     update_predecessor (finger, trail, trail_length);
4268     return;
4269   }
4270   
4271   return;
4272 }
4273
4274
4275 /* 
4276  * FIXME: if i have no predecessor and I get a new predecessor but the first
4277  * friend to reach to that hop is congested then?  
4278  * 1. check if you are the successor or not.
4279  * 2. if not then get the next hop from routing table, and pass the message,
4280  * 3. In case you are successor, then 
4281  *   3.1 check if you have a predecessor
4282  *   3.2 if no predecessor, then add the source of this message as your
4283  *       predecessor. To add, first you should generate a new trail id,
4284  *       invert the trail, send add trail message across new trail, add
4285  *       an entry in finger table. Now, destination also have routing
4286  *       table entry so add in your routing table also.
4287  *   3.3 If its closer than existing one, then do everything in step 1 and
4288  *       free existing finger. 
4289  *   3.3 If its same as the old one, then do nothing.
4290  *   3.4 if its not same as old one, and between source and old one, old one
4291  *       is the correct predecessor, then choose the shortest path to reach
4292  *       from you to your predecessor. Pass this trail to source of this message.
4293  *       It is the responsibility of source peer to scan the trail to reach to
4294  *       its new probable successor. 
4295  * 4. send verify successor result, with trail id of trail from source to
4296  * me. And also send the  trail from me to reach to my predecessor, if
4297  * my_predecessor != source. 
4298  *
4299  * Core handle for p2p verify successor messages.
4300  * @param cls closure
4301  * @param message message
4302  * @param peer peer identity this notification is about
4303  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4304  */
4305 static int
4306 handle_dht_p2p_verify_successor(void *cls, 
4307                                 const struct GNUNET_PeerIdentity *peer,
4308                                 const struct GNUNET_MessageHeader *message)
4309 {
4310   const struct PeerVerifySuccessorMessage *vsm;
4311   struct GNUNET_HashCode trail_id;
4312   struct GNUNET_PeerIdentity successor;
4313   struct GNUNET_PeerIdentity source_peer;
4314   struct GNUNET_PeerIdentity *trail;
4315   struct GNUNET_PeerIdentity *next_hop;
4316   struct GNUNET_PeerIdentity *trail_to_predecessor;
4317   struct FingerInfo *current_predecessor;
4318   struct FriendInfo *target_friend;
4319   unsigned int trail_to_predecessor_length;
4320   size_t msize;
4321   unsigned int trail_length;
4322   
4323   msize = ntohs (message->size);
4324   
4325   /* Here we pass trail to reach from source to successor, and in case successor
4326    * does not have any predecessor, then we will add source as my predecessor.
4327    * So we pass the trail along with trail id. */
4328   if (msize < sizeof (struct PeerVerifySuccessorMessage)) 
4329   {
4330     GNUNET_break_op (0);
4331     return GNUNET_YES;
4332   }
4333   
4334   vsm = (const struct PeerVerifySuccessorMessage *) message;
4335   trail_length = (msize - sizeof (struct PeerVerifySuccessorMessage))/
4336                   sizeof (struct GNUNET_PeerIdentity);
4337   if ((msize - sizeof (struct PeerVerifySuccessorMessage)) % 
4338       sizeof (struct GNUNET_PeerIdentity) != 0)
4339   {
4340     GNUNET_break_op (0);
4341     return GNUNET_OK;      
4342   } 
4343   
4344   trail_id = vsm->trail_id;
4345   source_peer = vsm->source_peer;
4346   successor = vsm->successor;
4347   trail = (struct GNUNET_PeerIdentity *)&vsm[1];
4348   
4349   //GDS_ROUTING_test_print(); //FIXME REMOVE AFTERWARDS. 
4350   //FIXME: we can have a check if peer is correct peer which should have
4351   // sent this message. use same function is_sender_peer_correct
4352   // but specify direction so that the function can be used in other functions
4353   //also. 
4354   
4355   /* I am not the successor of source_peer. Pass the message to next_hop on
4356    * the trail. */
4357   if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&successor, &my_identity)))
4358   {
4359     next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
4360     if (NULL == next_hop)
4361     {
4362       GNUNET_break (0);
4363       return GNUNET_SYSERR;
4364     }
4365     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
4366
4367     GDS_NEIGHBOURS_send_verify_successor_message (source_peer, successor,
4368                                                   trail_id, trail, trail_length,
4369                                                   target_friend);
4370     return GNUNET_OK;
4371   }
4372   
4373   /* I am the destination of this message. */
4374   
4375   /* Check if the source_peer could be our predecessor and if yes then update
4376    * it.  */
4377   compare_and_update_predecessor (source_peer, trail, trail_length);
4378   
4379   current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
4380   
4381   /* Is source of this message my predecessor. */
4382   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&current_predecessor->finger_identity,
4383                                              &source_peer)))
4384   {
4385     trail_to_predecessor = NULL;
4386     trail_to_predecessor_length = 0;
4387   }
4388   else
4389   {
4390     if (NULL == (GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
4391                                                     &current_predecessor->finger_identity)))
4392     {
4393       /* Only if current predecessor is not a friend, we have a trail to reach
4394        to it. Only in that case we pass the trail. */
4395       trail_to_predecessor = 
4396             trail_source_to_my_predecessor (trail, trail_length, 
4397                                             &trail_to_predecessor_length);
4398     }
4399     else
4400     {
4401       trail_to_predecessor = NULL;
4402       trail_to_predecessor_length = 0;
4403     }
4404   }
4405   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
4406   GDS_NEIGHBOURS_send_verify_successor_result (source_peer, my_identity,
4407                                                current_predecessor->finger_identity,
4408                                                trail_id, trail_to_predecessor,
4409                                                trail_to_predecessor_length,
4410                                                GDS_ROUTING_DEST_TO_SRC,
4411                                                target_friend);
4412   GNUNET_free_non_null (trail_to_predecessor);
4413   return GNUNET_OK;
4414 }
4415
4416
4417 /**
4418  * Construct the trail from me to probable successor that goes through current 
4419  * successor. Scan this trail to check if you can shortcut the trail somehow. 
4420  * In case we can shortcut the trail, don't send trail compression as we don't 
4421  * have any entry in routing table.
4422  * @param current_successor
4423  * @param probable_successor
4424  * @param trail_from_curr_to_probable_successor
4425  * @param trail_from_curr_to_probable_successor_length
4426  * @param trail_to_new_successor_length
4427  * @return 
4428  */
4429 static struct GNUNET_PeerIdentity *
4430 get_trail_to_new_successor (struct FingerInfo *current_successor,
4431                             struct GNUNET_PeerIdentity probable_successor,
4432                             const struct GNUNET_PeerIdentity *trail,
4433                             unsigned int trail_length,
4434                             unsigned int *trail_to_new_successor_length)
4435 {
4436   struct GNUNET_PeerIdentity *trail_to_new_successor;
4437   
4438    /* If the probable successor is a friend, then we don't need to have a trail
4439     * to reach to it.*/
4440   if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
4441                                                  &probable_successor))
4442   {
4443     trail_to_new_successor = NULL;
4444     *trail_to_new_successor_length = 0;
4445     return trail_to_new_successor;
4446   }
4447   
4448   /*
4449    * FIXME: can we some how use the select_finger_trail here?? 
4450    * complete this logic. 
4451    * 1. Choose the shortest trail to reach to current successor.
4452    * 2. append the trail with the current trail
4453    * 3. scan the trail for duplicate elements
4454    * 4. scan the trail for friend
4455    * 5. get the shortest trail. 
4456    * 6. send back the trail.
4457    */
4458   return NULL;
4459 }
4460
4461
4462 /**
4463  * Compare probable successor and current successor.
4464  * If the probable successor is the correct successor, then construct the trail
4465  * from me to probable successor that goes through current successor. Scan this
4466  * trail to check if you can shortcut the trail somehow. In case we can short
4467  * cut the trail, don't send trail compression as we don't have any entry in 
4468  * routing table.
4469  * Once you have scanned trail, then add an entry in finger table.
4470  * Add an entry in routing table (Only if new successor is NOT a friend).
4471  * @param probable_successor Peer which could be our successor
4472  * @param trail_from_curr_to_probable_successor Trail from current successor 
4473  *                                               to probable successor, NOT 
4474  *                                               including them.
4475  * @param trail_from_curr_to_probable_successor_length Total number of peers
4476  *                                               in @a trail_from_curr_to_probable_successor
4477  */
4478 static void
4479 compare_and_update_successor (struct GNUNET_PeerIdentity probable_successor,
4480                               const struct GNUNET_PeerIdentity *trail_from_curr_to_probable_successor,
4481                               unsigned int trail_from_curr_to_probable_successor_length)
4482 {
4483   struct GNUNET_PeerIdentity *closest_peer;
4484   struct GNUNET_PeerIdentity *trail_to_new_successor;
4485   struct GNUNET_HashCode trail_id;
4486   unsigned int trail_to_new_successor_length;
4487   uint64_t successor_value;
4488   struct FingerInfo *current_successor;
4489   struct FriendInfo *target_friend;
4490   
4491   current_successor = &finger_table[0];
4492   GNUNET_assert (GNUNET_YES == current_successor->is_present);
4493
4494   /* Compute the 64 bit value of successor identity. We need this as we need to
4495    * find the closest peer w.r.t this value.*/
4496   successor_value = compute_finger_identity_value (0);
4497   closest_peer = select_closest_peer (&current_successor->finger_identity,
4498                                       &probable_successor,
4499                                       successor_value, 0);
4500   
4501   /* If the current_successor is the closest one, then exit. */
4502   if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer,
4503                                             &current_successor->finger_identity))
4504     return;
4505   
4506   /* probable successor  is the closest_peer. */
4507   
4508   /* Get the trail to reach to your new successor. */
4509   trail_to_new_successor = get_trail_to_new_successor (current_successor,
4510                                                        probable_successor,
4511                                                        trail_from_curr_to_probable_successor,
4512                                                        trail_from_curr_to_probable_successor_length,
4513                                                        &trail_to_new_successor_length);
4514   /* Remove the existing successor. */
4515   remove_existing_finger (current_successor, 0);
4516   
4517   /* Generate a new trail id to reach to your new successor. */
4518   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
4519                               &trail_id, sizeof (trail_id));
4520   add_new_finger (probable_successor, trail_to_new_successor, 
4521                   trail_to_new_successor_length, trail_id, 0);
4522   
4523   /* If probable successor is not a friend, then add an entry in your own
4524    routing table. */
4525   if (trail_to_new_successor_length > 0)
4526   {
4527     GDS_ROUTING_add (trail_id, my_identity, trail_to_new_successor[0]);
4528     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
4529                                                        &trail_to_new_successor[0]);
4530   }
4531   else
4532   {
4533     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
4534                                                        &probable_successor);
4535   }
4536   
4537   GDS_NEIGHBOURS_send_notify_new_successor (my_identity, probable_successor,
4538                                             trail_from_curr_to_probable_successor,
4539                                             trail_from_curr_to_probable_successor_length,
4540                                             trail_id,
4541                                             target_friend);
4542   return;
4543 }
4544
4545
4546 /*
4547  * 1. If you are not the querying peer then pass on the message,
4548  * 2. If you are querying peer, then
4549  *   2.1 is new successor same as old one
4550  *     2.1.1 if yes then do noting
4551  *     2.1.2 if no then you need to notify the new one about your existence,
4552  *     2.1.2,1 also you need to remove the older successor, remove entry
4553  *             from finger table, send trail teardown message across all the trail
4554  *             of older successor. Call notify new successor with new trail id 
4555  *             and new trail to reach it. 
4556  * Core handle for p2p verify successor result messages.
4557  * @param cls closure
4558  * @param message message
4559  * @param peer peer identity this notification is about
4560  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4561  */
4562 static int
4563 handle_dht_p2p_verify_successor_result(void *cls, 
4564                                        const struct GNUNET_PeerIdentity *peer,
4565                                        const struct GNUNET_MessageHeader *message)
4566 {
4567   const struct PeerVerifySuccessorResultMessage *vsrm;
4568   enum GDS_ROUTING_trail_direction trail_direction;
4569   struct GNUNET_PeerIdentity querying_peer;
4570   struct GNUNET_HashCode trail_id;
4571   struct GNUNET_PeerIdentity *next_hop;
4572   struct FriendInfo *target_friend;
4573   struct GNUNET_PeerIdentity probable_successor;
4574   const struct GNUNET_PeerIdentity *trail;
4575   unsigned int trail_length;
4576   size_t msize;
4577
4578   msize = ntohs (message->size);
4579   /* We send a trail to reach from old successor to new successor, if
4580    * old_successor != new_successor.*/
4581   if (msize < sizeof (struct PeerVerifySuccessorResultMessage))
4582   {
4583     GNUNET_break_op (0);
4584     return GNUNET_YES;
4585   }
4586   
4587   vsrm = (const struct PeerVerifySuccessorResultMessage *) message;
4588   trail_length = (msize - sizeof (struct PeerVerifySuccessorResultMessage))/
4589                       sizeof (struct GNUNET_PeerIdentity);
4590   
4591   if ((msize - sizeof (struct PeerVerifySuccessorResultMessage)) % 
4592       sizeof (struct GNUNET_PeerIdentity) != 0)
4593   {
4594     GNUNET_break_op (0);
4595     return GNUNET_OK;      
4596   }  
4597   
4598   trail = (const struct GNUNET_PeerIdentity *) &vsrm[1];
4599   querying_peer = vsrm->querying_peer;
4600   trail_direction = ntohl (vsrm->trail_direction);
4601   trail_id = vsrm->trail_id;
4602   probable_successor = vsrm->probable_successor;
4603  
4604   //FIXME: add a check to ensure that peer from which you got the message is
4605   //the correct peer.
4606   /* I am the querying_peer. */
4607   if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer, &my_identity)))
4608   {
4609     compare_and_update_successor (probable_successor, trail, trail_length);
4610     return GNUNET_OK;
4611   }
4612   
4613   /*If you are not the querying peer then pass on the message */
4614   GNUNET_assert (NULL != (next_hop =
4615                          GDS_ROUTING_get_next_hop (trail_id, trail_direction)));
4616   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
4617   GDS_NEIGHBOURS_send_verify_successor_result (querying_peer,
4618                                                vsrm->current_successor,
4619                                                probable_successor, trail_id,
4620                                                trail,
4621                                                trail_length,
4622                                                trail_direction, target_friend);
4623   return GNUNET_OK;
4624 }
4625
4626
4627 /* 
4628  * Add entry in your routing table if source of the message is not a friend.
4629  * Irrespective if destination peer accepts source peer as predecessor or not, 
4630  * we need to add an entry. So, that in next round to verify successor, source 
4631  * is able to reach to its successor.
4632  * Check if you are the new successor of this message
4633  * 1. If yes the call function compare_and_update_successor(). This function
4634  *    checks if source is real predecessor or not and take action accordingly.
4635  * 2. If not then find the next hop to find the message from the trail that 
4636  *    you got from the message and pass on the message.
4637  * Core handle for p2p notify new successor messages.
4638  * @param cls closure
4639  * @param message message
4640  * @param peer peer identity this notification is about
4641  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4642  */
4643 static int
4644 handle_dht_p2p_notify_new_successor(void *cls, 
4645                                     const struct GNUNET_PeerIdentity *peer,
4646                                     const struct GNUNET_MessageHeader *message)
4647 {
4648   const struct PeerNotifyNewSuccessorMessage *nsm;
4649   struct GNUNET_PeerIdentity *trail;
4650   struct GNUNET_PeerIdentity source;
4651   struct GNUNET_PeerIdentity new_successor;
4652   struct GNUNET_HashCode trail_id;
4653   struct GNUNET_PeerIdentity next_hop;
4654   struct FriendInfo *target_friend;
4655   int my_index;
4656   size_t msize;
4657   uint32_t trail_length;
4658
4659   msize = ntohs (message->size);
4660   /* We have the trail to reach from source to new successor. */
4661   if (msize < sizeof (struct PeerNotifyNewSuccessorMessage))
4662   {
4663     GNUNET_break_op (0);
4664     return GNUNET_YES;
4665   }
4666
4667   nsm = (const struct PeerNotifyNewSuccessorMessage *) message;
4668   trail_length = (msize - sizeof (struct PeerNotifyNewSuccessorMessage))/
4669                   sizeof (struct GNUNET_PeerIdentity);
4670   if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
4671       sizeof (struct GNUNET_PeerIdentity) != 0)
4672   {
4673     GNUNET_break_op (0);
4674     return GNUNET_OK;      
4675   }
4676   
4677   trail = (struct GNUNET_PeerIdentity *) &nsm[1];
4678   source  = nsm->source_peer;
4679   new_successor = nsm->new_successor;
4680   trail_id = nsm->trail_id;  
4681   
4682   //FIXME: add a check to make sure peer is correct. 
4683   
4684   /* I am the new_successor to source_peer. */
4685   if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &new_successor))
4686   {
4687     /* Add an entry in routing table only if new predecessor is not a friend. */
4688     if (NULL == GNUNET_CONTAINER_multipeermap_get(friend_peermap, &source))
4689     {
4690       GDS_ROUTING_add (trail_id, *peer, my_identity);
4691     }
4692     compare_and_update_predecessor (source, trail, trail_length);
4693     return GNUNET_OK;
4694   }
4695   
4696   /* I am part of trail to reach to successor. */
4697   my_index = search_my_index (trail, trail_length);
4698   if (-1 == my_index)
4699   {
4700     GNUNET_break_op (0);
4701     return GNUNET_SYSERR;
4702   }
4703   if (trail_length == my_index)
4704     next_hop = new_successor;
4705   else
4706     next_hop = trail[my_index + 1];
4707   
4708   /* Add an entry in routing table for trail from source to its new successor. */
4709   GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, next_hop));
4710   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
4711   GDS_NEIGHBOURS_send_notify_new_successor (source, new_successor, trail,
4712                                             trail_length,
4713                                             trail_id, target_friend);
4714   return GNUNET_OK;
4715   
4716 }
4717
4718
4719 /**
4720  * 1. Set the congestion timeout for the friend which is congested and sent
4721  * you this message.
4722  * 2. Check if you were the source of this message
4723  *   2.1 If yes then exit. find_finger_trail_task is scheduled periodically.
4724  *       So, we will eventually send a new request to setup trail to finger.
4725  * 2. Check if you can handle more trails through you. (Routing table space)
4726  *   2.1 If not then you are congested. Set your congestion time and pass this
4727  *       message to peer before you in the trail setup so far. 
4728  *   2.2 If yes, the call find_successor(). It will give you the next hop to 
4729  *       pass this message.
4730  *      2.2.1 If you are the final destination, then send back the trail setup 
4731  *            result.
4732  *      2.2.2 If you are not the final dest, then send trail setup message to
4733  *            next_hop.
4734  * Core handler for P2P trail rejection message
4735  * @param cls closure
4736  * @param message message
4737  * @param peer peer identity this notification is about
4738  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4739  */
4740 static int
4741 handle_dht_p2p_trail_setup_rejection (void *cls,
4742                                       const struct GNUNET_PeerIdentity *peer,
4743                                       const struct GNUNET_MessageHeader *message)
4744 {
4745   const struct PeerTrailRejectionMessage *trail_rejection;
4746   unsigned int trail_length;
4747   const struct GNUNET_PeerIdentity *trail_peer_list;
4748   struct FriendInfo *target_friend;
4749   struct GNUNET_TIME_Relative congestion_timeout;
4750   struct GNUNET_HashCode trail_id;
4751   struct GNUNET_PeerIdentity next_destination;
4752   struct GNUNET_HashCode new_intermediate_trail_id;
4753   struct GNUNET_PeerIdentity next_peer;
4754   struct GNUNET_PeerIdentity source;
4755   struct GNUNET_PeerIdentity *next_hop;
4756   uint64_t ultimate_destination_finger_value;
4757   unsigned int is_predecessor;
4758   size_t msize;
4759
4760   msize = ntohs (message->size);
4761   /* We are passing the trail setup so far. */
4762   if (msize < sizeof (struct PeerTrailRejectionMessage))
4763   {
4764     GNUNET_break_op (0);
4765     return GNUNET_YES;
4766   }
4767
4768   trail_rejection = (const struct PeerTrailRejectionMessage *) message;
4769   trail_length = (msize - sizeof (struct PeerTrailRejectionMessage))/
4770                   sizeof (struct GNUNET_PeerIdentity);
4771   if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
4772       sizeof (struct GNUNET_PeerIdentity) != 0)
4773   {
4774     GNUNET_break_op (0);
4775     return GNUNET_OK;      
4776   }           
4777
4778   trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_rejection[1];
4779   is_predecessor = ntohl (trail_rejection->is_predecessor);
4780   congestion_timeout = trail_rejection->congestion_time;
4781   source = trail_rejection->source_peer;
4782   trail_id = trail_rejection->trail_id;
4783   ultimate_destination_finger_value = 
4784           GNUNET_ntohll (trail_rejection->ultimate_destination_finger_value);
4785
4786   /* First set the congestion time of the friend that sent you this message. */
4787   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
4788   target_friend->congestion_timestamp = 
4789           GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
4790                                     congestion_timeout);
4791
4792   /* I am the source peer which wants to setup the trail. Do nothing. 
4793    * send_find_finger_trail_task is scheduled periodically.*/
4794   if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &source)))
4795     return GNUNET_OK;
4796
4797   /* If I am congested then pass this message to peer before me in trail. */
4798   if(GNUNET_YES == GDS_ROUTING_threshold_reached())
4799   {
4800     struct GNUNET_PeerIdentity *new_trail;
4801     unsigned int new_trail_length;
4802     
4803     /* Remove yourself from the trail setup so far. */
4804     if (trail_length == 1)
4805     {
4806       new_trail = NULL;
4807       new_trail_length = 0;
4808       next_hop = &source;
4809     }
4810     else
4811     {
4812       memcpy (&next_hop , &trail_peer_list[trail_length - 2], 
4813               sizeof (struct GNUNET_PeerIdentity));
4814       
4815       /* Remove myself from the trail. */
4816       new_trail_length = trail_length -1;
4817       new_trail = GNUNET_malloc (new_trail_length * sizeof (struct GNUNET_PeerIdentity));
4818       memcpy (new_trail, trail_peer_list, new_trail_length * sizeof (struct GNUNET_PeerIdentity));
4819     }
4820
4821     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
4822     GDS_NEIGHBOURS_send_trail_rejection (source,
4823                                          ultimate_destination_finger_value,
4824                                          my_identity, is_predecessor,
4825                                          new_trail,new_trail_length,trail_id,
4826                                          target_friend, CONGESTION_TIMEOUT);
4827     GNUNET_free (new_trail);
4828     return GNUNET_OK;
4829   }
4830
4831   /* Look for next_hop to pass the trail setup message */
4832   next_hop = find_successor (ultimate_destination_finger_value,
4833                              &next_destination,
4834                              &new_intermediate_trail_id,
4835                              is_predecessor);
4836   
4837   /* Am I the final destination? */
4838   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))
4839   {
4840     /* Add an entry in routing table only 
4841      * 1. If I am not the original source which sent the request for trail setup 
4842      * 2. If trail length > 0. 
4843      * NOTE: In case trail length > 0 and source is my friend, then also I add
4844      *       an entry in routing table,as we will send a trail compression message
4845      *       later.
4846      */
4847     if ((0 != GNUNET_CRYPTO_cmp_peer_identity (&source, &my_identity)) ||
4848         (trail_length > 0))
4849       GNUNET_assert (GNUNET_YES == GDS_ROUTING_add (trail_id, *peer, my_identity));
4850     
4851     if (0 == trail_length)
4852       next_peer = source;
4853     else
4854       next_peer = trail_peer_list[trail_length-1];
4855     
4856     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
4857     GDS_NEIGHBOURS_send_trail_setup_result (source,
4858                                             my_identity,
4859                                             target_friend, trail_length,
4860                                             trail_peer_list,
4861                                             is_predecessor, 
4862                                             ultimate_destination_finger_value,
4863                                             trail_id);
4864   }
4865   else
4866   {
4867     struct GNUNET_PeerIdentity peer_list[trail_length + 1];
4868
4869     memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
4870     peer_list[trail_length] = my_identity;
4871
4872     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
4873     GDS_NEIGHBOURS_send_trail_setup (source,
4874                                      ultimate_destination_finger_value,
4875                                      next_destination,
4876                                      target_friend, trail_length + 1, peer_list,
4877                                      is_predecessor, trail_id,
4878                                      &new_intermediate_trail_id);
4879   }
4880   GNUNET_free (next_hop);
4881   return GNUNET_OK;
4882 }
4883
4884
4885 /*
4886  * If you are the new first friend, then update prev hop to source of this message
4887  * else get the next hop and pass this message forward to ultimately reach
4888  * new first_friend.
4889  * Core handle for p2p trail tear compression messages.
4890  * @param cls closure
4891  * @param message message
4892  * @param peer peer identity this notification is about
4893  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4894  */
4895 static int
4896 handle_dht_p2p_trail_compression (void *cls, const struct GNUNET_PeerIdentity *peer,
4897                                   const struct GNUNET_MessageHeader *message)
4898 {
4899   const struct PeerTrailCompressionMessage *trail_compression;
4900   struct GNUNET_PeerIdentity *next_hop;
4901   struct FriendInfo *target_friend;
4902   struct GNUNET_HashCode trail_id;
4903   size_t msize;
4904
4905   msize = ntohs (message->size);
4906   /* Here we pass only the trail id. */
4907   if (msize != sizeof (struct PeerTrailCompressionMessage))
4908   {
4909     GNUNET_break_op (0);
4910     return GNUNET_OK;
4911   }
4912   
4913   trail_compression = (const struct PeerTrailCompressionMessage *) message;
4914   trail_id = trail_compression->trail_id;
4915   //FIXME: again check if peer is the correct peer. same logic as 
4916   //trail teardown make a generic function. 
4917   
4918   /* Am I the new first friend to reach to finger of this trail. */
4919   if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_compression->new_first_friend),
4920                                              &my_identity)))
4921   {
4922     /* Update your prev hop to source of this message. */
4923     GDS_ROUTING_update_trail_prev_hop (trail_id,
4924                                        trail_compression->source_peer);
4925     return GNUNET_OK;
4926   }
4927   
4928   /* Pass the message to next hop to finally reach to new_first_friend. */
4929   next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
4930   if (NULL == next_hop)
4931   {
4932     GNUNET_break (0); 
4933     return GNUNET_OK;
4934   }
4935   
4936   GNUNET_assert (NULL != (target_friend = 
4937           GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop)));
4938   GDS_NEIGHBOURS_send_trail_compression (trail_compression->source_peer,
4939                                          trail_id,
4940                                          trail_compression->new_first_friend,
4941                                          target_friend);
4942   return GNUNET_OK;
4943 }
4944
4945
4946 /**
4947  * Remove entry from your own routing table and pass the message to next
4948  * peer in the trail. 
4949  * Core handler for trail teardown message.
4950  * @param cls closure
4951  * @param message message
4952  * @param peer sender of this messsage. 
4953  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
4954  */
4955 static int
4956 handle_dht_p2p_trail_teardown (void *cls, const struct GNUNET_PeerIdentity *peer,
4957                                const struct GNUNET_MessageHeader *message)
4958 {
4959   const struct PeerTrailTearDownMessage *trail_teardown;
4960   enum GDS_ROUTING_trail_direction trail_direction;
4961   struct GNUNET_HashCode trail_id;
4962   struct GNUNET_PeerIdentity *prev_hop;
4963   struct GNUNET_PeerIdentity *next_hop;
4964   size_t msize;
4965   msize = ntohs (message->size);
4966   /* Here we pass only the trail id. */
4967   if (msize != sizeof (struct PeerTrailTearDownMessage))
4968   {
4969     GNUNET_break_op (0);
4970     return GNUNET_OK;
4971   }
4972   
4973   trail_teardown = (const struct PeerTrailTearDownMessage *) message;
4974   trail_direction = ntohl (trail_teardown->trail_direction);
4975   trail_id = trail_teardown->trail_id;
4976   
4977   /* Check if peer is the real peer from which we should get this message.*/
4978   /* Get the prev_hop for this trail by getting the next hop in opposite direction. */
4979   /* FIXME: is using negation of trail direction correct. */
4980   prev_hop = GDS_ROUTING_get_next_hop (trail_id, !trail_direction);
4981   if (0 != GNUNET_CRYPTO_cmp_peer_identity (prev_hop, peer))
4982   {
4983     GNUNET_break (0);
4984     return GNUNET_SYSERR;
4985   }
4986   GNUNET_free_non_null (prev_hop);
4987   
4988   next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
4989   if (NULL == next_hop)
4990   {
4991     GNUNET_break (0);
4992     return GNUNET_SYSERR;
4993   }
4994   
4995   GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
4996   
4997   /* If next_hop is my_identity, it means I am the final destination. */
4998   if (0 == GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity))
4999     return GNUNET_OK;
5000   
5001   /* If not final destination, then send a trail teardown message to next hop.*/
5002   GDS_NEIGHBOURS_send_trail_teardown (trail_id, trail_direction, next_hop);
5003   GNUNET_free (next_hop);
5004   return GNUNET_OK;
5005 }
5006
5007
5008 /**
5009  * Add an entry in your routing table. If you are destination of this message
5010  * then next_hop in routing table should be your own identity. If you are NOT
5011  * destination, then get the next hop and forward message to it.
5012  * Core handle for p2p add trail message. 
5013  * @param cls closure
5014  * @param message message
5015  * @param peer peer identity this notification is about
5016  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5017  */
5018 static int
5019 handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
5020                           const struct GNUNET_MessageHeader *message)
5021 {
5022   const struct PeerAddTrailMessage *add_trail;
5023   const struct GNUNET_PeerIdentity *trail;
5024   struct GNUNET_HashCode trail_id;
5025   struct GNUNET_PeerIdentity destination_peer;
5026   struct GNUNET_PeerIdentity source_peer;
5027   struct GNUNET_PeerIdentity next_hop;
5028   unsigned int trail_length;
5029   unsigned int my_index;
5030   size_t msize;
5031
5032   msize = ntohs (message->size);
5033   /* In this message we pass the whole trail from source to destination as we
5034    * are adding that trail.*/
5035   if (msize < sizeof (struct PeerAddTrailMessage))
5036   {
5037     GNUNET_break_op (0);
5038     return GNUNET_OK;
5039   }
5040
5041   add_trail = (const struct PeerAddTrailMessage *) message;
5042   trail_length = (msize - sizeof (struct PeerAddTrailMessage))/
5043                   sizeof (struct GNUNET_PeerIdentity);
5044   if ((msize - sizeof (struct PeerAddTrailMessage)) % 
5045       sizeof (struct GNUNET_PeerIdentity) != 0)
5046   {
5047     GNUNET_break_op (0);
5048     return GNUNET_OK;      
5049   }           
5050
5051   trail = (const struct GNUNET_PeerIdentity *)&add_trail[1];
5052   destination_peer = add_trail->destination_peer;
5053   source_peer = add_trail->source_peer;
5054   trail_id = add_trail->trail_id;
5055
5056   //FIXME: add a check that sender peer is not malicious. Make it a generic
5057   // function so that it can be used in all other functions where we need the
5058   // same functionality.
5059   
5060   /* I am not the destination of the trail. */
5061   if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &destination_peer))
5062   {
5063     struct FriendInfo *target_friend;
5064
5065     /* Get my location in the trail. */
5066     my_index = search_my_index (trail, trail_length);
5067     if (GNUNET_SYSERR == my_index)
5068     {
5069       GNUNET_break_op (0);
5070       return GNUNET_SYSERR;
5071     }
5072
5073     if (0 == my_index)
5074       next_hop = source_peer;
5075     else
5076       next_hop = trail[trail_length - 1];
5077     
5078     /* Add in your routing table. */
5079     GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, next_hop, *peer));
5080     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
5081     GDS_NEIGHBOURS_send_add_trail (source_peer, destination_peer, trail_id,
5082                                    trail, trail_length, target_friend);
5083     return GNUNET_OK;
5084   }
5085   
5086   /* I am the destination. Add an entry in routing table. */
5087   GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, my_identity));
5088   return GNUNET_OK;
5089 }
5090
5091
5092 /**
5093  * Send trail teardown and free the finger trail in which the first
5094  * friend to reach to a finger is disconnected_friend 
5095  * @param disconnected_friend PeerIdentity of friend which got disconnected
5096  * @param remove_finger Finger whose trail we need to check if it has 
5097  *                      disconnected_friend as the first hop.
5098  * @return Total number of trails in which disconnected_friend was the first
5099  *         hop.
5100  */
5101 static int
5102 remove_matching_trails (const struct GNUNET_PeerIdentity *disconnected_friend,
5103                         struct FingerInfo *remove_finger)
5104 {
5105   unsigned int matching_trails_count;
5106   int i;
5107   
5108   /* Number of trails with disconnected_friend as the first hop in the trail
5109    * to reach from me to remove_finger, NOT including endpoints. */
5110   matching_trails_count = 0;
5111
5112   /* Iterate over all the trails of finger. */
5113   for (i = 0; i < remove_finger->trails_count; i++)
5114   {
5115     struct Trail *trail;
5116     trail = &remove_finger->trail_list[i];
5117     
5118     if (GNUNET_NO == trail->is_present)
5119       continue;
5120     
5121     /* First friend to reach to finger is disconnected_peer. */
5122     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&trail->trail_head->peer,
5123                                               disconnected_friend))
5124     {
5125       matching_trails_count++;
5126       send_trail_teardown (remove_finger, trail);
5127       if (trail->trail_length > 0)
5128       free_trail (trail);
5129     }
5130   }  
5131   return matching_trails_count;
5132 }
5133
5134
5135 /**
5136  * Iterate over finger_table entries. 
5137  * 0. Ignore finger which is my_identity or if no valid entry present at 
5138  *    that finger index. 
5139  * 1. If disconnected_friend is a finger, then free that entry. Don't send trail
5140  *    teardown message, as there is no trail to reach to a finger which is a friend. 
5141  * 2. Check if disconnected_friend is the first friend in the trail to reach to a finger.
5142  *   2.1 Send trail teardown message across all the trails in which disconnected
5143  *       friend is the first friend in the trail. If disconnected_friend is the 
5144  *       first friend in all the trails to reach finger, then remove the finger. 
5145  * @param disconnected_friend Peer identity of friend which got disconnected.
5146  */
5147 static void
5148 remove_matching_fingers (const struct GNUNET_PeerIdentity *disconnected_friend)
5149 {
5150   struct FingerInfo *remove_finger;
5151   int removed_trails_count;
5152   int i;
5153   
5154   /* Iterate over finger table entries. */
5155   for (i = 0; i < MAX_FINGERS; i++)
5156   {  
5157     remove_finger = &finger_table[i];
5158
5159     /* No finger stored at this trail index. */
5160     if (GNUNET_NO == remove_finger->is_present)
5161       continue;
5162     
5163     /* I am my own finger, then ignore this finger. */
5164     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->finger_identity,
5165                                               &my_identity))
5166       continue;
5167     
5168     /* Is disconnected friend a finger? */
5169     if (0 == GNUNET_CRYPTO_cmp_peer_identity (disconnected_friend,
5170                                               &remove_finger->finger_identity))
5171     {
5172       /* No trail to reach this finger as it is a friend, don't send 
5173        * trail_teardown message. */
5174       remove_finger->is_present = GNUNET_NO;
5175       memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
5176       continue;
5177     }
5178     
5179     /* Iterate over the list of trails to reach remove_finger. Check if 
5180      * disconnected_friend is the first friend in any of the trail. */
5181     removed_trails_count = remove_matching_trails (disconnected_friend, 
5182                                                    remove_finger);
5183     
5184     /* All the finger trails had disconnected_friend as the first friend,
5185      * so free the finger. */
5186     if (removed_trails_count == remove_finger->trails_count)
5187     {
5188       remove_finger->is_present = GNUNET_NO;
5189       memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
5190     }
5191   }
5192 }
5193
5194
5195 /**
5196  * Method called whenever a peer disconnects.
5197  *
5198  * @param cls closure
5199  * @param peer peer identity this notification is about
5200  */
5201 static void
5202 handle_core_disconnect (void *cls,
5203                                           const struct GNUNET_PeerIdentity *peer)
5204 {
5205   struct FriendInfo *remove_friend;
5206
5207   /* If disconnected to own identity, then return. */
5208   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
5209     return;
5210
5211   GNUNET_assert (NULL != (remove_friend =
5212                           GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)));
5213   
5214   /* Remove fingers with peer as first friend or if peer is a finger. */
5215   remove_matching_fingers (peer);
5216   
5217   /* Remove any trail from routing table of which peer is a part of. This function
5218    * internally sends a trail teardown message in the direction of which
5219    * disconnected peer is not part of. */
5220   GDS_ROUTING_remove_trail_by_peer (peer);
5221   
5222   /* Remove peer from friend_peermap. */
5223   GNUNET_assert (GNUNET_YES ==
5224                  GNUNET_CONTAINER_multipeermap_remove (friend_peermap,
5225                                                        peer,
5226                                                        remove_friend));
5227   
5228   if (0 != GNUNET_CONTAINER_multipeermap_size (friend_peermap))
5229     return;
5230
5231   /* If there are no more friends in friend_peermap, then don't schedule
5232    * find_finger_trail_task. */
5233   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
5234   {
5235       GNUNET_SCHEDULER_cancel (find_finger_trail_task);
5236       find_finger_trail_task = GNUNET_SCHEDULER_NO_TASK;
5237   }
5238   else
5239     GNUNET_break (0);
5240
5241 }
5242
5243
5244 /**
5245  * Method called whenever a peer connects.
5246  *
5247  * @param cls closure
5248  * @param peer_identity peer identity this notification is about
5249  */
5250 static void
5251 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
5252 {
5253   struct FriendInfo *friend;
5254
5255   /* Check for connect to self message */
5256   if (0 == memcmp (&my_identity, peer_identity, sizeof (struct GNUNET_PeerIdentity)))
5257     return;
5258
5259   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to %s\n", GNUNET_i2s (peer_identity));
5260
5261   /* If peer already exists in our friend_peermap, then exit. */
5262   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (friend_peermap, 
5263                                                             peer_identity))
5264   {
5265     GNUNET_break (0);
5266     return;
5267   }
5268
5269   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
5270                             GNUNET_NO);
5271
5272   friend = GNUNET_new (struct FriendInfo);
5273   friend->id = *peer_identity;
5274
5275   GNUNET_assert (GNUNET_OK ==
5276                  GNUNET_CONTAINER_multipeermap_put (friend_peermap,
5277                                                     peer_identity, friend,
5278                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
5279
5280
5281   /* got a first connection, good time to start with FIND FINGER TRAIL requests...*/ 
5282   if (GNUNET_SCHEDULER_NO_TASK == find_finger_trail_task)
5283     find_finger_trail_task = GNUNET_SCHEDULER_add_now (&send_find_finger_trail_message, NULL);
5284 }
5285
5286
5287 /**
5288  * To be called on core init/fail.
5289  *
5290  * @param cls service closure
5291  * @param identity the public identity of this peer
5292  */
5293 static void
5294 core_init (void *cls,
5295            const struct GNUNET_PeerIdentity *identity)
5296 {
5297   my_identity = *identity;
5298   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5299               "my_indentity = %s\n",GNUNET_i2s(&my_identity));
5300 #if 0
5301    FPRINTF (stderr,_("\nSUPU %s, %s, %d, my_identity = %s"),
5302    __FILE__, __func__,__LINE__, GNUNET_i2s (&my_identity));
5303 #endif
5304 }
5305
5306
5307 /**
5308  * Initialize finger table entries.
5309  */
5310 static void
5311 finger_table_init ()
5312 {
5313   int i;
5314   int j;
5315   
5316   for(i = 0; i < MAX_FINGERS; i++)
5317   {
5318     finger_table[i].is_present = GNUNET_NO;
5319     for (j = 0; j < MAXIMUM_TRAILS_PER_FINGER; j++)
5320       finger_table[i].trail_list[j].is_present = GNUNET_NO;
5321     memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
5322     
5323   }
5324 }
5325
5326
5327 /**
5328  * Initialize neighbours subsystem.
5329  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
5330  */
5331 int
5332 GDS_NEIGHBOURS_init (void)
5333 {
5334   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5335     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
5336     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
5337     {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT, 0},
5338     {&handle_dht_p2p_trail_setup, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP, 0},
5339     {&handle_dht_p2p_trail_setup_result, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT, 0},
5340     {&handle_dht_p2p_verify_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR, 0},
5341     {&handle_dht_p2p_verify_successor_result, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT, 0},
5342     {&handle_dht_p2p_notify_new_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR, 0},
5343     {&handle_dht_p2p_trail_setup_rejection, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_REJECTION, 0},
5344     {&handle_dht_p2p_trail_compression, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION, 
5345                                         sizeof (struct PeerTrailCompressionMessage)},
5346     {&handle_dht_p2p_trail_teardown, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN, 
5347                                      sizeof (struct PeerTrailTearDownMessage)},
5348     {&handle_dht_p2p_add_trail, GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL, 0},
5349     {NULL, 0, 0}
5350   };
5351
5352   core_api =
5353     GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
5354                          &handle_core_disconnect, NULL, GNUNET_NO, NULL,
5355                          GNUNET_NO, core_handlers);
5356   if (NULL == core_api)
5357     return GNUNET_SYSERR;
5358
5359   friend_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
5360   finger_table_init ();
5361   
5362   return GNUNET_OK;
5363 }
5364
5365
5366 /**
5367  * Shutdown neighbours subsystem.
5368  */
5369 void
5370 GDS_NEIGHBOURS_done (void)
5371 {
5372   if (NULL == core_api)
5373     return;
5374
5375   GNUNET_CORE_disconnect (core_api);
5376   core_api = NULL;
5377
5378   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (friend_peermap));
5379   GNUNET_CONTAINER_multipeermap_destroy (friend_peermap);
5380   friend_peermap = NULL;
5381
5382   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
5383   {
5384     GNUNET_break (0);
5385     GNUNET_SCHEDULER_cancel (find_finger_trail_task);
5386     find_finger_trail_task = GNUNET_SCHEDULER_NO_TASK;
5387   }
5388 }
5389
5390
5391 /**
5392  * Get my identity
5393  *
5394  * @return my identity
5395  */
5396 struct GNUNET_PeerIdentity
5397 GDS_NEIGHBOURS_get_my_id (void)
5398 {
5399   return my_identity;
5400 }