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