237db023c63ef508db149a119065471199647f79
[oweals/gnunet.git] / src / dht / gnunet-service-dht.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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-dht.c
23  * @brief GNUnet DHT service
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  *
27  * TODO:
28  * - decide which 'benchmark'/test functions to keep (malicious code, kademlia, etc.)
29  * - decide on 'stop_on_closest', 'stop_on_found', 'do_find_peer', 'paper_forwarding'
30  */
31
32 #include "platform.h"
33 #include "gnunet_block_lib.h"
34 #include "gnunet_client_lib.h"
35 #include "gnunet_getopt_lib.h"
36 #include "gnunet_os_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_service_lib.h"
39 #include "gnunet_nse_service.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_signal_lib.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_datacache_lib.h"
44 #include "gnunet_transport_service.h"
45 #include "gnunet_hello_lib.h"
46 #include "gnunet_dht_service.h"
47 #include "gnunet_statistics_service.h"
48 #include "dhtlog.h"
49 #include "dht.h"
50 #include <fenv.h>
51
52
53 /**
54  * How many buckets will we allow total.
55  */
56 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57
58 /**
59  * Should the DHT issue FIND_PEER requests to get better routing tables?
60  */
61 #define DEFAULT_DO_FIND_PEER GNUNET_YES
62
63 /**
64  * Defines whether find peer requests send their HELLO's outgoing,
65  * or expect replies to contain hellos.
66  */
67 #define FIND_PEER_WITH_HELLO GNUNET_YES
68
69 /**
70  * What is the maximum number of peers in a given bucket.
71  */
72 #define DEFAULT_BUCKET_SIZE 4
73
74 #define DEFAULT_CORE_QUEUE_SIZE 32
75
76 /**
77  * Minimum number of peers we need for "good" routing,
78  * any less than this and we will allow messages to
79  * travel much further through the network!
80  */
81 #define MINIMUM_PEER_THRESHOLD 20
82
83 /**
84  * Number of requests we track at most (for routing replies).
85  */
86 #define DHT_MAX_RECENT (1024 * 16)
87
88 /**
89  * How long do we wait at most when queueing messages with core
90  * that we are sending on behalf of other peers.
91  */
92 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
93
94 /**
95  * Default importance for handling messages on behalf of other peers.
96  */
97 #define DHT_DEFAULT_P2P_IMPORTANCE 0
98
99 /**
100  * How long to keep recent requests around by default.
101  */
102 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
103
104 /**
105  * Default time to wait to send find peer messages sent by the dht service.
106  */
107 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
108
109 /**
110  * Default importance for find peer messages sent by the dht service.
111  */
112 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
113
114 /**
115  * Default replication parameter for find peer messages sent by the dht service.
116  */
117 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
118
119 /**
120  * How long at least to wait before sending another find peer request.
121  */
122 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
123
124 /**
125  * How long at most to wait before sending another find peer request.
126  */
127 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
128
129 /**
130  * How often to update our preference levels for peers in our routing tables.
131  */
132 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
133
134 /**
135  * How long at most on average will we allow a reply forward to take
136  * (before we quit sending out new requests)
137  */
138 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
139
140 /**
141  * How many initial requests to send out (in true Kademlia fashion)
142  */
143 #define DEFAULT_KADEMLIA_REPLICATION 3
144
145 /**
146  * Default frequency for sending malicious get messages
147  */
148 #define DEFAULT_MALICIOUS_GET_FREQUENCY GNUNET_TIME_UNIT_SECONDS
149
150 /**
151  * Default frequency for sending malicious put messages
152  */
153 #define DEFAULT_MALICIOUS_PUT_FREQUENCY GNUNET_TIME_UNIT_SECONDS
154
155 /**
156  * How many time differences between requesting a core send and
157  * the actual callback to remember.
158  */
159 #define MAX_REPLY_TIMES 8
160
161
162 /**
163  * Linked list of messages to send to clients.
164  */
165 struct P2PPendingMessage
166 {
167   /**
168    * Pointer to next item in the list
169    */
170   struct P2PPendingMessage *next;
171
172   /**
173    * Pointer to previous item in the list
174    */
175   struct P2PPendingMessage *prev;
176
177   /**
178    * Message importance level.
179    */
180   unsigned int importance;
181
182   /**
183    * Time when this request was scheduled to be sent.
184    */
185   struct GNUNET_TIME_Absolute scheduled;
186
187   /**
188    * How long to wait before sending message.
189    */
190   struct GNUNET_TIME_Relative timeout;
191
192   /**
193    * Actual message to be sent; // avoid allocation
194    */
195   const struct GNUNET_MessageHeader *msg;       // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
196
197 };
198
199
200 /**
201  * Per-peer information.
202  */
203 struct PeerInfo
204 {
205   /**
206    * Next peer entry (DLL)
207    */
208   struct PeerInfo *next;
209
210   /**
211    *  Prev peer entry (DLL)
212    */
213   struct PeerInfo *prev;
214
215   /**
216    * Count of outstanding messages for peer.
217    */
218   unsigned int pending_count;
219
220   /**
221    * Head of pending messages to be sent to this peer.
222    */
223   struct P2PPendingMessage *head;
224
225   /**
226    * Tail of pending messages to be sent to this peer.
227    */
228   struct P2PPendingMessage *tail;
229
230   /**
231    * Core handle for sending messages to this peer.
232    */
233   struct GNUNET_CORE_TransmitHandle *th;
234
235   /**
236    * Task for scheduling message sends.
237    */
238   GNUNET_SCHEDULER_TaskIdentifier send_task;
239
240   /**
241    * Task for scheduling preference updates
242    */
243   GNUNET_SCHEDULER_TaskIdentifier preference_task;
244
245   /**
246    * Preference update context
247    */
248   struct GNUNET_CORE_InformationRequestContext *info_ctx;
249
250   /**
251    * What is the identity of the peer?
252    */
253   struct GNUNET_PeerIdentity id;
254
255 #if 0
256   /**
257    * What is the average latency for replies received?
258    */
259   struct GNUNET_TIME_Relative latency;
260
261   /**
262    * Transport level distance to peer.
263    */
264   unsigned int distance;
265 #endif
266
267   /**
268    * Task for scheduling periodic ping messages for this peer.
269    */
270   GNUNET_SCHEDULER_TaskIdentifier ping_task;
271 };
272
273
274 /**
275  * Peers are grouped into buckets.
276  */
277 struct PeerBucket
278 {
279   /**
280    * Head of DLL
281    */
282   struct PeerInfo *head;
283
284   /**
285    * Tail of DLL
286    */
287   struct PeerInfo *tail;
288
289   /**
290    * Number of peers in the bucket.
291    */
292   unsigned int peers_size;
293 };
294
295
296 /**
297  * Linked list of messages to send to clients.
298  */
299 struct PendingMessage
300 {
301   /**
302    * Pointer to next item in the list
303    */
304   struct PendingMessage *next;
305
306   /**
307    * Pointer to previous item in the list
308    */
309   struct PendingMessage *prev;
310
311   /**
312    * Actual message to be sent; // avoid allocation
313    */
314   const struct GNUNET_MessageHeader *msg;       // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
315
316 };
317
318
319 /**
320  * Struct containing information about a client,
321  * handle to connect to it, and any pending messages
322  * that need to be sent to it.
323  */
324 struct ClientList
325 {
326   /**
327    * Linked list of active clients
328    */
329   struct ClientList *next;
330
331   /**
332    * The handle to this client
333    */
334   struct GNUNET_SERVER_Client *client_handle;
335
336   /**
337    * Handle to the current transmission request, NULL
338    * if none pending.
339    */
340   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
341
342   /**
343    * Linked list of pending messages for this client
344    */
345   struct PendingMessage *pending_head;
346
347   /**
348    * Tail of linked list of pending messages for this client
349    */
350   struct PendingMessage *pending_tail;
351 };
352
353
354 /**
355  * Context containing information about a DHT message received.
356  */
357 struct DHT_MessageContext
358 {
359   /**
360    * The client this request was received from.
361    * (NULL if received from another peer)
362    */
363   struct ClientList *client;
364
365   /**
366    * The peer this request was received from.
367    * (NULL if received from local client)
368    */
369   const struct GNUNET_PeerIdentity *peer;
370
371   /**
372    * Bloomfilter for this routing request.
373    */
374   struct GNUNET_CONTAINER_BloomFilter *bloom;
375
376   /**
377    * extended query (see gnunet_block_lib.h).
378    */
379   const void *xquery;
380
381   /**
382    * Bloomfilter to filter out duplicate replies.
383    */
384   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
385
386   /**
387    * The key this request was about
388    */
389   GNUNET_HashCode key;
390
391   /**
392    * How long should we wait to transmit this request?
393    */
394   struct GNUNET_TIME_Relative timeout;
395
396   /**
397    * The unique identifier of this request
398    */
399   uint64_t unique_id;
400
401   /**
402    * Number of bytes in xquery.
403    */
404   size_t xquery_size;
405
406   /**
407    * Mutator value for the reply_bf, see gnunet_block_lib.h
408    */
409   uint32_t reply_bf_mutator;
410
411   /**
412    * Desired replication level
413    */
414   uint32_t replication;
415
416   /**
417    * Network size estimate, either ours or the sum of
418    * those routed to thus far. =~ Log of number of peers
419    * chosen from for this request.
420    */
421   uint32_t network_size;
422
423   /**
424    * Any message options for this request
425    */
426   uint32_t msg_options;
427
428   /**
429    * How many hops has the message already traversed?
430    */
431   uint32_t hop_count;
432
433   /**
434    * How many peer identities are present in the path history?
435    */
436   uint32_t path_history_len;
437
438   /**
439    * Path history.
440    */
441   char *path_history;
442
443   /**
444    * How important is this message?
445    */
446   unsigned int importance;
447
448   /**
449    * Should we (still) forward the request on to other peers?
450    */
451   int do_forward;
452
453   /**
454    * Did we forward this message? (may need to remember it!)
455    */
456   int forwarded;
457
458   /**
459    * Are we the closest known peer to this key (out of our neighbors?)
460    */
461   int closest;
462 };
463
464
465 /**
466  * Record used for remembering what peers are waiting for what
467  * responses (based on search key).
468  */
469 struct DHTRouteSource
470 {
471   /**
472    * This is a DLL.
473    */
474   struct DHTRouteSource *next;
475
476   /**
477    * This is a DLL.
478    */
479   struct DHTRouteSource *prev;
480
481   /**
482    * Source of the request.  Replies should be forwarded to
483    * this peer.
484    */
485   struct GNUNET_PeerIdentity source;
486
487   /**
488    * If this was a local request, remember the client; otherwise NULL.
489    */
490   struct ClientList *client;
491
492   /**
493    * Pointer to this nodes heap location (for removal)
494    */
495   struct GNUNET_CONTAINER_HeapNode *hnode;
496
497   /**
498    * Back pointer to the record storing this information.
499    */
500   struct DHTQueryRecord *record;
501
502   /**
503    * Task to remove this entry on timeout.
504    */
505   GNUNET_SCHEDULER_TaskIdentifier delete_task;
506
507   /**
508    * Bloomfilter of peers we have already sent back as
509    * replies to the initial request.  Allows us to not
510    * forward the same peer multiple times for a find peer
511    * request.
512    */
513   struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
514
515 };
516
517
518 /**
519  * Entry in the DHT routing table.
520  */
521 struct DHTQueryRecord
522 {
523   /**
524    * Head of DLL for result forwarding.
525    */
526   struct DHTRouteSource *head;
527
528   /**
529    * Tail of DLL for result forwarding.
530    */
531   struct DHTRouteSource *tail;
532
533   /**
534    * Key that the record concerns.
535    */
536   GNUNET_HashCode key;
537
538 };
539
540
541 /**
542  * Context used to calculate the number of find peer messages
543  * per X time units since our last scheduled find peer message
544  * was sent.  If we have seen too many messages, delay or don't
545  * send our own out.
546  */
547 struct FindPeerMessageContext
548 {
549   unsigned int count;
550
551   struct GNUNET_TIME_Absolute start;
552
553   struct GNUNET_TIME_Absolute end;
554 };
555
556
557 /**
558  * DHT Routing results structure
559  */
560 struct DHTResults
561 {
562   /*
563    * Min heap for removal upon reaching limit
564    */
565   struct GNUNET_CONTAINER_Heap *minHeap;
566
567   /*
568    * Hashmap for fast key based lookup
569    */
570   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
571
572 };
573
574
575 /**
576  * DHT structure for recent requests.
577  */
578 struct RecentRequests
579 {
580   /*
581    * Min heap for removal upon reaching limit
582    */
583   struct GNUNET_CONTAINER_Heap *minHeap;
584
585   /*
586    * Hashmap for key based lookup
587    */
588   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
589 };
590
591
592 struct RecentRequest
593 {
594   /**
595    * Position of this node in the min heap.
596    */
597   struct GNUNET_CONTAINER_HeapNode *heap_node;
598
599   /**
600    * Bloomfilter containing entries for peers
601    * we forwarded this request to.
602    */
603   struct GNUNET_CONTAINER_BloomFilter *bloom;
604
605   /**
606    * Timestamp of this request, for ordering
607    * the min heap.
608    */
609   struct GNUNET_TIME_Absolute timestamp;
610
611   /**
612    * Key of this request.
613    */
614   GNUNET_HashCode key;
615
616   /**
617    * Unique identifier for this request.
618    */
619   uint64_t uid;
620
621   /**
622    * Task to remove this entry on timeout.
623    */
624   GNUNET_SCHEDULER_TaskIdentifier remove_task;
625 };
626
627
628 /**
629  * log of the current network size estimate, used as the point where
630  * we switch between random and deterministic routing.  Default
631  * value of 4.0 is used if NSE module is not available (i.e. not
632  * configured).
633  */
634 static double log_of_network_size_estimate = 4.0;
635
636 /**
637  * Recent requests by hash/uid and by time inserted.
638  */
639 static struct RecentRequests recent;
640
641 /**
642  * Context to use to calculate find peer rates.
643  */
644 static struct FindPeerMessageContext find_peer_context;
645
646 /**
647  * Don't use our routing algorithm, always route
648  * to closest peer; initially send requests to 3
649  * peers.
650  */
651 static int strict_kademlia;
652
653 /**
654  * Routing option to end routing when closest peer found.
655  */
656 static int stop_on_closest;
657
658 /**
659  * Routing option to end routing when data is found.
660  */
661 static int stop_on_found;
662
663 /**
664  * Whether DHT needs to manage find peer requests, or
665  * an external force will do it on behalf of the DHT.
666  */
667 static int do_find_peer;
668
669 /**
670  * Use exactly the forwarding formula as described in
671  * the paper if set to GNUNET_YES, otherwise use the
672  * slightly modified version.
673  */
674 static int paper_forwarding;
675
676 /**
677  * PUT Peer Identities of peers we know about into
678  * the datacache.
679  */
680 static int put_peer_identities;
681
682 /**
683  * Use the "real" distance metric when selecting the
684  * next routing hop.  Can be less accurate.
685  */
686 static int use_real_distance;
687
688 /**
689  * How many peers have we added since we sent out our last
690  * find peer request?
691  */
692 static unsigned int newly_found_peers;
693
694 /**
695  * Container of active queries we should remember
696  */
697 static struct DHTResults forward_list;
698
699 /**
700  * Handle to the datacache service (for inserting/retrieving data)
701  */
702 static struct GNUNET_DATACACHE_Handle *datacache;
703
704 /**
705  * Handle for the statistics service.
706  */
707 struct GNUNET_STATISTICS_Handle *stats;
708
709 /**
710  * Handle to get our current HELLO.
711  */
712 static struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
713
714 /**
715  * The configuration the DHT service is running with
716  */
717 static const struct GNUNET_CONFIGURATION_Handle *cfg;
718
719 /**
720  * Handle to the core service
721  */
722 static struct GNUNET_CORE_Handle *coreAPI;
723
724 /**
725  * Handle to the transport service, for getting our hello
726  */
727 static struct GNUNET_TRANSPORT_Handle *transport_handle;
728
729 /**
730  * The identity of our peer.
731  */
732 static struct GNUNET_PeerIdentity my_identity;
733
734 /**
735  * Short id of the peer, for printing
736  */
737 static char *my_short_id;
738
739 /**
740  * Our HELLO
741  */
742 static struct GNUNET_MessageHeader *my_hello;
743
744 /**
745  * Task to run when we shut down, cleaning up all our trash
746  */
747 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
748
749 /**
750  * The lowest currently used bucket.
751  */
752 static unsigned int lowest_bucket;      /* Initially equal to MAX_BUCKETS - 1 */
753
754 /**
755  * The buckets (Kademlia routing table, complete with growth).
756  * Array of size MAX_BUCKET_SIZE.
757  */
758 static struct PeerBucket k_buckets[MAX_BUCKETS];
759
760 /**
761  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
762  */
763 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
764
765 /**
766  * Recently seen find peer requests.
767  */
768 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
769
770 /**
771  * Maximum size for each bucket.
772  */
773 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
774
775 /**
776  * List of active clients.
777  */
778 static struct ClientList *client_list;
779
780 /**
781  * Handle to the DHT logger.
782  */
783 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
784
785 /**
786  * Whether or not to send routing debugging information
787  * to the dht logging server
788  */
789 static unsigned int debug_routes;
790
791 /**
792  * Whether or not to send FULL route information to
793  * logging server
794  */
795 static unsigned int debug_routes_extended;
796
797 /**
798  * GNUNET_YES or GNUNET_NO, whether or not to act as
799  * a malicious node which drops all messages
800  */
801 static unsigned int malicious_dropper;
802
803 /**
804  * GNUNET_YES or GNUNET_NO, whether or not to act as
805  * a malicious node which sends out lots of GETS
806  */
807 static unsigned int malicious_getter;
808
809 /**
810  * GNUNET_YES or GNUNET_NO, whether or not to act as
811  * a malicious node which sends out lots of PUTS
812  */
813 static unsigned int malicious_putter;
814
815 /**
816  * Frequency for malicious get requests.
817  */
818 static struct GNUNET_TIME_Relative malicious_get_frequency;
819
820 /**
821  * Frequency for malicious put requests.
822  */
823 static struct GNUNET_TIME_Relative malicious_put_frequency;
824
825 /**
826  * Kademlia replication
827  */
828 static unsigned long long kademlia_replication;
829
830 /**
831  * Reply times for requests, if we are busy, don't send any
832  * more requests!
833  */
834 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
835
836 /**
837  * Current counter for replies.
838  */
839 static unsigned int reply_counter;
840
841 /**
842  * Our handle to the BLOCK library.
843  */
844 static struct GNUNET_BLOCK_Context *block_context;
845
846 /**
847  * Network size estimation handle.
848  */
849 static struct GNUNET_NSE_Handle *nse;
850
851
852 /**
853  * Callback that is called when network size estimate is updated.
854  *
855  * @param cls closure
856  * @param timestamp time when the estimate was received from the server (or created by the server)
857  * @param logestimate the log(Base 2) value of the current network size estimate
858  * @param std_dev standard deviation for the estimate
859  *
860  */
861 static void 
862 update_network_size_estimate (void *cls,
863                               struct GNUNET_TIME_Absolute timestamp,
864                               double logestimate, double std_dev)
865 {
866   log_of_network_size_estimate = logestimate;
867 }
868
869
870 /**
871  * Forward declaration.
872  */
873 static size_t
874 send_generic_reply (void *cls, size_t size, void *buf);
875
876
877 /** Declare here so retry_core_send is aware of it */
878 static size_t
879 core_transmit_notify (void *cls, size_t size, void *buf);
880
881
882 /**
883  * Convert unique ID to hash code.
884  *
885  * @param uid unique ID to convert
886  * @param hash set to uid (extended with zeros)
887  */
888 static void
889 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
890 {
891   memset (hash, 0, sizeof (GNUNET_HashCode));
892   *((uint64_t *) hash) = uid;
893 }
894
895
896 /**
897  * Given the largest send delay, artificially decrease it
898  * so the next time around we may have a chance at sending
899  * again.
900  */
901 static void
902 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
903 {
904   unsigned int i;
905
906   for (i = 0; i < MAX_REPLY_TIMES; i++)
907   {
908     if (reply_times[i].rel_value == max_time.rel_value)
909     {
910       reply_times[i].rel_value = reply_times[i].rel_value / 2;
911       return;
912     }
913   }
914 }
915
916
917 /**
918  * Find the maximum send time of the recently sent values.
919  *
920  * @return the average time between asking core to send a message
921  *         and when the buffer for copying it is passed
922  */
923 static struct GNUNET_TIME_Relative
924 get_max_send_delay ()
925 {
926   unsigned int i;
927   struct GNUNET_TIME_Relative max_time;
928
929   max_time = GNUNET_TIME_relative_get_zero ();
930
931   for (i = 0; i < MAX_REPLY_TIMES; i++)
932   {
933     if (reply_times[i].rel_value > max_time.rel_value)
934       max_time.rel_value = reply_times[i].rel_value;
935   }
936 #if DEBUG_DHT
937   if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
938     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
939                 (unsigned long long) max_time.rel_value);
940 #endif
941   return max_time;
942 }
943
944
945 static void
946 increment_stats (const char *value)
947 {
948   if (stats == NULL)
949     return;
950   GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);  
951 }
952
953
954 static void
955 decrement_stats (const char *value)
956 {
957   if (stats == NULL)
958     return;
959   GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);  
960 }
961
962
963 /**
964  *  Try to send another message from our core send list
965  */
966 static void
967 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
968 {
969   struct PeerInfo *peer = cls;
970   struct P2PPendingMessage *pending;
971   size_t ssize;
972
973   peer->send_task = GNUNET_SCHEDULER_NO_TASK;
974
975   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
976     return;
977
978   if (peer->th != NULL)
979     return;                     /* Message send already in progress */
980
981   pending = peer->head;
982   if (pending != NULL)
983   {
984     ssize = ntohs (pending->msg->size);
985 #if DEBUG_DHT > 1
986     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987                 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
988                 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
989 #endif
990     pending->scheduled = GNUNET_TIME_absolute_get ();
991     reply_counter++;
992     if (reply_counter >= MAX_REPLY_TIMES)
993       reply_counter = 0;
994     peer->th =
995         GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
996                                            pending->importance,
997                                            pending->timeout, &peer->id, ssize,
998                                            &core_transmit_notify, peer);
999     if (peer->th == NULL)
1000       increment_stats ("# notify transmit ready failed");
1001   }
1002 }
1003
1004
1005 /**
1006  * Function called to send a request out to another peer.
1007  * Called both for locally initiated requests and those
1008  * received from other peers.
1009  *
1010  * @param msg the encapsulated message
1011  * @param peer the peer to forward the message to
1012  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1013  */
1014 static void
1015 forward_result_message (const struct GNUNET_MessageHeader *msg,
1016                         struct PeerInfo *peer,
1017                         struct DHT_MessageContext *msg_ctx)
1018 {
1019   struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1020   struct P2PPendingMessage *pending;
1021   size_t msize;
1022   size_t psize;
1023   char *path_start;
1024   char *path_offset;
1025
1026 #if DEBUG_PATH
1027   unsigned int i;
1028 #endif
1029
1030   increment_stats (STAT_RESULT_FORWARDS);
1031   msize =
1032       sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1033       (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1034   GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1035   psize = sizeof (struct P2PPendingMessage) + msize;
1036   pending = GNUNET_malloc (psize);
1037   pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1038   pending->importance = DHT_SEND_PRIORITY;
1039   pending->timeout = GNUNET_TIME_relative_get_forever ();
1040   result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1041   result_message->header.size = htons (msize);
1042   result_message->header.type =
1043       htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1044   result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1045   if (msg_ctx->path_history_len > 0)
1046   {
1047     /* End of pending is where enc_msg starts */
1048     path_start = (char *) &pending[1];
1049     /* Offset by the size of the enc_msg */
1050     path_start += ntohs (msg->size);
1051     memcpy (path_start, msg_ctx->path_history,
1052             msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1053 #if DEBUG_PATH
1054     for (i = 0; i < msg_ctx->path_history_len; i++)
1055     {
1056       path_offset =
1057           &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1058       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1059                   "(forward_result) Key %s Found peer %d:%s\n",
1060                   GNUNET_h2s (&msg_ctx->key), i,
1061                   GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1062     }
1063 #endif
1064   }
1065   result_message->options = htonl (msg_ctx->msg_options);
1066   result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1067   GNUNET_assert (GNUNET_OK ==
1068                  GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1069                                                             result_message->
1070                                                             bloomfilter,
1071                                                             DHT_BLOOM_SIZE));
1072   result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1073   memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1074   /* Copy the enc_msg, then the path history as well! */
1075   memcpy (&result_message[1], msg, ntohs (msg->size));
1076   path_offset = (char *) &result_message[1];
1077   path_offset += ntohs (msg->size);
1078   /* If we have path history, copy it to the end of the whole thing */
1079   if (msg_ctx->path_history_len > 0)
1080     memcpy (path_offset, msg_ctx->path_history,
1081             msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1082 #if DEBUG_DHT > 1
1083   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084               "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1085               "DHT", msize, GNUNET_i2s (&peer->id));
1086 #endif
1087   peer->pending_count++;
1088   increment_stats ("# pending messages scheduled");
1089   GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1090                                      pending);
1091   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1092     peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1093 }
1094
1095
1096 /**
1097  * Called when core is ready to send a message we asked for
1098  * out to the destination.
1099  *
1100  * @param cls closure (NULL)
1101  * @param size number of bytes available in buf
1102  * @param buf where the callee should write the message
1103  * @return number of bytes written to buf
1104  */
1105 static size_t
1106 core_transmit_notify (void *cls, size_t size, void *buf)
1107 {
1108   struct PeerInfo *peer = cls;
1109   char *cbuf = buf;
1110   struct P2PPendingMessage *pending;
1111
1112   size_t off;
1113   size_t msize;
1114
1115   peer->th = NULL;
1116   if (buf == NULL)
1117   {
1118     /* client disconnected */
1119 #if DEBUG_DHT
1120     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1121                 my_short_id, "DHT");
1122 #endif
1123     return 0;
1124   }
1125
1126   if (peer->head == NULL)
1127     return 0;
1128
1129   off = 0;
1130   pending = peer->head;
1131 #if DUMB
1132   reply_times[reply_counter] =
1133       GNUNET_TIME_absolute_get_difference (pending->scheduled,
1134                                            GNUNET_TIME_absolute_get ());
1135   msize = ntohs (pending->msg->size);
1136   if (msize <= size)
1137   {
1138     off = msize;
1139     memcpy (cbuf, pending->msg, msize);
1140     peer->pending_count--;
1141     increment_stats ("# pending messages sent");
1142     GNUNET_assert (peer->pending_count >= 0);
1143     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1144     GNUNET_free (pending);
1145   }
1146 #else
1147   while (NULL != pending &&
1148          (size - off >= (msize = ntohs (pending->msg->size))))
1149   {
1150     memcpy (&cbuf[off], pending->msg, msize);
1151     off += msize;
1152     peer->pending_count--;
1153     increment_stats ("# pending messages sent");
1154     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1155     GNUNET_free (pending);
1156     pending = peer->head;
1157   }
1158 #endif
1159   if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1160     peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1161
1162   return off;
1163 }
1164
1165
1166 /**
1167  * Compute the distance between have and target as a 32-bit value.
1168  * Differences in the lower bits must count stronger than differences
1169  * in the higher bits.
1170  *
1171  * @return 0 if have==target, otherwise a number
1172  *           that is larger as the distance between
1173  *           the two hash codes increases
1174  */
1175 static unsigned int
1176 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1177 {
1178   unsigned int bucket;
1179   unsigned int msb;
1180   unsigned int lsb;
1181   unsigned int i;
1182
1183   /* We have to represent the distance between two 2^9 (=512)-bit
1184    * numbers as a 2^5 (=32)-bit number with "0" being used for the
1185    * two numbers being identical; furthermore, we need to
1186    * guarantee that a difference in the number of matching
1187    * bits is always represented in the result.
1188    *
1189    * We use 2^32/2^9 numerical values to distinguish between
1190    * hash codes that have the same LSB bit distance and
1191    * use the highest 2^9 bits of the result to signify the
1192    * number of (mis)matching LSB bits; if we have 0 matching
1193    * and hence 512 mismatching LSB bits we return -1 (since
1194    * 512 itself cannot be represented with 9 bits) */
1195
1196   /* first, calculate the most significant 9 bits of our
1197    * result, aka the number of LSBs */
1198   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1199   /* bucket is now a value between 0 and 512 */
1200   if (bucket == 512)
1201     return 0;                   /* perfect match */
1202   if (bucket == 0)
1203     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
1204                                  * below, we'd end up with max+1 (overflow)) */
1205
1206   /* calculate the most significant bits of the final result */
1207   msb = (512 - bucket) << (32 - 9);
1208   /* calculate the 32-9 least significant bits of the final result by
1209    * looking at the differences in the 32-9 bits following the
1210    * mismatching bit at 'bucket' */
1211   lsb = 0;
1212   for (i = bucket + 1;
1213        (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1214   {
1215     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1216         GNUNET_CRYPTO_hash_get_bit (have, i))
1217       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
1218                                                  * last bit set will be 31 -- if
1219                                                  * i does not reach 512 first... */
1220   }
1221   return msb | lsb;
1222 }
1223
1224
1225 /**
1226  * Return a number that is larger the closer the
1227  * "have" GNUNET_hash code is to the "target".
1228  *
1229  * @return inverse distance metric, non-zero.
1230  *         Must fudge the value if NO bits match.
1231  */
1232 static unsigned int
1233 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1234 {
1235   if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1236     return 1;                   /* Never return 0! */
1237   return ((unsigned int) -1) - distance (target, have);
1238 }
1239
1240
1241 /**
1242  * Find the optimal bucket for this key, regardless
1243  * of the current number of buckets in use.
1244  *
1245  * @param hc the hashcode to compare our identity to
1246  *
1247  * @return the proper bucket index, or GNUNET_SYSERR
1248  *         on error (same hashcode)
1249  */
1250 static int
1251 find_bucket (const GNUNET_HashCode * hc)
1252 {
1253   unsigned int bits;
1254
1255   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1256   if (bits == MAX_BUCKETS)
1257     return GNUNET_SYSERR;
1258   return MAX_BUCKETS - bits - 1;
1259 }
1260
1261
1262 /**
1263  * Find which k-bucket this peer should go into,
1264  * taking into account the size of the k-bucket
1265  * array.  This means that if more bits match than
1266  * there are currently buckets, lowest_bucket will
1267  * be returned.
1268  *
1269  * @param hc GNUNET_HashCode we are finding the bucket for.
1270  *
1271  * @return the proper bucket index for this key,
1272  *         or GNUNET_SYSERR on error (same hashcode)
1273  */
1274 static int
1275 find_current_bucket (const GNUNET_HashCode * hc)
1276 {
1277   int actual_bucket;
1278
1279   actual_bucket = find_bucket (hc);
1280   if (actual_bucket == GNUNET_SYSERR)   /* hc and our peer identity match! */
1281     return lowest_bucket;
1282   if (actual_bucket < lowest_bucket)    /* actual_bucket not yet used */
1283     return lowest_bucket;
1284   return actual_bucket;
1285 }
1286
1287
1288 /**
1289  * Find a routing table entry from a peer identity
1290  *
1291  * @param peer the peer identity to look up
1292  *
1293  * @return the routing table entry, or NULL if not found
1294  */
1295 static struct PeerInfo *
1296 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1297 {
1298   int bucket;
1299   struct PeerInfo *pos;
1300
1301   bucket = find_current_bucket (&peer->hashPubKey);
1302
1303   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1304     return NULL;
1305
1306   pos = k_buckets[bucket].head;
1307   while (pos != NULL)
1308   {
1309     if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1310       return pos;
1311     pos = pos->next;
1312   }
1313   return NULL;                  /* No such peer. */
1314 }
1315
1316 /* Forward declaration */
1317 static void
1318 update_core_preference (void *cls,
1319                         const struct GNUNET_SCHEDULER_TaskContext *tc);
1320
1321
1322 /**
1323  * Function called with statistics about the given peer.
1324  *
1325  * @param cls closure
1326  * @param peer identifies the peer
1327  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1328  * @param amount set to the amount that was actually reserved or unreserved;
1329  *               either the full requested amount or zero (no partial reservations)
1330  * @param res_delay if the reservation could not be satisfied (amount was 0), how
1331  *        long should the client wait until re-trying?
1332  * @param preference current traffic preference for the given peer
1333  */
1334 static void
1335 update_core_preference_finish (void *cls,
1336                                const struct GNUNET_PeerIdentity *peer,
1337                                struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1338                                int32_t amount,
1339                                struct GNUNET_TIME_Relative res_delay,
1340                                uint64_t preference)
1341 {
1342   struct PeerInfo *peer_info = cls;
1343
1344   peer_info->info_ctx = NULL;
1345   GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1346                                 &update_core_preference, peer_info);
1347 }
1348
1349 static void
1350 update_core_preference (void *cls,
1351                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1352 {
1353   struct PeerInfo *peer = cls;
1354   uint64_t preference;
1355   unsigned int matching;
1356
1357   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1358   {
1359     return;
1360   }
1361   matching =
1362       GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1363                                         &peer->id.hashPubKey);
1364   if (matching >= 64)
1365   {
1366 #if DEBUG_DHT
1367     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1368                 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1369                 matching);
1370 #endif
1371     matching = 63;
1372   }
1373   preference = 1LL << matching;
1374   peer->info_ctx =
1375       GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1376                                           GNUNET_TIME_UNIT_FOREVER_REL,
1377                                           GNUNET_BANDWIDTH_VALUE_MAX, 0,
1378                                           preference,
1379                                           &update_core_preference_finish, peer);
1380 }
1381
1382
1383 /**
1384  * Given a peer and its corresponding bucket,
1385  * remove it from that bucket.  Does not free
1386  * the PeerInfo struct, nor cancel messages
1387  * or free messages waiting to be sent to this
1388  * peer!
1389  *
1390  * @param peer the peer to remove
1391  * @param bucket the bucket the peer belongs to
1392  */
1393 static void
1394 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1395 {
1396   GNUNET_assert (k_buckets[bucket].peers_size > 0);
1397   GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1398                                peer);
1399   k_buckets[bucket].peers_size--;
1400 #if CHANGE_LOWEST
1401   if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1402       (lowest_bucket < MAX_BUCKETS - 1))
1403     lowest_bucket++;
1404 #endif
1405 }
1406
1407 /**
1408  * Removes peer from a bucket, then frees associated
1409  * resources and frees peer.
1410  *
1411  * @param peer peer to be removed and freed
1412  * @param bucket which bucket this peer belongs to
1413  */
1414 static void
1415 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1416 {
1417   struct P2PPendingMessage *pos;
1418   struct P2PPendingMessage *next;
1419
1420   remove_peer (peer, bucket);   /* First remove the peer from its bucket */
1421   if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1422     GNUNET_SCHEDULER_cancel (peer->send_task);
1423   if ((peer->th != NULL) && (coreAPI != NULL))
1424     GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1425
1426   pos = peer->head;
1427   while (pos != NULL)           /* Remove any pending messages for this peer */
1428   {
1429     increment_stats
1430         ("# dht pending messages discarded (due to disconnect/shutdown)");
1431     next = pos->next;
1432     GNUNET_free (pos);
1433     pos = next;
1434   }
1435
1436   GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1437                  (all_known_peers, &peer->id.hashPubKey));
1438   GNUNET_assert (GNUNET_YES ==
1439                  GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1440                                                        &peer->id.hashPubKey,
1441                                                        peer));
1442   GNUNET_free (peer);
1443   decrement_stats (STAT_PEERS_KNOWN);
1444 }
1445
1446
1447 /**
1448  * Iterator over hash map entries.
1449  *
1450  * @param cls closure
1451  * @param key current key code
1452  * @param value PeerInfo of the peer to move to new lowest bucket
1453  * @return GNUNET_YES if we should continue to
1454  *         iterate,
1455  *         GNUNET_NO if not.
1456  */
1457 static int
1458 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1459 {
1460   struct PeerInfo *peer = value;
1461   int new_bucket;
1462
1463   GNUNET_assert (lowest_bucket > 0);
1464   new_bucket = lowest_bucket - 1;
1465   remove_peer (peer, lowest_bucket);
1466   GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1467                                      k_buckets[new_bucket].tail,
1468                                      k_buckets[new_bucket].tail, peer);
1469   k_buckets[new_bucket].peers_size++;
1470   return GNUNET_YES;
1471 }
1472
1473
1474 /**
1475  * The current lowest bucket is full, so change the lowest
1476  * bucket to the next lower down, and move any appropriate
1477  * entries in the current lowest bucket to the new bucket.
1478  */
1479 static void
1480 enable_next_bucket ()
1481 {
1482   struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1483   struct PeerInfo *pos;
1484
1485   GNUNET_assert (lowest_bucket > 0);
1486   to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1487   pos = k_buckets[lowest_bucket].head;
1488
1489   /* Populate the array of peers which should be in the next lowest bucket */
1490   while (pos != NULL)
1491   {
1492     if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1493       GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1494                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1495     pos = pos->next;
1496   }
1497
1498   /* Remove peers from lowest bucket, insert into next lowest bucket */
1499   GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1500   GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1501   lowest_bucket = lowest_bucket - 1;
1502 }
1503
1504
1505 /**
1506  * Find the closest peer in our routing table to the
1507  * given hashcode.
1508  *
1509  * @return The closest peer in our routing table to the
1510  *         key, or NULL on error.
1511  */
1512 static struct PeerInfo *
1513 find_closest_peer (const GNUNET_HashCode * hc)
1514 {
1515   struct PeerInfo *pos;
1516   struct PeerInfo *current_closest;
1517   unsigned int lowest_distance;
1518   unsigned int temp_distance;
1519   int bucket;
1520   int count;
1521
1522   lowest_distance = -1;
1523
1524   if (k_buckets[lowest_bucket].peers_size == 0)
1525     return NULL;
1526
1527   current_closest = NULL;
1528   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1529   {
1530     pos = k_buckets[bucket].head;
1531     count = 0;
1532     while ((pos != NULL) && (count < bucket_size))
1533     {
1534       temp_distance = distance (&pos->id.hashPubKey, hc);
1535       if (temp_distance <= lowest_distance)
1536       {
1537         lowest_distance = temp_distance;
1538         current_closest = pos;
1539       }
1540       pos = pos->next;
1541       count++;
1542     }
1543   }
1544   GNUNET_assert (current_closest != NULL);
1545   return current_closest;
1546 }
1547
1548
1549 /**
1550  * Function called to send a request out to another peer.
1551  * Called both for locally initiated requests and those
1552  * received from other peers.
1553  *
1554  * @param msg the encapsulated message
1555  * @param peer the peer to forward the message to
1556  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1557  */
1558 static void
1559 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1560                  struct DHT_MessageContext *msg_ctx)
1561 {
1562   struct GNUNET_DHT_P2PRouteMessage *route_message;
1563   struct P2PPendingMessage *pending;
1564   size_t msize;
1565   size_t psize;
1566   char *route_path;
1567
1568   increment_stats (STAT_ROUTE_FORWARDS);
1569   GNUNET_assert (peer != NULL);
1570   if ((msg_ctx->closest != GNUNET_YES) &&
1571       (peer == find_closest_peer (&msg_ctx->key)))
1572     increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1573
1574   msize =
1575       sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1576       (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1577   GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1578   psize = sizeof (struct P2PPendingMessage) + msize;
1579   pending = GNUNET_malloc (psize);
1580   pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1581   pending->importance = msg_ctx->importance;
1582   pending->timeout = msg_ctx->timeout;
1583   route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1584   route_message->header.size = htons (msize);
1585   route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1586   route_message->options = htonl (msg_ctx->msg_options);
1587   route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1588   route_message->network_size = htonl (msg_ctx->network_size);
1589   route_message->desired_replication_level = htonl (msg_ctx->replication);
1590   route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1591   if (msg_ctx->bloom != NULL)
1592     GNUNET_assert (GNUNET_OK ==
1593                    GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1594                                                               route_message->
1595                                                               bloomfilter,
1596                                                               DHT_BLOOM_SIZE));
1597   memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1598   memcpy (&route_message[1], msg, ntohs (msg->size));
1599   if (GNUNET_DHT_RO_RECORD_ROUTE ==
1600       (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1601   {
1602     route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1603     /* Set pointer to start of enc_msg */
1604     route_path = (char *) &route_message[1];
1605     /* Offset to the end of the enc_msg */
1606     route_path += ntohs (msg->size);
1607     /* Copy the route_path after enc_msg */
1608     memcpy (route_path, msg_ctx->path_history,
1609             msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1610   }
1611 #if DEBUG_DHT > 1
1612   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613               "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1614               "DHT", msize, GNUNET_i2s (&peer->id));
1615 #endif
1616   peer->pending_count++;
1617   increment_stats ("# pending messages scheduled");
1618   GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1619                                      pending);
1620   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1621     peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1622 }
1623
1624
1625 /**
1626  * Task run to check for messages that need to be sent to a client.
1627  *
1628  * @param client a ClientList, containing the client and any messages to be sent to it
1629  */
1630 static void
1631 process_pending_messages (struct ClientList *client)
1632 {
1633   if ( (client->pending_head == NULL) ||
1634        (client->transmit_handle != NULL) )
1635     return;
1636   client->transmit_handle =
1637       GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1638                                            ntohs (client->pending_head->
1639                                                   msg->size),
1640                                            GNUNET_TIME_UNIT_FOREVER_REL,
1641                                            &send_generic_reply, client);
1642 }
1643
1644 /**
1645  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1646  * request.  A ClientList is passed as closure, take the head of the list
1647  * and copy it into buf, which has the result of sending the message to the
1648  * client.
1649  *
1650  * @param cls closure to this call
1651  * @param size maximum number of bytes available to send
1652  * @param buf where to copy the actual message to
1653  *
1654  * @return the number of bytes actually copied, 0 indicates failure
1655  */
1656 static size_t
1657 send_generic_reply (void *cls, size_t size, void *buf)
1658 {
1659   struct ClientList *client = cls;
1660   char *cbuf = buf;
1661   struct PendingMessage *reply;
1662   size_t off;
1663   size_t msize;
1664
1665   client->transmit_handle = NULL;
1666   if (buf == NULL)
1667   {
1668     /* client disconnected */
1669     return 0;
1670   }
1671   off = 0;
1672   while ((NULL != (reply = client->pending_head)) &&
1673          (size >= off + (msize = ntohs (reply->msg->size))))
1674   {
1675     GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1676                                  reply);
1677     memcpy (&cbuf[off], reply->msg, msize);
1678     GNUNET_free (reply);
1679     off += msize;
1680   }
1681   process_pending_messages (client);
1682 #if DEBUG_DHT
1683   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684               "Transmitted %u bytes of replies to client\n",
1685               (unsigned int) off);
1686 #endif
1687   return off;
1688 }
1689
1690
1691 /**
1692  * Add a PendingMessage to the clients list of messages to be sent
1693  *
1694  * @param client the active client to send the message to
1695  * @param pending_message the actual message to send
1696  */
1697 static void
1698 add_pending_message (struct ClientList *client,
1699                      struct PendingMessage *pending_message)
1700 {
1701   GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1702                                      client->pending_tail, pending_message);
1703   process_pending_messages (client);
1704 }
1705
1706
1707 /**
1708  * Called when a reply needs to be sent to a client, as
1709  * a result it found to a GET or FIND PEER request.
1710  *
1711  * @param client the client to send the reply to
1712  * @param message the encapsulated message to send
1713  * @param msg_ctx the context of the received message
1714  */
1715 static void
1716 send_reply_to_client (struct ClientList *client,
1717                       const struct GNUNET_MessageHeader *message,
1718                       struct DHT_MessageContext *msg_ctx)
1719 {
1720   struct GNUNET_DHT_RouteResultMessage *reply;
1721   struct PendingMessage *pending_message;
1722   uint16_t msize;
1723   size_t tsize;
1724   char *reply_offset;
1725
1726 #if DEBUG_PATH
1727   char *path_offset;
1728   unsigned int i;
1729 #endif
1730 #if DEBUG_DHT
1731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1732               my_short_id, "DHT");
1733 #endif
1734   msize = ntohs (message->size);
1735   tsize =
1736       sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1737       (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1738   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1739   {
1740     GNUNET_break_op (0);
1741     return;
1742   }
1743   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1744   pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1745   reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
1746   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1747   reply->header.size = htons (tsize);
1748   reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
1749   reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1750   memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1751   reply_offset = (char *) &reply[1];
1752   memcpy (&reply[1], message, msize);
1753   if (msg_ctx->path_history_len > 0)
1754   {
1755     reply_offset += msize;
1756     memcpy (reply_offset, msg_ctx->path_history,
1757             msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1758   }
1759 #if DEBUG_PATH
1760   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761               "Returning message with outgoing path length %d\n",
1762               msg_ctx->path_history_len);
1763   for (i = 0; i < msg_ctx->path_history_len; i++)
1764   {
1765     path_offset =
1766         &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1767     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
1768                 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1769   }
1770 #endif
1771   add_pending_message (client, pending_message);
1772 }
1773
1774 /**
1775  * Consider whether or not we would like to have this peer added to
1776  * our routing table.  Check whether bucket for this peer is full,
1777  * if so return negative; if not return positive.  Since peers are
1778  * only added on CORE level connect, this doesn't actually add the
1779  * peer to the routing table.
1780  *
1781  * @param peer the peer we are considering adding
1782  *
1783  * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1784  *         already full)
1785  */
1786 static int
1787 consider_peer (struct GNUNET_PeerIdentity *peer)
1788 {
1789   int bucket;
1790
1791   if ((GNUNET_YES ==
1792        GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
1793                                                &peer->hashPubKey)) ||
1794       (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
1795     return GNUNET_NO;           /* We already know this peer (are connected even!) */
1796   bucket = find_current_bucket (&peer->hashPubKey);
1797
1798   if ((k_buckets[bucket].peers_size < bucket_size) ||
1799       ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1800     return GNUNET_YES;
1801
1802   return GNUNET_NO;
1803 }
1804
1805
1806 /**
1807  * Task used to remove forwarding entries, either
1808  * after timeout, when full, or on shutdown.
1809  *
1810  * @param cls the entry to remove
1811  * @param tc context, reason, etc.
1812  */
1813 static void
1814 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1815 {
1816   struct DHTRouteSource *source_info = cls;
1817   struct DHTQueryRecord *record;
1818
1819   source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
1820   record = source_info->record;
1821   GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
1822
1823   if (record->head == NULL)     /* No more entries in DLL */
1824   {
1825     GNUNET_assert (GNUNET_YES ==
1826                    GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
1827                                                          &record->key, record));
1828     GNUNET_free (record);
1829   }
1830   if (source_info->find_peers_responded != NULL)
1831     GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
1832   GNUNET_free (source_info);
1833 }
1834
1835 /**
1836  * Main function that handles whether or not to route a result
1837  * message to other peers, or to send to our local client.
1838  *
1839  * @param msg the result message to be routed
1840  * @param msg_ctx context of the message we are routing
1841  *
1842  * @return the number of peers the message was routed to,
1843  *         GNUNET_SYSERR on failure
1844  */
1845 static int
1846 route_result_message (struct GNUNET_MessageHeader *msg,
1847                       struct DHT_MessageContext *msg_ctx)
1848 {
1849   struct GNUNET_PeerIdentity new_peer;
1850   struct DHTQueryRecord *record;
1851   struct DHTRouteSource *pos;
1852   struct PeerInfo *peer_info;
1853   const struct GNUNET_MessageHeader *hello_msg;
1854
1855 #if DEBUG_DHT > 1
1856   unsigned int i;
1857 #endif
1858
1859   increment_stats (STAT_RESULTS);
1860   /**
1861    * If a find peer result message is received and contains a valid
1862    * HELLO for another peer, offer it to the transport service.
1863    */
1864   if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1865   {
1866     if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
1867       GNUNET_break_op (0);
1868
1869     hello_msg = &msg[1];
1870     if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1871         (GNUNET_SYSERR ==
1872          GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
1873                               &new_peer)))
1874     {
1875       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1876                   "%s:%s Received non-HELLO message type in find peer result message!\n",
1877                   my_short_id, "DHT");
1878       GNUNET_break_op (0);
1879       return GNUNET_NO;
1880     }
1881     else                        /* We have a valid hello, and peer id stored in new_peer */
1882     {
1883       find_peer_context.count++;
1884       increment_stats (STAT_FIND_PEER_REPLY);
1885       if (GNUNET_YES == consider_peer (&new_peer))
1886       {
1887         increment_stats (STAT_HELLOS_PROVIDED);
1888         GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
1889         GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
1890       }
1891     }
1892   }
1893
1894   if (malicious_dropper == GNUNET_YES)
1895     record = NULL;
1896   else
1897     record =
1898         GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
1899
1900   if (record == NULL)           /* No record of this message! */
1901   {
1902 #if DEBUG_DHT
1903     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904                 "`%s:%s': Have no record of response key %s uid %llu\n",
1905                 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1906                 msg_ctx->unique_id);
1907 #endif
1908 #if DEBUG_DHT_ROUTING
1909     if ((debug_routes_extended) && (dhtlog_handle != NULL))
1910     {
1911       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1912                                    msg_ctx->hop_count, GNUNET_SYSERR,
1913                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
1914                                    NULL);
1915     }
1916 #endif
1917     if (msg_ctx->bloom != NULL)
1918     {
1919       GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
1920       msg_ctx->bloom = NULL;
1921     }
1922     return 0;
1923   }
1924
1925   pos = record->head;
1926   while (pos != NULL)
1927   {
1928 #if STRICT_FORWARDING
1929     if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)  /* If we have already forwarded this peer id, don't do it again! */
1930     {
1931       if (GNUNET_YES ==
1932           GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
1933                                              &new_peer.hashPubKey))
1934       {
1935         increment_stats ("# find peer responses NOT forwarded (bloom match)");
1936         pos = pos->next;
1937         continue;
1938       }
1939       else
1940         GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
1941                                           &new_peer.hashPubKey);
1942     }
1943 #endif
1944
1945     if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity)))  /* Local client (or DHT) initiated request! */
1946     {
1947 #if DEBUG_DHT
1948       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949                   "`%s:%s': Sending response key %s uid %llu to client\n",
1950                   my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1951                   msg_ctx->unique_id);
1952 #endif
1953 #if DEBUG_DHT_ROUTING
1954       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1955       {
1956         dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1957                                      msg_ctx->hop_count, GNUNET_YES,
1958                                      &my_identity, &msg_ctx->key, msg_ctx->peer,
1959                                      NULL);
1960       }
1961 #endif
1962       increment_stats (STAT_RESULTS_TO_CLIENT);
1963       if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1964         increment_stats (STAT_GET_REPLY);
1965 #if DEBUG_DHT > 1
1966       for (i = 0; i < msg_ctx->path_history_len; i++)
1967       {
1968         char *path_offset;
1969
1970         path_offset =
1971             &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1972         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1973                     "(before client) Key %s Found peer %d:%s\n",
1974                     GNUNET_h2s (&msg_ctx->key), i,
1975                     GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1976       }
1977 #endif
1978       send_reply_to_client (pos->client, msg, msg_ctx);
1979     }
1980     else                        /* Send to peer */
1981     {
1982       peer_info = find_peer_by_id (&pos->source);
1983       if (peer_info == NULL)    /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1984       {
1985         pos = pos->next;
1986         continue;
1987       }
1988
1989       if (msg_ctx->bloom == NULL)
1990         msg_ctx->bloom =
1991             GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
1992                                                DHT_BLOOM_K);
1993       GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
1994                                         &my_identity.hashPubKey);
1995       if ((GNUNET_NO ==
1996            GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
1997                                               &peer_info->id.hashPubKey)))
1998       {
1999 #if DEBUG_DHT
2000         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001                     "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2002                     my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2003                     msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2004 #endif
2005 #if DEBUG_DHT_ROUTING
2006         if ((debug_routes_extended) && (dhtlog_handle != NULL))
2007         {
2008           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2009                                        msg_ctx->hop_count, GNUNET_NO,
2010                                        &my_identity, &msg_ctx->key,
2011                                        msg_ctx->peer, &pos->source);
2012         }
2013 #endif
2014         forward_result_message (msg, peer_info, msg_ctx);
2015         /* Try removing forward entries after sending once, only allows ONE response per request */
2016         if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2017         {
2018           GNUNET_SCHEDULER_cancel (pos->delete_task);
2019           pos->delete_task =
2020               GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2021         }
2022       }
2023       else
2024       {
2025 #if DEBUG_DHT
2026         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027                     "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2028                     my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2029                     msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2030 #endif
2031       }
2032     }
2033     pos = pos->next;
2034   }
2035   if (msg_ctx->bloom != NULL)
2036   {
2037     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2038     msg_ctx->bloom = NULL;
2039   }
2040   return 0;
2041 }
2042
2043
2044 /**
2045  * Iterator for local get request results,
2046  *
2047  * @param cls closure for iterator, a DatacacheGetContext
2048  * @param exp when does this value expire?
2049  * @param key the key this data is stored under
2050  * @param size the size of the data identified by key
2051  * @param data the actual data
2052  * @param type the type of the data
2053  *
2054  * @return GNUNET_OK to continue iteration, anything else
2055  * to stop iteration.
2056  */
2057 static int
2058 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2059                         const GNUNET_HashCode * key, size_t size,
2060                         const char *data, enum GNUNET_BLOCK_Type type)
2061 {
2062   struct DHT_MessageContext *msg_ctx = cls;
2063   struct DHT_MessageContext *new_msg_ctx;
2064   struct GNUNET_DHT_GetResultMessage *get_result;
2065   enum GNUNET_BLOCK_EvaluationResult eval;
2066   const struct DHTPutEntry *put_entry;
2067   int get_size;
2068   char *path_offset;
2069
2070 #if DEBUG_PATH
2071   unsigned int i;
2072 #endif
2073
2074 #if DEBUG_DHT
2075   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2076               "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2077               "DHT", "GET");
2078 #endif
2079
2080   put_entry = (const struct DHTPutEntry *) data;
2081
2082   if (size !=
2083       sizeof (struct DHTPutEntry) + put_entry->data_size +
2084       (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2085   {
2086     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2087                 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2088                 put_entry->data_size, put_entry->path_length,
2089                 sizeof (struct DHTPutEntry) + put_entry->data_size +
2090                 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2091                 size);
2092     msg_ctx->do_forward = GNUNET_NO;
2093     return GNUNET_OK;
2094   }
2095
2096   eval =
2097       GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2098                              msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2099                              msg_ctx->xquery_size, &put_entry[1],
2100                              put_entry->data_size);
2101
2102   switch (eval)
2103   {
2104   case GNUNET_BLOCK_EVALUATION_OK_LAST:
2105     msg_ctx->do_forward = GNUNET_NO;
2106   case GNUNET_BLOCK_EVALUATION_OK_MORE:
2107     new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2108     memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2109     if (GNUNET_DHT_RO_RECORD_ROUTE ==
2110         (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2111     {
2112       new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2113       new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2114       /* Assign to previous msg_ctx path history, caller should free after our return */
2115       new_msg_ctx->path_history = msg_ctx->path_history;
2116 #if DEBUG_PATH
2117       for (i = 0; i < new_msg_ctx->path_history_len; i++)
2118       {
2119         path_offset =
2120             &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2121         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2122                     "(get_iterator) Key %s Found peer %d:%s\n",
2123                     GNUNET_h2s (&msg_ctx->key), i,
2124                     GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2125       }
2126 #endif
2127     }
2128
2129     get_size =
2130         sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2131         (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2132     get_result = GNUNET_malloc (get_size);
2133     get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2134     get_result->header.size = htons (get_size);
2135     get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2136     get_result->type = htons (type);
2137     get_result->put_path_length = htons (put_entry->path_length);
2138     path_offset = (char *) &put_entry[1];
2139     path_offset += put_entry->data_size;
2140 #if DEBUG_PATH
2141     for (i = 0; i < put_entry->path_length; i++)
2142     {
2143       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144                   "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2145                   GNUNET_h2s (&msg_ctx->key), i,
2146                   GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2147                               &path_offset[i *
2148                                            sizeof (struct
2149                                                    GNUNET_PeerIdentity)]));
2150     }
2151 #endif
2152     /* Copy the actual data and the path_history to the end of the get result */
2153     memcpy (&get_result[1], &put_entry[1],
2154             put_entry->data_size +
2155             (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2156     new_msg_ctx->peer = &my_identity;
2157     new_msg_ctx->bloom =
2158         GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2159     new_msg_ctx->hop_count = 0;
2160     new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2;   /* Make result routing a higher priority */
2161     new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2162     increment_stats (STAT_GET_RESPONSE_START);
2163     route_result_message (&get_result->header, new_msg_ctx);
2164     GNUNET_free (new_msg_ctx);
2165     GNUNET_free (get_result);
2166     break;
2167   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2168 #if DEBUG_DHT
2169     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2170                 my_short_id, "DHT");
2171 #endif
2172     break;
2173   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2174 #if DEBUG_DHT
2175     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2176                 my_short_id, "DHT");
2177 #endif
2178     break;
2179   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2180 #if DEBUG_DHT
2181     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182                 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2183 #endif
2184     GNUNET_break (0);
2185     break;
2186   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2187     GNUNET_break_op (0);
2188     msg_ctx->do_forward = GNUNET_NO;
2189     break;
2190   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2191 #if DEBUG_DHT
2192     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2193                 "`%s:%s': Unsupported block type (%u) in response!\n",
2194                 my_short_id, "DHT", type);
2195 #endif
2196     /* msg_ctx->do_forward = GNUNET_NO;  // not sure... */
2197     break;
2198   }
2199   return GNUNET_OK;
2200 }
2201
2202
2203 /**
2204  * Main function that handles whether or not to route a message to other
2205  * peers.
2206  *
2207  * @param msg the message to be routed
2208  * @param msg_ctx the context containing all pertinent information about the message
2209  */
2210 static void
2211 route_message (const struct GNUNET_MessageHeader *msg,
2212                struct DHT_MessageContext *msg_ctx);
2213
2214
2215 /**
2216  * Server handler for all dht get requests, look for data,
2217  * if found, send response either to clients or other peers.
2218  *
2219  * @param msg the actual get message
2220  * @param msg_ctx struct containing pertinent information about the get request
2221  *
2222  * @return number of items found for GET request
2223  */
2224 static unsigned int
2225 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2226                 struct DHT_MessageContext *msg_ctx)
2227 {
2228   const struct GNUNET_DHT_GetMessage *get_msg;
2229   uint16_t msize;
2230   uint16_t bf_size;
2231   unsigned int results;
2232   const char *end;
2233   enum GNUNET_BLOCK_Type type;
2234
2235   msize = ntohs (msg->size);
2236   if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2237   {
2238     GNUNET_break (0);
2239     return 0;
2240   }
2241   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2242   bf_size = ntohs (get_msg->bf_size);
2243   msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2244   msg_ctx->reply_bf_mutator = get_msg->bf_mutator;
2245   if (msize !=
2246       sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2247   {
2248     GNUNET_break (0);
2249     return 0;
2250   }
2251   end = (const char *) &get_msg[1];
2252   if (msg_ctx->xquery_size == 0)
2253   {
2254     msg_ctx->xquery = NULL;
2255   }
2256   else
2257   {
2258     msg_ctx->xquery = (const void *) end;
2259     end += msg_ctx->xquery_size;
2260   }
2261   if (bf_size == 0)
2262   {
2263     msg_ctx->reply_bf = NULL;
2264   }
2265   else
2266   {
2267     msg_ctx->reply_bf =
2268         GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2269                                            GNUNET_DHT_GET_BLOOMFILTER_K);
2270   }
2271   type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2272 #if DEBUG_DHT
2273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2275               my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2276               msg_ctx->unique_id);
2277 #endif
2278   increment_stats (STAT_GETS);
2279   results = 0;
2280 #if HAVE_MALICIOUS
2281   if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2282   {
2283     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2284     return results;
2285   }
2286 #endif
2287   msg_ctx->do_forward = GNUNET_YES;
2288   if (datacache != NULL)
2289     results =
2290         GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2291                               &datacache_get_iterator, msg_ctx);
2292 #if DEBUG_DHT
2293   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294               "`%s:%s': Found %d results for `%s' request uid %llu\n",
2295               my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2296 #endif
2297   if (results >= 1)
2298   {
2299 #if DEBUG_DHT_ROUTING
2300     if ((debug_routes) && (dhtlog_handle != NULL))
2301     {
2302       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2303                                    msg_ctx->hop_count, GNUNET_YES, &my_identity,
2304                                    &msg_ctx->key);
2305     }
2306
2307     if ((debug_routes_extended) && (dhtlog_handle != NULL))
2308     {
2309       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2310                                    msg_ctx->hop_count, GNUNET_YES, &my_identity,
2311                                    &msg_ctx->key, msg_ctx->peer, NULL);
2312     }
2313 #endif
2314   }
2315   else
2316   {
2317     /* check query valid */
2318     if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2319         GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2320                                &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2321                                msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2322     {
2323       GNUNET_break_op (0);
2324       msg_ctx->do_forward = GNUNET_NO;
2325     }
2326   }
2327
2328   if (msg_ctx->hop_count == 0)  /* Locally initiated request */
2329   {
2330 #if DEBUG_DHT_ROUTING
2331     if ((debug_routes) && (dhtlog_handle != NULL))
2332     {
2333       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2334                                    msg_ctx->hop_count, GNUNET_NO, &my_identity,
2335                                    &msg_ctx->key);
2336     }
2337 #endif
2338   }
2339   if (msg_ctx->do_forward == GNUNET_YES)
2340     route_message (msg, msg_ctx);
2341   GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2342   return results;
2343 }
2344
2345
2346 static void
2347 remove_recent_find_peer (void *cls,
2348                          const struct GNUNET_SCHEDULER_TaskContext *tc)
2349 {
2350   GNUNET_HashCode *key = cls;
2351
2352   GNUNET_assert (GNUNET_YES ==
2353                  GNUNET_CONTAINER_multihashmap_remove
2354                  (recent_find_peer_requests, key, NULL));
2355   GNUNET_free (key);
2356 }
2357
2358
2359 /**
2360  * Server handler for initiating local dht find peer requests
2361  *
2362  * @param find_msg the actual find peer message
2363  * @param msg_ctx struct containing pertinent information about the request
2364  *
2365  */
2366 static void
2367 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2368                       struct DHT_MessageContext *msg_ctx)
2369 {
2370   struct GNUNET_MessageHeader *find_peer_result;
2371   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2372   struct DHT_MessageContext *new_msg_ctx;
2373   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2374   size_t hello_size;
2375   size_t tsize;
2376   GNUNET_HashCode *recent_hash;
2377   struct GNUNET_MessageHeader *other_hello;
2378   size_t other_hello_size;
2379   struct GNUNET_PeerIdentity peer_id;
2380
2381   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2382   GNUNET_break_op (ntohs (find_msg->size) >=
2383                    (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2384   if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2385     return;
2386   other_hello = NULL;
2387   other_hello_size = 0;
2388   if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2389   {
2390     other_hello_size =
2391         ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2392     other_hello = GNUNET_malloc (other_hello_size);
2393     memcpy (other_hello, &find_peer_message[1], other_hello_size);
2394     if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2395         || (GNUNET_OK !=
2396             GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2397                                  &peer_id)))
2398     {
2399       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2400                   "Received invalid HELLO message in find peer request!\n");
2401       GNUNET_free (other_hello);
2402       return;
2403     }
2404 #if FIND_PEER_WITH_HELLO
2405     if (GNUNET_YES == consider_peer (&peer_id))
2406     {
2407       increment_stats (STAT_HELLOS_PROVIDED);
2408       GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2409       GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2410       route_message (find_msg, msg_ctx);
2411       GNUNET_free (other_hello);
2412       return;
2413     }
2414     else                        /* We don't want this peer! */
2415     {
2416       route_message (find_msg, msg_ctx);
2417       GNUNET_free (other_hello);
2418       return;
2419     }
2420 #endif
2421   }
2422
2423 #if DEBUG_DHT
2424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2426               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2427               ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2428 #endif
2429   if (my_hello == NULL)
2430   {
2431 #if DEBUG_DHT
2432     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2433                 "`%s': Our HELLO is null, can't return.\n", "DHT");
2434 #endif
2435     GNUNET_free_non_null (other_hello);
2436     route_message (find_msg, msg_ctx);
2437     return;
2438   }
2439
2440   incoming_bloom =
2441       GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2442                                          DHT_BLOOM_SIZE, DHT_BLOOM_K);
2443   if (GNUNET_YES ==
2444       GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2445                                          &my_identity.hashPubKey))
2446   {
2447     increment_stats (STAT_BLOOM_FIND_PEER);
2448     GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2449     GNUNET_free_non_null (other_hello);
2450     route_message (find_msg, msg_ctx);
2451     return;                     /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2452   }
2453   GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2454
2455 #if RESTRICT_FIND_PEER
2456
2457   /**
2458    * Ignore any find peer requests from a peer we have seen very recently.
2459    */
2460   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent_find_peer_requests, &msg_ctx->key))  /* We have recently responded to a find peer request for this peer! */
2461   {
2462     increment_stats ("# dht find peer requests ignored (recently seen!)");
2463     GNUNET_free_non_null (other_hello);
2464     return;
2465   }
2466
2467   /**
2468    * Use this check to only allow the peer to respond to find peer requests if
2469    * it would be beneficial to have the requesting peer in this peers routing
2470    * table.  Can be used to thwart peers flooding the network with find peer
2471    * requests that we don't care about.  However, if a new peer is joining
2472    * the network and has no other peers this is a problem (assume all buckets
2473    * full, no one will respond!).
2474    */
2475   memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2476   if (GNUNET_NO == consider_peer (&peer_id))
2477   {
2478     increment_stats ("# dht find peer requests ignored (do not need!)");
2479     GNUNET_free_non_null (other_hello);
2480     route_message (find_msg, msg_ctx);
2481     return;
2482   }
2483 #endif
2484
2485   recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2486   memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2487   if (GNUNET_SYSERR !=
2488       GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2489                                          &msg_ctx->key, NULL,
2490                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2491   {
2492 #if DEBUG_DHT
2493     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2494                 "Adding recent remove task for key `%s`!\n",
2495                 GNUNET_h2s (&msg_ctx->key));
2496 #endif
2497     /* Only add a task if there wasn't one for this key already! */
2498     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2499                                   (GNUNET_TIME_UNIT_SECONDS, 30),
2500                                   &remove_recent_find_peer, recent_hash);
2501   }
2502   else
2503   {
2504     GNUNET_free (recent_hash);
2505 #if DEBUG_DHT
2506     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507                 "Received duplicate find peer request too soon!\n");
2508 #endif
2509   }
2510
2511   /* Simplistic find_peer functionality, always return our hello */
2512   hello_size = ntohs (my_hello->size);
2513   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2514
2515   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2516   {
2517     GNUNET_break_op (0);
2518     GNUNET_free_non_null (other_hello);
2519     return;
2520   }
2521
2522   find_peer_result = GNUNET_malloc (tsize);
2523   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2524   find_peer_result->size = htons (tsize);
2525   memcpy (&find_peer_result[1], my_hello, hello_size);
2526 #if DEBUG_DHT
2527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2528               "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2529               hello_size);
2530 #endif
2531
2532   new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2533   memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2534   new_msg_ctx->peer = &my_identity;
2535   new_msg_ctx->bloom =
2536       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2537   new_msg_ctx->hop_count = 0;
2538   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2;     /* Make find peer requests a higher priority */
2539   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2540   increment_stats (STAT_FIND_PEER_ANSWER);
2541   if (GNUNET_DHT_RO_RECORD_ROUTE ==
2542       (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2543   {
2544     new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2545     new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2546     /* Assign to previous msg_ctx path history, caller should free after our return */
2547     new_msg_ctx->path_history = msg_ctx->path_history;
2548   }
2549   route_result_message (find_peer_result, new_msg_ctx);
2550   GNUNET_free (new_msg_ctx);
2551 #if DEBUG_DHT_ROUTING
2552   if ((debug_routes) && (dhtlog_handle != NULL))
2553   {
2554     dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2555                                  msg_ctx->hop_count, GNUNET_YES, &my_identity,
2556                                  &msg_ctx->key);
2557   }
2558 #endif
2559   GNUNET_free_non_null (other_hello);
2560   GNUNET_free (find_peer_result);
2561   route_message (find_msg, msg_ctx);
2562 }
2563
2564
2565 /**
2566  * Server handler for initiating local dht put requests
2567  *
2568  * @param msg the actual put message
2569  * @param msg_ctx struct containing pertinent information about the request
2570  */
2571 static void
2572 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2573                 struct DHT_MessageContext *msg_ctx)
2574 {
2575   const struct GNUNET_DHT_PutMessage *put_msg;
2576   struct DHTPutEntry *put_entry;
2577   unsigned int put_size;
2578   char *path_offset;
2579   enum GNUNET_BLOCK_Type put_type;
2580   size_t data_size;
2581   int ret;
2582   GNUNET_HashCode key;
2583   struct DHTQueryRecord *record;
2584
2585   GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2586
2587   put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2588   put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2589 #if HAVE_MALICIOUS
2590   if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2591   {
2592 #if DEBUG_DHT_ROUTING
2593     if ((debug_routes_extended) && (dhtlog_handle != NULL))
2594     {
2595           /** Log routes that die due to high load! */
2596       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2597                                    msg_ctx->hop_count, GNUNET_SYSERR,
2598                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
2599                                    NULL);
2600     }
2601 #endif
2602     return;
2603   }
2604 #endif
2605   data_size =
2606       ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2607   ret =
2608       GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2609                             &key);
2610   if (GNUNET_NO == ret)
2611   {
2612 #if DEBUG_DHT_ROUTING
2613     if ((debug_routes_extended) && (dhtlog_handle != NULL))
2614     {
2615       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2616                                    msg_ctx->hop_count, GNUNET_SYSERR,
2617                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
2618                                    NULL);
2619     }
2620 #endif
2621     /* invalid reply */
2622     GNUNET_break_op (0);
2623     return;
2624   }
2625   if ((GNUNET_YES == ret) &&
2626       (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2627   {
2628 #if DEBUG_DHT_ROUTING
2629     if ((debug_routes_extended) && (dhtlog_handle != NULL))
2630     {
2631       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2632                                    msg_ctx->hop_count, GNUNET_SYSERR,
2633                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
2634                                    NULL);
2635     }
2636 #endif
2637     /* invalid wrapper: key mismatch! */
2638     GNUNET_break_op (0);
2639     return;
2640   }
2641   /* ret == GNUNET_SYSERR means that there is no known relationship between
2642    * data and the key, so we cannot check it */
2643 #if DEBUG_DHT
2644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2646               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2647               msg_ctx->unique_id);
2648 #endif
2649 #if DEBUG_DHT_ROUTING
2650   if (msg_ctx->hop_count == 0)  /* Locally initiated request */
2651   {
2652     if ((debug_routes) && (dhtlog_handle != NULL))
2653     {
2654       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2655                                    msg_ctx->hop_count, GNUNET_NO, &my_identity,
2656                                    &msg_ctx->key);
2657     }
2658   }
2659 #endif
2660
2661 //   GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 1\n");
2662   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2663   if (NULL != record)
2664   {
2665     struct DHTRouteSource *pos;
2666     struct GNUNET_DHT_GetMessage *gmsg;
2667     size_t gsize;
2668
2669 //     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 2\n");
2670     pos = record->head;
2671     while (pos != NULL)
2672     {
2673       /* TODO: do only for local started requests? or also for remote peers? */
2674       /* TODO: include this in statistics? under what? */
2675       if (NULL == pos->client)
2676         continue;
2677
2678       gsize = data_size + sizeof(struct GNUNET_DHT_GetMessage);
2679       gmsg = GNUNET_malloc(gsize);
2680       gmsg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2681       gmsg->header.size = htons(gsize);
2682       gmsg->type = put_msg->type;
2683       memcpy(&gmsg[1], &put_msg[1], data_size);
2684
2685       /* TODO: duplicate and reverse order of path_history? */
2686       send_reply_to_client (pos->client, &gmsg->header, msg_ctx);
2687       GNUNET_free(gmsg);
2688     }
2689   }
2690 //   GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT END\n");
2691
2692   if (msg_ctx->closest != GNUNET_YES)
2693   {
2694     route_message (msg, msg_ctx);
2695     return;
2696   }
2697
2698 #if DEBUG_DHT
2699   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2701               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2702               msg_ctx->unique_id);
2703 #endif
2704
2705 #if DEBUG_DHT_ROUTING
2706   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2707   {
2708     dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2709                                  msg_ctx->hop_count, GNUNET_YES, &my_identity,
2710                                  &msg_ctx->key, msg_ctx->peer, NULL);
2711   }
2712
2713   if ((debug_routes) && (dhtlog_handle != NULL))
2714   {
2715     dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2716                                  msg_ctx->hop_count, GNUNET_YES, &my_identity,
2717                                  &msg_ctx->key);
2718   }
2719 #endif
2720
2721   increment_stats (STAT_PUTS_INSERTED);
2722   if (datacache != NULL)
2723   {
2724     /* Put size is actual data size plus struct overhead plus path length (if any) */
2725     put_size =
2726         data_size + sizeof (struct DHTPutEntry) +
2727         (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2728     put_entry = GNUNET_malloc (put_size);
2729     put_entry->data_size = data_size;
2730     put_entry->path_length = msg_ctx->path_history_len;
2731     /* Copy data to end of put entry */
2732     memcpy (&put_entry[1], &put_msg[1], data_size);
2733     if (msg_ctx->path_history_len > 0)
2734     {
2735       /* Copy path after data */
2736       path_offset = (char *) &put_entry[1];
2737       path_offset += data_size;
2738       memcpy (path_offset, msg_ctx->path_history,
2739               msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2740     }
2741
2742     ret =
2743         GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2744                               (const char *) put_entry, put_type,
2745                               GNUNET_TIME_absolute_ntoh (put_msg->expiration));
2746     GNUNET_free (put_entry);
2747   }
2748   else
2749     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750                 "`%s:%s': %s request received, but have no datacache!\n",
2751                 my_short_id, "DHT", "PUT");
2752
2753   if (stop_on_closest == GNUNET_NO)
2754     route_message (msg, msg_ctx);
2755 }
2756
2757
2758 /**
2759  * To how many peers should we (on average)
2760  * forward the request to obtain the desired
2761  * target_replication count (on average).
2762  *
2763  * returns: target_replication / (est. hops) + (target_replication * hop_count)
2764  * where est. hops is typically 2 * the routing table depth
2765  *
2766  * @param hop_count number of hops the message has traversed
2767  * @param target_replication the number of total paths desired
2768  *
2769  * @return Some number of peers to forward the message to
2770  */
2771 static unsigned int
2772 get_forward_count (unsigned int hop_count, size_t target_replication)
2773 {
2774   uint32_t random_value;
2775   unsigned int forward_count;
2776   float target_value;
2777
2778   /**
2779    * If we are behaving in strict kademlia mode, send multiple initial requests,
2780    * but then only send to 1 or 0 peers based strictly on the number of hops.
2781    */
2782   if (strict_kademlia == GNUNET_YES)
2783   {
2784     if (hop_count == 0)
2785       return kademlia_replication;
2786      if (hop_count < log_of_network_size_estimate * 2.0)
2787       return 1;
2788     return 0;
2789   }
2790
2791   if (hop_count > log_of_network_size_estimate * 2.0)
2792   {
2793     if (GNUNET_YES == paper_forwarding) 
2794     {
2795       /* Once we have reached our ideal number of hops, don't stop forwarding! */
2796       return 1;
2797     }
2798 #if DEBUG_DHT
2799     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,                
2800                 "Hop count too high (est %f, lowest %d), NOT Forwarding request\n",
2801                 log_of_network_size_estimate * 2.0, lowest_bucket);
2802 #endif
2803     return 0;
2804   }
2805
2806   if (GNUNET_YES == paper_forwarding)
2807   {
2808     /* FIXME: re-run replication trials with this formula */
2809     target_value =
2810         1 + (target_replication - 1.0) / (log_of_network_size_estimate +
2811                                           ((float) (target_replication - 1.0) *
2812                                            hop_count));
2813     /* Set forward count to floor of target_value */
2814     forward_count = (unsigned int) target_value;
2815     /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2816     target_value = target_value - forward_count;
2817     random_value =
2818         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2819
2820     if (random_value < (target_value * UINT32_MAX))
2821       forward_count += 1;
2822   }
2823   else
2824   {
2825     random_value = 0;
2826     forward_count = 1;
2827     target_value =
2828         target_replication / (log_of_network_size_estimate +
2829                               ((float) target_replication * hop_count));
2830     if (target_value > 1)
2831     {
2832       /* Set forward count to floor of target_value */
2833       forward_count = (unsigned int) target_value;
2834       /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2835       target_value = target_value - forward_count;
2836     }
2837     else
2838       random_value =
2839           GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2840
2841     if (random_value < (target_value * UINT32_MAX))
2842       forward_count += 1;
2843   }
2844
2845   return forward_count;
2846 }
2847
2848
2849 /**
2850  * Check whether my identity is closer than any known peers.
2851  * If a non-null bloomfilter is given, check if this is the closest
2852  * peer that hasn't already been routed to.
2853  *
2854  * @param target hash code to check closeness to
2855  * @param bloom bloomfilter, exclude these entries from the decision
2856  * @return GNUNET_YES if node location is closest,
2857  *         GNUNET_NO otherwise.
2858  */
2859 static int
2860 am_closest_peer (const GNUNET_HashCode * target,
2861                  struct GNUNET_CONTAINER_BloomFilter *bloom)
2862 {
2863   int bits;
2864   int other_bits;
2865   int bucket_num;
2866   int count;
2867   struct PeerInfo *pos;
2868   unsigned int my_distance;
2869
2870   if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
2871     return GNUNET_YES;
2872
2873   bucket_num = find_current_bucket (target);
2874
2875   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
2876   my_distance = distance (&my_identity.hashPubKey, target);
2877   pos = k_buckets[bucket_num].head;
2878   count = 0;
2879   while ((pos != NULL) && (count < bucket_size))
2880   {
2881     if ((bloom != NULL) &&
2882         (GNUNET_YES ==
2883          GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2884     {
2885       pos = pos->next;
2886       continue;                 /* Skip already checked entries */
2887     }
2888
2889     other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
2890     if (other_bits > bits)
2891       return GNUNET_NO;
2892     else if (other_bits == bits)        /* We match the same number of bits */
2893     {
2894       if (strict_kademlia != GNUNET_YES)        /* Return that we at as close as any other peer */
2895         return GNUNET_YES;
2896       if (distance (&pos->id.hashPubKey, target) < my_distance)    /* Check all known peers, only return if we are the true closest */
2897         return GNUNET_NO;
2898     }
2899     pos = pos->next;
2900   }
2901
2902   /* No peers closer, we are the closest! */
2903   return GNUNET_YES;
2904 }
2905
2906
2907 /**
2908  * Select a peer from the routing table that would be a good routing
2909  * destination for sending a message for "target".  The resulting peer
2910  * must not be in the set of blocked peers.<p>
2911  *
2912  * Note that we should not ALWAYS select the closest peer to the
2913  * target, peers further away from the target should be chosen with
2914  * exponentially declining probability.
2915  *
2916  * @param target the key we are selecting a peer to route to
2917  * @param bloom a bloomfilter containing entries this request has seen already
2918  * @param hops how many hops has this message traversed thus far
2919  *
2920  * @return Peer to route to, or NULL on error
2921  */
2922 static struct PeerInfo *
2923 select_peer (const GNUNET_HashCode * target,
2924              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2925 {
2926   unsigned int bc;
2927   unsigned int count;
2928   unsigned int selected;
2929   struct PeerInfo *pos;
2930   unsigned int distance;
2931   unsigned int largest_distance;
2932   struct PeerInfo *chosen;
2933
2934   /** If we are doing kademlia routing (saves some cycles) */
2935   if ( (strict_kademlia == GNUNET_YES) ||
2936        (hops >= log_of_network_size_estimate) )
2937   {
2938     /* greedy selection (closest peer that is not in bloomfilter) */
2939     largest_distance = 0;
2940     chosen = NULL;
2941     for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2942     {
2943       pos = k_buckets[bc].head;
2944       count = 0;
2945       while ((pos != NULL) && (count < bucket_size))
2946       {
2947         /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2948         if (GNUNET_NO ==
2949             GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2950         {
2951           distance = inverse_distance (target, &pos->id.hashPubKey);
2952           if (distance > largest_distance)
2953           {
2954             chosen = pos;
2955             largest_distance = distance;
2956           }
2957         }
2958         count++;
2959         pos = pos->next;
2960       }
2961     }
2962     if ((largest_distance > 0) && (chosen != NULL))
2963     {
2964       GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
2965       return chosen;
2966     }
2967     return NULL; /* no peer available or we are the closest */
2968   }
2969
2970
2971   /* select "random" peer */
2972   /* count number of peers that are available and not filtered */
2973   count = 0;
2974   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2975   {
2976     pos = k_buckets[bc].head;
2977     while ((pos != NULL) && (count < bucket_size))
2978     {
2979       if (GNUNET_YES ==
2980           GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2981       {
2982         pos = pos->next;
2983         continue;               /* Ignore bloomfiltered peers */
2984       }
2985       count++;
2986       pos = pos->next;
2987     }
2988   }
2989   if (count == 0)      /* No peers to select from! */
2990   {
2991     increment_stats ("# failed to select peer");
2992     return NULL;
2993   }
2994   /* Now actually choose a peer */
2995   selected =
2996       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
2997   count = 0;
2998   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2999   {
3000     pos = k_buckets[bc].head;
3001     while ((pos != NULL) && (count < bucket_size))
3002     {
3003       if (GNUNET_YES ==
3004           GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3005       {
3006         pos = pos->next;
3007         continue;               /* Ignore bloomfiltered peers */
3008       }
3009       if (0 == selected--)
3010         return pos;     
3011       pos = pos->next;
3012     }
3013   }
3014   GNUNET_break (0);
3015   return NULL;
3016 }
3017
3018
3019 /**
3020  * Task used to remove recent entries, either
3021  * after timeout, when full, or on shutdown.
3022  *
3023  * @param cls the entry to remove
3024  * @param tc context, reason, etc.
3025  */
3026 static void
3027 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3028 {
3029   struct RecentRequest *req = cls;
3030   static GNUNET_HashCode hash;
3031
3032   GNUNET_assert (req != NULL);
3033   hash_from_uid (req->uid, &hash);
3034   GNUNET_assert (GNUNET_YES ==
3035                  GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3036                                                        req));
3037   GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3038   GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3039   GNUNET_free (req);
3040
3041   /*
3042    * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3043    * {
3044    * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3045    * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3046    * }
3047    */
3048 }
3049
3050 /**
3051  * Remember this routing request so that if a reply is
3052  * received we can either forward it to the correct peer
3053  * or return the result locally.
3054  *
3055  * @param msg_ctx Context of the route request
3056  *
3057  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3058  */
3059 static int
3060 cache_response (struct DHT_MessageContext *msg_ctx)
3061 {
3062   struct DHTQueryRecord *record;
3063   struct DHTRouteSource *source_info;
3064   struct DHTRouteSource *pos;
3065   struct GNUNET_TIME_Absolute now;
3066   unsigned int current_size;
3067
3068   current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3069
3070 #if DELETE_WHEN_FULL
3071   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3072   {
3073     source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3074     GNUNET_assert (source_info != NULL);
3075     record = source_info->record;
3076     GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3077     if (record->head == NULL)   /* No more entries in DLL */
3078     {
3079       GNUNET_assert (GNUNET_YES ==
3080                      GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3081                                                            &record->key,
3082                                                            record));
3083       GNUNET_free (record);
3084     }
3085     if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3086     {
3087       GNUNET_SCHEDULER_cancel (source_info->delete_task);
3088       source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3089     }
3090     if (source_info->find_peers_responded != NULL)
3091       GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3092     GNUNET_free (source_info);
3093     current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3094   }
3095 #endif
3096   /** Non-local request and have too many outstanding forwards, discard! */
3097   if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3098     return GNUNET_NO;
3099
3100   now = GNUNET_TIME_absolute_get ();
3101   record =
3102       GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3103   if (record != NULL)           /* Already know this request! */
3104   {
3105     pos = record->head;
3106     while (pos != NULL)
3107     {
3108       if ( (NULL != msg_ctx->peer) &&
3109            (0 ==
3110             memcmp (msg_ctx->peer, &pos->source,
3111                     sizeof (struct GNUNET_PeerIdentity))) )
3112         break;                  /* Already have this peer in reply list! */
3113       pos = pos->next;
3114     }
3115     if ((pos != NULL) && (pos->client == msg_ctx->client))      /* Seen this already */
3116     {
3117       GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3118                                          now.abs_value);
3119       return GNUNET_NO;
3120     }
3121   }
3122   else
3123   {
3124     record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3125     GNUNET_assert (GNUNET_OK ==
3126                    GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3127                                                       &msg_ctx->key, record,
3128                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3129     memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3130   }
3131
3132   source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3133   source_info->record = record;
3134   source_info->delete_task =
3135       GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3136                                     source_info);
3137   source_info->find_peers_responded =
3138       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3139   memcpy (&source_info->source, msg_ctx->peer,
3140           sizeof (struct GNUNET_PeerIdentity));
3141   GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3142                                      source_info);
3143   if (msg_ctx->client != NULL)  /* For local request, set timeout so high it effectively never gets pushed out */
3144   {
3145     source_info->client = msg_ctx->client;
3146     now = GNUNET_TIME_absolute_get_forever ();
3147   }
3148   source_info->hnode =
3149       GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3150                                     now.abs_value);
3151 #if DEBUG_DHT > 1
3152   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3153               "`%s:%s': Created new forward source info for %s uid %llu\n",
3154               my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3155               msg_ctx->unique_id);
3156 #endif
3157   return GNUNET_YES;
3158 }
3159
3160
3161 /**
3162  * Main function that handles whether or not to route a message to other
3163  * peers.
3164  *
3165  * @param msg the message to be routed
3166  * @param msg_ctx the context containing all pertinent information about the message
3167  */
3168 static void
3169 route_message (const struct GNUNET_MessageHeader *msg,
3170                struct DHT_MessageContext *msg_ctx)
3171 {
3172   int i;
3173   struct PeerInfo *selected;
3174
3175 #if DEBUG_DHT_ROUTING > 1
3176   struct PeerInfo *nearest;
3177 #endif
3178   unsigned int target_forward_count;
3179   unsigned int forward_count;
3180   struct RecentRequest *recent_req;
3181   GNUNET_HashCode unique_hash;
3182   char *stat_forward_count;
3183   char *temp_stat_str;
3184
3185 #if DEBUG_DHT_ROUTING
3186   int ret;
3187 #endif
3188
3189   if (malicious_dropper == GNUNET_YES)
3190   {
3191 #if DEBUG_DHT_ROUTING
3192     if ((debug_routes_extended) && (dhtlog_handle != NULL))
3193     {
3194       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3195                                    msg_ctx->hop_count, GNUNET_SYSERR,
3196                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
3197                                    NULL);
3198     }
3199 #endif
3200     if (msg_ctx->bloom != NULL)
3201     {
3202       GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3203       msg_ctx->bloom = NULL;
3204     }
3205     return;
3206   }
3207
3208   increment_stats (STAT_ROUTES);
3209   target_forward_count =
3210       get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3211   GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3212                    target_forward_count);
3213   increment_stats (stat_forward_count);
3214   GNUNET_free (stat_forward_count);
3215   if (msg_ctx->bloom == NULL)
3216     msg_ctx->bloom =
3217         GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3218
3219   if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3220       (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3221     target_forward_count = 0;
3222
3223   /**
3224    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3225    * any closer peers (which is being checked for below).  Since we are doing recursive
3226    * routing we have no choice but to stop forwarding in this case.  This means that at
3227    * any given step the request may NOT be forwarded to alpha peers (because routes will
3228    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3229    * have fulfilled the Kademlia requirements for routing table fullness this will never
3230    * ever ever be a problem.
3231    *
3232    * However, is this fair?
3233    *
3234    * Since we use these requests to build our routing tables (and we build them in the
3235    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3236    * routing tables still get constructed.
3237    */
3238   if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3239       (msg_ctx->hop_count > 0) &&
3240       (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3241     target_forward_count = 0;
3242
3243
3244   GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3245   hash_from_uid (msg_ctx->unique_id, &unique_hash);
3246   if (GNUNET_YES ==
3247       GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3248   {
3249     recent_req =
3250         GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3251     GNUNET_assert (recent_req != NULL);
3252     if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3253       increment_stats (STAT_DUPLICATE_UID);
3254     else
3255     {
3256       increment_stats (STAT_RECENT_SEEN);
3257       GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3258                                         DHT_BLOOM_SIZE);
3259     }
3260   }
3261   else
3262   {
3263     recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3264     recent_req->uid = msg_ctx->unique_id;
3265     memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3266     recent_req->remove_task =
3267         GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3268                                       recent_req);
3269     recent_req->heap_node =
3270         GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3271                                       GNUNET_TIME_absolute_get ().abs_value);
3272     recent_req->bloom =
3273         GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3274     GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3275                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3276   }
3277
3278   if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3279   {
3280     recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3281     GNUNET_assert (recent_req != NULL);
3282     GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3283     recent_req->remove_task = 
3284         GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3285   }
3286
3287   forward_count = 0;
3288   for (i = 0; i < target_forward_count; i++)
3289   {
3290     selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3291
3292     if (selected != NULL)
3293     {
3294       forward_count++;
3295       if (GNUNET_CRYPTO_hash_matching_bits
3296           (&selected->id.hashPubKey,
3297            &msg_ctx->key) >=
3298           GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3299                                             &msg_ctx->key))
3300         GNUNET_asprintf (&temp_stat_str,
3301                          "# requests routed to close(r) peer hop %u",
3302                          msg_ctx->hop_count);
3303       else
3304         GNUNET_asprintf (&temp_stat_str,
3305                          "# requests routed to less close peer hop %u",
3306                          msg_ctx->hop_count);
3307       if (temp_stat_str != NULL)
3308       {
3309         increment_stats (temp_stat_str);
3310         GNUNET_free (temp_stat_str);
3311       }
3312       GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3313                                         &selected->id.hashPubKey);
3314 #if DEBUG_DHT_ROUTING > 1
3315       nearest = find_closest_peer (&msg_ctx->key);
3316       nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3317       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318                   "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3319                   my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3320                   msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
3321                   GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
3322                                                     msg_ctx->key),
3323                   distance (&nearest->id.hashPubKey, msg_ctx->key));
3324       GNUNET_free (nearest_buf);
3325 #endif
3326 #if DEBUG_DHT_ROUTING
3327       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3328       {
3329         dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3330                                      msg_ctx->hop_count, GNUNET_NO,
3331                                      &my_identity, &msg_ctx->key, msg_ctx->peer,
3332                                      &selected->id);
3333       }
3334 #endif
3335       forward_message (msg, selected, msg_ctx);
3336     }
3337   }
3338
3339   if (msg_ctx->bloom != NULL)
3340   {
3341     GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3342                                       DHT_BLOOM_SIZE);
3343     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3344     msg_ctx->bloom = NULL;
3345   }
3346
3347 #if DEBUG_DHT_ROUTING
3348   if (forward_count == 0)
3349     ret = GNUNET_SYSERR;
3350   else
3351     ret = GNUNET_NO;
3352
3353   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3354   {
3355     dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3356                                  msg_ctx->hop_count, ret, &my_identity,
3357                                  &msg_ctx->key, msg_ctx->peer, NULL);
3358   }
3359 #endif
3360 }
3361
3362
3363 /**
3364  * Main function that handles whether or not to route a message to other
3365  * peers.
3366  *
3367  * @param msg the message to be routed
3368  * @param msg_ctx the context containing all pertinent information about the message
3369  */
3370 static void
3371 demultiplex_message (const struct GNUNET_MessageHeader *msg,
3372                      struct DHT_MessageContext *msg_ctx)
3373 {
3374   /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
3375   msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
3376
3377   switch (ntohs (msg->type))
3378   {
3379   case GNUNET_MESSAGE_TYPE_DHT_GET:    /* Add to hashmap of requests seen, search for data (always) */
3380     cache_response (msg_ctx);
3381     handle_dht_get (msg, msg_ctx);
3382     break;
3383   case GNUNET_MESSAGE_TYPE_DHT_PUT:    /* Check if closest, if so insert data. */
3384     increment_stats (STAT_PUTS);
3385     handle_dht_put (msg, msg_ctx);
3386     break;
3387   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:      /* Check if closest and not started by us, check options, add to requests seen */
3388     increment_stats (STAT_FIND_PEER);
3389     if (((msg_ctx->hop_count > 0) &&
3390          (0 !=
3391           memcmp (msg_ctx->peer, &my_identity,
3392                   sizeof (struct GNUNET_PeerIdentity)))) ||
3393         (msg_ctx->client != NULL))
3394     {
3395       cache_response (msg_ctx);
3396       if ((msg_ctx->closest == GNUNET_YES) ||
3397           (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3398         handle_dht_find_peer (msg, msg_ctx);
3399     }
3400     else
3401       route_message (msg, msg_ctx);
3402 #if DEBUG_DHT_ROUTING
3403     if (msg_ctx->hop_count == 0)        /* Locally initiated request */
3404     {
3405       if ((debug_routes) && (dhtlog_handle != NULL))
3406       {
3407         dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
3408         dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3409                                      msg_ctx->hop_count, GNUNET_NO,
3410                                      &my_identity, &msg_ctx->key);
3411       }
3412     }
3413 #endif
3414     break;
3415   default:
3416     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3417                 "`%s': Message type (%d) not handled, forwarding anyway!\n",
3418                 "DHT", ntohs (msg->type));
3419     route_message (msg, msg_ctx);
3420   }
3421 }
3422
3423
3424 /**
3425  * Iterator over hash map entries.
3426  *
3427  * @param cls client to search for in source routes
3428  * @param key current key code (ignored)
3429  * @param value value in the hash map, a DHTQueryRecord
3430  * @return GNUNET_YES if we should continue to
3431  *         iterate,
3432  *         GNUNET_NO if not.
3433  */
3434 static int
3435 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
3436 {
3437   struct ClientList *client = cls;
3438   struct DHTQueryRecord *record = value;
3439   struct DHTRouteSource *pos;
3440
3441   pos = record->head;
3442   while (pos != NULL)
3443   {
3444     if (pos->client == client)
3445       break;
3446     pos = pos->next;
3447   }
3448   if (pos != NULL)
3449   {
3450     GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
3451     GNUNET_CONTAINER_heap_remove_node (pos->hnode);
3452     if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3453     {
3454       GNUNET_SCHEDULER_cancel (pos->delete_task);
3455       pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
3456     }
3457     if (pos->find_peers_responded != NULL)
3458       GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
3459     GNUNET_free (pos);
3460   }
3461   if (record->head == NULL)     /* No more entries in DLL */
3462   {
3463     GNUNET_assert (GNUNET_YES ==
3464                    GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3465                                                          &record->key, record));
3466     GNUNET_free (record);
3467   }
3468   return GNUNET_YES;
3469 }
3470
3471 /**
3472  * Functions with this signature are called whenever a client
3473  * is disconnected on the network level.
3474  *
3475  * @param cls closure (NULL for dht)
3476  * @param client identification of the client; NULL
3477  *        for the last call when the server is destroyed
3478  */
3479 static void
3480 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3481 {
3482   struct ClientList *pos = client_list;
3483   struct ClientList *prev;
3484   struct ClientList *found;
3485   struct PendingMessage *reply;
3486
3487   prev = NULL;
3488   found = NULL;
3489   while (pos != NULL)
3490   {
3491     if (pos->client_handle == client)
3492     {
3493       if (prev != NULL)
3494         prev->next = pos->next;
3495       else
3496         client_list = pos->next;
3497       found = pos;
3498       break;
3499     }
3500     prev = pos;
3501     pos = pos->next;
3502   }
3503
3504   if (found != NULL)
3505   {
3506     if (found->transmit_handle != NULL)
3507       GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
3508
3509     while (NULL != (reply = found->pending_head))
3510     {
3511       GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
3512                                    reply);
3513       GNUNET_free (reply);
3514     }
3515     GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
3516                                            &find_client_records, found);
3517     GNUNET_free (found);
3518   }
3519 }
3520
3521 /**
3522  * Find a client if it exists, add it otherwise.
3523  *
3524  * @param client the server handle to the client
3525  *
3526  * @return the client if found, a new client otherwise
3527  */
3528 static struct ClientList *
3529 find_active_client (struct GNUNET_SERVER_Client *client)
3530 {
3531   struct ClientList *pos = client_list;
3532   struct ClientList *ret;
3533
3534   while (pos != NULL)
3535   {
3536     if (pos->client_handle == client)
3537       return pos;
3538     pos = pos->next;
3539   }
3540
3541   ret = GNUNET_malloc (sizeof (struct ClientList));
3542   ret->client_handle = client;
3543   ret->next = client_list;
3544   client_list = ret;
3545
3546   return ret;
3547 }
3548
3549 #if HAVE_MALICIOUS
3550 /**
3551  * Task to send a malicious put message across the network.
3552  *
3553  * @param cls closure for this task
3554  * @param tc the context under which the task is running
3555  */
3556 static void
3557 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3558 {
3559   static struct GNUNET_DHT_PutMessage put_message;
3560   static struct DHT_MessageContext msg_ctx;
3561   static GNUNET_HashCode key;
3562   uint32_t random_key;
3563
3564   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3565     return;
3566   put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
3567   put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3568   put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3569   put_message.expiration =
3570       GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
3571   memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3572   random_key =
3573       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3574   GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3575   memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3576   msg_ctx.unique_id =
3577       GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3578                      (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3579   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3580   msg_ctx.msg_options = ntohl (0);
3581   msg_ctx.network_size = log_of_network_size_estimate;
3582   msg_ctx.peer = &my_identity;
3583   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3584   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3585 #if DEBUG_DHT_ROUTING
3586   if (dhtlog_handle != NULL)
3587     dhtlog_handle->insert_dhtkey (NULL, &key);
3588 #endif
3589   increment_stats (STAT_PUT_START);
3590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3591               "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
3592               "DHT", GNUNET_h2s (&key));
3593   demultiplex_message (&put_message.header, &msg_ctx);
3594   GNUNET_SCHEDULER_add_delayed (malicious_put_frequency, 
3595                                 &malicious_put_task, NULL);
3596 }
3597
3598
3599 /**
3600  * Task to send a malicious put message across the network.
3601  *
3602  * @param cls closure for this task
3603  * @param tc the context under which the task is running
3604  */
3605 static void
3606 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3607 {
3608   static struct GNUNET_DHT_GetMessage get_message;
3609   struct DHT_MessageContext msg_ctx;
3610   static GNUNET_HashCode key;
3611   uint32_t random_key;
3612
3613   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3614     return;
3615
3616   get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
3617   get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
3618   get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3619   memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3620   random_key =
3621       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3622   GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3623   memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3624   msg_ctx.unique_id =
3625       GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3626                      (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3627   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3628   msg_ctx.msg_options = ntohl (0);
3629   msg_ctx.network_size = log_of_network_size_estimate;
3630   msg_ctx.peer = &my_identity;
3631   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3632   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3633 #if DEBUG_DHT_ROUTING
3634   if (dhtlog_handle != NULL)
3635     dhtlog_handle->insert_dhtkey (NULL, &key);
3636 #endif
3637   increment_stats (STAT_GET_START);
3638   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639               "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
3640               "DHT", GNUNET_h2s (&key));
3641   demultiplex_message (&get_message.header, &msg_ctx);
3642   GNUNET_SCHEDULER_add_delayed (malicious_get_frequency,
3643                                 &malicious_get_task, NULL);
3644 }
3645 #endif
3646
3647
3648 /**
3649  * Iterator over hash map entries.
3650  *
3651  * @param cls closure
3652  * @param key current key code
3653  * @param value value in the hash map
3654  * @return GNUNET_YES if we should continue to
3655  *         iterate,
3656  *         GNUNET_NO if not.
3657  */
3658 static int
3659 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
3660 {
3661   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3662
3663   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3664   return GNUNET_YES;
3665 }
3666
3667 /**
3668  * Task to send a find peer message for our own peer identifier
3669  * so that we can find the closest peers in the network to ourselves
3670  * and attempt to connect to them.
3671  *
3672  * @param cls closure for this task
3673  * @param tc the context under which the task is running
3674  */
3675 static void
3676 send_find_peer_message (void *cls,
3677                         const struct GNUNET_SCHEDULER_TaskContext *tc)
3678 {
3679   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3680   struct DHT_MessageContext msg_ctx;
3681   struct GNUNET_TIME_Relative next_send_time;
3682   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3683
3684   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3685     return;
3686
3687   if ((newly_found_peers > bucket_size) && (GNUNET_YES == do_find_peer))        /* If we are finding peers already, no need to send out our request right now! */
3688   {
3689     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3690                 "Have %d newly found peers since last find peer message sent!\n",
3691                 newly_found_peers);
3692     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3693                                   &send_find_peer_message, NULL);
3694     newly_found_peers = 0;
3695     return;
3696   }
3697
3698   increment_stats (STAT_FIND_PEER_START);
3699 #if FIND_PEER_WITH_HELLO
3700   find_peer_msg =
3701       GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3702                      GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
3703                                         my_hello));
3704   find_peer_msg->header.size =
3705       htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3706              GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3707   memcpy (&find_peer_msg[1], my_hello,
3708           GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3709 #else
3710   find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
3711   find_peer_msg->header.size =
3712       htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
3713 #endif
3714   find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3715   temp_bloom =
3716       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3717   GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
3718                                          temp_bloom);
3719   GNUNET_assert (GNUNET_OK ==
3720                  GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
3721                                                             find_peer_msg->
3722                                                             bloomfilter,
3723                                                             DHT_BLOOM_SIZE));
3724   GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
3725   memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3726   memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
3727   msg_ctx.unique_id =
3728       GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3729                      (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
3730   msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3731   msg_ctx.msg_options = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
3732   msg_ctx.network_size = log_of_network_size_estimate;
3733   msg_ctx.peer = &my_identity;
3734   msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3735   msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3736
3737   demultiplex_message (&find_peer_msg->header, &msg_ctx);
3738   GNUNET_free (find_peer_msg);
3739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3740               "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
3741               "DHT", "FIND PEER");
3742   if (newly_found_peers < bucket_size)
3743   {
3744     next_send_time.rel_value =
3745         (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
3746         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3747                                   DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
3748   }
3749   else
3750   {
3751     next_send_time.rel_value =
3752         DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
3753         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3754                                   DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
3755                                   DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
3756   }
3757
3758   GNUNET_assert (next_send_time.rel_value != 0);
3759   find_peer_context.count = 0;
3760   newly_found_peers = 0;
3761   find_peer_context.start = GNUNET_TIME_absolute_get ();
3762   if (GNUNET_YES == do_find_peer)
3763   {
3764     GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
3765                                   NULL);
3766   }
3767 }
3768
3769 /**
3770  * Handler for any generic DHT messages, calls the appropriate handler
3771  * depending on message type, sends confirmation if responses aren't otherwise
3772  * expected.
3773  *
3774  * @param cls closure for the service
3775  * @param client the client we received this message from
3776  * @param message the actual message received
3777  */
3778 static void
3779 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3780                                 const struct GNUNET_MessageHeader *message)
3781 {
3782   const struct GNUNET_DHT_RouteMessage *dht_msg =
3783       (const struct GNUNET_DHT_RouteMessage *) message;
3784   const struct GNUNET_MessageHeader *enc_msg;
3785   struct DHT_MessageContext msg_ctx;
3786
3787   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3788 #if DEBUG_DHT
3789   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3790               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3791               my_short_id, "DHT", "GENERIC", ntohs (message->type),
3792               GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
3793 #endif
3794 #if DEBUG_DHT_ROUTING
3795   if (dhtlog_handle != NULL)
3796     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3797 #endif
3798
3799   memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3800   msg_ctx.client = find_active_client (client);
3801   memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
3802   msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3803   msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
3804   msg_ctx.msg_options = ntohl (dht_msg->options);
3805   if (GNUNET_DHT_RO_RECORD_ROUTE ==
3806       (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
3807   {
3808     msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
3809     memcpy (msg_ctx.path_history, &my_identity,
3810             sizeof (struct GNUNET_PeerIdentity));
3811     msg_ctx.path_history_len = 1;
3812   }
3813   msg_ctx.network_size = log_of_network_size_estimate;
3814   msg_ctx.peer = &my_identity; /* FIXME bart NULL? Fix doxygen? */
3815   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4;  /* Make local routing a higher priority */
3816   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3817
3818   if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3819     increment_stats (STAT_GET_START);
3820   else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3821     increment_stats (STAT_PUT_START);
3822   else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3823     increment_stats (STAT_FIND_PEER_START);
3824
3825   if (GNUNET_YES == malicious_dropper)
3826   {
3827     if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3828     {
3829 #if DEBUG_DHT_ROUTING
3830       if ((debug_routes) && (dhtlog_handle != NULL))
3831       {
3832         dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
3833                                      msg_ctx.hop_count, GNUNET_NO, &my_identity,
3834                                      &msg_ctx.key);
3835       }
3836 #endif
3837     }
3838     else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3839     {
3840 #if DEBUG_DHT_ROUTING
3841       if ((debug_routes) && (dhtlog_handle != NULL))
3842       {
3843         dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
3844                                      msg_ctx.hop_count, GNUNET_NO, &my_identity,
3845                                      &msg_ctx.key);
3846       }
3847 #endif
3848     }
3849     GNUNET_SERVER_receive_done (client, GNUNET_OK);
3850     GNUNET_free_non_null (msg_ctx.path_history);
3851     return;
3852   }
3853
3854   demultiplex_message (enc_msg, &msg_ctx);
3855   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3856
3857 }
3858
3859 /**
3860  * Handler for any locally received DHT control messages,
3861  * sets malicious flags mostly for now.
3862  *
3863  * @param cls closure for the service
3864  * @param client the client we received this message from
3865  * @param message the actual message received
3866  *
3867  */
3868 static void
3869 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3870                             const struct GNUNET_MessageHeader *message)
3871 {
3872   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3873       (const struct GNUNET_DHT_ControlMessage *) message;
3874
3875 #if DEBUG_DHT
3876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877               "`%s:%s': Received `%s' request from client, command %d\n",
3878               my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
3879 #endif
3880
3881   switch (ntohs (dht_control_msg->command))
3882   {
3883   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3884     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3885                 "Sending self seeking find peer request!\n");
3886     GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
3887     break;
3888 #if HAVE_MALICIOUS
3889   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3890     if (ntohs (dht_control_msg->variable) > 0)
3891       malicious_get_frequency.rel_value = ntohs (dht_control_msg->variable);
3892     if (malicious_get_frequency.rel_value == 0)
3893       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3894     if (malicious_getter != GNUNET_YES)
3895       GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
3896     malicious_getter = GNUNET_YES;
3897     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3898                 "%s:%s Initiating malicious GET behavior, frequency %llu\n",
3899                 my_short_id, "DHT", malicious_get_frequency.rel_value);
3900     break;
3901   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3902     if (ntohs (dht_control_msg->variable) > 0)
3903       malicious_put_frequency.rel_value = ntohs (dht_control_msg->variable);
3904     if (malicious_put_frequency.rel_value == 0)
3905       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3906     if (malicious_putter != GNUNET_YES)
3907       GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
3908     malicious_putter = GNUNET_YES;
3909     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3910                 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
3911                 my_short_id, "DHT", malicious_put_frequency);
3912     break;
3913   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3914 #if DEBUG_DHT_ROUTING
3915     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3916       dhtlog_handle->set_malicious (&my_identity);
3917 #endif
3918     malicious_dropper = GNUNET_YES;
3919     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920                 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
3921                 "DHT");
3922     break;
3923 #endif
3924   default:
3925     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3926                 "%s:%s Unknown control command type `%d'!\n", my_short_id,
3927                 "DHT", ntohs (dht_control_msg->command));
3928     break;
3929   }
3930
3931   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3932 }
3933
3934 /**
3935  * Handler for any generic DHT stop messages, calls the appropriate handler
3936  * depending on message type (if processed locally)
3937  *
3938  * @param cls closure for the service
3939  * @param client the client we received this message from
3940  * @param message the actual message received
3941  *
3942  */
3943 static void
3944 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
3945                              const struct GNUNET_MessageHeader *message)
3946 {
3947
3948   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3949       (const struct GNUNET_DHT_StopMessage *) message;
3950   struct DHTQueryRecord *record;
3951   struct DHTRouteSource *pos;
3952
3953 #if DEBUG_DHT
3954   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3955               "`%s:%s': Received `%s' request from client, uid %llu\n",
3956               my_short_id, "DHT", "GENERIC STOP",
3957               GNUNET_ntohll (dht_stop_msg->unique_id));
3958 #endif
3959   record =
3960       GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
3961                                          &dht_stop_msg->key);
3962   if (record != NULL)
3963   {
3964     pos = record->head;
3965
3966     while (pos != NULL)
3967     {
3968       /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
3969       if ((pos->client != NULL) && (pos->client->client_handle == client))
3970       {
3971         if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3972           GNUNET_SCHEDULER_cancel (pos->delete_task);
3973         pos->delete_task =
3974             GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
3975       }
3976       pos = pos->next;
3977     }
3978   }
3979
3980   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3981 }
3982
3983
3984 /**
3985  * Core handler for p2p route requests.
3986  *
3987  * @param cls closure
3988  * @param message message
3989  * @param peer peer identity this notification is about
3990  * @param atsi performance data
3991  * @return GNUNET_OK to keep the connection open,
3992  *         GNUNET_SYSERR to close it (signal serious error)
3993  */
3994 static int
3995 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
3996                               const struct GNUNET_MessageHeader *message,
3997                               const struct GNUNET_TRANSPORT_ATS_Information
3998                               *atsi)
3999 {
4000 #if DEBUG_DHT
4001   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4002               "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4003               "DHT", GNUNET_i2s (peer));
4004 #endif
4005   struct GNUNET_DHT_P2PRouteMessage *incoming =
4006       (struct GNUNET_DHT_P2PRouteMessage *) message;
4007   struct GNUNET_MessageHeader *enc_msg =
4008       (struct GNUNET_MessageHeader *) &incoming[1];
4009   struct DHT_MessageContext *msg_ctx;
4010   char *route_path;
4011   int path_size;
4012
4013   if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4014   {
4015     GNUNET_break_op (0);
4016     return GNUNET_YES;
4017   }
4018
4019   if (malicious_dropper == GNUNET_YES)
4020   {
4021 #if DEBUG_DHT_ROUTING
4022     if ((debug_routes_extended) && (dhtlog_handle != NULL))
4023     {
4024           /** Log routes that die due to high load! */
4025       dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4026                                    DHTLOG_ROUTE, ntohl (incoming->hop_count),
4027                                    GNUNET_SYSERR, &my_identity, &incoming->key,
4028                                    peer, NULL);
4029     }
4030 #endif
4031     return GNUNET_YES;
4032   }
4033
4034   if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4035   {
4036     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4037                 "Sending of previous replies took too long, backing off!\n");
4038     increment_stats ("# route requests dropped due to high load");
4039     decrease_max_send_delay (get_max_send_delay ());
4040 #if DEBUG_DHT_ROUTING
4041     if ((debug_routes_extended) && (dhtlog_handle != NULL))
4042     {
4043         /** Log routes that die due to high load! */
4044       dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4045                                    DHTLOG_ROUTE, ntohl (incoming->hop_count),
4046                                    GNUNET_SYSERR, &my_identity, &incoming->key,
4047                                    peer, NULL);
4048     }
4049 #endif
4050     return GNUNET_YES;
4051   }
4052   msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4053   msg_ctx->bloom =
4054       GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4055                                          DHT_BLOOM_K);
4056   GNUNET_assert (msg_ctx->bloom != NULL);
4057   msg_ctx->hop_count = ntohl (incoming->hop_count);
4058   memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4059   msg_ctx->replication = ntohl (incoming->desired_replication_level);
4060   msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4061   msg_ctx->msg_options = ntohl (incoming->options);
4062   if (GNUNET_DHT_RO_RECORD_ROUTE ==
4063       (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4064   {
4065     path_size =
4066         ntohl (incoming->outgoing_path_length) *
4067         sizeof (struct GNUNET_PeerIdentity);
4068     if (ntohs (message->size) !=
4069           (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4070           ntohs (enc_msg->size) + path_size))
4071     {
4072       GNUNET_break_op(0);
4073       return GNUNET_YES;
4074     }
4075     route_path = (char *) &incoming[1];
4076     route_path = route_path + ntohs (enc_msg->size);
4077     msg_ctx->path_history =
4078         GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4079     memcpy (msg_ctx->path_history, route_path, path_size);
4080     memcpy (&msg_ctx->path_history[path_size], &my_identity,
4081             sizeof (struct GNUNET_PeerIdentity));
4082     msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4083   }
4084   msg_ctx->network_size = ntohl (incoming->network_size);
4085   msg_ctx->peer = peer;
4086   msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4087   msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4088   demultiplex_message (enc_msg, msg_ctx);
4089   if (msg_ctx->bloom != NULL)
4090   {
4091     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4092     msg_ctx->bloom = NULL;
4093   }
4094   GNUNET_free (msg_ctx);
4095   return GNUNET_YES;
4096 }
4097
4098
4099 /**
4100  * Core handler for p2p route results.
4101  *
4102  * @param cls closure
4103  * @param message message
4104  * @param peer peer identity this notification is about
4105  * @param atsi performance data
4106  *
4107  */
4108 static int
4109 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4110                              const struct GNUNET_MessageHeader *message,
4111                              const struct GNUNET_TRANSPORT_ATS_Information
4112                              *atsi)
4113 {
4114 #if DEBUG_DHT
4115   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4116               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4117               GNUNET_i2s (peer));
4118 #endif
4119   const struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4120       (const struct GNUNET_DHT_P2PRouteResultMessage *) message;
4121   struct GNUNET_MessageHeader *enc_msg =
4122       (struct GNUNET_MessageHeader *) &incoming[1];
4123   struct DHT_MessageContext msg_ctx;
4124
4125 #if DEBUG_PATH
4126   char *path_offset;
4127   unsigned int i;
4128 #endif
4129   if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4130   {
4131     GNUNET_break_op (0);
4132     return GNUNET_YES;
4133   }
4134
4135   if (malicious_dropper == GNUNET_YES)
4136   {
4137 #if DEBUG_DHT_ROUTING
4138     if ((debug_routes_extended) && (dhtlog_handle != NULL))
4139     {
4140           /** Log routes that die due to high load! */
4141       dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4142                                    DHTLOG_ROUTE, ntohl (incoming->hop_count),
4143                                    GNUNET_SYSERR, &my_identity, &incoming->key,
4144                                    peer, NULL);
4145     }
4146 #endif
4147     return GNUNET_YES;
4148   }
4149
4150   memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4151   memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4152   msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4153   msg_ctx.msg_options = ntohl (incoming->options);
4154   msg_ctx.hop_count = ntohl (incoming->hop_count);
4155   msg_ctx.peer = peer;
4156   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2;  /* Make result routing a higher priority */
4157   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4158   if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4159        (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4160       (ntohl (incoming->outgoing_path_length) > 0))
4161   {
4162     if (ntohs (message->size) -
4163         sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4164         ntohs (enc_msg->size) !=
4165         ntohl (incoming->outgoing_path_length) *
4166         sizeof (struct GNUNET_PeerIdentity))
4167     {
4168 #if DEBUG_DHT
4169       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4170                   "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4171                   ntohs (message->size), ntohs (enc_msg->size),
4172                   ntohs (message->size) -
4173                   sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4174                   ntohs (enc_msg->size),
4175                   ntohl (incoming->outgoing_path_length) *
4176                   sizeof (struct GNUNET_PeerIdentity));
4177 #endif
4178       GNUNET_break_op (0);
4179       return GNUNET_NO;
4180     }
4181     msg_ctx.path_history = (char *) &incoming[1];
4182     msg_ctx.path_history += ntohs (enc_msg->size);
4183     msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4184 #if DEBUG_PATH
4185     for (i = 0; i < msg_ctx.path_history_len; i++)
4186     {
4187       path_offset =
4188           &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4189       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4190                   "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4191                   GNUNET_h2s (&msg_ctx.key), i,
4192                   GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
4193     }
4194 #endif
4195   }
4196   msg_ctx.bloom =
4197       GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4198                                          DHT_BLOOM_K);
4199   GNUNET_assert (msg_ctx.bloom != NULL);
4200   route_result_message (enc_msg, &msg_ctx);
4201   return GNUNET_YES;
4202 }
4203
4204
4205 /**
4206  * Receive the HELLO from transport service,
4207  * free current and replace if necessary.
4208  *
4209  * @param cls NULL
4210  * @param message HELLO message of peer
4211  */
4212 static void
4213 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4214 {
4215 #if DEBUG_DHT
4216   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4217               "Received our `%s' from transport service\n", "HELLO");
4218 #endif
4219
4220   GNUNET_assert (message != NULL);
4221   GNUNET_free_non_null (my_hello);
4222   my_hello = GNUNET_malloc (ntohs (message->size));
4223   memcpy (my_hello, message, ntohs (message->size));
4224 }
4225
4226
4227 /**
4228  * Task run during shutdown.
4229  *
4230  * @param cls unused
4231  * @param tc unused
4232  */
4233 static void
4234 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4235 {
4236   int bucket_count;
4237   struct PeerInfo *pos;
4238
4239   if (NULL != ghh)
4240   {
4241     GNUNET_TRANSPORT_get_hello_cancel (ghh);
4242     ghh = NULL;
4243   }
4244   if (transport_handle != NULL)
4245   {
4246     GNUNET_free_non_null (my_hello);
4247     GNUNET_TRANSPORT_disconnect (transport_handle);
4248     transport_handle = NULL;
4249   }
4250   if (NULL != nse)
4251   {
4252     GNUNET_NSE_disconnect (nse);
4253     nse = NULL;
4254   }
4255   if (coreAPI != NULL)
4256   {
4257 #if DEBUG_DHT
4258     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
4259                 my_short_id, "DHT");
4260 #endif
4261     GNUNET_CORE_disconnect (coreAPI);
4262     coreAPI = NULL;
4263   }
4264   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4265   {
4266     while (k_buckets[bucket_count].head != NULL)
4267     {
4268       pos = k_buckets[bucket_count].head;
4269 #if DEBUG_DHT
4270       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4271                   "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
4272                   "DHT", GNUNET_i2s (&pos->id), bucket_count);
4273 #endif
4274       delete_peer (pos, bucket_count);
4275     }
4276   }
4277   if (datacache != NULL)
4278   {
4279 #if DEBUG_DHT
4280     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
4281                 my_short_id, "DHT");
4282 #endif
4283     GNUNET_DATACACHE_destroy (datacache);
4284     datacache = NULL;
4285   }
4286   if (stats != NULL)
4287   {
4288     GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4289     stats = NULL;
4290   }
4291   if (dhtlog_handle != NULL)
4292   {
4293     GNUNET_DHTLOG_disconnect (dhtlog_handle);
4294     dhtlog_handle = NULL;
4295   }
4296   if (block_context != NULL)
4297   {
4298     GNUNET_BLOCK_context_destroy (block_context);
4299     block_context = NULL;
4300   }
4301   GNUNET_free_non_null (my_short_id);
4302   my_short_id = NULL;
4303 }
4304
4305
4306 /**
4307  * To be called on core init/fail.
4308  *
4309  * @param cls service closure
4310  * @param server handle to the server for this service
4311  * @param identity the public identity of this peer
4312  * @param publicKey the public key of this peer
4313  */
4314 void
4315 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4316            const struct GNUNET_PeerIdentity *identity,
4317            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4318 {
4319
4320   if (server == NULL)
4321   {
4322 #if DEBUG_DHT
4323     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
4324                 "dht", GNUNET_i2s (identity));
4325 #endif
4326     GNUNET_SCHEDULER_cancel (cleanup_task);
4327     GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4328     return;
4329   }
4330 #if DEBUG_DHT
4331   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332               "%s: Core connection initialized, I am peer: %s\n", "dht",
4333               GNUNET_i2s (identity));
4334 #endif
4335
4336   /* Copy our identity so we can use it */
4337   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4338   if (my_short_id != NULL)
4339     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4340                 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
4341                 "DHT SERVICE");
4342   my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
4343   if (dhtlog_handle != NULL)
4344     dhtlog_handle->insert_node (NULL, &my_identity);
4345 }
4346
4347
4348 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4349   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
4350    0},
4351   {&handle_dht_local_route_stop, NULL,
4352    GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4353   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4354   {NULL, NULL, 0, 0}
4355 };
4356
4357
4358 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4359   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4360   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4361   {NULL, 0, 0}
4362 };
4363
4364
4365 /**
4366  * Method called whenever a peer connects.
4367  *
4368  * @param cls closure
4369  * @param peer peer identity this notification is about
4370  * @param atsi performance data
4371  */
4372 static void
4373 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4374                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4375 {
4376   struct PeerInfo *ret;
4377   struct DHTPutEntry *put_entry;
4378   int peer_bucket;
4379
4380   /* Check for connect to self message */
4381   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4382     return;
4383
4384 #if DEBUG_DHT
4385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4386               "%s:%s Receives core connect message for peer %s distance %d!\n",
4387               my_short_id, "dht", GNUNET_i2s (peer), distance);
4388 #endif
4389
4390   if (GNUNET_YES ==
4391       GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4392                                               &peer->hashPubKey))
4393   {
4394 #if DEBUG_DHT
4395     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4396                 "%s:%s Received %s message for peer %s, but already have peer in RT!",
4397                 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
4398 #endif
4399     GNUNET_break (0);
4400     return;
4401   }
4402
4403   if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
4404   {
4405     put_entry =
4406         GNUNET_malloc (sizeof (struct DHTPutEntry) +
4407                        sizeof (struct GNUNET_PeerIdentity));
4408     put_entry->path_length = 0;
4409     put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
4410     memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
4411     GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
4412                           sizeof (struct DHTPutEntry) +
4413                           sizeof (struct GNUNET_PeerIdentity),
4414                           (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
4415                           GNUNET_TIME_absolute_get_forever ());
4416     GNUNET_free (put_entry);
4417   }
4418   else if (datacache == NULL)
4419     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4420                 "DHT has no connection to datacache!\n");
4421
4422   peer_bucket = find_current_bucket (&peer->hashPubKey);
4423   GNUNET_assert (peer_bucket >= lowest_bucket);
4424   GNUNET_assert (peer_bucket < MAX_BUCKETS);
4425   ret = GNUNET_malloc (sizeof (struct PeerInfo));
4426 #if 0
4427   ret->latency = latency;
4428   ret->distance = distance;
4429 #endif
4430   ret->id = *peer;
4431   GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
4432                                      k_buckets[peer_bucket].tail,
4433                                      k_buckets[peer_bucket].tail, ret);
4434   k_buckets[peer_bucket].peers_size++;
4435 #if DO_UPDATE_PREFERENCE
4436   if ((GNUNET_CRYPTO_hash_matching_bits
4437        (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
4438       (k_buckets[peer_bucket].peers_size <= bucket_size))
4439     ret->preference_task =
4440         GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
4441 #endif
4442   if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
4443     enable_next_bucket ();
4444   newly_found_peers++;
4445   GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
4446                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4447   increment_stats (STAT_PEERS_KNOWN);
4448
4449 #if DEBUG_DHT
4450   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4451               "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
4452               ret == NULL ? "NOT ADDED" : "PEER ADDED");
4453 #endif
4454 }
4455
4456
4457 /**
4458  * Method called whenever a peer disconnects.
4459  *
4460  * @param cls closure
4461  * @param peer peer identity this notification is about
4462  */
4463 static void
4464 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4465 {
4466   struct PeerInfo *to_remove;
4467   int current_bucket;
4468
4469   /* Check for disconnect from self message */
4470   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4471     return;
4472 #if DEBUG_DHT
4473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4474               "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
4475               my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
4476 #endif
4477
4478   if (GNUNET_YES !=
4479       GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4480                                               &peer->hashPubKey))
4481   {
4482     GNUNET_break (0);
4483 #if DEBUG_DHT
4484     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4485                 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
4486                 my_short_id, "DHT", GNUNET_i2s (peer));
4487 #endif
4488     return;
4489   }
4490   increment_stats (STAT_DISCONNECTS);
4491   GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
4492                  (all_known_peers, &peer->hashPubKey));
4493   to_remove =
4494       GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
4495   GNUNET_assert (to_remove != NULL);
4496   if (NULL != to_remove->info_ctx)
4497   {
4498     GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
4499     to_remove->info_ctx = NULL;
4500   }
4501   GNUNET_assert (0 ==
4502                  memcmp (peer, &to_remove->id,
4503                          sizeof (struct GNUNET_PeerIdentity)));
4504   current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
4505   delete_peer (to_remove, current_bucket);
4506 }
4507
4508
4509 /**
4510  * Process dht requests.
4511  *
4512  * @param cls closure
4513  * @param server the initialized server
4514  * @param c configuration to use
4515  */
4516 static void
4517 run (void *cls, struct GNUNET_SERVER_Handle *server,
4518      const struct GNUNET_CONFIGURATION_Handle *c)
4519 {
4520   struct GNUNET_TIME_Relative next_send_time;
4521   unsigned long long temp_config_num;
4522
4523   cfg = c;
4524   datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4525   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4526   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4527   nse = GNUNET_NSE_connect (cfg,
4528                             &update_network_size_estimate, NULL);
4529   coreAPI = GNUNET_CORE_connect (cfg,   /* Main configuration */
4530                                  DEFAULT_CORE_QUEUE_SIZE,       /* queue size */
4531                                  NULL,  /* Closure passed to DHT functions */
4532                                  &core_init,    /* Call core_init once connected */
4533                                  &handle_core_connect,  /* Handle connects */
4534                                  &handle_core_disconnect,       /* remove peers on disconnects */
4535                                  NULL,  /* Do we care about "status" updates? */
4536                                  NULL,  /* Don't want notified about all incoming messages */
4537                                  GNUNET_NO,     /* For header only inbound notification */
4538                                  NULL,  /* Don't want notified about all outbound messages */
4539                                  GNUNET_NO,     /* For header only outbound notification */
4540                                  core_handlers);        /* Register these handlers */
4541
4542   if (coreAPI == NULL)
4543     return;
4544   transport_handle =
4545       GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
4546   if (transport_handle != NULL)
4547     ghh = GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4548   else
4549     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4550                 "Failed to connect to transport service!\n");
4551   block_context = GNUNET_BLOCK_context_create (cfg);
4552   lowest_bucket = MAX_BUCKETS - 1;
4553   forward_list.hashmap =
4554       GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
4555   forward_list.minHeap =
4556       GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4557   all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4558   GNUNET_assert (all_known_peers != NULL);
4559   if (GNUNET_YES ==
4560       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4561                                             "mysql_logging"))
4562   {
4563     debug_routes = GNUNET_YES;
4564   }
4565
4566   if (GNUNET_YES ==
4567       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
4568   {
4569     strict_kademlia = GNUNET_YES;
4570   }
4571
4572   if (GNUNET_YES ==
4573       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
4574   {
4575     stop_on_closest = GNUNET_YES;
4576   }
4577
4578   if (GNUNET_YES ==
4579       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
4580   {
4581     stop_on_found = GNUNET_YES;
4582   }
4583
4584   if (GNUNET_YES ==
4585       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
4586   {
4587     malicious_getter = GNUNET_YES;
4588     if (GNUNET_NO ==
4589         GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4590                                              "MALICIOUS_GET_FREQUENCY",
4591                                              &malicious_get_frequency))
4592       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4593   }
4594
4595   if (GNUNET_YES ==
4596       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
4597   {
4598     malicious_putter = GNUNET_YES;
4599     if (GNUNET_NO ==
4600         GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4601                                              "MALICIOUS_PUT_FREQUENCY",
4602                                              &malicious_put_frequency))
4603       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4604   }
4605
4606   if (GNUNET_OK ==
4607       GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
4608                                              &temp_config_num))
4609   {
4610     bucket_size = (unsigned int) temp_config_num;
4611   }
4612
4613   if (GNUNET_OK !=
4614       GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
4615                                              &kademlia_replication))
4616   {
4617     kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4618   }
4619
4620   if (GNUNET_YES ==
4621       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
4622   {
4623     malicious_dropper = GNUNET_YES;
4624   }
4625
4626   if (GNUNET_NO ==
4627       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
4628   {
4629     do_find_peer = GNUNET_NO;
4630   }
4631   else
4632     do_find_peer = GNUNET_YES;
4633
4634   if (GNUNET_YES ==
4635       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
4636     use_real_distance = GNUNET_YES;
4637
4638   if (GNUNET_YES ==
4639       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4640                                             "mysql_logging_extended"))
4641   {
4642     debug_routes = GNUNET_YES;
4643     debug_routes_extended = GNUNET_YES;
4644   }
4645
4646 #if DEBUG_DHT_ROUTING
4647   if (GNUNET_YES == debug_routes)
4648   {
4649     dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
4650     if (dhtlog_handle == NULL)
4651     {
4652       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4653                   "Could not connect to mysql logging server, logging will not happen!");
4654     }
4655   }
4656 #endif
4657
4658   if (GNUNET_YES ==
4659       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
4660     paper_forwarding = GNUNET_YES;
4661
4662   if (GNUNET_YES ==
4663       GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
4664     put_peer_identities = GNUNET_YES;
4665
4666   stats = GNUNET_STATISTICS_create ("dht", cfg);
4667
4668   if (stats != NULL)
4669   {
4670     GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
4671     GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4672     GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4673     GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
4674     GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4675     GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4676     GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
4677     GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
4678     GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4679     GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
4680     GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4681     GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
4682     GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
4683     GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4684     GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4685     GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4686     GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
4687     GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4688     GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4689     GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4690   }
4691   if (GNUNET_YES == do_find_peer)
4692   {
4693     next_send_time.rel_value =
4694         DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4695         GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4696                                   (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
4697                                    2) -
4698                                   DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4699     find_peer_context.start = GNUNET_TIME_absolute_get ();
4700     GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4701                                   &find_peer_context);
4702   }
4703
4704   /* Scheduled the task to clean up when shutdown is called */
4705   cleanup_task =
4706       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4707                                     &shutdown_task, NULL);
4708 }
4709
4710
4711 /**
4712  * The main function for the dht service.
4713  *
4714  * @param argc number of arguments from the command line
4715  * @param argv command line arguments
4716  * @return 0 ok, 1 on error
4717  */
4718 int
4719 main (int argc, char *const *argv)
4720 {
4721   int ret;
4722
4723   recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
4724   recent.minHeap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4725   recent_find_peer_requests =
4726       GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4727   ret =
4728       (GNUNET_OK ==
4729        GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
4730                            NULL)) ? 0 : 1;
4731   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
4732   GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4733   recent.hashmap = NULL;  
4734   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
4735   GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4736   recent.minHeap = NULL;
4737   GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4738   recent_find_peer_requests = NULL;  
4739   return ret;
4740 }
4741
4742 /* end of gnunet-service-dht.c */