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