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