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