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