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