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