big scheduler refactoring, expect some issues
[oweals/gnunet.git] / src / fs / gnunet-service-fs.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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 fs/gnunet-service-fs.c
23  * @brief gnunet anonymity protocol implementation
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - more statistics
28  */
29 #include "platform.h"
30 #include <float.h>
31 #include "gnunet_constants.h"
32 #include "gnunet_core_service.h"
33 #include "gnunet_dht_service.h"
34 #include "gnunet_datastore_service.h"
35 #include "gnunet_load_lib.h"
36 #include "gnunet_peer_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_signatures.h"
39 #include "gnunet_statistics_service.h"
40 #include "gnunet_util_lib.h"
41 #include "gnunet-service-fs_indexing.h"
42 #include "fs.h"
43
44 #define DEBUG_FS GNUNET_NO
45
46 /**
47  * Should we introduce random latency in processing?  Required for proper
48  * implementation of GAP, but can be disabled for performance evaluation of
49  * the basic routing algorithm.
50  *
51  * Note that with delays enabled, performance can be significantly lower
52  * (several orders of magnitude in 2-peer test runs); if you want to
53  * measure throughput of other components, set this to NO.  Also, you
54  * might want to consider changing 'RETRY_PROBABILITY_INV' to 1 for
55  * a rather wasteful mode of operation (that might still get the highest
56  * throughput overall).
57  *
58  * Performance measurements (for 50 MB file, 2 peers):
59  *
60  * - Without delays: 3300 kb/s
61  * - With    delays:  101 kb/s
62  */
63 #define SUPPORT_DELAYS GNUNET_NO
64
65 /**
66  * Size for the hash map for DHT requests from the FS
67  * service.  Should be about the number of concurrent
68  * DHT requests we plan to make.
69  */
70 #define FS_DHT_HT_SIZE 1024
71
72 /**
73  * At what frequency should our datastore load decrease
74  * automatically (since if we don't use it, clearly the
75  * load must be going down).
76  */
77 #define DATASTORE_LOAD_AUTODECLINE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250)
78
79 /**
80  * How often do we flush trust values to disk?
81  */
82 #define TRUST_FLUSH_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
83
84 /**
85  * How often do we at most PUT content into the DHT?
86  */
87 #define MAX_DHT_PUT_FREQ GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
88
89 /**
90  * Inverse of the probability that we will submit the same query
91  * to the same peer again.  If the same peer already got the query
92  * repeatedly recently, the probability is multiplied by the inverse
93  * of this number each time.  Note that we only try about every TTL_DECREMENT/2
94  * plus MAX_CORK_DELAY (so roughly every 3.5s).
95  *
96  * Note that this factor is a key influence to performance in small
97  * networks (especially test networks of 2 peers) because if there is
98  * only a single peer with the data, this value will determine how
99  * soon we might re-try.  For example, a value of 3 can result in 
100  * 1.7 MB/s transfer rates for a 10 MB file when a value of 1 would
101  * give us 5 MB/s.  OTOH, obviously re-trying the same peer can be
102  * rather inefficient in larger networks, hence picking 1 is in 
103  * general not the best choice.
104  *
105  * Performance measurements (for 50 MB file, 2 peers, no delays):
106  *
107  * - 1: 3300 kb/s (consistently)
108  * - 3: 2046 kb/s, 754 kb/s, 3490 kb/s
109  * - 5:  759 kb/s, 968 kb/s, 1160 kb/s
110  *
111  * Note that this does NOT mean that the value should be 1 since
112  * a 2-peer network is far from representative here (and this fails
113  * to take into consideration bandwidth wasted by repeatedly 
114  * sending queries to peers that don't have the content).  Also,
115  * it is expected that higher values lead to more inconsistent
116  * measurements since this only affects lost messages towards the
117  * end of the download.
118  *
119  * Finally, we should probably consider changing this and making
120  * it dependent on the number of connected peers or a related
121  * metric (bad magic constants...).
122  */
123 #define RETRY_PROBABILITY_INV 1
124
125 /**
126  * What is the maximum delay for a P2P FS message (in our interaction
127  * with core)?  FS-internal delays are another story.  The value is
128  * chosen based on the 32k block size.  Given that peers typcially
129  * have at least 1 kb/s bandwidth, 45s waits give us a chance to
130  * transmit one message even to the lowest-bandwidth peers.
131  */
132 #define MAX_TRANSMIT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 45)
133
134 /**
135  * Maximum number of requests (from other peers, overall) that we're
136  * willing to have pending at any given point in time.  Can be changed
137  * via the configuration file (32k is just the default).
138  */
139 static unsigned long long max_pending_requests = (32 * 1024);
140
141
142 /**
143  * Information we keep for each pending reply.  The
144  * actual message follows at the end of this struct.
145  */
146 struct PendingMessage;
147
148 /**
149  * Function called upon completion of a transmission.
150  *
151  * @param cls closure
152  * @param pid ID of receiving peer, 0 on transmission error
153  */
154 typedef void (*TransmissionContinuation)(void * cls, 
155                                          GNUNET_PEER_Id tpid);
156
157
158 /**
159  * Information we keep for each pending message (GET/PUT).  The
160  * actual message follows at the end of this struct.
161  */
162 struct PendingMessage
163 {
164   /**
165    * This is a doubly-linked list of messages to the same peer.
166    */
167   struct PendingMessage *next;
168
169   /**
170    * This is a doubly-linked list of messages to the same peer.
171    */
172   struct PendingMessage *prev;
173
174   /**
175    * Entry in pending message list for this pending message.
176    */ 
177   struct PendingMessageList *pml;  
178
179   /**
180    * Function to call immediately once we have transmitted this
181    * message.
182    */
183   TransmissionContinuation cont;
184
185   /**
186    * Closure for cont.
187    */
188   void *cont_cls;
189
190   /**
191    * Do not transmit this pending message until this deadline.
192    */
193   struct GNUNET_TIME_Absolute delay_until;
194
195   /**
196    * Size of the reply; actual reply message follows
197    * at the end of this struct.
198    */
199   size_t msize;
200   
201   /**
202    * How important is this message for us?
203    */
204   uint32_t priority;
205  
206 };
207
208
209 /**
210  * Information about a peer that we are connected to.
211  * We track data that is useful for determining which
212  * peers should receive our requests.  We also keep
213  * a list of messages to transmit to this peer.
214  */
215 struct ConnectedPeer
216 {
217
218   /**
219    * List of the last clients for which this peer successfully
220    * answered a query.
221    */
222   struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
223
224   /**
225    * List of the last PIDs for which
226    * this peer successfully answered a query;
227    * We use 0 to indicate no successful reply.
228    */
229   GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
230
231   /**
232    * Average delay between sending the peer a request and
233    * getting a reply (only calculated over the requests for
234    * which we actually got a reply).   Calculated
235    * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
236    */ 
237   struct GNUNET_TIME_Relative avg_delay;
238
239   /**
240    * Point in time until which this peer does not want us to migrate content
241    * to it.
242    */
243   struct GNUNET_TIME_Absolute migration_blocked;
244
245   /**
246    * Time until when we blocked this peer from migrating
247    * data to us.
248    */
249   struct GNUNET_TIME_Absolute last_migration_block;
250
251   /**
252    * Transmission times for the last MAX_QUEUE_PER_PEER
253    * requests for this peer.  Used as a ring buffer, current
254    * offset is stored in 'last_request_times_off'.  If the
255    * oldest entry is more recent than the 'avg_delay', we should
256    * not send any more requests right now.
257    */
258   struct GNUNET_TIME_Absolute last_request_times[MAX_QUEUE_PER_PEER];
259
260   /**
261    * Handle for an active request for transmission to this
262    * peer, or NULL.
263    */
264   struct GNUNET_CORE_TransmitHandle *cth;
265
266   /**
267    * Messages (replies, queries, content migration) we would like to
268    * send to this peer in the near future.  Sorted by priority, head.
269    */
270   struct PendingMessage *pending_messages_head;
271
272   /**
273    * Messages (replies, queries, content migration) we would like to
274    * send to this peer in the near future.  Sorted by priority, tail.
275    */
276   struct PendingMessage *pending_messages_tail;
277
278   /**
279    * How long does it typically take for us to transmit a message
280    * to this peer?  (delay between the request being issued and
281    * the callback being invoked).
282    */
283   struct GNUNET_LOAD_Value *transmission_delay;
284
285   /**
286    * Time when the last transmission request was issued.
287    */
288   struct GNUNET_TIME_Absolute last_transmission_request_start;
289
290   /**
291    * ID of delay task for scheduling transmission.
292    */
293   GNUNET_SCHEDULER_TaskIdentifier delayed_transmission_request_task;
294
295   /**
296    * Average priority of successful replies.  Calculated
297    * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
298    */
299   double avg_priority;
300
301   /**
302    * Increase in traffic preference still to be submitted
303    * to the core service for this peer.
304    */
305   uint64_t inc_preference;
306
307   /**
308    * Trust rating for this peer
309    */
310   uint32_t trust;
311
312   /**
313    * Trust rating for this peer on disk.
314    */
315   uint32_t disk_trust;
316
317   /**
318    * The peer's identity.
319    */
320   GNUNET_PEER_Id pid;  
321
322   /**
323    * Size of the linked list of 'pending_messages'.
324    */
325   unsigned int pending_requests;
326
327   /**
328    * Which offset in "last_p2p_replies" will be updated next?
329    * (we go round-robin).
330    */
331   unsigned int last_p2p_replies_woff;
332
333   /**
334    * Which offset in "last_client_replies" will be updated next?
335    * (we go round-robin).
336    */
337   unsigned int last_client_replies_woff;
338
339   /**
340    * Current offset into 'last_request_times' ring buffer.
341    */
342   unsigned int last_request_times_off;
343
344 };
345
346
347 /**
348  * Information we keep for each pending request.  We should try to
349  * keep this struct as small as possible since its memory consumption
350  * is key to how many requests we can have pending at once.
351  */
352 struct PendingRequest;
353
354
355 /**
356  * Doubly-linked list of requests we are performing
357  * on behalf of the same client.
358  */
359 struct ClientRequestList
360 {
361
362   /**
363    * This is a doubly-linked list.
364    */
365   struct ClientRequestList *next;
366
367   /**
368    * This is a doubly-linked list.
369    */
370   struct ClientRequestList *prev;
371
372   /**
373    * Request this entry represents.
374    */
375   struct PendingRequest *req;
376
377   /**
378    * Client list this request belongs to.
379    */
380   struct ClientList *client_list;
381
382 };
383
384
385 /**
386  * Replies to be transmitted to the client.  The actual
387  * response message is allocated after this struct.
388  */
389 struct ClientResponseMessage
390 {
391   /**
392    * This is a doubly-linked list.
393    */
394   struct ClientResponseMessage *next;
395
396   /**
397    * This is a doubly-linked list.
398    */
399   struct ClientResponseMessage *prev;
400
401   /**
402    * Client list entry this response belongs to.
403    */
404   struct ClientList *client_list;
405
406   /**
407    * Number of bytes in the response.
408    */
409   size_t msize;
410 };
411
412
413 /**
414  * Linked list of clients we are performing requests
415  * for right now.
416  */
417 struct ClientList
418 {
419   /**
420    * This is a linked list.
421    */
422   struct ClientList *next;
423
424   /**
425    * ID of a client making a request, NULL if this entry is for a
426    * peer.
427    */
428   struct GNUNET_SERVER_Client *client;
429
430   /**
431    * Head of list of requests performed on behalf
432    * of this client right now.
433    */
434   struct ClientRequestList *rl_head;
435
436   /**
437    * Tail of list of requests performed on behalf
438    * of this client right now.
439    */
440   struct ClientRequestList *rl_tail;
441
442   /**
443    * Head of linked list of responses.
444    */
445   struct ClientResponseMessage *res_head;
446
447   /**
448    * Tail of linked list of responses.
449    */
450   struct ClientResponseMessage *res_tail;
451
452   /**
453    * Context for sending replies.
454    */
455   struct GNUNET_CONNECTION_TransmitHandle *th;
456
457 };
458
459
460 /**
461  * Information about a peer that we have forwarded this
462  * request to already.  
463  */
464 struct UsedTargetEntry
465 {
466   /**
467    * What was the last time we have transmitted this request to this
468    * peer?
469    */
470   struct GNUNET_TIME_Absolute last_request_time;
471
472   /**
473    * How often have we transmitted this request to this peer?
474    */
475   unsigned int num_requests;
476
477   /**
478    * PID of the target peer.
479    */
480   GNUNET_PEER_Id pid;
481
482 };
483
484
485
486
487
488 /**
489  * Doubly-linked list of messages we are performing
490  * due to a pending request.
491  */
492 struct PendingMessageList
493 {
494
495   /**
496    * This is a doubly-linked list of messages on behalf of the same request.
497    */
498   struct PendingMessageList *next;
499
500   /**
501    * This is a doubly-linked list of messages on behalf of the same request.
502    */
503   struct PendingMessageList *prev;
504
505   /**
506    * Message this entry represents.
507    */
508   struct PendingMessage *pm;
509
510   /**
511    * Request this entry belongs to.
512    */
513   struct PendingRequest *req;
514
515   /**
516    * Peer this message is targeted for.
517    */
518   struct ConnectedPeer *target;
519
520 };
521
522
523 /**
524  * Information we keep for each pending request.  We should try to
525  * keep this struct as small as possible since its memory consumption
526  * is key to how many requests we can have pending at once.
527  */
528 struct PendingRequest
529 {
530
531   /**
532    * If this request was made by a client, this is our entry in the
533    * client request list; otherwise NULL.
534    */
535   struct ClientRequestList *client_request_list;
536
537   /**
538    * Entry of peer responsible for this entry (if this request
539    * was made by a peer).
540    */
541   struct ConnectedPeer *cp;
542
543   /**
544    * If this is a namespace query, pointer to the hash of the public
545    * key of the namespace; otherwise NULL.  Pointer will be to the 
546    * end of this struct (so no need to free it).
547    */
548   const GNUNET_HashCode *namespace;
549
550   /**
551    * Bloomfilter we use to filter out replies that we don't care about
552    * (anymore).  NULL as long as we are interested in all replies.
553    */
554   struct GNUNET_CONTAINER_BloomFilter *bf;
555
556   /**
557    * Context of our GNUNET_CORE_peer_change_preference call.
558    */
559   struct GNUNET_CORE_InformationRequestContext *irc;
560
561   /**
562    * Reference to DHT get operation for this request (or NULL).
563    */
564   struct GNUNET_DHT_GetHandle *dht_get;
565
566   /**
567    * Hash code of all replies that we have seen so far (only valid
568    * if client is not NULL since we only track replies like this for
569    * our own clients).
570    */
571   GNUNET_HashCode *replies_seen;
572
573   /**
574    * Node in the heap representing this entry; NULL
575    * if we have no heap node.
576    */
577   struct GNUNET_CONTAINER_HeapNode *hnode;
578
579   /**
580    * Head of list of messages being performed on behalf of this
581    * request.
582    */
583   struct PendingMessageList *pending_head;
584
585   /**
586    * Tail of list of messages being performed on behalf of this
587    * request.
588    */
589   struct PendingMessageList *pending_tail;
590
591   /**
592    * When did we first see this request (form this peer), or, if our
593    * client is initiating, when did we last initiate a search?
594    */
595   struct GNUNET_TIME_Absolute start_time;
596
597   /**
598    * The query that this request is for.
599    */
600   GNUNET_HashCode query;
601
602   /**
603    * The task responsible for transmitting queries
604    * for this request.
605    */
606   GNUNET_SCHEDULER_TaskIdentifier task;
607
608   /**
609    * (Interned) Peer identifier that identifies a preferred target
610    * for requests.
611    */
612   GNUNET_PEER_Id target_pid;
613
614   /**
615    * (Interned) Peer identifiers of peers that have already
616    * received our query for this content.
617    */
618   struct UsedTargetEntry *used_targets;
619   
620   /**
621    * Our entry in the queue (non-NULL while we wait for our
622    * turn to interact with the local database).
623    */
624   struct GNUNET_DATASTORE_QueueEntry *qe;
625
626   /**
627    * Size of the 'bf' (in bytes).
628    */
629   size_t bf_size;
630
631   /**
632    * Desired anonymity level; only valid for requests from a local client.
633    */
634   uint32_t anonymity_level;
635
636   /**
637    * How many entries in "used_targets" are actually valid?
638    */
639   unsigned int used_targets_off;
640
641   /**
642    * How long is the "used_targets" array?
643    */
644   unsigned int used_targets_size;
645
646   /**
647    * Number of results found for this request.
648    */
649   unsigned int results_found;
650
651   /**
652    * How many entries in "replies_seen" are actually valid?
653    */
654   unsigned int replies_seen_off;
655
656   /**
657    * How long is the "replies_seen" array?
658    */
659   unsigned int replies_seen_size;
660   
661   /**
662    * Priority with which this request was made.  If one of our clients
663    * made the request, then this is the current priority that we are
664    * using when initiating the request.  This value is used when
665    * we decide to reward other peers with trust for providing a reply.
666    */
667   uint32_t priority;
668
669   /**
670    * Priority points left for us to spend when forwarding this request
671    * to other peers.
672    */
673   uint32_t remaining_priority;
674
675   /**
676    * Number to mingle hashes for bloom-filter tests with.
677    */
678   int32_t mingle;
679
680   /**
681    * TTL with which we saw this request (or, if we initiated, TTL that
682    * we used for the request).
683    */
684   int32_t ttl;
685   
686   /**
687    * Type of the content that this request is for.
688    */
689   enum GNUNET_BLOCK_Type type;
690
691   /**
692    * Remove this request after transmission of the current response.
693    */
694   int8_t do_remove;
695
696   /**
697    * GNUNET_YES if we should not forward this request to other peers.
698    */
699   int8_t local_only;
700
701   /**
702    * GNUNET_YES if we should not forward this request to other peers.
703    */
704   int8_t forward_only;
705
706 };
707
708
709 /**
710  * Block that is ready for migration to other peers.  Actual data is at the end of the block.
711  */
712 struct MigrationReadyBlock
713 {
714
715   /**
716    * This is a doubly-linked list.
717    */
718   struct MigrationReadyBlock *next;
719
720   /**
721    * This is a doubly-linked list.
722    */
723   struct MigrationReadyBlock *prev;
724
725   /**
726    * Query for the block.
727    */
728   GNUNET_HashCode query;
729
730   /**
731    * When does this block expire? 
732    */
733   struct GNUNET_TIME_Absolute expiration;
734
735   /**
736    * Peers we would consider forwarding this
737    * block to.  Zero for empty entries.
738    */
739   GNUNET_PEER_Id target_list[MIGRATION_LIST_SIZE];
740
741   /**
742    * Size of the block.
743    */
744   size_t size;
745
746   /**
747    *  Number of targets already used.
748    */
749   unsigned int used_targets;
750
751   /**
752    * Type of the block.
753    */
754   enum GNUNET_BLOCK_Type type;
755 };
756
757
758 /**
759  * Our connection to the datastore.
760  */
761 static struct GNUNET_DATASTORE_Handle *dsh;
762
763 /**
764  * Our block context.
765  */
766 static struct GNUNET_BLOCK_Context *block_ctx;
767
768 /**
769  * Our block configuration.
770  */
771 static struct GNUNET_CONFIGURATION_Handle *block_cfg;
772
773 /**
774  * Our configuration.
775  */
776 static const struct GNUNET_CONFIGURATION_Handle *cfg;
777
778 /**
779  * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
780  */
781 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
782
783 /**
784  * Map of peer identifiers to "struct PendingRequest" (for that peer).
785  */
786 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
787
788 /**
789  * Map of query identifiers to "struct PendingRequest" (for that query).
790  */
791 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
792
793 /**
794  * Heap with the request that will expire next at the top.  Contains
795  * pointers of type "struct PendingRequest*"; these will *also* be
796  * aliased from the "requests_by_peer" data structures and the
797  * "requests_by_query" table.  Note that requests from our clients
798  * don't expire and are thus NOT in the "requests_by_expiration"
799  * (or the "requests_by_peer" tables).
800  */
801 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
802
803 /**
804  * Handle for reporting statistics.
805  */
806 static struct GNUNET_STATISTICS_Handle *stats;
807
808 /**
809  * Linked list of clients we are currently processing requests for.
810  */
811 static struct ClientList *client_list;
812
813 /**
814  * Pointer to handle to the core service (points to NULL until we've
815  * connected to it).
816  */
817 static struct GNUNET_CORE_Handle *core;
818
819 /**
820  * Head of linked list of blocks that can be migrated.
821  */
822 static struct MigrationReadyBlock *mig_head;
823
824 /**
825  * Tail of linked list of blocks that can be migrated.
826  */
827 static struct MigrationReadyBlock *mig_tail;
828
829 /**
830  * Request to datastore for migration (or NULL).
831  */
832 static struct GNUNET_DATASTORE_QueueEntry *mig_qe;
833
834 /**
835  * Request to datastore for DHT PUTs (or NULL).
836  */
837 static struct GNUNET_DATASTORE_QueueEntry *dht_qe;
838
839 /**
840  * Type we will request for the next DHT PUT round from the datastore.
841  */
842 static enum GNUNET_BLOCK_Type dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
843
844 /**
845  * Where do we store trust information?
846  */
847 static char *trustDirectory;
848
849 /**
850  * ID of task that collects blocks for migration.
851  */
852 static GNUNET_SCHEDULER_TaskIdentifier mig_task;
853
854 /**
855  * ID of task that collects blocks for DHT PUTs.
856  */
857 static GNUNET_SCHEDULER_TaskIdentifier dht_task;
858
859 /**
860  * What is the maximum frequency at which we are allowed to
861  * poll the datastore for migration content?
862  */
863 static struct GNUNET_TIME_Relative min_migration_delay;
864
865 /**
866  * Handle for DHT operations.
867  */
868 static struct GNUNET_DHT_Handle *dht_handle;
869
870 /**
871  * Size of the doubly-linked list of migration blocks.
872  */
873 static unsigned int mig_size;
874
875 /**
876  * Are we allowed to migrate content to this peer.
877  */
878 static int active_migration;
879
880 /**
881  * How many entires with zero anonymity do we currently estimate
882  * to have in the database?
883  */
884 static unsigned int zero_anonymity_count_estimate;
885
886 /**
887  * Typical priorities we're seeing from other peers right now.  Since
888  * most priorities will be zero, this value is the weighted average of
889  * non-zero priorities seen "recently".  In order to ensure that new
890  * values do not dramatically change the ratio, values are first
891  * "capped" to a reasonable range (+N of the current value) and then
892  * averaged into the existing value by a ratio of 1:N.  Hence
893  * receiving the largest possible priority can still only raise our
894  * "current_priorities" by at most 1.
895  */
896 static double current_priorities;
897
898 /**
899  * Datastore 'GET' load tracking.
900  */
901 static struct GNUNET_LOAD_Value *datastore_get_load;
902
903 /**
904  * Datastore 'PUT' load tracking.
905  */
906 static struct GNUNET_LOAD_Value *datastore_put_load;
907
908 /**
909  * How long do requests typically stay in the routing table?
910  */
911 static struct GNUNET_LOAD_Value *rt_entry_lifetime;
912
913 /**
914  * We've just now completed a datastore request.  Update our
915  * datastore load calculations.
916  *
917  * @param start time when the datastore request was issued
918  */
919 static void
920 update_datastore_delays (struct GNUNET_TIME_Absolute start)
921 {
922   struct GNUNET_TIME_Relative delay;
923
924   delay = GNUNET_TIME_absolute_get_duration (start);
925   GNUNET_LOAD_update (datastore_get_load,
926                       delay.rel_value);
927 }
928
929
930 /**
931  * Get the filename under which we would store the GNUNET_HELLO_Message
932  * for the given host and protocol.
933  * @return filename of the form DIRECTORY/HOSTID
934  */
935 static char *
936 get_trust_filename (const struct GNUNET_PeerIdentity *id)
937 {
938   struct GNUNET_CRYPTO_HashAsciiEncoded fil;
939   char *fn;
940
941   GNUNET_CRYPTO_hash_to_enc (&id->hashPubKey, &fil);
942   GNUNET_asprintf (&fn, "%s%s%s", trustDirectory, DIR_SEPARATOR_STR, &fil);
943   return fn;
944 }
945
946
947
948 /**
949  * Transmit messages by copying it to the target buffer
950  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
951  * for writing in the meantime.  In that case, do nothing
952  * (the disconnect or shutdown handler will take care of the rest).
953  * If we were able to transmit messages and there are still more
954  * pending, ask core again for further calls to this function.
955  *
956  * @param cls closure, pointer to the 'struct ConnectedPeer*'
957  * @param size number of bytes available in buf
958  * @param buf where the callee should write the message
959  * @return number of bytes written to buf
960  */
961 static size_t
962 transmit_to_peer (void *cls,
963                   size_t size, void *buf);
964
965
966 /* ******************* clean up functions ************************ */
967
968 /**
969  * Delete the given migration block.
970  *
971  * @param mb block to delete
972  */
973 static void
974 delete_migration_block (struct MigrationReadyBlock *mb)
975 {
976   GNUNET_CONTAINER_DLL_remove (mig_head,
977                                mig_tail,
978                                mb);
979   GNUNET_PEER_decrement_rcs (mb->target_list,
980                              MIGRATION_LIST_SIZE);
981   mig_size--;
982   GNUNET_free (mb);
983 }
984
985
986 /**
987  * Compare the distance of two peers to a key.
988  *
989  * @param key key
990  * @param p1 first peer
991  * @param p2 second peer
992  * @return GNUNET_YES if P1 is closer to key than P2
993  */
994 static int
995 is_closer (const GNUNET_HashCode *key,
996            const struct GNUNET_PeerIdentity *p1,
997            const struct GNUNET_PeerIdentity *p2)
998 {
999   return GNUNET_CRYPTO_hash_xorcmp (&p1->hashPubKey,
1000                                     &p2->hashPubKey,
1001                                     key);
1002 }
1003
1004
1005 /**
1006  * Consider migrating content to a given peer.
1007  *
1008  * @param cls 'struct MigrationReadyBlock*' to select
1009  *            targets for (or NULL for none)
1010  * @param key ID of the peer 
1011  * @param value 'struct ConnectedPeer' of the peer
1012  * @return GNUNET_YES (always continue iteration)
1013  */
1014 static int
1015 consider_migration (void *cls,
1016                     const GNUNET_HashCode *key,
1017                     void *value)
1018 {
1019   struct MigrationReadyBlock *mb = cls;
1020   struct ConnectedPeer *cp = value;
1021   struct MigrationReadyBlock *pos;
1022   struct GNUNET_PeerIdentity cppid;
1023   struct GNUNET_PeerIdentity otherpid;
1024   struct GNUNET_PeerIdentity worstpid;
1025   size_t msize;
1026   unsigned int i;
1027   unsigned int repl;
1028   
1029   /* consider 'cp' as a migration target for mb */
1030   if (GNUNET_TIME_absolute_get_remaining (cp->migration_blocked).rel_value > 0)
1031     return GNUNET_YES; /* peer has requested no migration! */
1032   if (mb != NULL)
1033     {
1034       GNUNET_PEER_resolve (cp->pid,
1035                            &cppid);
1036       repl = MIGRATION_LIST_SIZE;
1037       for (i=0;i<MIGRATION_LIST_SIZE;i++)
1038         {
1039           if (mb->target_list[i] == 0)
1040             {
1041               mb->target_list[i] = cp->pid;
1042               GNUNET_PEER_change_rc (mb->target_list[i], 1);
1043               repl = MIGRATION_LIST_SIZE;
1044               break;
1045             }
1046           GNUNET_PEER_resolve (mb->target_list[i],
1047                                &otherpid);
1048           if ( (repl == MIGRATION_LIST_SIZE) &&
1049                is_closer (&mb->query,
1050                           &cppid,
1051                           &otherpid)) 
1052             {
1053               repl = i;
1054               worstpid = otherpid;
1055             }
1056           else if ( (repl != MIGRATION_LIST_SIZE) &&
1057                     (is_closer (&mb->query,
1058                                 &worstpid,
1059                                 &otherpid) ) )
1060             {
1061               repl = i;
1062               worstpid = otherpid;
1063             }       
1064         }
1065       if (repl != MIGRATION_LIST_SIZE) 
1066         {
1067           GNUNET_PEER_change_rc (mb->target_list[repl], -1);
1068           mb->target_list[repl] = cp->pid;
1069           GNUNET_PEER_change_rc (mb->target_list[repl], 1);
1070         }
1071     }
1072
1073   /* consider scheduling transmission to cp for content migration */
1074   if (cp->cth != NULL)        
1075     return GNUNET_YES; 
1076   msize = 0;
1077   pos = mig_head;
1078   while (pos != NULL)
1079     {
1080       for (i=0;i<MIGRATION_LIST_SIZE;i++)
1081         {
1082           if (cp->pid == pos->target_list[i])
1083             {
1084               if (msize == 0)
1085                 msize = pos->size;
1086               else
1087                 msize = GNUNET_MIN (msize,
1088                                     pos->size);
1089               break;
1090             }
1091         }
1092       pos = pos->next;
1093     }
1094   if (msize == 0)
1095     return GNUNET_YES; /* no content available */
1096 #if DEBUG_FS
1097   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1098               "Trying to migrate at least %u bytes to peer `%s'\n",
1099               msize,
1100               GNUNET_h2s (key));
1101 #endif
1102   if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1103     {
1104       GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1105       cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1106     }
1107   cp->cth 
1108     = GNUNET_CORE_notify_transmit_ready (core,
1109                                          0, GNUNET_TIME_UNIT_FOREVER_REL,
1110                                          (const struct GNUNET_PeerIdentity*) key,
1111                                          msize + sizeof (struct PutMessage),
1112                                          &transmit_to_peer,
1113                                          cp);
1114   return GNUNET_YES;
1115 }
1116
1117
1118 /**
1119  * Task that is run periodically to obtain blocks for content
1120  * migration
1121  * 
1122  * @param cls unused
1123  * @param tc scheduler context (also unused)
1124  */
1125 static void
1126 gather_migration_blocks (void *cls,
1127                          const struct GNUNET_SCHEDULER_TaskContext *tc);
1128
1129
1130
1131
1132 /**
1133  * Task that is run periodically to obtain blocks for DHT PUTs.
1134  * 
1135  * @param cls type of blocks to gather
1136  * @param tc scheduler context (unused)
1137  */
1138 static void
1139 gather_dht_put_blocks (void *cls,
1140                        const struct GNUNET_SCHEDULER_TaskContext *tc);
1141
1142
1143 /**
1144  * If the migration task is not currently running, consider
1145  * (re)scheduling it with the appropriate delay.
1146  */
1147 static void
1148 consider_migration_gathering ()
1149 {
1150   struct GNUNET_TIME_Relative delay;
1151
1152   if (dsh == NULL)
1153     return;
1154   if (mig_qe != NULL)
1155     return;
1156   if (mig_task != GNUNET_SCHEDULER_NO_TASK)
1157     return;
1158   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1159                                          mig_size);
1160   delay = GNUNET_TIME_relative_divide (delay,
1161                                        MAX_MIGRATION_QUEUE);
1162   delay = GNUNET_TIME_relative_max (delay,
1163                                     min_migration_delay);
1164   mig_task = GNUNET_SCHEDULER_add_delayed (delay,
1165                                            &gather_migration_blocks,
1166                                            NULL);
1167 }
1168
1169
1170 /**
1171  * If the DHT PUT gathering task is not currently running, consider
1172  * (re)scheduling it with the appropriate delay.
1173  */
1174 static void
1175 consider_dht_put_gathering (void *cls)
1176 {
1177   struct GNUNET_TIME_Relative delay;
1178
1179   if (dsh == NULL)
1180     return;
1181   if (dht_qe != NULL)
1182     return;
1183   if (dht_task != GNUNET_SCHEDULER_NO_TASK)
1184     return;
1185   if (zero_anonymity_count_estimate > 0)
1186     {
1187       delay = GNUNET_TIME_relative_divide (GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY,
1188                                            zero_anonymity_count_estimate);
1189       delay = GNUNET_TIME_relative_min (delay,
1190                                         MAX_DHT_PUT_FREQ);
1191     }
1192   else
1193     {
1194       /* if we have NO zero-anonymity content yet, wait 5 minutes for some to
1195          (hopefully) appear */
1196       delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5);
1197     }
1198   dht_task = GNUNET_SCHEDULER_add_delayed (delay,
1199                                            &gather_dht_put_blocks,
1200                                            cls);
1201 }
1202
1203
1204 /**
1205  * Process content offered for migration.
1206  *
1207  * @param cls closure
1208  * @param key key for the content
1209  * @param size number of bytes in data
1210  * @param data content stored
1211  * @param type type of the content
1212  * @param priority priority of the content
1213  * @param anonymity anonymity-level for the content
1214  * @param expiration expiration time for the content
1215  * @param uid unique identifier for the datum;
1216  *        maybe 0 if no unique identifier is available
1217  */
1218 static void
1219 process_migration_content (void *cls,
1220                            const GNUNET_HashCode * key,
1221                            size_t size,
1222                            const void *data,
1223                            enum GNUNET_BLOCK_Type type,
1224                            uint32_t priority,
1225                            uint32_t anonymity,
1226                            struct GNUNET_TIME_Absolute
1227                            expiration, uint64_t uid)
1228 {
1229   struct MigrationReadyBlock *mb;
1230   
1231   if (key == NULL)
1232     {
1233       mig_qe = NULL;
1234       if (mig_size < MAX_MIGRATION_QUEUE)  
1235         consider_migration_gathering ();
1236       return;
1237     }
1238   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1239     {
1240       if (GNUNET_OK !=
1241           GNUNET_FS_handle_on_demand_block (key, size, data,
1242                                             type, priority, anonymity,
1243                                             expiration, uid, 
1244                                             &process_migration_content,
1245                                             NULL))
1246         {
1247           GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1248         }
1249       return;
1250     }
1251 #if DEBUG_FS
1252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1253               "Retrieved block `%s' of type %u for migration\n",
1254               GNUNET_h2s (key),
1255               type);
1256 #endif
1257   mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
1258   mb->query = *key;
1259   mb->expiration = expiration;
1260   mb->size = size;
1261   mb->type = type;
1262   memcpy (&mb[1], data, size);
1263   GNUNET_CONTAINER_DLL_insert_after (mig_head,
1264                                      mig_tail,
1265                                      mig_tail,
1266                                      mb);
1267   mig_size++;
1268   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1269                                          &consider_migration,
1270                                          mb);
1271   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1272 }
1273
1274
1275 /**
1276  * Function called upon completion of the DHT PUT operation.
1277  */
1278 static void
1279 dht_put_continuation (void *cls,
1280                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1281 {
1282   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1283 }
1284
1285
1286 /**
1287  * Store content in DHT.
1288  *
1289  * @param cls closure
1290  * @param key key for the content
1291  * @param size number of bytes in data
1292  * @param data content stored
1293  * @param type type of the content
1294  * @param priority priority of the content
1295  * @param anonymity anonymity-level for the content
1296  * @param expiration expiration time for the content
1297  * @param uid unique identifier for the datum;
1298  *        maybe 0 if no unique identifier is available
1299  */
1300 static void
1301 process_dht_put_content (void *cls,
1302                          const GNUNET_HashCode * key,
1303                          size_t size,
1304                          const void *data,
1305                          enum GNUNET_BLOCK_Type type,
1306                          uint32_t priority,
1307                          uint32_t anonymity,
1308                          struct GNUNET_TIME_Absolute
1309                          expiration, uint64_t uid)
1310
1311   static unsigned int counter;
1312   static GNUNET_HashCode last_vhash;
1313   static GNUNET_HashCode vhash;
1314
1315   if (key == NULL)
1316     {
1317       dht_qe = NULL;
1318       consider_dht_put_gathering (cls);
1319       return;
1320     }
1321   /* slightly funky code to estimate the total number of values with zero
1322      anonymity from the maximum observed length of a monotonically increasing 
1323      sequence of hashes over the contents */
1324   GNUNET_CRYPTO_hash (data, size, &vhash);
1325   if (GNUNET_CRYPTO_hash_cmp (&vhash, &last_vhash) <= 0)
1326     {
1327       if (zero_anonymity_count_estimate > 0)
1328         zero_anonymity_count_estimate /= 2;
1329       counter = 0;
1330     }
1331   last_vhash = vhash;
1332   if (counter < 31)
1333     counter++;
1334   if (zero_anonymity_count_estimate < (1 << counter))
1335     zero_anonymity_count_estimate = (1 << counter);
1336 #if DEBUG_FS
1337   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338               "Retrieved block `%s' of type %u for DHT PUT\n",
1339               GNUNET_h2s (key),
1340               type);
1341 #endif
1342   GNUNET_DHT_put (dht_handle,
1343                   key,
1344                   GNUNET_DHT_RO_NONE,
1345                   type,
1346                   size,
1347                   data,
1348                   expiration,
1349                   GNUNET_TIME_UNIT_FOREVER_REL,
1350                   &dht_put_continuation,
1351                   cls);
1352 }
1353
1354
1355 /**
1356  * Task that is run periodically to obtain blocks for content
1357  * migration
1358  * 
1359  * @param cls unused
1360  * @param tc scheduler context (also unused)
1361  */
1362 static void
1363 gather_migration_blocks (void *cls,
1364                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1365 {
1366   mig_task = GNUNET_SCHEDULER_NO_TASK;
1367   if (dsh != NULL)
1368     {
1369       mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, UINT_MAX,
1370                                             GNUNET_TIME_UNIT_FOREVER_REL,
1371                                             &process_migration_content, NULL);
1372       GNUNET_assert (mig_qe != NULL);
1373     }
1374 }
1375
1376
1377 /**
1378  * Task that is run periodically to obtain blocks for DHT PUTs.
1379  * 
1380  * @param cls type of blocks to gather
1381  * @param tc scheduler context (unused)
1382  */
1383 static void
1384 gather_dht_put_blocks (void *cls,
1385                        const struct GNUNET_SCHEDULER_TaskContext *tc)
1386 {
1387   dht_task = GNUNET_SCHEDULER_NO_TASK;
1388   if (dsh != NULL)
1389     {
1390       if (dht_put_type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
1391         dht_put_type = GNUNET_BLOCK_TYPE_FS_KBLOCK;
1392       dht_qe = GNUNET_DATASTORE_get_zero_anonymity (dsh, 0, UINT_MAX,
1393                                                     GNUNET_TIME_UNIT_FOREVER_REL,
1394                                                     dht_put_type++,
1395                                                     &process_dht_put_content, NULL);
1396       GNUNET_assert (dht_qe != NULL);
1397     }
1398 }
1399
1400
1401 /**
1402  * We're done with a particular message list entry.
1403  * Free all associated resources.
1404  * 
1405  * @param pml entry to destroy
1406  */
1407 static void
1408 destroy_pending_message_list_entry (struct PendingMessageList *pml)
1409 {
1410   GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
1411                                pml->req->pending_tail,
1412                                pml);
1413   GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
1414                                pml->target->pending_messages_tail,
1415                                pml->pm);
1416   pml->target->pending_requests--;
1417   GNUNET_free (pml->pm);
1418   GNUNET_free (pml);
1419 }
1420
1421
1422 /**
1423  * Destroy the given pending message (and call the respective
1424  * continuation).
1425  *
1426  * @param pm message to destroy
1427  * @param tpid id of peer that the message was delivered to, or 0 for none
1428  */
1429 static void
1430 destroy_pending_message (struct PendingMessage *pm,
1431                          GNUNET_PEER_Id tpid)
1432 {
1433   struct PendingMessageList *pml = pm->pml;
1434   TransmissionContinuation cont;
1435   void *cont_cls;
1436
1437   cont = pm->cont;
1438   cont_cls = pm->cont_cls;
1439   if (pml != NULL)
1440     {
1441       GNUNET_assert (pml->pm == pm);
1442       GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1443       destroy_pending_message_list_entry (pml);
1444     }
1445   else
1446     {
1447       GNUNET_free (pm);
1448     }
1449   if (cont != NULL)
1450     cont (cont_cls, tpid);  
1451 }
1452
1453
1454 /**
1455  * We're done processing a particular request.
1456  * Free all associated resources.
1457  *
1458  * @param pr request to destroy
1459  */
1460 static void
1461 destroy_pending_request (struct PendingRequest *pr)
1462 {
1463   struct GNUNET_PeerIdentity pid;
1464   unsigned int i;
1465
1466   if (pr->hnode != NULL)
1467     {
1468       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1469                                          pr->hnode);
1470       pr->hnode = NULL;
1471     }
1472   if (NULL == pr->client_request_list)
1473     {
1474       GNUNET_STATISTICS_update (stats,
1475                                 gettext_noop ("# P2P searches active"),
1476                                 -1,
1477                                 GNUNET_NO);
1478     }
1479   else
1480     {
1481       GNUNET_STATISTICS_update (stats,
1482                                 gettext_noop ("# client searches active"),
1483                                 -1,
1484                                 GNUNET_NO);
1485     }
1486   if (GNUNET_YES == 
1487       GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1488                                             &pr->query,
1489                                             pr))
1490     {
1491       GNUNET_LOAD_update (rt_entry_lifetime,
1492                           GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1493     }
1494   if (pr->qe != NULL)
1495      {
1496       GNUNET_DATASTORE_cancel (pr->qe);
1497       pr->qe = NULL;
1498     }
1499   if (pr->dht_get != NULL)
1500     {
1501       GNUNET_DHT_get_stop (pr->dht_get);
1502       pr->dht_get = NULL;
1503     }
1504   if (pr->client_request_list != NULL)
1505     {
1506       GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1507                                    pr->client_request_list->client_list->rl_tail,
1508                                    pr->client_request_list);
1509       GNUNET_free (pr->client_request_list);
1510       pr->client_request_list = NULL;
1511     }
1512   if (pr->cp != NULL)
1513     {
1514       GNUNET_PEER_resolve (pr->cp->pid,
1515                            &pid);
1516       (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1517                                                    &pid.hashPubKey,
1518                                                    pr);
1519       pr->cp = NULL;
1520     }
1521   if (pr->bf != NULL)
1522     {
1523       GNUNET_CONTAINER_bloomfilter_free (pr->bf);                                        
1524       pr->bf = NULL;
1525     }
1526   if (pr->irc != NULL)
1527     {
1528       GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1529       pr->irc = NULL;
1530     }
1531   if (pr->replies_seen != NULL)
1532     {
1533       GNUNET_free (pr->replies_seen);
1534       pr->replies_seen = NULL;
1535     }
1536   if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1537     {
1538       GNUNET_SCHEDULER_cancel (pr->task);
1539       pr->task = GNUNET_SCHEDULER_NO_TASK;
1540     }
1541   while (NULL != pr->pending_head)    
1542     destroy_pending_message_list_entry (pr->pending_head);
1543   GNUNET_PEER_change_rc (pr->target_pid, -1);
1544   if (pr->used_targets != NULL)
1545     {
1546       for (i=0;i<pr->used_targets_off;i++)
1547         GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1548       GNUNET_free (pr->used_targets);
1549       pr->used_targets_off = 0;
1550       pr->used_targets_size = 0;
1551       pr->used_targets = NULL;
1552     }
1553   GNUNET_free (pr);
1554 }
1555
1556
1557 /**
1558  * Method called whenever a given peer connects.
1559  *
1560  * @param cls closure, not used
1561  * @param peer peer identity this notification is about
1562  * @param latency reported latency of the connection with 'other'
1563  * @param distance reported distance (DV) to 'other' 
1564  */
1565 static void 
1566 peer_connect_handler (void *cls,
1567                       const struct
1568                       GNUNET_PeerIdentity * peer,
1569                       struct GNUNET_TIME_Relative latency,
1570                       uint32_t distance)
1571 {
1572   struct ConnectedPeer *cp;
1573   struct MigrationReadyBlock *pos;
1574   char *fn;
1575   uint32_t trust;
1576
1577   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1578                                           &peer->hashPubKey);
1579   if (NULL != cp)
1580     {
1581       GNUNET_break (0);
1582       return;
1583     }
1584   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1585   cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1586   cp->pid = GNUNET_PEER_intern (peer);
1587
1588   fn = get_trust_filename (peer);
1589   if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1590       (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1591     cp->disk_trust = cp->trust = ntohl (trust);
1592   GNUNET_free (fn);
1593
1594   GNUNET_break (GNUNET_OK ==
1595                 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1596                                                    &peer->hashPubKey,
1597                                                    cp,
1598                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1599
1600   pos = mig_head;
1601   while (NULL != pos)
1602     {
1603       (void) consider_migration (pos, &peer->hashPubKey, cp);
1604       pos = pos->next;
1605     }
1606 }
1607
1608
1609 /**
1610  * Method called whenever a given peer has a status change.
1611  *
1612  * @param cls closure
1613  * @param peer peer identity this notification is about
1614  * @param latency reported latency of the connection with 'other'
1615  * @param distance reported distance (DV) to 'other' 
1616  * @param bandwidth_in available amount of inbound bandwidth
1617  * @param bandwidth_out available amount of outbound bandwidth
1618  * @param timeout absolute time when this peer will time out
1619  *        unless we see some further activity from it
1620  */
1621 static void
1622 peer_status_handler (void *cls,
1623                      const struct
1624                      GNUNET_PeerIdentity * peer,
1625                      struct GNUNET_TIME_Relative latency,
1626                      uint32_t distance,
1627                      struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1628                      struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1629                      struct GNUNET_TIME_Absolute timeout)
1630 {
1631   struct ConnectedPeer *cp;
1632
1633   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1634                                           &peer->hashPubKey);
1635   if (cp == NULL)
1636     {
1637       GNUNET_break (0);
1638       return;
1639     }
1640   GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1641                                  latency);  
1642 }
1643
1644
1645
1646 /**
1647  * Increase the host credit by a value.
1648  *
1649  * @param host which peer to change the trust value on
1650  * @param value is the int value by which the
1651  *  host credit is to be increased or decreased
1652  * @returns the actual change in trust (positive or negative)
1653  */
1654 static int
1655 change_host_trust (struct ConnectedPeer *host, int value)
1656 {
1657   if (value == 0)
1658     return 0;
1659   GNUNET_assert (host != NULL);
1660   if (value > 0)
1661     {
1662       if (host->trust + value < host->trust)
1663         {
1664           value = UINT32_MAX - host->trust;
1665           host->trust = UINT32_MAX;
1666         }
1667       else
1668         host->trust += value;
1669     }
1670   else
1671     {
1672       if (host->trust < -value)
1673         {
1674           value = -host->trust;
1675           host->trust = 0;
1676         }
1677       else
1678         host->trust += value;
1679     }
1680   return value;
1681 }
1682
1683
1684 /**
1685  * Write host-trust information to a file - flush the buffer entry!
1686  */
1687 static int
1688 flush_trust (void *cls,
1689              const GNUNET_HashCode *key,
1690              void *value)
1691 {
1692   struct ConnectedPeer *host = value;
1693   char *fn;
1694   uint32_t trust;
1695   struct GNUNET_PeerIdentity pid;
1696
1697   if (host->trust == host->disk_trust)
1698     return GNUNET_OK;                     /* unchanged */
1699   GNUNET_PEER_resolve (host->pid,
1700                        &pid);
1701   fn = get_trust_filename (&pid);
1702   if (host->trust == 0)
1703     {
1704       if ((0 != UNLINK (fn)) && (errno != ENOENT))
1705         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1706                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1707     }
1708   else
1709     {
1710       trust = htonl (host->trust);
1711       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
1712                                                     sizeof(uint32_t),
1713                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1714                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1715         host->disk_trust = host->trust;
1716     }
1717   GNUNET_free (fn);
1718   return GNUNET_OK;
1719 }
1720
1721 /**
1722  * Call this method periodically to scan data/hosts for new hosts.
1723  */
1724 static void
1725 cron_flush_trust (void *cls,
1726                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1727 {
1728
1729   if (NULL == connected_peers)
1730     return;
1731   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1732                                          &flush_trust,
1733                                          NULL);
1734   if (NULL == tc)
1735     return;
1736   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1737     return;
1738   GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1739 }
1740
1741
1742 /**
1743  * Free (each) request made by the peer.
1744  *
1745  * @param cls closure, points to peer that the request belongs to
1746  * @param key current key code
1747  * @param value value in the hash map
1748  * @return GNUNET_YES (we should continue to iterate)
1749  */
1750 static int
1751 destroy_request (void *cls,
1752                  const GNUNET_HashCode * key,
1753                  void *value)
1754 {
1755   const struct GNUNET_PeerIdentity * peer = cls;
1756   struct PendingRequest *pr = value;
1757   
1758   GNUNET_break (GNUNET_YES ==
1759                 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1760                                                       &peer->hashPubKey,
1761                                                       pr));
1762   destroy_pending_request (pr);
1763   return GNUNET_YES;
1764 }
1765
1766
1767 /**
1768  * Method called whenever a peer disconnects.
1769  *
1770  * @param cls closure, not used
1771  * @param peer peer identity this notification is about
1772  */
1773 static void
1774 peer_disconnect_handler (void *cls,
1775                          const struct
1776                          GNUNET_PeerIdentity * peer)
1777 {
1778   struct ConnectedPeer *cp;
1779   struct PendingMessage *pm;
1780   unsigned int i;
1781   struct MigrationReadyBlock *pos;
1782   struct MigrationReadyBlock *next;
1783
1784   GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1785                                               &peer->hashPubKey,
1786                                               &destroy_request,
1787                                               (void*) peer);
1788   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1789                                           &peer->hashPubKey);
1790   if (cp == NULL)
1791     return;
1792   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1793     {
1794       if (NULL != cp->last_client_replies[i])
1795         {
1796           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1797           cp->last_client_replies[i] = NULL;
1798         }
1799     }
1800   GNUNET_break (GNUNET_YES ==
1801                 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1802                                                       &peer->hashPubKey,
1803                                                       cp));
1804   /* remove this peer from migration considerations; schedule
1805      alternatives */
1806   next = mig_head;
1807   while (NULL != (pos = next))
1808     {
1809       next = pos->next;
1810       for (i=0;i<MIGRATION_LIST_SIZE;i++)
1811         {
1812           if (pos->target_list[i] == cp->pid)
1813             {
1814               GNUNET_PEER_change_rc (pos->target_list[i], -1);
1815               pos->target_list[i] = 0;
1816             }
1817          }
1818       if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1819         {
1820           delete_migration_block (pos);
1821           consider_migration_gathering ();
1822           continue;
1823         }
1824       GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1825                                              &consider_migration,
1826                                              pos);
1827     }
1828   GNUNET_PEER_change_rc (cp->pid, -1);
1829   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1830   if (NULL != cp->cth)
1831     {
1832       GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1833       cp->cth = NULL;
1834     }
1835   if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1836     {
1837       GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1838       cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1839     }
1840   while (NULL != (pm = cp->pending_messages_head))
1841     destroy_pending_message (pm, 0 /* delivery failed */);
1842   GNUNET_LOAD_value_free (cp->transmission_delay);
1843   GNUNET_break (0 == cp->pending_requests);
1844   GNUNET_free (cp);
1845 }
1846
1847
1848 /**
1849  * Iterator over hash map entries that removes all occurences
1850  * of the given 'client' from the 'last_client_replies' of the
1851  * given connected peer.
1852  *
1853  * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1854  * @param key current key code (unused)
1855  * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1856  * @return GNUNET_YES (we should continue to iterate)
1857  */
1858 static int
1859 remove_client_from_last_client_replies (void *cls,
1860                                         const GNUNET_HashCode * key,
1861                                         void *value)
1862 {
1863   struct GNUNET_SERVER_Client *client = cls;
1864   struct ConnectedPeer *cp = value;
1865   unsigned int i;
1866
1867   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1868     {
1869       if (cp->last_client_replies[i] == client)
1870         {
1871           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1872           cp->last_client_replies[i] = NULL;
1873         }
1874     }  
1875   return GNUNET_YES;
1876 }
1877
1878
1879 /**
1880  * A client disconnected.  Remove all of its pending queries.
1881  *
1882  * @param cls closure, NULL
1883  * @param client identification of the client
1884  */
1885 static void
1886 handle_client_disconnect (void *cls,
1887                           struct GNUNET_SERVER_Client
1888                           * client)
1889 {
1890   struct ClientList *pos;
1891   struct ClientList *prev;
1892   struct ClientRequestList *rcl;
1893   struct ClientResponseMessage *creply;
1894
1895   if (client == NULL)
1896     return;
1897   prev = NULL;
1898   pos = client_list;
1899   while ( (NULL != pos) &&
1900           (pos->client != client) )
1901     {
1902       prev = pos;
1903       pos = pos->next;
1904     }
1905   if (pos == NULL)
1906     return; /* no requests pending for this client */
1907   while (NULL != (rcl = pos->rl_head))
1908     {
1909       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1910                   "Destroying pending request `%s' on disconnect\n",
1911                   GNUNET_h2s (&rcl->req->query));
1912       destroy_pending_request (rcl->req);
1913     }
1914   if (prev == NULL)
1915     client_list = pos->next;
1916   else
1917     prev->next = pos->next;
1918   if (pos->th != NULL)
1919     {
1920       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1921       pos->th = NULL;
1922     }
1923   while (NULL != (creply = pos->res_head))
1924     {
1925       GNUNET_CONTAINER_DLL_remove (pos->res_head,
1926                                    pos->res_tail,
1927                                    creply);
1928       GNUNET_free (creply);
1929     }    
1930   GNUNET_SERVER_client_drop (pos->client);
1931   GNUNET_free (pos);
1932   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1933                                          &remove_client_from_last_client_replies,
1934                                          client);
1935 }
1936
1937
1938 /**
1939  * Iterator to free peer entries.
1940  *
1941  * @param cls closure, unused
1942  * @param key current key code
1943  * @param value value in the hash map (peer entry)
1944  * @return GNUNET_YES (we should continue to iterate)
1945  */
1946 static int 
1947 clean_peer (void *cls,
1948             const GNUNET_HashCode * key,
1949             void *value)
1950 {
1951   peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1952   return GNUNET_YES;
1953 }
1954
1955
1956 /**
1957  * Task run during shutdown.
1958  *
1959  * @param cls unused
1960  * @param tc unused
1961  */
1962 static void
1963 shutdown_task (void *cls,
1964                const struct GNUNET_SCHEDULER_TaskContext *tc)
1965 {
1966   if (mig_qe != NULL)
1967     {
1968       GNUNET_DATASTORE_cancel (mig_qe);
1969       mig_qe = NULL;
1970     }
1971   if (dht_qe != NULL)
1972     {
1973       GNUNET_DATASTORE_cancel (dht_qe);
1974       dht_qe = NULL;
1975     }
1976   if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1977     {
1978       GNUNET_SCHEDULER_cancel (mig_task);
1979       mig_task = GNUNET_SCHEDULER_NO_TASK;
1980     }
1981   if (GNUNET_SCHEDULER_NO_TASK != dht_task)
1982     {
1983       GNUNET_SCHEDULER_cancel (dht_task);
1984       dht_task = GNUNET_SCHEDULER_NO_TASK;
1985     }
1986   while (client_list != NULL)
1987     handle_client_disconnect (NULL,
1988                               client_list->client);
1989   cron_flush_trust (NULL, NULL);
1990   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1991                                          &clean_peer,
1992                                          NULL);
1993   GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1994   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1995   requests_by_expiration_heap = 0;
1996   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1997   connected_peers = NULL;
1998   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1999   GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2000   query_request_map = NULL;
2001   GNUNET_LOAD_value_free (rt_entry_lifetime);
2002   rt_entry_lifetime = NULL;
2003   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2004   GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2005   peer_request_map = NULL;
2006   GNUNET_assert (NULL != core);
2007   GNUNET_CORE_disconnect (core);
2008   core = NULL;
2009   if (stats != NULL)
2010     {
2011       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2012       stats = NULL;
2013     }
2014   if (dsh != NULL)
2015     {
2016       GNUNET_DATASTORE_disconnect (dsh,
2017                                    GNUNET_NO);
2018       dsh = NULL;
2019     }
2020   while (mig_head != NULL)
2021     delete_migration_block (mig_head);
2022   GNUNET_assert (0 == mig_size);
2023   GNUNET_DHT_disconnect (dht_handle);
2024   dht_handle = NULL;
2025   GNUNET_LOAD_value_free (datastore_get_load);
2026   datastore_get_load = NULL;
2027   GNUNET_LOAD_value_free (datastore_put_load);
2028   datastore_put_load = NULL;
2029   GNUNET_BLOCK_context_destroy (block_ctx);
2030   block_ctx = NULL;
2031   GNUNET_CONFIGURATION_destroy (block_cfg);
2032   block_cfg = NULL;
2033   cfg = NULL;  
2034   GNUNET_free_non_null (trustDirectory);
2035   trustDirectory = NULL;
2036 }
2037
2038
2039 /* ******************* Utility functions  ******************** */
2040
2041
2042 /**
2043  * We've had to delay a request for transmission to core, but now
2044  * we should be ready.  Run it.
2045  *
2046  * @param cls the 'struct ConnectedPeer' for which a request was delayed
2047  * @param tc task context (unused)
2048  */
2049 static void
2050 delayed_transmission_request (void *cls,
2051                               const struct GNUNET_SCHEDULER_TaskContext *tc)
2052 {
2053   struct ConnectedPeer *cp = cls;
2054   struct GNUNET_PeerIdentity pid;
2055   struct PendingMessage *pm;
2056
2057   pm = cp->pending_messages_head;
2058   cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2059   GNUNET_assert (cp->cth == NULL);
2060   if (pm == NULL)
2061     return;
2062   GNUNET_PEER_resolve (cp->pid,
2063                        &pid);
2064   cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2065   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2066                                                pm->priority,
2067                                                GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2068                                                &pid,
2069                                                pm->msize,
2070                                                &transmit_to_peer,
2071                                                cp);
2072 }
2073
2074
2075 /**
2076  * Transmit messages by copying it to the target buffer
2077  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
2078  * for writing in the meantime.  In that case, do nothing
2079  * (the disconnect or shutdown handler will take care of the rest).
2080  * If we were able to transmit messages and there are still more
2081  * pending, ask core again for further calls to this function.
2082  *
2083  * @param cls closure, pointer to the 'struct ConnectedPeer*'
2084  * @param size number of bytes available in buf
2085  * @param buf where the callee should write the message
2086  * @return number of bytes written to buf
2087  */
2088 static size_t
2089 transmit_to_peer (void *cls,
2090                   size_t size, void *buf)
2091 {
2092   struct ConnectedPeer *cp = cls;
2093   char *cbuf = buf;
2094   struct PendingMessage *pm;
2095   struct PendingMessage *next_pm;
2096   struct GNUNET_TIME_Absolute now;
2097   struct GNUNET_TIME_Relative min_delay;
2098   struct MigrationReadyBlock *mb;
2099   struct MigrationReadyBlock *next;
2100   struct PutMessage migm;
2101   size_t msize;
2102   unsigned int i;
2103   struct GNUNET_PeerIdentity pid;
2104  
2105   cp->cth = NULL;
2106   if (NULL == buf)
2107     {
2108 #if DEBUG_FS
2109       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110                   "Dropping message, core too busy.\n");
2111 #endif
2112       GNUNET_LOAD_update (cp->transmission_delay,
2113                           UINT64_MAX);
2114       return 0;
2115     }  
2116   GNUNET_LOAD_update (cp->transmission_delay,
2117                       GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2118   now = GNUNET_TIME_absolute_get ();
2119   msize = 0;
2120   min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2121   next_pm = cp->pending_messages_head;
2122   while ( (NULL != (pm = next_pm) ) &&
2123           (pm->msize <= size) )
2124     {
2125       next_pm = pm->next;
2126       if (pm->delay_until.abs_value > now.abs_value)
2127         {
2128           min_delay = GNUNET_TIME_relative_min (min_delay,
2129                                                 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2130           continue;
2131         }
2132       memcpy (&cbuf[msize], &pm[1], pm->msize);
2133       msize += pm->msize;
2134       size -= pm->msize;
2135       if (NULL == pm->pml)
2136         {
2137           GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2138                                        cp->pending_messages_tail,
2139                                        pm);
2140           cp->pending_requests--;
2141         }
2142       destroy_pending_message (pm, cp->pid);
2143     }
2144   if (pm != NULL)
2145     min_delay = GNUNET_TIME_UNIT_ZERO;
2146   if (NULL != cp->pending_messages_head)
2147     {     
2148       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2149       cp->delayed_transmission_request_task
2150         = GNUNET_SCHEDULER_add_delayed (min_delay,
2151                                         &delayed_transmission_request,
2152                                         cp);
2153     }
2154   if (pm == NULL)
2155     {      
2156       GNUNET_PEER_resolve (cp->pid,
2157                            &pid);
2158       next = mig_head;
2159       while (NULL != (mb = next))
2160         {
2161           next = mb->next;
2162           for (i=0;i<MIGRATION_LIST_SIZE;i++)
2163             {
2164               if ( (cp->pid == mb->target_list[i]) &&
2165                    (mb->size + sizeof (migm) <= size) )
2166                 {
2167                   GNUNET_PEER_change_rc (mb->target_list[i], -1);
2168                   mb->target_list[i] = 0;
2169                   mb->used_targets++;
2170                   memset (&migm, 0, sizeof (migm));
2171                   migm.header.size = htons (sizeof (migm) + mb->size);
2172                   migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2173                   migm.type = htonl (mb->type);
2174                   migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2175                   memcpy (&cbuf[msize], &migm, sizeof (migm));
2176                   msize += sizeof (migm);
2177                   size -= sizeof (migm);
2178                   memcpy (&cbuf[msize], &mb[1], mb->size);
2179                   msize += mb->size;
2180                   size -= mb->size;
2181 #if DEBUG_FS
2182                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2183                               "Pushing migration block `%s' (%u bytes) to `%s'\n",
2184                               GNUNET_h2s (&mb->query),
2185                               (unsigned int) mb->size,
2186                               GNUNET_i2s (&pid));
2187 #endif    
2188                   break;
2189                 }
2190               else
2191                 {
2192 #if DEBUG_FS
2193                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194                               "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2195                               GNUNET_h2s (&mb->query),
2196                               (unsigned int) mb->size,
2197                               GNUNET_i2s (&pid));
2198 #endif    
2199                 }
2200             }
2201           if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2202                (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2203             {
2204               delete_migration_block (mb);
2205               consider_migration_gathering ();
2206             }
2207         }
2208       consider_migration (NULL, 
2209                           &pid.hashPubKey,
2210                           cp);
2211     }
2212 #if DEBUG_FS
2213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2214               "Transmitting %u bytes to peer with PID %u\n",
2215               (unsigned int) msize,
2216               (unsigned int) cp->pid);
2217 #endif
2218   return msize;
2219 }
2220
2221
2222 /**
2223  * Add a message to the set of pending messages for the given peer.
2224  *
2225  * @param cp peer to send message to
2226  * @param pm message to queue
2227  * @param pr request on which behalf this message is being queued
2228  */
2229 static void
2230 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2231                                   struct PendingMessage *pm,
2232                                   struct PendingRequest *pr)
2233 {
2234   struct PendingMessage *pos;
2235   struct PendingMessageList *pml;
2236   struct GNUNET_PeerIdentity pid;
2237
2238   GNUNET_assert (pm->next == NULL);
2239   GNUNET_assert (pm->pml == NULL);    
2240   if (pr != NULL)
2241     {
2242       pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2243       pml->req = pr;
2244       pml->target = cp;
2245       pml->pm = pm;
2246       pm->pml = pml;  
2247       GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2248                                    pr->pending_tail,
2249                                    pml);
2250     }
2251   pos = cp->pending_messages_head;
2252   while ( (pos != NULL) &&
2253           (pm->priority < pos->priority) )
2254     pos = pos->next;    
2255   GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2256                                      cp->pending_messages_tail,
2257                                      pos,
2258                                      pm);
2259   cp->pending_requests++;
2260   if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2261     {
2262       GNUNET_STATISTICS_update (stats,
2263                                 gettext_noop ("# P2P searches discarded (queue length bound)"),
2264                                 1,
2265                                 GNUNET_NO);
2266       destroy_pending_message (cp->pending_messages_tail, 0);  
2267     }
2268   GNUNET_PEER_resolve (cp->pid, &pid);
2269   if (NULL != cp->cth)
2270     {
2271       GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2272       cp->cth = NULL;
2273     }
2274   if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2275     {
2276       GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2277       cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2278     }
2279   /* need to schedule transmission */
2280   cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2281   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2282                                                cp->pending_messages_head->priority,
2283                                                MAX_TRANSMIT_DELAY,
2284                                                &pid,
2285                                                cp->pending_messages_head->msize,
2286                                                &transmit_to_peer,
2287                                                cp);
2288   if (cp->cth == NULL)
2289     {
2290 #if DEBUG_FS
2291       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292                   "Failed to schedule transmission with core!\n");
2293 #endif
2294       GNUNET_STATISTICS_update (stats,
2295                                 gettext_noop ("# CORE transmission failures"),
2296                                 1,
2297                                 GNUNET_NO);
2298     }
2299 }
2300
2301
2302 /**
2303  * Test if the DATABASE (GET) load on this peer is too high
2304  * to even consider processing the query at
2305  * all.  
2306  * 
2307  * @return GNUNET_YES if the load is too high to do anything (load high)
2308  *         GNUNET_NO to process normally (load normal)
2309  *         GNUNET_SYSERR to process for free (load low)
2310  */
2311 static int
2312 test_get_load_too_high (uint32_t priority)
2313 {
2314   double ld;
2315
2316   ld = GNUNET_LOAD_get_load (datastore_get_load);
2317   if (ld < 1)
2318     return GNUNET_SYSERR;    
2319   if (ld <= priority)    
2320     return GNUNET_NO;    
2321   return GNUNET_YES;
2322 }
2323
2324
2325
2326
2327 /**
2328  * Test if the DATABASE (PUT) load on this peer is too high
2329  * to even consider processing the query at
2330  * all.  
2331  * 
2332  * @return GNUNET_YES if the load is too high to do anything (load high)
2333  *         GNUNET_NO to process normally (load normal or low)
2334  */
2335 static int
2336 test_put_load_too_high (uint32_t priority)
2337 {
2338   double ld;
2339
2340   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2341     return GNUNET_NO; /* very fast */
2342   ld = GNUNET_LOAD_get_load (datastore_put_load);
2343   if (ld < 2.0 * (1 + priority))
2344     return GNUNET_NO;
2345   GNUNET_STATISTICS_update (stats,
2346                             gettext_noop ("# storage requests dropped due to high load"),
2347                             1,
2348                             GNUNET_NO);
2349   return GNUNET_YES;
2350 }
2351
2352
2353 /* ******************* Pending Request Refresh Task ******************** */
2354
2355
2356
2357 /**
2358  * We use a random delay to make the timing of requests less
2359  * predictable.  This function returns such a random delay.  We add a base
2360  * delay of MAX_CORK_DELAY (1s).
2361  *
2362  * FIXME: make schedule dependent on the specifics of the request?
2363  * Or bandwidth and number of connected peers and load?
2364  *
2365  * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2366  */
2367 static struct GNUNET_TIME_Relative
2368 get_processing_delay ()
2369 {
2370   return 
2371     GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2372                               GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2373                                                              GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2374                                                                                        TTL_DECREMENT)));
2375 }
2376
2377
2378 /**
2379  * We're processing a GET request from another peer and have decided
2380  * to forward it to other peers.  This function is called periodically
2381  * and should forward the request to other peers until we have all
2382  * possible replies.  If we have transmitted the *only* reply to
2383  * the initiator we should destroy the pending request.  If we have
2384  * many replies in the queue to the initiator, we should delay sending
2385  * out more queries until the reply queue has shrunk some.
2386  *
2387  * @param cls our "struct ProcessGetContext *"
2388  * @param tc unused
2389  */
2390 static void
2391 forward_request_task (void *cls,
2392                       const struct GNUNET_SCHEDULER_TaskContext *tc);
2393
2394
2395 /**
2396  * Function called after we either failed or succeeded
2397  * at transmitting a query to a peer.  
2398  *
2399  * @param cls the requests "struct PendingRequest*"
2400  * @param tpid ID of receiving peer, 0 on transmission error
2401  */
2402 static void
2403 transmit_query_continuation (void *cls,
2404                              GNUNET_PEER_Id tpid)
2405 {
2406   struct PendingRequest *pr = cls;
2407   unsigned int i;
2408
2409   GNUNET_STATISTICS_update (stats,
2410                             gettext_noop ("# queries scheduled for forwarding"),
2411                             -1,
2412                             GNUNET_NO);
2413   if (tpid == 0)   
2414     {
2415 #if DEBUG_FS
2416       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2417                   "Transmission of request failed, will try again later.\n");
2418 #endif
2419       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2420         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2421                                                  &forward_request_task,
2422                                                  pr); 
2423       return;    
2424     }
2425 #if DEBUG_FS
2426   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2427               "Transmitted query `%s'\n",
2428               GNUNET_h2s (&pr->query));
2429 #endif
2430   GNUNET_STATISTICS_update (stats,
2431                             gettext_noop ("# queries forwarded"),
2432                             1,
2433                             GNUNET_NO);
2434   for (i=0;i<pr->used_targets_off;i++)
2435     if (pr->used_targets[i].pid == tpid)
2436       break; /* found match! */    
2437   if (i == pr->used_targets_off)
2438     {
2439       /* need to create new entry */
2440       if (pr->used_targets_off == pr->used_targets_size)
2441         GNUNET_array_grow (pr->used_targets,
2442                            pr->used_targets_size,
2443                            pr->used_targets_size * 2 + 2);
2444       GNUNET_PEER_change_rc (tpid, 1);
2445       pr->used_targets[pr->used_targets_off].pid = tpid;
2446       pr->used_targets[pr->used_targets_off].num_requests = 0;
2447       i = pr->used_targets_off++;
2448     }
2449   pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2450   pr->used_targets[i].num_requests++;
2451   if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2452     pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2453                                              &forward_request_task,
2454                                              pr);
2455 }
2456
2457
2458 /**
2459  * How many bytes should a bloomfilter be if we have already seen
2460  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
2461  * of bits set per entry.  Furthermore, we should not re-size the
2462  * filter too often (to keep it cheap).
2463  *
2464  * Since other peers will also add entries but not resize the filter,
2465  * we should generally pick a slightly larger size than what the
2466  * strict math would suggest.
2467  *
2468  * @return must be a power of two and smaller or equal to 2^15.
2469  */
2470 static size_t
2471 compute_bloomfilter_size (unsigned int entry_count)
2472 {
2473   size_t size;
2474   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2475   uint16_t max = 1 << 15;
2476
2477   if (entry_count > max)
2478     return max;
2479   size = 8;
2480   while ((size < max) && (size < ideal))
2481     size *= 2;
2482   if (size > max)
2483     return max;
2484   return size;
2485 }
2486
2487
2488 /**
2489  * Recalculate our bloom filter for filtering replies.  This function
2490  * will create a new bloom filter from scratch, so it should only be
2491  * called if we have no bloomfilter at all (and hence can create a
2492  * fresh one of minimal size without problems) OR if our peer is the
2493  * initiator (in which case we may resize to larger than mimimum size).
2494  *
2495  * @param pr request for which the BF is to be recomputed
2496  */
2497 static void
2498 refresh_bloomfilter (struct PendingRequest *pr)
2499 {
2500   unsigned int i;
2501   size_t nsize;
2502   GNUNET_HashCode mhash;
2503
2504   nsize = compute_bloomfilter_size (pr->replies_seen_off);
2505   if (nsize == pr->bf_size)
2506     return; /* size not changed */
2507   if (pr->bf != NULL)
2508     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2509   pr->bf_size = nsize;
2510   pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2511   pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
2512                                               pr->bf_size,
2513                                               BLOOMFILTER_K);
2514   for (i=0;i<pr->replies_seen_off;i++)
2515     {
2516       GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2517                                 pr->mingle,
2518                                 &mhash);
2519       GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2520     }
2521 }
2522
2523
2524 /**
2525  * Function called after we've tried to reserve a certain amount of
2526  * bandwidth for a reply.  Check if we succeeded and if so send our
2527  * query.
2528  *
2529  * @param cls the requests "struct PendingRequest*"
2530  * @param peer identifies the peer
2531  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
2532  * @param bpm_out set to the current bandwidth limit (sending) for this peer
2533  * @param amount set to the amount that was actually reserved or unreserved
2534  * @param preference current traffic preference for the given peer
2535  */
2536 static void
2537 target_reservation_cb (void *cls,
2538                        const struct
2539                        GNUNET_PeerIdentity * peer,
2540                        struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
2541                        struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2542                        int amount,
2543                        uint64_t preference)
2544 {
2545   struct PendingRequest *pr = cls;
2546   struct ConnectedPeer *cp;
2547   struct PendingMessage *pm;
2548   struct GetMessage *gm;
2549   GNUNET_HashCode *ext;
2550   char *bfdata;
2551   size_t msize;
2552   unsigned int k;
2553   int no_route;
2554   uint32_t bm;
2555   unsigned int i;
2556
2557   pr->irc = NULL;
2558   if (peer == NULL)
2559     {
2560       /* error in communication with core, try again later */
2561       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2562         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2563                                                  &forward_request_task,
2564                                                  pr);
2565       return;
2566     }
2567   /* (3) transmit, update ttl/priority */
2568   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2569                                           &peer->hashPubKey);
2570   if (cp == NULL)
2571     {
2572       /* Peer must have just left */
2573 #if DEBUG_FS
2574       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2575                   "Selected peer disconnected!\n");
2576 #endif
2577       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2578         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2579                                                  &forward_request_task,
2580                                                  pr);
2581       return;
2582     }
2583   no_route = GNUNET_NO;
2584   if (amount == 0)
2585     {
2586       if (pr->cp == NULL)
2587         {
2588 #if DEBUG_FS > 1
2589           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2590                       "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2591                       amount,
2592                       DBLOCK_SIZE);
2593 #endif
2594           GNUNET_STATISTICS_update (stats,
2595                                     gettext_noop ("# reply bandwidth reservation requests failed"),
2596                                     1,
2597                                     GNUNET_NO);
2598           if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2599             pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2600                                                      &forward_request_task,
2601                                                      pr);
2602           return;  /* this target round failed */
2603         }
2604       no_route = GNUNET_YES;
2605     }
2606   
2607   GNUNET_STATISTICS_update (stats,
2608                             gettext_noop ("# queries scheduled for forwarding"),
2609                             1,
2610                             GNUNET_NO);
2611   for (i=0;i<pr->used_targets_off;i++)
2612     if (pr->used_targets[i].pid == cp->pid) 
2613       {
2614         GNUNET_STATISTICS_update (stats,
2615                                   gettext_noop ("# queries retransmitted to same target"),
2616                                   1,
2617                                   GNUNET_NO);
2618         break;
2619       } 
2620
2621   /* build message and insert message into priority queue */
2622 #if DEBUG_FS
2623   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624               "Forwarding request `%s' to `%4s'!\n",
2625               GNUNET_h2s (&pr->query),
2626               GNUNET_i2s (peer));
2627 #endif
2628   k = 0;
2629   bm = 0;
2630   if (GNUNET_YES == no_route)
2631     {
2632       bm |= GET_MESSAGE_BIT_RETURN_TO;
2633       k++;      
2634     }
2635   if (pr->namespace != NULL)
2636     {
2637       bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2638       k++;
2639     }
2640   if (pr->target_pid != 0)
2641     {
2642       bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2643       k++;
2644     }
2645   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2646   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2647   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2648   pm->msize = msize;
2649   gm = (struct GetMessage*) &pm[1];
2650   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2651   gm->header.size = htons (msize);
2652   gm->type = htonl (pr->type);
2653   pr->remaining_priority /= 2;
2654   gm->priority = htonl (pr->remaining_priority);
2655   gm->ttl = htonl (pr->ttl);
2656   gm->filter_mutator = htonl(pr->mingle); 
2657   gm->hash_bitmap = htonl (bm);
2658   gm->query = pr->query;
2659   ext = (GNUNET_HashCode*) &gm[1];
2660   k = 0;
2661   if (GNUNET_YES == no_route)
2662     GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2663   if (pr->namespace != NULL)
2664     memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2665   if (pr->target_pid != 0)
2666     GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2667   bfdata = (char *) &ext[k];
2668   if (pr->bf != NULL)
2669     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2670                                                bfdata,
2671                                                pr->bf_size);
2672   pm->cont = &transmit_query_continuation;
2673   pm->cont_cls = pr;
2674   cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2675   add_to_pending_messages_for_peer (cp, pm, pr);
2676 }
2677
2678
2679 /**
2680  * Closure used for "target_peer_select_cb".
2681  */
2682 struct PeerSelectionContext 
2683 {
2684   /**
2685    * The request for which we are selecting
2686    * peers.
2687    */
2688   struct PendingRequest *pr;
2689
2690   /**
2691    * Current "prime" target.
2692    */
2693   struct GNUNET_PeerIdentity target;
2694
2695   /**
2696    * How much do we like this target?
2697    */
2698   double target_score;
2699
2700 };
2701
2702
2703 /**
2704  * Function called for each connected peer to determine
2705  * which one(s) would make good targets for forwarding.
2706  *
2707  * @param cls closure (struct PeerSelectionContext)
2708  * @param key current key code (peer identity)
2709  * @param value value in the hash map (struct ConnectedPeer)
2710  * @return GNUNET_YES if we should continue to
2711  *         iterate,
2712  *         GNUNET_NO if not.
2713  */
2714 static int
2715 target_peer_select_cb (void *cls,
2716                        const GNUNET_HashCode * key,
2717                        void *value)
2718 {
2719   struct PeerSelectionContext *psc = cls;
2720   struct ConnectedPeer *cp = value;
2721   struct PendingRequest *pr = psc->pr;
2722   struct GNUNET_TIME_Relative delay;
2723   double score;
2724   unsigned int i;
2725   unsigned int pc;
2726
2727   /* 1) check that this peer is not the initiator */
2728   if (cp == pr->cp)
2729     {
2730 #if DEBUG_FS
2731       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732                   "Skipping initiator in forwarding selection\n");
2733 #endif
2734       return GNUNET_YES; /* skip */        
2735     }
2736
2737   /* 2) check if we have already (recently) forwarded to this peer */
2738   /* 2a) this particular request */
2739   pc = 0;
2740   for (i=0;i<pr->used_targets_off;i++)
2741     if (pr->used_targets[i].pid == cp->pid) 
2742       {
2743         pc = pr->used_targets[i].num_requests;
2744         GNUNET_assert (pc > 0);
2745         if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2746                                            RETRY_PROBABILITY_INV * pc))
2747           {
2748 #if DEBUG_FS
2749             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750                         "NOT re-trying query that was previously transmitted %u times\n",
2751                         (unsigned int) pc);
2752 #endif
2753             return GNUNET_YES; /* skip */
2754           }
2755         break;
2756       }
2757 #if DEBUG_FS
2758   if (0 < pc)
2759     {
2760       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2761                   "Re-trying query that was previously transmitted %u times to this peer\n",
2762                   (unsigned int) pc);
2763     }
2764 #endif
2765   /* 2b) many other requests to this peer */
2766   delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2767   if (delay.rel_value <= cp->avg_delay.rel_value)
2768     {
2769 #if DEBUG_FS
2770       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771                   "NOT sending query since we send %u others to this peer in the last %llums\n",
2772                   MAX_QUEUE_PER_PEER,
2773                   cp->avg_delay.rel_value);
2774 #endif
2775       return GNUNET_YES; /* skip */      
2776     }
2777
2778   /* 3) calculate how much we'd like to forward to this peer,
2779      starting with a random value that is strong enough
2780      to at least give any peer a chance sometimes 
2781      (compared to the other factors that come later) */
2782   /* 3a) count successful (recent) routes from cp for same source */
2783   if (pr->cp != NULL)
2784     {
2785       score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2786                                         P2P_SUCCESS_LIST_SIZE);
2787       for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2788         if (cp->last_p2p_replies[i] == pr->cp->pid)
2789           score += 1.0; /* likely successful based on hot path */
2790     }
2791   else
2792     {
2793       score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2794                                         CS2P_SUCCESS_LIST_SIZE);
2795       for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2796         if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2797           score += 1.0; /* likely successful based on hot path */
2798     }
2799   /* 3b) include latency */
2800   if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2801     score += 1.0; /* likely fast based on latency */
2802   /* 3c) include priorities */
2803   if (cp->avg_priority <= pr->remaining_priority / 2.0)
2804     score += 1.0; /* likely successful based on priorities */
2805   /* 3d) penalize for queue size */  
2806   score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER); 
2807   /* 3e) include peer proximity */
2808   score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2809                                                     &pr->query)) / (double) UINT32_MAX);
2810   /* 4) super-bonus for being the known target */
2811   if (pr->target_pid == cp->pid)
2812     score += 100.0;
2813   /* store best-fit in closure */
2814 #if DEBUG_FS
2815   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2816               "Peer `%s' gets score %f for forwarding query, max is %f\n",
2817               GNUNET_h2s (key),
2818               score,
2819               psc->target_score);
2820 #endif  
2821   score++; /* avoid zero */
2822   if (score > psc->target_score)
2823     {
2824       psc->target_score = score;
2825       psc->target.hashPubKey = *key; 
2826     }
2827   return GNUNET_YES;
2828 }
2829   
2830
2831 /**
2832  * The priority level imposes a bound on the maximum
2833  * value for the ttl that can be requested.
2834  *
2835  * @param ttl_in requested ttl
2836  * @param prio given priority
2837  * @return ttl_in if ttl_in is below the limit,
2838  *         otherwise the ttl-limit for the given priority
2839  */
2840 static int32_t
2841 bound_ttl (int32_t ttl_in, uint32_t prio)
2842 {
2843   unsigned long long allowed;
2844
2845   if (ttl_in <= 0)
2846     return ttl_in;
2847   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2848   if (ttl_in > allowed)      
2849     {
2850       if (allowed >= (1 << 30))
2851         return 1 << 30;
2852       return allowed;
2853     }
2854   return ttl_in;
2855 }
2856
2857
2858 /**
2859  * Iterator called on each result obtained for a DHT
2860  * operation that expects a reply
2861  *
2862  * @param cls closure
2863  * @param exp when will this value expire
2864  * @param key key of the result
2865  * @param get_path NULL-terminated array of pointers
2866  *                 to the peers on reverse GET path (or NULL if not recorded)
2867  * @param put_path NULL-terminated array of pointers
2868  *                 to the peers on the PUT path (or NULL if not recorded)
2869  * @param type type of the result
2870  * @param size number of bytes in data
2871  * @param data pointer to the result data
2872  */
2873 static void
2874 process_dht_reply (void *cls,
2875                    struct GNUNET_TIME_Absolute exp,
2876                    const GNUNET_HashCode * key,
2877                    const struct GNUNET_PeerIdentity * const *get_path,
2878                    const struct GNUNET_PeerIdentity * const *put_path,
2879                    enum GNUNET_BLOCK_Type type,
2880                    size_t size,
2881                    const void *data);
2882
2883
2884 /**
2885  * We're processing a GET request and have decided
2886  * to forward it to other peers.  This function is called periodically
2887  * and should forward the request to other peers until we have all
2888  * possible replies.  If we have transmitted the *only* reply to
2889  * the initiator we should destroy the pending request.  If we have
2890  * many replies in the queue to the initiator, we should delay sending
2891  * out more queries until the reply queue has shrunk some.
2892  *
2893  * @param cls our "struct ProcessGetContext *"
2894  * @param tc unused
2895  */
2896 static void
2897 forward_request_task (void *cls,
2898                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2899 {
2900   struct PendingRequest *pr = cls;
2901   struct PeerSelectionContext psc;
2902   struct ConnectedPeer *cp; 
2903   struct GNUNET_TIME_Relative delay;
2904
2905   pr->task = GNUNET_SCHEDULER_NO_TASK;
2906   if (pr->irc != NULL)
2907     {
2908 #if DEBUG_FS
2909       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2910                   "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2911                   GNUNET_h2s (&pr->query));
2912 #endif
2913       return; /* already pending */
2914     }
2915   if (GNUNET_YES == pr->local_only)
2916     return; /* configured to not do P2P search */
2917   /* (0) try DHT */
2918   if ( (0 == pr->anonymity_level) &&
2919        (GNUNET_YES != pr->forward_only) &&
2920        (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
2921        (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
2922     {
2923       pr->dht_get = GNUNET_DHT_get_start (dht_handle,
2924                                           GNUNET_TIME_UNIT_FOREVER_REL,
2925                                           pr->type,
2926                                           &pr->query,
2927                                           GNUNET_DHT_RO_NONE,
2928                                           pr->bf,
2929                                           pr->mingle,
2930                                           pr->namespace,
2931                                           (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
2932                                           &process_dht_reply,
2933                                           pr);
2934     }
2935   /* (1) select target */
2936   psc.pr = pr;
2937   psc.target_score = -DBL_MAX;
2938   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2939                                          &target_peer_select_cb,
2940                                          &psc);  
2941   if (psc.target_score == -DBL_MAX)
2942     {
2943       delay = get_processing_delay ();
2944 #if DEBUG_FS 
2945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2946                   "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2947                   GNUNET_h2s (&pr->query),
2948                   delay.rel_value);
2949 #endif
2950       pr->task = GNUNET_SCHEDULER_add_delayed (delay,
2951                                                &forward_request_task,
2952                                                pr);
2953       return; /* nobody selected */
2954     }
2955   /* (3) update TTL/priority */
2956   if (pr->client_request_list != NULL)
2957     {
2958       /* FIXME: use better algorithm!? */
2959       if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2960                                          4))
2961         pr->priority++;
2962       /* bound priority we use by priorities we see from other peers
2963          rounded up (must round up so that we can see non-zero
2964          priorities, but round up as little as possible to make it
2965          plausible that we forwarded another peers request) */
2966       if (pr->priority > current_priorities + 1.0)
2967         pr->priority = (uint32_t) current_priorities + 1.0;
2968       pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2969                            pr->priority);
2970 #if DEBUG_FS
2971       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2972                   "Trying query `%s' with priority %u and TTL %d.\n",
2973                   GNUNET_h2s (&pr->query),
2974                   pr->priority,
2975                   pr->ttl);
2976 #endif
2977     }
2978
2979   /* (3) reserve reply bandwidth */
2980   if (GNUNET_NO == pr->forward_only)
2981     {
2982       cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2983                                               &psc.target.hashPubKey);
2984       GNUNET_assert (NULL != cp);
2985       pr->irc = GNUNET_CORE_peer_change_preference (cfg,
2986                                                     &psc.target,
2987                                                     GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
2988                                                     GNUNET_BANDWIDTH_value_init (UINT32_MAX),
2989                                                     DBLOCK_SIZE * 2, 
2990                                                     cp->inc_preference,
2991                                                     &target_reservation_cb,
2992                                                     pr);
2993       cp->inc_preference = 0;
2994     }
2995   else
2996     {
2997       /* force forwarding */
2998       static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
2999       target_reservation_cb (pr, &psc.target,
3000                              zerobw, zerobw, 0, 0.0);
3001     }
3002 }
3003
3004
3005 /* **************************** P2P PUT Handling ************************ */
3006
3007
3008 /**
3009  * Function called after we either failed or succeeded
3010  * at transmitting a reply to a peer.  
3011  *
3012  * @param cls the requests "struct PendingRequest*"
3013  * @param tpid ID of receiving peer, 0 on transmission error
3014  */
3015 static void
3016 transmit_reply_continuation (void *cls,
3017                              GNUNET_PEER_Id tpid)
3018 {
3019   struct PendingRequest *pr = cls;
3020   
3021   switch (pr->type)
3022     {
3023     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3024     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3025       /* only one reply expected, done with the request! */
3026       destroy_pending_request (pr);
3027       break;
3028     case GNUNET_BLOCK_TYPE_ANY:
3029     case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3030     case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3031       break;
3032     default:
3033       GNUNET_break (0);
3034       break;
3035     }
3036 }
3037
3038
3039 /**
3040  * Transmit the given message by copying it to the target buffer
3041  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
3042  * for writing in the meantime.  In that case, do nothing
3043  * (the disconnect or shutdown handler will take care of the rest).
3044  * If we were able to transmit messages and there are still more
3045  * pending, ask core again for further calls to this function.
3046  *
3047  * @param cls closure, pointer to the 'struct ClientList*'
3048  * @param size number of bytes available in buf
3049  * @param buf where the callee should write the message
3050  * @return number of bytes written to buf
3051  */
3052 static size_t
3053 transmit_to_client (void *cls,
3054                   size_t size, void *buf)
3055 {
3056   struct ClientList *cl = cls;
3057   char *cbuf = buf;
3058   struct ClientResponseMessage *creply;
3059   size_t msize;
3060   
3061   cl->th = NULL;
3062   if (NULL == buf)
3063     {
3064 #if DEBUG_FS
3065       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3066                   "Not sending reply, client communication problem.\n");
3067 #endif
3068       return 0;
3069     }
3070   msize = 0;
3071   while ( (NULL != (creply = cl->res_head) ) &&
3072           (creply->msize <= size) )
3073     {
3074       memcpy (&cbuf[msize], &creply[1], creply->msize);
3075       msize += creply->msize;
3076       size -= creply->msize;
3077       GNUNET_CONTAINER_DLL_remove (cl->res_head,
3078                                    cl->res_tail,
3079                                    creply);
3080       GNUNET_free (creply);
3081     }
3082   if (NULL != creply)
3083     cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3084                                                   creply->msize,
3085                                                   GNUNET_TIME_UNIT_FOREVER_REL,
3086                                                   &transmit_to_client,
3087                                                   cl);
3088 #if DEBUG_FS
3089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3090               "Transmitted %u bytes to client\n",
3091               (unsigned int) msize);
3092 #endif
3093   return msize;
3094 }
3095
3096
3097 /**
3098  * Closure for "process_reply" function.
3099  */
3100 struct ProcessReplyClosure
3101 {
3102   /**
3103    * The data for the reply.
3104    */
3105   const void *data;
3106
3107   /**
3108    * Who gave us this reply? NULL for local host (or DHT)
3109    */
3110   struct ConnectedPeer *sender;
3111
3112   /**
3113    * When the reply expires.
3114    */
3115   struct GNUNET_TIME_Absolute expiration;
3116
3117   /**
3118    * Size of data.
3119    */
3120   size_t size;
3121
3122   /**
3123    * Type of the block.
3124    */
3125   enum GNUNET_BLOCK_Type type;
3126
3127   /**
3128    * How much was this reply worth to us?
3129    */
3130   uint32_t priority;
3131
3132   /**
3133    * Evaluation result (returned).
3134    */
3135   enum GNUNET_BLOCK_EvaluationResult eval;
3136
3137   /**
3138    * Did we finish processing the associated request?
3139    */ 
3140   int finished;
3141
3142   /**
3143    * Did we find a matching request?
3144    */
3145   int request_found;
3146 };
3147
3148
3149 /**
3150  * We have received a reply; handle it!
3151  *
3152  * @param cls response (struct ProcessReplyClosure)
3153  * @param key our query
3154  * @param value value in the hash map (info about the query)
3155  * @return GNUNET_YES (we should continue to iterate)
3156  */
3157 static int
3158 process_reply (void *cls,
3159                const GNUNET_HashCode * key,
3160                void *value)
3161 {
3162   struct ProcessReplyClosure *prq = cls;
3163   struct PendingRequest *pr = value;
3164   struct PendingMessage *reply;
3165   struct ClientResponseMessage *creply;
3166   struct ClientList *cl;
3167   struct PutMessage *pm;
3168   struct ConnectedPeer *cp;
3169   struct GNUNET_TIME_Relative cur_delay;
3170 #if SUPPORT_DELAYS  
3171 struct GNUNET_TIME_Relative art_delay;
3172 #endif
3173   size_t msize;
3174   unsigned int i;
3175
3176 #if DEBUG_FS
3177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3178               "Matched result (type %u) for query `%s' with pending request\n",
3179               (unsigned int) prq->type,
3180               GNUNET_h2s (key));
3181 #endif  
3182   GNUNET_STATISTICS_update (stats,
3183                             gettext_noop ("# replies received and matched"),
3184                             1,
3185                             GNUNET_NO);
3186   if (prq->sender != NULL)
3187     {
3188       for (i=0;i<pr->used_targets_off;i++)
3189         if (pr->used_targets[i].pid == prq->sender->pid)
3190           break;
3191       if (i < pr->used_targets_off)
3192         {
3193           cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);      
3194           prq->sender->avg_delay.rel_value
3195             = (prq->sender->avg_delay.rel_value * 
3196                (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N; 
3197           prq->sender->avg_priority
3198             = (prq->sender->avg_priority * 
3199                (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3200         }
3201       if (pr->cp != NULL)
3202         {
3203           GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3204                                  [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], 
3205                                  -1);
3206           GNUNET_PEER_change_rc (pr->cp->pid, 1);
3207           prq->sender->last_p2p_replies
3208             [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3209             = pr->cp->pid;
3210         }
3211       else
3212         {
3213           if (NULL != prq->sender->last_client_replies
3214               [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3215             GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3216                                        [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3217           prq->sender->last_client_replies
3218             [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3219             = pr->client_request_list->client_list->client;
3220           GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3221         }
3222     }
3223   prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3224                                      prq->type,
3225                                      key,
3226                                      &pr->bf,
3227                                      pr->mingle,
3228                                      pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3229                                      prq->data,
3230                                      prq->size);
3231   switch (prq->eval)
3232     {
3233     case GNUNET_BLOCK_EVALUATION_OK_MORE:
3234       break;
3235     case GNUNET_BLOCK_EVALUATION_OK_LAST:
3236       while (NULL != pr->pending_head)
3237         destroy_pending_message_list_entry (pr->pending_head);
3238       if (pr->qe != NULL)
3239         {
3240           if (pr->client_request_list != NULL)
3241             GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
3242                                         GNUNET_YES);
3243           GNUNET_DATASTORE_cancel (pr->qe);
3244           pr->qe = NULL;
3245         }
3246       pr->do_remove = GNUNET_YES;
3247       if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3248         {
3249           GNUNET_SCHEDULER_cancel (pr->task);
3250           pr->task = GNUNET_SCHEDULER_NO_TASK;
3251         }
3252       GNUNET_break (GNUNET_YES ==
3253                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3254                                                           key,
3255                                                           pr));
3256       GNUNET_LOAD_update (rt_entry_lifetime,
3257                           GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3258       break;
3259     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3260       GNUNET_STATISTICS_update (stats,
3261                                 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3262                                 1,
3263                                 GNUNET_NO);
3264 #if DEBUG_FS
3265 /*      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266                   "Duplicate response `%s', discarding.\n",
3267                   GNUNET_h2s (&mhash));*/
3268 #endif
3269       return GNUNET_YES; /* duplicate */
3270     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3271       return GNUNET_YES; /* wrong namespace */  
3272     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3273       GNUNET_break (0);
3274       return GNUNET_YES;
3275     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3276       GNUNET_break (0);
3277       return GNUNET_YES;
3278     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3279       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3280                   _("Unsupported block type %u\n"),
3281                   prq->type);
3282       return GNUNET_NO;
3283     }
3284   if (pr->client_request_list != NULL)
3285     {
3286       if (pr->replies_seen_size == pr->replies_seen_off)
3287         GNUNET_array_grow (pr->replies_seen,
3288                            pr->replies_seen_size,
3289                            pr->replies_seen_size * 2 + 4);      
3290       GNUNET_CRYPTO_hash (prq->data,
3291                           prq->size,
3292                           &pr->replies_seen[pr->replies_seen_off++]);         
3293       refresh_bloomfilter (pr);
3294     }
3295   if (NULL == prq->sender)
3296     {
3297 #if DEBUG_FS
3298       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3299                   "Found result for query `%s' in local datastore\n",
3300                   GNUNET_h2s (key));
3301 #endif
3302       GNUNET_STATISTICS_update (stats,
3303                                 gettext_noop ("# results found locally"),
3304                                 1,
3305                                 GNUNET_NO);      
3306     }
3307   prq->priority += pr->remaining_priority;
3308   pr->remaining_priority = 0;
3309   pr->results_found++;
3310   prq->request_found = GNUNET_YES;
3311   if (NULL != pr->client_request_list)
3312     {
3313       GNUNET_STATISTICS_update (stats,
3314                                 gettext_noop ("# replies received for local clients"),
3315                                 1,
3316                                 GNUNET_NO);
3317       cl = pr->client_request_list->client_list;
3318       msize = sizeof (struct PutMessage) + prq->size;
3319       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3320       creply->msize = msize;
3321       creply->client_list = cl;
3322       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3323                                          cl->res_tail,
3324                                          cl->res_tail,
3325                                          creply);      
3326       pm = (struct PutMessage*) &creply[1];
3327       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3328       pm->header.size = htons (msize);
3329       pm->type = htonl (prq->type);
3330       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3331       memcpy (&pm[1], prq->data, prq->size);      
3332       if (NULL == cl->th)
3333         {
3334 #if DEBUG_FS
3335           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3336                       "Transmitting result for query `%s' to client\n",
3337                       GNUNET_h2s (key));
3338 #endif  
3339           cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3340                                                         msize,
3341                                                         GNUNET_TIME_UNIT_FOREVER_REL,
3342                                                         &transmit_to_client,
3343                                                         cl);
3344         }
3345       GNUNET_break (cl->th != NULL);
3346       if (pr->do_remove)                
3347         {
3348           prq->finished = GNUNET_YES;
3349           destroy_pending_request (pr);         
3350         }
3351     }
3352   else
3353     {
3354       cp = pr->cp;
3355 #if DEBUG_FS
3356       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3357                   "Transmitting result for query `%s' to other peer (PID=%u)\n",
3358                   GNUNET_h2s (key),
3359                   (unsigned int) cp->pid);
3360 #endif  
3361       GNUNET_STATISTICS_update (stats,
3362                                 gettext_noop ("# replies received for other peers"),
3363                                 1,
3364                                 GNUNET_NO);
3365       msize = sizeof (struct PutMessage) + prq->size;
3366       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3367       reply->cont = &transmit_reply_continuation;
3368       reply->cont_cls = pr;
3369 #if SUPPORT_DELAYS
3370       art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3371                                                  GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3372                                                                            TTL_DECREMENT));
3373       reply->delay_until 
3374         = GNUNET_TIME_relative_to_absolute (art_delay);
3375       GNUNET_STATISTICS_update (stats,
3376                                 gettext_noop ("cummulative artificial delay introduced (ms)"),
3377                                 art_delay.abs_value,
3378                                 GNUNET_NO);
3379 #endif
3380       reply->msize = msize;
3381       reply->priority = UINT32_MAX; /* send replies first! */
3382       pm = (struct PutMessage*) &reply[1];
3383       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3384       pm->header.size = htons (msize);
3385       pm->type = htonl (prq->type);
3386       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3387       memcpy (&pm[1], prq->data, prq->size);
3388       add_to_pending_messages_for_peer (cp, reply, pr);
3389     }
3390   return GNUNET_YES;
3391 }
3392
3393
3394 /**
3395  * Iterator called on each result obtained for a DHT
3396  * operation that expects a reply
3397  *
3398  * @param cls closure
3399  * @param exp when will this value expire
3400  * @param key key of the result
3401  * @param get_path NULL-terminated array of pointers
3402  *                 to the peers on reverse GET path (or NULL if not recorded)
3403  * @param put_path NULL-terminated array of pointers
3404  *                 to the peers on the PUT path (or NULL if not recorded)
3405  * @param type type of the result
3406  * @param size number of bytes in data
3407  * @param data pointer to the result data
3408  */
3409 static void
3410 process_dht_reply (void *cls,
3411                    struct GNUNET_TIME_Absolute exp,
3412                    const GNUNET_HashCode * key,
3413                    const struct GNUNET_PeerIdentity * const *get_path,
3414                    const struct GNUNET_PeerIdentity * const *put_path,
3415                    enum GNUNET_BLOCK_Type type,
3416                    size_t size,
3417                    const void *data)
3418 {
3419   struct PendingRequest *pr = cls;
3420   struct ProcessReplyClosure prq;
3421
3422   memset (&prq, 0, sizeof (prq));
3423   prq.data = data;
3424   prq.expiration = exp;
3425   prq.size = size;  
3426   prq.type = type;
3427   process_reply (&prq, key, pr);
3428 }
3429
3430
3431
3432 /**
3433  * Continuation called to notify client about result of the
3434  * operation.
3435  *
3436  * @param cls closure
3437  * @param success GNUNET_SYSERR on failure
3438  * @param msg NULL on success, otherwise an error message
3439  */
3440 static void 
3441 put_migration_continuation (void *cls,
3442                             int success,
3443                             const char *msg)
3444 {
3445   struct GNUNET_TIME_Absolute *start = cls;
3446   struct GNUNET_TIME_Relative delay;
3447   
3448   delay = GNUNET_TIME_absolute_get_duration (*start);
3449   GNUNET_free (start);
3450   GNUNET_LOAD_update (datastore_put_load,
3451                       delay.rel_value);
3452   if (GNUNET_OK == success)
3453     return;
3454   GNUNET_STATISTICS_update (stats,
3455                             gettext_noop ("# datastore 'put' failures"),
3456                             1,
3457                             GNUNET_NO);
3458 }
3459
3460
3461 /**
3462  * Handle P2P "PUT" message.
3463  *
3464  * @param cls closure, always NULL
3465  * @param other the other peer involved (sender or receiver, NULL
3466  *        for loopback messages where we are both sender and receiver)
3467  * @param message the actual message
3468  * @param latency reported latency of the connection with 'other'
3469  * @param distance reported distance (DV) to 'other' 
3470  * @return GNUNET_OK to keep the connection open,
3471  *         GNUNET_SYSERR to close it (signal serious error)
3472  */
3473 static int
3474 handle_p2p_put (void *cls,
3475                 const struct GNUNET_PeerIdentity *other,
3476                 const struct GNUNET_MessageHeader *message,
3477                 struct GNUNET_TIME_Relative latency,
3478                 uint32_t distance)
3479 {
3480   const struct PutMessage *put;
3481   uint16_t msize;
3482   size_t dsize;
3483   enum GNUNET_BLOCK_Type type;
3484   struct GNUNET_TIME_Absolute expiration;
3485   GNUNET_HashCode query;
3486   struct ProcessReplyClosure prq;
3487   struct GNUNET_TIME_Absolute *start;
3488   struct GNUNET_TIME_Relative block_time;  
3489   double putl;
3490   struct ConnectedPeer *cp; 
3491   struct PendingMessage *pm;
3492   struct MigrationStopMessage *msm;
3493
3494   msize = ntohs (message->size);
3495   if (msize < sizeof (struct PutMessage))
3496     {
3497       GNUNET_break_op(0);
3498       return GNUNET_SYSERR;
3499     }
3500   put = (const struct PutMessage*) message;
3501   dsize = msize - sizeof (struct PutMessage);
3502   type = ntohl (put->type);
3503   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3504
3505   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3506     return GNUNET_SYSERR;
3507   if (GNUNET_OK !=
3508       GNUNET_BLOCK_get_key (block_ctx,
3509                             type,
3510                             &put[1],
3511                             dsize,
3512                             &query))
3513     {
3514       GNUNET_break_op (0);
3515       return GNUNET_SYSERR;
3516     }
3517 #if DEBUG_FS
3518   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3519               "Received result for query `%s' from peer `%4s'\n",
3520               GNUNET_h2s (&query),
3521               GNUNET_i2s (other));
3522 #endif
3523   GNUNET_STATISTICS_update (stats,
3524                             gettext_noop ("# replies received (overall)"),
3525                             1,
3526                             GNUNET_NO);
3527   /* now, lookup 'query' */
3528   prq.data = (const void*) &put[1];
3529   if (other != NULL)
3530     prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3531                                                     &other->hashPubKey);
3532   else
3533     prq.sender = NULL;
3534   prq.size = dsize;
3535   prq.type = type;
3536   prq.expiration = expiration;
3537   prq.priority = 0;
3538   prq.finished = GNUNET_NO;
3539   prq.request_found = GNUNET_NO;
3540   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3541                                               &query,
3542                                               &process_reply,
3543                                               &prq);
3544   if (prq.sender != NULL)
3545     {
3546       prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3547       prq.sender->trust += prq.priority;
3548     }
3549   if ( (GNUNET_YES == active_migration) &&
3550        (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3551     {      
3552 #if DEBUG_FS
3553       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3554                   "Replicating result for query `%s' with priority %u\n",
3555                   GNUNET_h2s (&query),
3556                   prq.priority);
3557 #endif
3558       start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3559       *start = GNUNET_TIME_absolute_get ();
3560       GNUNET_DATASTORE_put (dsh,
3561                             0, &query, dsize, &put[1],
3562                             type, prq.priority, 1 /* anonymity */, 
3563                             expiration, 
3564                             1 + prq.priority, MAX_DATASTORE_QUEUE,
3565                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3566                             &put_migration_continuation, 
3567                             start);
3568     }
3569   putl = GNUNET_LOAD_get_load (datastore_put_load);
3570   if ( (GNUNET_NO == prq.request_found) &&
3571        ( (GNUNET_YES != active_migration) ||
3572          (putl > 2.5 * (1 + prq.priority)) ) )
3573     {
3574       cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3575                                               &other->hashPubKey);
3576       if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3577         return GNUNET_OK; /* already blocked */
3578       /* We're too busy; send MigrationStop message! */
3579       if (GNUNET_YES != active_migration) 
3580         putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3581       block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3582                                                   5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3583                                                                                    (unsigned int) (60000 * putl * putl)));
3584       
3585       cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3586       pm = GNUNET_malloc (sizeof (struct PendingMessage) + 
3587                           sizeof (struct MigrationStopMessage));
3588       pm->msize = sizeof (struct MigrationStopMessage);
3589       pm->priority = UINT32_MAX;
3590       msm = (struct MigrationStopMessage*) &pm[1];
3591       msm->header.size = htons (sizeof (struct MigrationStopMessage));
3592       msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3593       msm->duration = GNUNET_TIME_relative_hton (block_time);
3594       add_to_pending_messages_for_peer (cp,
3595                                         pm,
3596                                         NULL);
3597     }
3598   return GNUNET_OK;
3599 }
3600
3601
3602 /**
3603  * Handle P2P "MIGRATION_STOP" message.
3604  *
3605  * @param cls closure, always NULL
3606  * @param other the other peer involved (sender or receiver, NULL
3607  *        for loopback messages where we are both sender and receiver)
3608  * @param message the actual message
3609  * @param latency reported latency of the connection with 'other'
3610  * @param distance reported distance (DV) to 'other' 
3611  * @return GNUNET_OK to keep the connection open,
3612  *         GNUNET_SYSERR to close it (signal serious error)
3613  */
3614 static int
3615 handle_p2p_migration_stop (void *cls,
3616                            const struct GNUNET_PeerIdentity *other,
3617                            const struct GNUNET_MessageHeader *message,
3618                            struct GNUNET_TIME_Relative latency,
3619                            uint32_t distance)
3620 {
3621   struct ConnectedPeer *cp; 
3622   const struct MigrationStopMessage *msm;
3623
3624   msm = (const struct MigrationStopMessage*) message;
3625   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3626                                           &other->hashPubKey);
3627   if (cp == NULL)
3628     {
3629       GNUNET_break (0);
3630       return GNUNET_OK;
3631     }
3632   cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3633   return GNUNET_OK;
3634 }
3635
3636
3637
3638 /* **************************** P2P GET Handling ************************ */
3639
3640
3641 /**
3642  * Closure for 'check_duplicate_request_{peer,client}'.
3643  */
3644 struct CheckDuplicateRequestClosure
3645 {
3646   /**
3647    * The new request we should check if it already exists.
3648    */
3649   const struct PendingRequest *pr;
3650
3651   /**
3652    * Existing request found by the checker, NULL if none.
3653    */
3654   struct PendingRequest *have;
3655 };
3656
3657
3658 /**
3659  * Iterator over entries in the 'query_request_map' that
3660  * tries to see if we have the same request pending from
3661  * the same client already.
3662  *
3663  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3664  * @param key current key code (query, ignored, must match)
3665  * @param value value in the hash map (a 'struct PendingRequest' 
3666  *              that already exists)
3667  * @return GNUNET_YES if we should continue to
3668  *         iterate (no match yet)
3669  *         GNUNET_NO if not (match found).
3670  */
3671 static int
3672 check_duplicate_request_client (void *cls,
3673                                 const GNUNET_HashCode * key,
3674                                 void *value)
3675 {
3676   struct CheckDuplicateRequestClosure *cdc = cls;
3677   struct PendingRequest *have = value;
3678
3679   if (have->client_request_list == NULL)
3680     return GNUNET_YES;
3681   if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3682        (cdc->pr != have) )
3683     {
3684       cdc->have = have;
3685       return GNUNET_NO;
3686     }
3687   return GNUNET_YES;
3688 }
3689
3690
3691 /**
3692  * We're processing (local) results for a search request
3693  * from another peer.  Pass applicable results to the
3694  * peer and if we are done either clean up (operation
3695  * complete) or forward to other peers (more results possible).
3696  *
3697  * @param cls our closure (struct LocalGetContext)
3698  * @param key key for the content
3699  * @param size number of bytes in data
3700  * @param data content stored
3701  * @param type type of the content
3702  * @param priority priority of the content
3703  * @param anonymity anonymity-level for the content
3704  * @param expiration expiration time for the content
3705  * @param uid unique identifier for the datum;
3706  *        maybe 0 if no unique identifier is available
3707  */
3708 static void
3709 process_local_reply (void *cls,
3710                      const GNUNET_HashCode * key,
3711                      size_t size,
3712                      const void *data,
3713                      enum GNUNET_BLOCK_Type type,
3714                      uint32_t priority,
3715                      uint32_t anonymity,
3716                      struct GNUNET_TIME_Absolute
3717                      expiration, 
3718                      uint64_t uid)
3719 {
3720   struct PendingRequest *pr = cls;
3721   struct ProcessReplyClosure prq;
3722   struct CheckDuplicateRequestClosure cdrc;
3723   GNUNET_HashCode query;
3724   unsigned int old_rf;
3725   
3726   if (NULL == key)
3727     {
3728 #if DEBUG_FS > 1
3729       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3730                   "Done processing local replies, forwarding request to other peers.\n");
3731 #endif
3732       pr->qe = NULL;
3733       if (pr->client_request_list != NULL)
3734         {
3735           GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
3736                                       GNUNET_YES);
3737           /* Figure out if this is a duplicate request and possibly
3738              merge 'struct PendingRequest' entries */
3739           cdrc.have = NULL;
3740           cdrc.pr = pr;
3741           GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3742                                                       &pr->query,
3743                                                       &check_duplicate_request_client,
3744                                                       &cdrc);
3745           if (cdrc.have != NULL)
3746             {
3747 #if DEBUG_FS
3748               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3749                           "Received request for block `%s' twice from client, will only request once.\n",
3750                           GNUNET_h2s (&pr->query));
3751 #endif
3752               
3753               destroy_pending_request (pr);
3754               return;
3755             }
3756         }
3757       if (pr->local_only == GNUNET_YES)
3758         {
3759           destroy_pending_request (pr);
3760           return;
3761         }
3762       /* no more results */
3763       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3764         pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3765                                              pr);      
3766       return;
3767     }
3768 #if DEBUG_FS
3769   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3770               "New local response to `%s' of type %u.\n",
3771               GNUNET_h2s (key),
3772               type);
3773 #endif
3774   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3775     {
3776 #if DEBUG_FS
3777       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3778                   "Found ONDEMAND block, performing on-demand encoding\n");
3779 #endif
3780       GNUNET_STATISTICS_update (stats,
3781                                 gettext_noop ("# on-demand blocks matched requests"),
3782                                 1,
3783                                 GNUNET_NO);
3784       if (GNUNET_OK != 
3785           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
3786                                             anonymity, expiration, uid, 
3787                                             &process_local_reply,
3788                                             pr))
3789       if (pr->qe != NULL)
3790         {
3791           GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3792         }
3793       return;
3794     }
3795   old_rf = pr->results_found;
3796   memset (&prq, 0, sizeof (prq));
3797   prq.data = data;
3798   prq.expiration = expiration;
3799   prq.size = size;  
3800   if (GNUNET_OK != 
3801       GNUNET_BLOCK_get_key (block_ctx,
3802                             type,
3803                             data,
3804                             size,
3805                             &query))
3806     {
3807       GNUNET_break (0);
3808       GNUNET_DATASTORE_remove (dsh,
3809                                key,
3810                                size, data,
3811                                -1, -1, 
3812                                GNUNET_TIME_UNIT_FOREVER_REL,
3813                                NULL, NULL);
3814       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3815       return;
3816     }
3817   prq.type = type;
3818   prq.priority = priority;  
3819   prq.finished = GNUNET_NO;
3820   prq.request_found = GNUNET_NO;
3821   if ( (old_rf == 0) &&
3822        (pr->results_found == 0) )
3823     update_datastore_delays (pr->start_time);
3824   process_reply (&prq, key, pr);
3825   if (prq.finished == GNUNET_YES)
3826     return;
3827   if (pr->qe == NULL)
3828     return; /* done here */
3829   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
3830     {
3831       pr->local_only = GNUNET_YES; /* do not forward */
3832       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3833       return;
3834     }
3835   if ( (pr->client_request_list == NULL) &&
3836        ( (GNUNET_YES == test_get_load_too_high (0)) ||
3837          (pr->results_found > 5 + 2 * pr->priority) ) )
3838     {
3839 #if DEBUG_FS > 2
3840       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3841                   "Load too high, done with request\n");
3842 #endif
3843       GNUNET_STATISTICS_update (stats,
3844                                 gettext_noop ("# processing result set cut short due to load"),
3845                                 1,
3846                                 GNUNET_NO);
3847       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
3848       return;
3849     }
3850   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3851 }
3852
3853
3854 /**
3855  * We've received a request with the specified priority.  Bound it
3856  * according to how much we trust the given peer.
3857  * 
3858  * @param prio_in requested priority
3859  * @param cp the peer making the request
3860  * @return effective priority
3861  */
3862 static int32_t
3863 bound_priority (uint32_t prio_in,
3864                 struct ConnectedPeer *cp)
3865 {
3866 #define N ((double)128.0)
3867   uint32_t ret;
3868   double rret;
3869   int ld;
3870
3871   ld = test_get_load_too_high (0);
3872   if (ld == GNUNET_SYSERR)
3873     {
3874       GNUNET_STATISTICS_update (stats,
3875                                 gettext_noop ("# requests done for free (low load)"),
3876                                 1,
3877                                 GNUNET_NO);
3878       return 0; /* excess resources */
3879     }
3880   ret = change_host_trust (cp, prio_in);
3881   if (ret > 0)
3882     {
3883       if (ret > current_priorities + N)
3884         rret = current_priorities + N;
3885       else
3886         rret = ret;
3887       current_priorities 
3888         = (current_priorities * (N-1) + rret)/N;
3889     }
3890   if ( (ld == GNUNET_YES) && (ret > 0) )
3891     {
3892       /* try with charging */
3893       ld = test_get_load_too_high (ret);
3894     }
3895   if (ld == GNUNET_YES)
3896     {
3897       GNUNET_STATISTICS_update (stats,
3898                                 gettext_noop ("# request dropped, priority insufficient"),
3899                                 1,
3900                                 GNUNET_NO);
3901       /* undo charge */
3902       if (ret != 0)
3903         change_host_trust (cp, -ret);
3904       return -1; /* not enough resources */
3905     }
3906   else
3907     {
3908       GNUNET_STATISTICS_update (stats,
3909                                 gettext_noop ("# requests done for a price (normal load)"),
3910                                 1,
3911                                 GNUNET_NO);
3912     }
3913 #undef N
3914   return ret;
3915 }
3916
3917
3918 /**
3919  * Iterator over entries in the 'query_request_map' that
3920  * tries to see if we have the same request pending from
3921  * the same peer already.
3922  *
3923  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3924  * @param key current key code (query, ignored, must match)
3925  * @param value value in the hash map (a 'struct PendingRequest' 
3926  *              that already exists)
3927  * @return GNUNET_YES if we should continue to
3928  *         iterate (no match yet)
3929  *         GNUNET_NO if not (match found).
3930  */
3931 static int
3932 check_duplicate_request_peer (void *cls,
3933                               const GNUNET_HashCode * key,
3934                               void *value)
3935 {
3936   struct CheckDuplicateRequestClosure *cdc = cls;
3937   struct PendingRequest *have = value;
3938
3939   if (cdc->pr->target_pid == have->target_pid)
3940     {
3941       cdc->have = have;
3942       return GNUNET_NO;
3943     }
3944   return GNUNET_YES;
3945 }
3946
3947
3948 /**
3949  * Handle P2P "GET" request.
3950  *
3951  * @param cls closure, always NULL
3952  * @param other the other peer involved (sender or receiver, NULL
3953  *        for loopback messages where we are both sender and receiver)
3954  * @param message the actual message
3955  * @param latency reported latency of the connection with 'other'
3956  * @param distance reported distance (DV) to 'other' 
3957  * @return GNUNET_OK to keep the connection open,
3958  *         GNUNET_SYSERR to close it (signal serious error)
3959  */
3960 static int
3961 handle_p2p_get (void *cls,
3962                 const struct GNUNET_PeerIdentity *other,
3963                 const struct GNUNET_MessageHeader *message,
3964                 struct GNUNET_TIME_Relative latency,
3965                 uint32_t distance)
3966 {
3967   struct PendingRequest *pr;
3968   struct ConnectedPeer *cp;
3969   struct ConnectedPeer *cps;
3970   struct CheckDuplicateRequestClosure cdc;
3971   struct GNUNET_TIME_Relative timeout;
3972   uint16_t msize;
3973   const struct GetMessage *gm;
3974   unsigned int bits;
3975   const GNUNET_HashCode *opt;
3976   uint32_t bm;
3977   size_t bfsize;
3978   uint32_t ttl_decrement;
3979   int32_t priority;
3980   enum GNUNET_BLOCK_Type type;
3981   int have_ns;
3982
3983   msize = ntohs(message->size);
3984   if (msize < sizeof (struct GetMessage))
3985     {
3986       GNUNET_break_op (0);
3987       return GNUNET_SYSERR;
3988     }
3989   gm = (const struct GetMessage*) message;
3990 #if DEBUG_FS
3991   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3992               "Received request for `%s'\n",
3993               GNUNET_h2s (&gm->query));
3994 #endif
3995   type = ntohl (gm->type);
3996   bm = ntohl (gm->hash_bitmap);
3997   bits = 0;
3998   while (bm > 0)
3999     {
4000       if (1 == (bm & 1))
4001         bits++;
4002       bm >>= 1;
4003     }
4004   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4005     {
4006       GNUNET_break_op (0);
4007       return GNUNET_SYSERR;
4008     }  
4009   opt = (const GNUNET_HashCode*) &gm[1];
4010   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4011   /* bfsize must be power of 2, check! */
4012   if (0 != ( (bfsize - 1) & bfsize))
4013     {
4014       GNUNET_break_op (0);
4015       return GNUNET_SYSERR;
4016     }
4017   bm = ntohl (gm->hash_bitmap);
4018   bits = 0;
4019   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4020                                            &other->hashPubKey);
4021   if (NULL == cps)
4022     {
4023       /* peer must have just disconnected */
4024       GNUNET_STATISTICS_update (stats,
4025                                 gettext_noop ("# requests dropped due to initiator not being connected"),
4026                                 1,
4027                                 GNUNET_NO);
4028       return GNUNET_SYSERR;
4029     }
4030   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4031     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4032                                             &opt[bits++]);
4033   else
4034     cp = cps;
4035   if (cp == NULL)
4036     {
4037 #if DEBUG_FS
4038       if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4039         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4040                     "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4041                     GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4042       
4043       else
4044         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4045                     "Failed to find peer `%4s' in connection set. Dropping query.\n",
4046                     GNUNET_i2s (other));
4047 #endif
4048       GNUNET_STATISTICS_update (stats,
4049                                 gettext_noop ("# requests dropped due to missing reverse route"),
4050                                 1,
4051                                 GNUNET_NO);
4052      /* FIXME: try connect? */
4053       return GNUNET_OK;
4054     }
4055   /* note that we can really only check load here since otherwise
4056      peers could find out that we are overloaded by not being
4057      disconnected after sending us a malformed query... */
4058   priority = bound_priority (ntohl (gm->priority), cps);
4059   if (priority < 0)
4060     {
4061 #if DEBUG_FS
4062       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4063                   "Dropping query from `%s', this peer is too busy.\n",
4064                   GNUNET_i2s (other));
4065 #endif
4066       return GNUNET_OK;
4067     }
4068 #if DEBUG_FS 
4069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4070               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4071               GNUNET_h2s (&gm->query),
4072               (unsigned int) type,
4073               GNUNET_i2s (other),
4074               (unsigned int) bm);
4075 #endif
4076   have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4077   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
4078                       (have_ns ? sizeof(GNUNET_HashCode) : 0));
4079   if (have_ns)
4080     {
4081       pr->namespace = (GNUNET_HashCode*) &pr[1];
4082       memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4083     }
4084   if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4085        (GNUNET_LOAD_get_average (cp->transmission_delay) > 
4086         GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4087     {
4088       /* don't have BW to send to peer, or would likely take longer than we have for it,
4089          so at best indirect the query */
4090       priority = 0;
4091       pr->forward_only = GNUNET_YES;
4092     }
4093   pr->type = type;
4094   pr->mingle = ntohl (gm->filter_mutator);
4095   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4096     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4097   pr->anonymity_level = 1;
4098   pr->priority = (uint32_t) priority;
4099   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4100   pr->query = gm->query;
4101   /* decrement ttl (always) */
4102   ttl_decrement = 2 * TTL_DECREMENT +
4103     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4104                               TTL_DECREMENT);
4105   if ( (pr->ttl < 0) &&
4106        (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4107     {
4108 #if DEBUG_FS
4109       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4110                   "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4111                   GNUNET_i2s (other),
4112                   pr->ttl,
4113                   ttl_decrement);
4114 #endif
4115       GNUNET_STATISTICS_update (stats,
4116                                 gettext_noop ("# requests dropped due TTL underflow"),
4117                                 1,
4118                                 GNUNET_NO);
4119       /* integer underflow => drop (should be very rare)! */      
4120       GNUNET_free (pr);
4121       return GNUNET_OK;
4122     } 
4123   pr->ttl -= ttl_decrement;
4124   pr->start_time = GNUNET_TIME_absolute_get ();
4125
4126   /* get bloom filter */
4127   if (bfsize > 0)
4128     {
4129       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4130                                                   bfsize,
4131                                                   BLOOMFILTER_K);
4132       pr->bf_size = bfsize;
4133     }
4134   cdc.have = NULL;
4135   cdc.pr = pr;
4136   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4137                                               &gm->query,
4138                                               &check_duplicate_request_peer,
4139                                               &cdc);
4140   if (cdc.have != NULL)
4141     {
4142       if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4143           pr->start_time.abs_value + pr->ttl)
4144         {
4145           /* existing request has higher TTL, drop new one! */
4146           cdc.have->priority += pr->priority;
4147           destroy_pending_request (pr);
4148 #if DEBUG_FS
4149           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4150                       "Have existing request with higher TTL, dropping new request.\n",
4151                       GNUNET_i2s (other));
4152 #endif
4153           GNUNET_STATISTICS_update (stats,
4154                                     gettext_noop ("# requests dropped due to higher-TTL request"),
4155                                     1,
4156                                     GNUNET_NO);
4157           return GNUNET_OK;
4158         }
4159       else
4160         {
4161           /* existing request has lower TTL, drop old one! */
4162           pr->priority += cdc.have->priority;
4163           /* Possible optimization: if we have applicable pending
4164              replies in 'cdc.have', we might want to move those over
4165              (this is a really rare special-case, so it is not clear
4166              that this would be worth it) */
4167           destroy_pending_request (cdc.have);
4168           /* keep processing 'pr'! */
4169         }
4170     }
4171
4172   pr->cp = cp;
4173   GNUNET_break (GNUNET_OK ==
4174                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4175                                                    &gm->query,
4176                                                    pr,
4177                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4178   GNUNET_break (GNUNET_OK ==
4179                 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4180                                                    &other->hashPubKey,
4181                                                    pr,
4182                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4183   
4184   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4185                                             pr,
4186                                             pr->start_time.abs_value + pr->ttl);
4187
4188   GNUNET_STATISTICS_update (stats,
4189                             gettext_noop ("# P2P searches received"),
4190                             1,
4191                             GNUNET_NO);
4192   GNUNET_STATISTICS_update (stats,
4193                             gettext_noop ("# P2P searches active"),
4194                             1,
4195                             GNUNET_NO);
4196
4197   /* calculate change in traffic preference */
4198   cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4199   /* process locally */
4200   if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4201     type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4202   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4203                                            (pr->priority + 1)); 
4204   if (GNUNET_YES != pr->forward_only)
4205     {
4206 #if DEBUG_FS
4207       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4208                   "Handing request for `%s' to datastore\n",
4209                   GNUNET_h2s (&gm->query));
4210 #endif
4211       pr->qe = GNUNET_DATASTORE_get (dsh,
4212                                      &gm->query,
4213                                      type,                             
4214                                      pr->priority + 1,
4215                                      MAX_DATASTORE_QUEUE,                                
4216                                      timeout,
4217                                      &process_local_reply,
4218                                      pr);
4219       if (NULL == pr->qe)
4220         {
4221           GNUNET_STATISTICS_update (stats,
4222                                     gettext_noop ("# requests dropped by datastore (queue length limit)"),
4223                                     1,
4224                                     GNUNET_NO);
4225         }
4226     }
4227   else
4228     {
4229       GNUNET_STATISTICS_update (stats,
4230                                 gettext_noop ("# requests forwarded due to high load"),
4231                                 1,
4232                                 GNUNET_NO);
4233     }
4234
4235   /* Are multiple results possible (and did we look locally)?  If so, start processing remotely now! */
4236   switch (pr->type)
4237     {
4238     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4239     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4240       /* only one result, wait for datastore */
4241       if (GNUNET_YES != pr->forward_only)
4242         {
4243           GNUNET_STATISTICS_update (stats,
4244                                     gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4245                                     1,
4246                                     GNUNET_NO);
4247           break;
4248         }
4249     default:
4250       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4251         pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4252                                              pr);
4253     }
4254
4255   /* make sure we don't track too many requests */
4256   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4257     {
4258       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4259       GNUNET_assert (pr != NULL);
4260       destroy_pending_request (pr);
4261     }
4262   return GNUNET_OK;
4263 }
4264
4265
4266 /* **************************** CS GET Handling ************************ */
4267
4268
4269 /**
4270  * Handle START_SEARCH-message (search request from client).
4271  *
4272  * @param cls closure
4273  * @param client identification of the client
4274  * @param message the actual message
4275  */
4276 static void
4277 handle_start_search (void *cls,
4278                      struct GNUNET_SERVER_Client *client,
4279                      const struct GNUNET_MessageHeader *message)
4280 {
4281   static GNUNET_HashCode all_zeros;
4282   const struct SearchMessage *sm;
4283   struct ClientList *cl;
4284   struct ClientRequestList *crl;
4285   struct PendingRequest *pr;
4286   uint16_t msize;
4287   unsigned int sc;
4288   enum GNUNET_BLOCK_Type type;
4289
4290   msize = ntohs (message->size);
4291   if ( (msize < sizeof (struct SearchMessage)) ||
4292        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4293     {
4294       GNUNET_break (0);
4295       GNUNET_SERVER_receive_done (client,
4296                                   GNUNET_SYSERR);
4297       return;
4298     }
4299   GNUNET_STATISTICS_update (stats,
4300                             gettext_noop ("# client searches received"),
4301                             1,
4302                             GNUNET_NO);
4303   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4304   sm = (const struct SearchMessage*) message;
4305   type = ntohl (sm->type);
4306 #if DEBUG_FS
4307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4308               "Received request for `%s' of type %u from local client\n",
4309               GNUNET_h2s (&sm->query),
4310               (unsigned int) type);
4311 #endif
4312   cl = client_list;
4313   while ( (cl != NULL) &&
4314           (cl->client != client) )
4315     cl = cl->next;
4316   if (cl == NULL)
4317     {
4318       cl = GNUNET_malloc (sizeof (struct ClientList));
4319       cl->client = client;
4320       GNUNET_SERVER_client_keep (client);
4321       cl->next = client_list;
4322       client_list = cl;
4323     }
4324   /* detect duplicate KBLOCK requests */
4325   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4326        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4327        (type == GNUNET_BLOCK_TYPE_ANY) )
4328     {
4329       crl = cl->rl_head;
4330       while ( (crl != NULL) &&
4331               ( (0 != memcmp (&crl->req->query,
4332                               &sm->query,
4333                               sizeof (GNUNET_HashCode))) ||
4334                 (crl->req->type != type) ) )
4335         crl = crl->next;
4336       if (crl != NULL)  
4337         { 
4338 #if DEBUG_FS
4339           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4340                       "Have existing request, merging content-seen lists.\n");
4341 #endif
4342           pr = crl->req;
4343           /* Duplicate request (used to send long list of
4344              known/blocked results); merge 'pr->replies_seen'
4345              and update bloom filter */
4346           GNUNET_array_grow (pr->replies_seen,
4347                              pr->replies_seen_size,
4348                              pr->replies_seen_off + sc);
4349           memcpy (&pr->replies_seen[pr->replies_seen_off],
4350                   &sm[1],
4351                   sc * sizeof (GNUNET_HashCode));
4352           pr->replies_seen_off += sc;
4353           refresh_bloomfilter (pr);
4354           GNUNET_STATISTICS_update (stats,
4355                                     gettext_noop ("# client searches updated (merged content seen list)"),
4356                                     1,
4357                                     GNUNET_NO);
4358           GNUNET_SERVER_receive_done (client,
4359                                       GNUNET_OK);
4360           return;
4361         }
4362     }
4363   GNUNET_STATISTICS_update (stats,
4364                             gettext_noop ("# client searches active"),
4365                             1,
4366                             GNUNET_NO);
4367   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
4368                       ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4369   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4370   memset (crl, 0, sizeof (struct ClientRequestList));
4371   crl->client_list = cl;
4372   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4373                                cl->rl_tail,
4374                                crl);  
4375   crl->req = pr;
4376   pr->type = type;
4377   pr->client_request_list = crl;
4378   GNUNET_array_grow (pr->replies_seen,
4379                      pr->replies_seen_size,
4380                      sc);
4381   memcpy (pr->replies_seen,
4382           &sm[1],
4383           sc * sizeof (GNUNET_HashCode));
4384   pr->replies_seen_off = sc;
4385   pr->anonymity_level = ntohl (sm->anonymity_level); 
4386   pr->start_time = GNUNET_TIME_absolute_get ();
4387   refresh_bloomfilter (pr);
4388   pr->query = sm->query;
4389   if (0 == (1 & ntohl (sm->options)))
4390     pr->local_only = GNUNET_NO;
4391   else
4392     pr->local_only = GNUNET_YES;
4393   switch (type)
4394     {
4395     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4396     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4397       if (0 != memcmp (&sm->target,
4398                        &all_zeros,
4399                        sizeof (GNUNET_HashCode)))
4400         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4401       break;
4402     case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4403       pr->namespace = (GNUNET_HashCode*) &pr[1];
4404       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4405       break;
4406     default:
4407       break;
4408     }
4409   GNUNET_break (GNUNET_OK ==
4410                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4411                                                    &sm->query,
4412                                                    pr,
4413                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4414   if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4415     type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4416   pr->qe = GNUNET_DATASTORE_get (dsh,
4417                                  &sm->query,
4418                                  type,
4419                                  -3, -1,
4420                                  GNUNET_CONSTANTS_SERVICE_TIMEOUT,                             
4421                                  &process_local_reply,
4422                                  pr);
4423 }
4424
4425
4426 /* **************************** Startup ************************ */
4427
4428 /**
4429  * Process fs requests.
4430  *
4431  * @param server the initialized server
4432  * @param c configuration to use
4433  */
4434 static int
4435 main_init (struct GNUNET_SERVER_Handle *server,
4436            const struct GNUNET_CONFIGURATION_Handle *c)
4437 {
4438   static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4439     {
4440       { &handle_p2p_get, 
4441         GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4442       { &handle_p2p_put, 
4443         GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4444       { &handle_p2p_migration_stop, 
4445         GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4446         sizeof (struct MigrationStopMessage) },
4447       { NULL, 0, 0 }
4448     };
4449   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4450     {&GNUNET_FS_handle_index_start, NULL, 
4451      GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4452     {&GNUNET_FS_handle_index_list_get, NULL, 
4453      GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4454     {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
4455      sizeof (struct UnindexMessage) },
4456     {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
4457      0 },
4458     {NULL, NULL, 0, 0}
4459   };
4460   unsigned long long enc = 128;
4461
4462   cfg = c;
4463   stats = GNUNET_STATISTICS_create ("fs", cfg);
4464   min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4465   if ( (GNUNET_OK !=
4466         GNUNET_CONFIGURATION_get_value_number (cfg,
4467                                                "fs",
4468                                                "MAX_PENDING_REQUESTS",
4469                                                &max_pending_requests)) ||
4470        (GNUNET_OK !=
4471         GNUNET_CONFIGURATION_get_value_number (cfg,
4472                                                "fs",
4473                                                "EXPECTED_NEIGHBOUR_COUNT",
4474                                                &enc)) ||
4475        (GNUNET_OK != 
4476         GNUNET_CONFIGURATION_get_value_time (cfg,
4477                                              "fs",
4478                                              "MIN_MIGRATION_DELAY",
4479                                              &min_migration_delay)) )
4480     {
4481       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4482                   _("Configuration fails to specify certain parameters, assuming default values."));
4483     }
4484   connected_peers = GNUNET_CONTAINER_multihashmap_create (enc); 
4485   query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4486   rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4487   peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4488   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
4489   core = GNUNET_CORE_connect (cfg,
4490                               GNUNET_TIME_UNIT_FOREVER_REL,
4491                               NULL,
4492                               NULL,
4493                               &peer_connect_handler,
4494                               &peer_disconnect_handler,
4495                               &peer_status_handler,
4496                               NULL, GNUNET_NO,
4497                               NULL, GNUNET_NO,
4498                               p2p_handlers);
4499   if (NULL == core)
4500     {
4501       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4502                   _("Failed to connect to `%s' service.\n"),
4503                   "core");
4504       GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4505       connected_peers = NULL;
4506       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4507       query_request_map = NULL;
4508       GNUNET_LOAD_value_free (rt_entry_lifetime);
4509       rt_entry_lifetime = NULL;
4510       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4511       requests_by_expiration_heap = NULL;
4512       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4513       peer_request_map = NULL;
4514       if (dsh != NULL)
4515         {
4516           GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4517           dsh = NULL;
4518         }
4519       return GNUNET_SYSERR;
4520     }
4521   /* FIXME: distinguish between sending and storing in options? */
4522   if (active_migration) 
4523     {
4524       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4525                   _("Content migration is enabled, will start to gather data\n"));
4526       consider_migration_gathering ();
4527     }
4528   consider_dht_put_gathering (NULL);
4529   GNUNET_SERVER_disconnect_notify (server, 
4530                                    &handle_client_disconnect,
4531                                    NULL);
4532   GNUNET_assert (GNUNET_OK ==
4533                  GNUNET_CONFIGURATION_get_value_filename (cfg,
4534                                                           "fs",
4535                                                           "TRUST",
4536                                                           &trustDirectory));
4537   GNUNET_DISK_directory_create (trustDirectory);
4538   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4539                                       &cron_flush_trust, NULL);
4540
4541
4542   GNUNET_SERVER_add_handlers (server, handlers);
4543   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4544                                 &shutdown_task,
4545                                 NULL);
4546   return GNUNET_OK;
4547 }
4548
4549
4550 /**
4551  * Process fs requests.
4552  *
4553  * @param cls closure
4554  * @param server the initialized server
4555  * @param cfg configuration to use
4556  */
4557 static void
4558 run (void *cls,
4559      struct GNUNET_SERVER_Handle *server,
4560      const struct GNUNET_CONFIGURATION_Handle *cfg)
4561 {
4562   active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4563                                                            "FS",
4564                                                            "ACTIVEMIGRATION");
4565   dsh = GNUNET_DATASTORE_connect (cfg);
4566   if (dsh == NULL)
4567     {
4568       GNUNET_SCHEDULER_shutdown ();
4569       return;
4570     }
4571   datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4572   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4573   block_cfg = GNUNET_CONFIGURATION_create ();
4574   GNUNET_CONFIGURATION_set_value_string (block_cfg,
4575                                          "block",
4576                                          "PLUGINS",
4577                                          "fs");
4578   block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4579   GNUNET_assert (NULL != block_ctx);
4580   dht_handle = GNUNET_DHT_connect (cfg,
4581                                    FS_DHT_HT_SIZE);
4582   if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4583        (GNUNET_OK != main_init (server, cfg)) )
4584     {    
4585       GNUNET_SCHEDULER_shutdown ();
4586       GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4587       dsh = NULL;
4588       GNUNET_DHT_disconnect (dht_handle);
4589       dht_handle = NULL;
4590       GNUNET_BLOCK_context_destroy (block_ctx);
4591       block_ctx = NULL;
4592       GNUNET_CONFIGURATION_destroy (block_cfg);
4593       block_cfg = NULL;
4594       GNUNET_LOAD_value_free (datastore_get_load);
4595       datastore_get_load = NULL;
4596       GNUNET_LOAD_value_free (datastore_put_load);
4597       datastore_put_load = NULL;
4598       return;   
4599     }
4600 }
4601
4602
4603 /**
4604  * The main function for the fs service.
4605  *
4606  * @param argc number of arguments from the command line
4607  * @param argv command line arguments
4608  * @return 0 ok, 1 on error
4609  */
4610 int
4611 main (int argc, char *const *argv)
4612 {
4613   return (GNUNET_OK ==
4614           GNUNET_SERVICE_run (argc,
4615                               argv,
4616                               "fs",
4617                               GNUNET_SERVICE_OPTION_NONE,
4618                               &run, NULL)) ? 0 : 1;
4619 }
4620
4621 /* end of gnunet-service-fs.c */