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