66b7a5e93251374b3cfb599473176ac4cf9b7970
[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   pml->target->pending_requests--;
1482   GNUNET_free (pml->pm);
1483   GNUNET_free (pml);
1484 }
1485
1486
1487 /**
1488  * Destroy the given pending message (and call the respective
1489  * continuation).
1490  *
1491  * @param pm message to destroy
1492  * @param tpid id of peer that the message was delivered to, or 0 for none
1493  */
1494 static void
1495 destroy_pending_message (struct PendingMessage *pm,
1496                          GNUNET_PEER_Id tpid)
1497 {
1498   struct PendingMessageList *pml = pm->pml;
1499   TransmissionContinuation cont;
1500   void *cont_cls;
1501
1502   cont = pm->cont;
1503   cont_cls = pm->cont_cls;
1504   if (pml != NULL)
1505     {
1506       GNUNET_assert (pml->pm == pm);
1507       GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1508       destroy_pending_message_list_entry (pml);
1509     }
1510   else
1511     {
1512       GNUNET_free (pm);
1513     }
1514   if (cont != NULL)
1515     cont (cont_cls, tpid);  
1516 }
1517
1518
1519 /**
1520  * We're done processing a particular request.
1521  * Free all associated resources.
1522  *
1523  * @param pr request to destroy
1524  */
1525 static void
1526 destroy_pending_request (struct PendingRequest *pr)
1527 {
1528   struct GNUNET_PeerIdentity pid;
1529   unsigned int i;
1530
1531   if (pr->hnode != NULL)
1532     {
1533       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1534                                          pr->hnode);
1535       pr->hnode = NULL;
1536     }
1537   if (NULL == pr->client_request_list)
1538     {
1539       GNUNET_STATISTICS_update (stats,
1540                                 gettext_noop ("# P2P searches active"),
1541                                 -1,
1542                                 GNUNET_NO);
1543     }
1544   else
1545     {
1546       GNUNET_STATISTICS_update (stats,
1547                                 gettext_noop ("# client searches active"),
1548                                 -1,
1549                                 GNUNET_NO);
1550     }
1551   if (GNUNET_YES == 
1552       GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1553                                             &pr->query,
1554                                             pr))
1555     {
1556       GNUNET_LOAD_update (rt_entry_lifetime,
1557                           GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
1558     }
1559   if (pr->qe != NULL)
1560      {
1561       GNUNET_DATASTORE_cancel (pr->qe);
1562       pr->qe = NULL;
1563     }
1564   if (pr->dht_get != NULL)
1565     {
1566       GNUNET_DHT_get_stop (pr->dht_get);
1567       pr->dht_get = NULL;
1568     }
1569   if (pr->client_request_list != NULL)
1570     {
1571       GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1572                                    pr->client_request_list->client_list->rl_tail,
1573                                    pr->client_request_list);
1574       GNUNET_free (pr->client_request_list);
1575       pr->client_request_list = NULL;
1576     }
1577   if (pr->cp != NULL)
1578     {
1579       GNUNET_PEER_resolve (pr->cp->pid,
1580                            &pid);
1581       (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1582                                                    &pid.hashPubKey,
1583                                                    pr);
1584       pr->cp = NULL;
1585     }
1586   if (pr->bf != NULL)
1587     {
1588       GNUNET_CONTAINER_bloomfilter_free (pr->bf);                                        
1589       pr->bf = NULL;
1590     }
1591   if (pr->pirc != NULL)
1592     {
1593       GNUNET_CORE_peer_change_preference_cancel (pr->pirc->irc);
1594       pr->pirc->irc = NULL;
1595       pr->pirc = NULL;
1596     }
1597   if (pr->replies_seen != NULL)
1598     {
1599       GNUNET_free (pr->replies_seen);
1600       pr->replies_seen = NULL;
1601     }
1602   if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1603     {
1604       GNUNET_SCHEDULER_cancel (pr->task);
1605       pr->task = GNUNET_SCHEDULER_NO_TASK;
1606     }
1607   while (NULL != pr->pending_head)    
1608     destroy_pending_message_list_entry (pr->pending_head);
1609   GNUNET_PEER_change_rc (pr->target_pid, -1);
1610   if (pr->used_targets != NULL)
1611     {
1612       for (i=0;i<pr->used_targets_off;i++)
1613         GNUNET_PEER_change_rc (pr->used_targets[i].pid, -1);
1614       GNUNET_free (pr->used_targets);
1615       pr->used_targets_off = 0;
1616       pr->used_targets_size = 0;
1617       pr->used_targets = NULL;
1618     }
1619   GNUNET_free (pr);
1620 }
1621
1622
1623 /**
1624  * Find latency information in 'atsi'.
1625  *
1626  * @param atsi performance data
1627  * @return connection latency
1628  */
1629 static struct GNUNET_TIME_Relative
1630 get_latency (const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1631 {
1632   if (atsi == NULL)
1633     return GNUNET_TIME_UNIT_SECONDS;
1634   while ( (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) &&
1635           (ntohl (atsi->type) != GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY) )
1636     atsi++;
1637   if (ntohl (atsi->type) == GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR) 
1638     {
1639       GNUNET_break (0);
1640       /* how can we not have latency data? */
1641       return GNUNET_TIME_UNIT_SECONDS;
1642     }
1643   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1644                                         ntohl (atsi->value));
1645 }
1646
1647
1648 /**
1649  * Method called whenever a given peer connects.
1650  *
1651  * @param cls closure, not used
1652  * @param peer peer identity this notification is about
1653  * @param atsi performance information
1654  */
1655 static void 
1656 peer_connect_handler (void *cls,
1657                       const struct
1658                       GNUNET_PeerIdentity * peer,
1659                       const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1660 {
1661   struct ConnectedPeer *cp;
1662   struct MigrationReadyBlock *pos;
1663   char *fn;
1664   uint32_t trust;
1665   struct GNUNET_TIME_Relative latency;
1666
1667   if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1668     return;
1669   latency = get_latency (atsi);
1670   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1671                                           &peer->hashPubKey);
1672   if (NULL != cp)
1673     {
1674       GNUNET_break (0);
1675       return;
1676     }
1677   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1678   cp->transmission_delay = GNUNET_LOAD_value_init (latency);
1679   cp->pid = GNUNET_PEER_intern (peer);
1680
1681   fn = get_trust_filename (peer);
1682   if ((GNUNET_DISK_file_test (fn) == GNUNET_YES) &&
1683       (sizeof (trust) == GNUNET_DISK_fn_read (fn, &trust, sizeof (trust))))
1684     cp->disk_trust = cp->trust = ntohl (trust);
1685   GNUNET_free (fn);
1686
1687   GNUNET_break (GNUNET_OK ==
1688                 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1689                                                    &peer->hashPubKey,
1690                                                    cp,
1691                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1692
1693   pos = mig_head;
1694   while (NULL != pos)
1695     {
1696       (void) consider_migration (pos, &peer->hashPubKey, cp);
1697       pos = pos->next;
1698     }
1699 }
1700
1701
1702 /**
1703  * Method called whenever a given peer has a status change.
1704  *
1705  * @param cls closure
1706  * @param peer peer identity this notification is about
1707  * @param bandwidth_in available amount of inbound bandwidth
1708  * @param bandwidth_out available amount of outbound bandwidth
1709  * @param timeout absolute time when this peer will time out
1710  *        unless we see some further activity from it
1711  * @param atsi status information
1712  */
1713 static void
1714 peer_status_handler (void *cls,
1715                      const struct
1716                      GNUNET_PeerIdentity * peer,
1717                      struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in,
1718                      struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
1719                      struct GNUNET_TIME_Absolute timeout,
1720                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1721 {
1722   struct ConnectedPeer *cp;
1723   struct GNUNET_TIME_Relative latency;
1724
1725   latency = get_latency (atsi);
1726   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1727                                           &peer->hashPubKey);
1728   if (cp == NULL)
1729     {
1730       GNUNET_break (0);
1731       return;
1732     }
1733   GNUNET_LOAD_value_set_decline (cp->transmission_delay,
1734                                  latency);  
1735 }
1736
1737
1738
1739 /**
1740  * Increase the host credit by a value.
1741  *
1742  * @param host which peer to change the trust value on
1743  * @param value is the int value by which the
1744  *  host credit is to be increased or decreased
1745  * @returns the actual change in trust (positive or negative)
1746  */
1747 static int
1748 change_host_trust (struct ConnectedPeer *host, int value)
1749 {
1750   if (value == 0)
1751     return 0;
1752   GNUNET_assert (host != NULL);
1753   if (value > 0)
1754     {
1755       if (host->trust + value < host->trust)
1756         {
1757           value = UINT32_MAX - host->trust;
1758           host->trust = UINT32_MAX;
1759         }
1760       else
1761         host->trust += value;
1762     }
1763   else
1764     {
1765       if (host->trust < -value)
1766         {
1767           value = -host->trust;
1768           host->trust = 0;
1769         }
1770       else
1771         host->trust += value;
1772     }
1773   return value;
1774 }
1775
1776
1777 /**
1778  * Write host-trust information to a file - flush the buffer entry!
1779  */
1780 static int
1781 flush_trust (void *cls,
1782              const GNUNET_HashCode *key,
1783              void *value)
1784 {
1785   struct ConnectedPeer *host = value;
1786   char *fn;
1787   uint32_t trust;
1788   struct GNUNET_PeerIdentity pid;
1789
1790   if (host->trust == host->disk_trust)
1791     return GNUNET_OK;                     /* unchanged */
1792   GNUNET_PEER_resolve (host->pid,
1793                        &pid);
1794   fn = get_trust_filename (&pid);
1795   if (host->trust == 0)
1796     {
1797       if ((0 != UNLINK (fn)) && (errno != ENOENT))
1798         GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING |
1799                                   GNUNET_ERROR_TYPE_BULK, "unlink", fn);
1800     }
1801   else
1802     {
1803       trust = htonl (host->trust);
1804       if (sizeof(uint32_t) == GNUNET_DISK_fn_write (fn, &trust, 
1805                                                     sizeof(uint32_t),
1806                                                     GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE
1807                                                     | GNUNET_DISK_PERM_GROUP_READ | GNUNET_DISK_PERM_OTHER_READ))
1808         host->disk_trust = host->trust;
1809     }
1810   GNUNET_free (fn);
1811   return GNUNET_OK;
1812 }
1813
1814 /**
1815  * Call this method periodically to scan data/hosts for new hosts.
1816  */
1817 static void
1818 cron_flush_trust (void *cls,
1819                   const struct GNUNET_SCHEDULER_TaskContext *tc)
1820 {
1821
1822   if (NULL == connected_peers)
1823     return;
1824   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1825                                          &flush_trust,
1826                                          NULL);
1827   if (NULL == tc)
1828     return;
1829   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1830     return;
1831   GNUNET_SCHEDULER_add_delayed (TRUST_FLUSH_FREQ, &cron_flush_trust, NULL);
1832 }
1833
1834
1835 /**
1836  * Free (each) request made by the peer.
1837  *
1838  * @param cls closure, points to peer that the request belongs to
1839  * @param key current key code
1840  * @param value value in the hash map
1841  * @return GNUNET_YES (we should continue to iterate)
1842  */
1843 static int
1844 destroy_request (void *cls,
1845                  const GNUNET_HashCode * key,
1846                  void *value)
1847 {
1848   const struct GNUNET_PeerIdentity * peer = cls;
1849   struct PendingRequest *pr = value;
1850   
1851   GNUNET_break (GNUNET_YES ==
1852                 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1853                                                       &peer->hashPubKey,
1854                                                       pr));
1855   destroy_pending_request (pr);
1856   return GNUNET_YES;
1857 }
1858
1859
1860 /**
1861  * Method called whenever a peer disconnects.
1862  *
1863  * @param cls closure, not used
1864  * @param peer peer identity this notification is about
1865  */
1866 static void
1867 peer_disconnect_handler (void *cls,
1868                          const struct
1869                          GNUNET_PeerIdentity * peer)
1870 {
1871   struct ConnectedPeer *cp;
1872   struct PendingMessage *pm;
1873   unsigned int i;
1874   struct MigrationReadyBlock *pos;
1875   struct MigrationReadyBlock *next;
1876
1877   if (0 == memcmp (&my_id, peer, sizeof (struct GNUNET_PeerIdentity)))
1878     return;
1879   GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1880                                               &peer->hashPubKey,
1881                                               &destroy_request,
1882                                               (void*) peer);
1883   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1884                                           &peer->hashPubKey);
1885   if (cp == NULL)
1886     return;
1887   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1888     {
1889       if (NULL != cp->last_client_replies[i])
1890         {
1891           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1892           cp->last_client_replies[i] = NULL;
1893         }
1894     }
1895   GNUNET_break (GNUNET_YES ==
1896                 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1897                                                       &peer->hashPubKey,
1898                                                       cp));
1899   if (cp->irc != NULL)
1900     {
1901       GNUNET_CORE_peer_change_preference_cancel (cp->irc);
1902       cp->irc = NULL;
1903       cp->pr->pirc = NULL;
1904       cp->pr = NULL;
1905     }
1906
1907   /* remove this peer from migration considerations; schedule
1908      alternatives */
1909   next = mig_head;
1910   while (NULL != (pos = next))
1911     {
1912       next = pos->next;
1913       for (i=0;i<MIGRATION_LIST_SIZE;i++)
1914         {
1915           if (pos->target_list[i] == cp->pid)
1916             {
1917               GNUNET_PEER_change_rc (pos->target_list[i], -1);
1918               pos->target_list[i] = 0;
1919             }
1920          }
1921       if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1922         {
1923           delete_migration_block (pos);
1924           consider_migration_gathering ();
1925           continue;
1926         }
1927       GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1928                                              &consider_migration,
1929                                              pos);
1930     }
1931   GNUNET_PEER_change_rc (cp->pid, -1);
1932   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1933   if (NULL != cp->cth)
1934     {
1935       GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1936       cp->cth = NULL;
1937     }
1938   if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
1939     {
1940       GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
1941       cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
1942     }
1943   while (NULL != (pm = cp->pending_messages_head))
1944     destroy_pending_message (pm, 0 /* delivery failed */);
1945   GNUNET_LOAD_value_free (cp->transmission_delay);
1946   GNUNET_break (0 == cp->pending_requests);
1947   GNUNET_free (cp);
1948 }
1949
1950
1951 /**
1952  * Iterator over hash map entries that removes all occurences
1953  * of the given 'client' from the 'last_client_replies' of the
1954  * given connected peer.
1955  *
1956  * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1957  * @param key current key code (unused)
1958  * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1959  * @return GNUNET_YES (we should continue to iterate)
1960  */
1961 static int
1962 remove_client_from_last_client_replies (void *cls,
1963                                         const GNUNET_HashCode * key,
1964                                         void *value)
1965 {
1966   struct GNUNET_SERVER_Client *client = cls;
1967   struct ConnectedPeer *cp = value;
1968   unsigned int i;
1969
1970   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1971     {
1972       if (cp->last_client_replies[i] == client)
1973         {
1974           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1975           cp->last_client_replies[i] = NULL;
1976         }
1977     }  
1978   return GNUNET_YES;
1979 }
1980
1981
1982 /**
1983  * A client disconnected.  Remove all of its pending queries.
1984  *
1985  * @param cls closure, NULL
1986  * @param client identification of the client
1987  */
1988 static void
1989 handle_client_disconnect (void *cls,
1990                           struct GNUNET_SERVER_Client
1991                           * client)
1992 {
1993   struct ClientList *pos;
1994   struct ClientList *prev;
1995   struct ClientRequestList *rcl;
1996   struct ClientResponseMessage *creply;
1997
1998   if (client == NULL)
1999     return;
2000   prev = NULL;
2001   pos = client_list;
2002   while ( (NULL != pos) &&
2003           (pos->client != client) )
2004     {
2005       prev = pos;
2006       pos = pos->next;
2007     }
2008   if (pos == NULL)
2009     return; /* no requests pending for this client */
2010   while (NULL != (rcl = pos->rl_head))
2011     {
2012       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2013                   "Destroying pending request `%s' on disconnect\n",
2014                   GNUNET_h2s (&rcl->req->query));
2015       destroy_pending_request (rcl->req);
2016     }
2017   if (prev == NULL)
2018     client_list = pos->next;
2019   else
2020     prev->next = pos->next;
2021   if (pos->th != NULL)
2022     {
2023       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
2024       pos->th = NULL;
2025     }
2026   while (NULL != (creply = pos->res_head))
2027     {
2028       GNUNET_CONTAINER_DLL_remove (pos->res_head,
2029                                    pos->res_tail,
2030                                    creply);
2031       GNUNET_free (creply);
2032     }    
2033   GNUNET_SERVER_client_drop (pos->client);
2034   GNUNET_free (pos);
2035   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2036                                          &remove_client_from_last_client_replies,
2037                                          client);
2038 }
2039
2040
2041 /**
2042  * Iterator to free peer entries.
2043  *
2044  * @param cls closure, unused
2045  * @param key current key code
2046  * @param value value in the hash map (peer entry)
2047  * @return GNUNET_YES (we should continue to iterate)
2048  */
2049 static int 
2050 clean_peer (void *cls,
2051             const GNUNET_HashCode * key,
2052             void *value)
2053 {
2054   peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
2055   return GNUNET_YES;
2056 }
2057
2058
2059 /**
2060  * Task run during shutdown.
2061  *
2062  * @param cls unused
2063  * @param tc unused
2064  */
2065 static void
2066 shutdown_task (void *cls,
2067                const struct GNUNET_SCHEDULER_TaskContext *tc)
2068 {
2069   if (mig_qe != NULL)
2070     {
2071       GNUNET_DATASTORE_cancel (mig_qe);
2072       mig_qe = NULL;
2073     }
2074   if (dht_qe != NULL)
2075     {
2076       GNUNET_DATASTORE_cancel (dht_qe);
2077       dht_qe = NULL;
2078     }
2079   if (GNUNET_SCHEDULER_NO_TASK != mig_task)
2080     {
2081       GNUNET_SCHEDULER_cancel (mig_task);
2082       mig_task = GNUNET_SCHEDULER_NO_TASK;
2083     }
2084   if (GNUNET_SCHEDULER_NO_TASK != dht_task)
2085     {
2086       GNUNET_SCHEDULER_cancel (dht_task);
2087       dht_task = GNUNET_SCHEDULER_NO_TASK;
2088     }
2089   while (client_list != NULL)
2090     handle_client_disconnect (NULL,
2091                               client_list->client);
2092   cron_flush_trust (NULL, NULL);
2093   GNUNET_assert (NULL != core);
2094   GNUNET_CORE_disconnect (core);
2095   core = NULL;
2096   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2097                                          &clean_peer,
2098                                          NULL);
2099   GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
2100   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2101   requests_by_expiration_heap = 0;
2102   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2103   connected_peers = NULL;
2104   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
2105   GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2106   query_request_map = NULL;
2107   GNUNET_LOAD_value_free (rt_entry_lifetime);
2108   rt_entry_lifetime = NULL;
2109   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
2110   GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2111   peer_request_map = NULL;
2112   if (stats != NULL)
2113     {
2114       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
2115       stats = NULL;
2116     }
2117   if (dsh != NULL)
2118     {
2119       GNUNET_DATASTORE_disconnect (dsh,
2120                                    GNUNET_NO);
2121       dsh = NULL;
2122     }
2123   while (mig_head != NULL)
2124     delete_migration_block (mig_head);
2125   GNUNET_assert (0 == mig_size);
2126   GNUNET_DHT_disconnect (dht_handle);
2127   dht_handle = NULL;
2128   GNUNET_LOAD_value_free (datastore_get_load);
2129   datastore_get_load = NULL;
2130   GNUNET_LOAD_value_free (datastore_put_load);
2131   datastore_put_load = NULL;
2132   GNUNET_BLOCK_context_destroy (block_ctx);
2133   block_ctx = NULL;
2134   GNUNET_CONFIGURATION_destroy (block_cfg);
2135   block_cfg = NULL;
2136   cfg = NULL;  
2137   GNUNET_free_non_null (trustDirectory);
2138   trustDirectory = NULL;
2139   GNUNET_SCHEDULER_cancel (cover_age_task);
2140   cover_age_task = GNUNET_SCHEDULER_NO_TASK;
2141 }
2142
2143
2144 /* ******************* Utility functions  ******************** */
2145
2146
2147 /**
2148  * We've had to delay a request for transmission to core, but now
2149  * we should be ready.  Run it.
2150  *
2151  * @param cls the 'struct ConnectedPeer' for which a request was delayed
2152  * @param tc task context (unused)
2153  */
2154 static void
2155 delayed_transmission_request (void *cls,
2156                               const struct GNUNET_SCHEDULER_TaskContext *tc)
2157 {
2158   struct ConnectedPeer *cp = cls;
2159   struct GNUNET_PeerIdentity pid;
2160   struct PendingMessage *pm;
2161
2162   pm = cp->pending_messages_head;
2163   cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2164   GNUNET_assert (cp->cth == NULL);
2165   if (pm == NULL)
2166     return;
2167   GNUNET_PEER_resolve (cp->pid,
2168                        &pid);
2169   cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2170   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2171                                                pm->priority,
2172                                                GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2173                                                &pid,
2174                                                pm->msize,
2175                                                &transmit_to_peer,
2176                                                cp);
2177 }
2178
2179
2180 /**
2181  * Transmit messages by copying it to the target buffer
2182  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
2183  * for writing in the meantime.  In that case, do nothing
2184  * (the disconnect or shutdown handler will take care of the rest).
2185  * If we were able to transmit messages and there are still more
2186  * pending, ask core again for further calls to this function.
2187  *
2188  * @param cls closure, pointer to the 'struct ConnectedPeer*'
2189  * @param size number of bytes available in buf
2190  * @param buf where the callee should write the message
2191  * @return number of bytes written to buf
2192  */
2193 static size_t
2194 transmit_to_peer (void *cls,
2195                   size_t size, void *buf)
2196 {
2197   struct ConnectedPeer *cp = cls;
2198   char *cbuf = buf;
2199   struct PendingMessage *pm;
2200   struct PendingMessage *next_pm;
2201   struct GNUNET_TIME_Absolute now;
2202   struct GNUNET_TIME_Relative min_delay;
2203   struct MigrationReadyBlock *mb;
2204   struct MigrationReadyBlock *next;
2205   struct PutMessage migm;
2206   size_t msize;
2207   unsigned int i;
2208   struct GNUNET_PeerIdentity pid;
2209  
2210   cp->cth = NULL;
2211   if (NULL == buf)
2212     {
2213 #if DEBUG_FS
2214       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215                   "Dropping message, core too busy.\n");
2216 #endif
2217       GNUNET_LOAD_update (cp->transmission_delay,
2218                           UINT64_MAX);
2219       
2220       if (NULL != (pm = cp->pending_messages_head))
2221         {
2222           GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2223                                        cp->pending_messages_tail,
2224                                        pm);
2225           cp->pending_requests--;    
2226           destroy_pending_message (pm, 0);
2227         }
2228       if (NULL != (pm = cp->pending_messages_head))
2229         {
2230           GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2231           min_delay = GNUNET_TIME_absolute_get_remaining (pm->delay_until);
2232           cp->delayed_transmission_request_task
2233             = GNUNET_SCHEDULER_add_delayed (min_delay,
2234                                             &delayed_transmission_request,
2235                                             cp);
2236         }
2237       return 0;
2238     }  
2239   GNUNET_LOAD_update (cp->transmission_delay,
2240                       GNUNET_TIME_absolute_get_duration (cp->last_transmission_request_start).rel_value);
2241   now = GNUNET_TIME_absolute_get ();
2242   msize = 0;
2243   min_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2244   next_pm = cp->pending_messages_head;
2245   while ( (NULL != (pm = next_pm) ) &&
2246           (pm->msize <= size) )
2247     {
2248       next_pm = pm->next;
2249       if (pm->delay_until.abs_value > now.abs_value)
2250         {
2251           min_delay = GNUNET_TIME_relative_min (min_delay,
2252                                                 GNUNET_TIME_absolute_get_remaining (pm->delay_until));
2253           continue;
2254         }
2255       memcpy (&cbuf[msize], &pm[1], pm->msize);
2256       msize += pm->msize;
2257       size -= pm->msize;
2258       if (NULL == pm->pml)
2259         {
2260           GNUNET_CONTAINER_DLL_remove (cp->pending_messages_head,
2261                                        cp->pending_messages_tail,
2262                                        pm);
2263           cp->pending_requests--;
2264         }
2265       destroy_pending_message (pm, cp->pid);
2266     }
2267   if (pm != NULL)
2268     min_delay = GNUNET_TIME_UNIT_ZERO;
2269   if (NULL != cp->pending_messages_head)
2270     {     
2271       GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == cp->delayed_transmission_request_task);
2272       cp->delayed_transmission_request_task
2273         = GNUNET_SCHEDULER_add_delayed (min_delay,
2274                                         &delayed_transmission_request,
2275                                         cp);
2276     }
2277   if (pm == NULL)
2278     {      
2279       GNUNET_PEER_resolve (cp->pid,
2280                            &pid);
2281       next = mig_head;
2282       while (NULL != (mb = next))
2283         {
2284           next = mb->next;
2285           for (i=0;i<MIGRATION_LIST_SIZE;i++)
2286             {
2287               if ( (cp->pid == mb->target_list[i]) &&
2288                    (mb->size + sizeof (migm) <= size) )
2289                 {
2290                   GNUNET_PEER_change_rc (mb->target_list[i], -1);
2291                   mb->target_list[i] = 0;
2292                   mb->used_targets++;
2293                   memset (&migm, 0, sizeof (migm));
2294                   migm.header.size = htons (sizeof (migm) + mb->size);
2295                   migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2296                   migm.type = htonl (mb->type);
2297                   migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
2298                   memcpy (&cbuf[msize], &migm, sizeof (migm));
2299                   msize += sizeof (migm);
2300                   size -= sizeof (migm);
2301                   memcpy (&cbuf[msize], &mb[1], mb->size);
2302                   msize += mb->size;
2303                   size -= mb->size;
2304 #if DEBUG_FS
2305                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306                               "Pushing migration block `%s' (%u bytes) to `%s'\n",
2307                               GNUNET_h2s (&mb->query),
2308                               (unsigned int) mb->size,
2309                               GNUNET_i2s (&pid));
2310 #endif    
2311                   break;
2312                 }
2313               else
2314                 {
2315 #if DEBUG_FS
2316                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317                               "Migration block `%s' (%u bytes) is not on migration list for peer `%s'\n",
2318                               GNUNET_h2s (&mb->query),
2319                               (unsigned int) mb->size,
2320                               GNUNET_i2s (&pid));
2321 #endif    
2322                 }
2323             }
2324           if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
2325                (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
2326             {
2327               delete_migration_block (mb);
2328               consider_migration_gathering ();
2329             }
2330         }
2331       consider_migration (NULL, 
2332                           &pid.hashPubKey,
2333                           cp);
2334     }
2335 #if DEBUG_FS
2336   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2337               "Transmitting %u bytes to peer with PID %u\n",
2338               (unsigned int) msize,
2339               (unsigned int) cp->pid);
2340 #endif
2341   return msize;
2342 }
2343
2344
2345 /**
2346  * Add a message to the set of pending messages for the given peer.
2347  *
2348  * @param cp peer to send message to
2349  * @param pm message to queue
2350  * @param pr request on which behalf this message is being queued
2351  */
2352 static void
2353 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
2354                                   struct PendingMessage *pm,
2355                                   struct PendingRequest *pr)
2356 {
2357   struct PendingMessage *pos;
2358   struct PendingMessageList *pml;
2359   struct GNUNET_PeerIdentity pid;
2360
2361   GNUNET_assert (pm->next == NULL);
2362   GNUNET_assert (pm->pml == NULL);    
2363   if (pr != NULL)
2364     {
2365       pml = GNUNET_malloc (sizeof (struct PendingMessageList));
2366       pml->req = pr;
2367       pml->target = cp;
2368       pml->pm = pm;
2369       pm->pml = pml;  
2370       GNUNET_CONTAINER_DLL_insert (pr->pending_head,
2371                                    pr->pending_tail,
2372                                    pml);
2373     }
2374   pos = cp->pending_messages_head;
2375   while ( (pos != NULL) &&
2376           (pm->priority < pos->priority) )
2377     pos = pos->next;    
2378   GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
2379                                      cp->pending_messages_tail,
2380                                      pos,
2381                                      pm);
2382   cp->pending_requests++;
2383   if (cp->pending_requests > MAX_QUEUE_PER_PEER)
2384     {
2385       GNUNET_STATISTICS_update (stats,
2386                                 gettext_noop ("# P2P searches discarded (queue length bound)"),
2387                                 1,
2388                                 GNUNET_NO);
2389       destroy_pending_message (cp->pending_messages_tail, 0);  
2390     }
2391   GNUNET_PEER_resolve (cp->pid, &pid);
2392   if (NULL != cp->cth)
2393     {
2394       GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
2395       cp->cth = NULL;
2396     }
2397   if (cp->delayed_transmission_request_task != GNUNET_SCHEDULER_NO_TASK)
2398     {
2399       GNUNET_SCHEDULER_cancel (cp->delayed_transmission_request_task);
2400       cp->delayed_transmission_request_task = GNUNET_SCHEDULER_NO_TASK;
2401     }
2402   /* need to schedule transmission */
2403   cp->last_transmission_request_start = GNUNET_TIME_absolute_get ();
2404   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
2405                                                cp->pending_messages_head->priority,
2406                                                MAX_TRANSMIT_DELAY,
2407                                                &pid,
2408                                                cp->pending_messages_head->msize,
2409                                                &transmit_to_peer,
2410                                                cp);
2411   if (cp->cth == NULL)
2412     {
2413 #if DEBUG_FS
2414       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2415                   "Failed to schedule transmission with core!\n");
2416 #endif
2417       GNUNET_STATISTICS_update (stats,
2418                                 gettext_noop ("# CORE transmission failures"),
2419                                 1,
2420                                 GNUNET_NO);
2421     }
2422 }
2423
2424
2425 /**
2426  * Test if the DATABASE (GET) load on this peer is too high
2427  * to even consider processing the query at
2428  * all.  
2429  * 
2430  * @return GNUNET_YES if the load is too high to do anything (load high)
2431  *         GNUNET_NO to process normally (load normal)
2432  *         GNUNET_SYSERR to process for free (load low)
2433  */
2434 static int
2435 test_get_load_too_high (uint32_t priority)
2436 {
2437   double ld;
2438
2439   ld = GNUNET_LOAD_get_load (datastore_get_load);
2440   if (ld < 1)
2441     return GNUNET_SYSERR;    
2442   if (ld <= priority)    
2443     return GNUNET_NO;    
2444   return GNUNET_YES;
2445 }
2446
2447
2448
2449
2450 /**
2451  * Test if the DATABASE (PUT) load on this peer is too high
2452  * to even consider processing the query at
2453  * all.  
2454  * 
2455  * @return GNUNET_YES if the load is too high to do anything (load high)
2456  *         GNUNET_NO to process normally (load normal or low)
2457  */
2458 static int
2459 test_put_load_too_high (uint32_t priority)
2460 {
2461   double ld;
2462
2463   if (GNUNET_LOAD_get_average (datastore_put_load) < 50)
2464     return GNUNET_NO; /* very fast */
2465   ld = GNUNET_LOAD_get_load (datastore_put_load);
2466   if (ld < 2.0 * (1 + priority))
2467     return GNUNET_NO;
2468   GNUNET_STATISTICS_update (stats,
2469                             gettext_noop ("# storage requests dropped due to high load"),
2470                             1,
2471                             GNUNET_NO);
2472   return GNUNET_YES;
2473 }
2474
2475
2476 /* ******************* Pending Request Refresh Task ******************** */
2477
2478
2479
2480 /**
2481  * We use a random delay to make the timing of requests less
2482  * predictable.  This function returns such a random delay.  We add a base
2483  * delay of MAX_CORK_DELAY (1s).
2484  *
2485  * FIXME: make schedule dependent on the specifics of the request?
2486  * Or bandwidth and number of connected peers and load?
2487  *
2488  * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
2489  */
2490 static struct GNUNET_TIME_Relative
2491 get_processing_delay ()
2492 {
2493   return 
2494     GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
2495                               GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
2496                                                              GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2497                                                                                        TTL_DECREMENT)));
2498 }
2499
2500
2501 /**
2502  * We're processing a GET request from another peer and have decided
2503  * to forward it to other peers.  This function is called periodically
2504  * and should forward the request to other peers until we have all
2505  * possible replies.  If we have transmitted the *only* reply to
2506  * the initiator we should destroy the pending request.  If we have
2507  * many replies in the queue to the initiator, we should delay sending
2508  * out more queries until the reply queue has shrunk some.
2509  *
2510  * @param cls our "struct ProcessGetContext *"
2511  * @param tc unused
2512  */
2513 static void
2514 forward_request_task (void *cls,
2515                       const struct GNUNET_SCHEDULER_TaskContext *tc);
2516
2517
2518 /**
2519  * Function called after we either failed or succeeded
2520  * at transmitting a query to a peer.  
2521  *
2522  * @param cls the requests "struct PendingRequest*"
2523  * @param tpid ID of receiving peer, 0 on transmission error
2524  */
2525 static void
2526 transmit_query_continuation (void *cls,
2527                              GNUNET_PEER_Id tpid)
2528 {
2529   struct PendingRequest *pr = cls;
2530   unsigned int i;
2531
2532   GNUNET_STATISTICS_update (stats,
2533                             gettext_noop ("# queries scheduled for forwarding"),
2534                             -1,
2535                             GNUNET_NO);
2536   if (tpid == 0)   
2537     {
2538 #if DEBUG_FS
2539       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540                   "Transmission of request failed, will try again later.\n");
2541 #endif
2542       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2543         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2544                                                  &forward_request_task,
2545                                                  pr); 
2546       return;    
2547     }
2548 #if DEBUG_FS
2549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550               "Transmitted query `%s'\n",
2551               GNUNET_h2s (&pr->query));
2552 #endif
2553   GNUNET_STATISTICS_update (stats,
2554                             gettext_noop ("# queries forwarded"),
2555                             1,
2556                             GNUNET_NO);
2557   for (i=0;i<pr->used_targets_off;i++)
2558     if (pr->used_targets[i].pid == tpid)
2559       break; /* found match! */    
2560   if (i == pr->used_targets_off)
2561     {
2562       /* need to create new entry */
2563       if (pr->used_targets_off == pr->used_targets_size)
2564         GNUNET_array_grow (pr->used_targets,
2565                            pr->used_targets_size,
2566                            pr->used_targets_size * 2 + 2);
2567       GNUNET_PEER_change_rc (tpid, 1);
2568       pr->used_targets[pr->used_targets_off].pid = tpid;
2569       pr->used_targets[pr->used_targets_off].num_requests = 0;
2570       i = pr->used_targets_off++;
2571     }
2572   pr->used_targets[i].last_request_time = GNUNET_TIME_absolute_get ();
2573   pr->used_targets[i].num_requests++;
2574   if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2575     pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2576                                              &forward_request_task,
2577                                              pr);
2578 }
2579
2580
2581 /**
2582  * How many bytes should a bloomfilter be if we have already seen
2583  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
2584  * of bits set per entry.  Furthermore, we should not re-size the
2585  * filter too often (to keep it cheap).
2586  *
2587  * Since other peers will also add entries but not resize the filter,
2588  * we should generally pick a slightly larger size than what the
2589  * strict math would suggest.
2590  *
2591  * @return must be a power of two and smaller or equal to 2^15.
2592  */
2593 static size_t
2594 compute_bloomfilter_size (unsigned int entry_count)
2595 {
2596   size_t size;
2597   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
2598   uint16_t max = 1 << 15;
2599
2600   if (entry_count > max)
2601     return max;
2602   size = 8;
2603   while ((size < max) && (size < ideal))
2604     size *= 2;
2605   if (size > max)
2606     return max;
2607   return size;
2608 }
2609
2610
2611 /**
2612  * Recalculate our bloom filter for filtering replies.  This function
2613  * will create a new bloom filter from scratch, so it should only be
2614  * called if we have no bloomfilter at all (and hence can create a
2615  * fresh one of minimal size without problems) OR if our peer is the
2616  * initiator (in which case we may resize to larger than mimimum size).
2617  *
2618  * @param pr request for which the BF is to be recomputed
2619  */
2620 static void
2621 refresh_bloomfilter (struct PendingRequest *pr)
2622 {
2623   unsigned int i;
2624   size_t nsize;
2625   GNUNET_HashCode mhash;
2626
2627   nsize = compute_bloomfilter_size (pr->replies_seen_off);
2628   if (nsize == pr->bf_size)
2629     return; /* size not changed */
2630   if (pr->bf != NULL)
2631     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2632   pr->bf_size = nsize;
2633   pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
2634   pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
2635                                               pr->bf_size,
2636                                               BLOOMFILTER_K);
2637   for (i=0;i<pr->replies_seen_off;i++)
2638     {
2639       GNUNET_BLOCK_mingle_hash (&pr->replies_seen[i],
2640                                 pr->mingle,
2641                                 &mhash);
2642       GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
2643     }
2644 }
2645
2646
2647 /**
2648  * Function called after we've tried to reserve a certain amount of
2649  * bandwidth for a reply.  Check if we succeeded and if so send our
2650  * query.
2651  *
2652  * @param cls the requests "struct PendingRequest*"
2653  * @param peer identifies the peer
2654  * @param bpm_out set to the current bandwidth limit (sending) for this peer
2655  * @param amount set to the amount that was actually reserved or unreserved
2656  * @param preference current traffic preference for the given peer
2657  */
2658 static void
2659 target_reservation_cb (void *cls,
2660                        const struct
2661                        GNUNET_PeerIdentity * peer,
2662                        struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
2663                        int amount,
2664                        uint64_t preference)
2665 {
2666   struct PendingRequest *pr = cls;
2667   struct ConnectedPeer *cp;
2668   struct PendingMessage *pm;
2669   struct GetMessage *gm;
2670   GNUNET_HashCode *ext;
2671   char *bfdata;
2672   size_t msize;
2673   unsigned int k;
2674   int no_route;
2675   uint32_t bm;
2676   unsigned int i;
2677
2678   /* (3) transmit, update ttl/priority */
2679   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2680                                           &peer->hashPubKey);
2681   if (cp == NULL)
2682     {
2683       /* Peer must have just left */
2684 #if DEBUG_FS
2685       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686                   "Selected peer disconnected!\n");
2687 #endif
2688       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2689         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2690                                                  &forward_request_task,
2691                                                  pr);
2692       return;
2693     }
2694   cp->irc = NULL;
2695   pr->pirc = NULL;
2696   if (peer == NULL)
2697     {
2698       /* error in communication with core, try again later */
2699       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2700         pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2701                                                  &forward_request_task,
2702                                                  pr);
2703       return;
2704     }
2705   no_route = GNUNET_NO;
2706   if (amount == 0)
2707     {
2708       if (pr->cp == NULL)
2709         {
2710 #if DEBUG_FS > 1
2711           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2712                       "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
2713                       amount,
2714                       DBLOCK_SIZE);
2715 #endif
2716           GNUNET_STATISTICS_update (stats,
2717                                     gettext_noop ("# reply bandwidth reservation requests failed"),
2718                                     1,
2719                                     GNUNET_NO);
2720           if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2721             pr->task = GNUNET_SCHEDULER_add_delayed (get_processing_delay (),
2722                                                      &forward_request_task,
2723                                                      pr);
2724           return;  /* this target round failed */
2725         }
2726       no_route = GNUNET_YES;
2727     }
2728   
2729   GNUNET_STATISTICS_update (stats,
2730                             gettext_noop ("# queries scheduled for forwarding"),
2731                             1,
2732                             GNUNET_NO);
2733   for (i=0;i<pr->used_targets_off;i++)
2734     if (pr->used_targets[i].pid == cp->pid) 
2735       {
2736         GNUNET_STATISTICS_update (stats,
2737                                   gettext_noop ("# queries retransmitted to same target"),
2738                                   1,
2739                                   GNUNET_NO);
2740         break;
2741       } 
2742
2743   /* build message and insert message into priority queue */
2744 #if DEBUG_FS
2745   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2746               "Forwarding request `%s' to `%4s'!\n",
2747               GNUNET_h2s (&pr->query),
2748               GNUNET_i2s (peer));
2749 #endif
2750   k = 0;
2751   bm = 0;
2752   if (GNUNET_YES == no_route)
2753     {
2754       bm |= GET_MESSAGE_BIT_RETURN_TO;
2755       k++;      
2756     }
2757   if (pr->namespace != NULL)
2758     {
2759       bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
2760       k++;
2761     }
2762   if (pr->target_pid != 0)
2763     {
2764       bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
2765       k++;
2766     }
2767   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
2768   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2769   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
2770   pm->msize = msize;
2771   gm = (struct GetMessage*) &pm[1];
2772   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
2773   gm->header.size = htons (msize);
2774   gm->type = htonl (pr->type);
2775   pr->remaining_priority /= 2;
2776   gm->priority = htonl (pr->remaining_priority);
2777   gm->ttl = htonl (pr->ttl);
2778   gm->filter_mutator = htonl(pr->mingle); 
2779   gm->hash_bitmap = htonl (bm);
2780   gm->query = pr->query;
2781   ext = (GNUNET_HashCode*) &gm[1];
2782   k = 0;
2783   if (GNUNET_YES == no_route)
2784     GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2785   if (pr->namespace != NULL)
2786     memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
2787   if (pr->target_pid != 0)
2788     GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
2789   bfdata = (char *) &ext[k];
2790   if (pr->bf != NULL)
2791     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
2792                                                bfdata,
2793                                                pr->bf_size);
2794   pm->cont = &transmit_query_continuation;
2795   pm->cont_cls = pr;
2796   cp->last_request_times[(cp->last_request_times_off++) % MAX_QUEUE_PER_PEER] = GNUNET_TIME_absolute_get ();
2797   add_to_pending_messages_for_peer (cp, pm, pr);
2798 }
2799
2800
2801 /**
2802  * Closure used for "target_peer_select_cb".
2803  */
2804 struct PeerSelectionContext 
2805 {
2806   /**
2807    * The request for which we are selecting
2808    * peers.
2809    */
2810   struct PendingRequest *pr;
2811
2812   /**
2813    * Current "prime" target.
2814    */
2815   struct GNUNET_PeerIdentity target;
2816
2817   /**
2818    * How much do we like this target?
2819    */
2820   double target_score;
2821
2822   /**
2823    * Does it make sense to we re-try quickly again?
2824    */
2825   int fast_retry;
2826
2827 };
2828
2829
2830 /**
2831  * Function called for each connected peer to determine
2832  * which one(s) would make good targets for forwarding.
2833  *
2834  * @param cls closure (struct PeerSelectionContext)
2835  * @param key current key code (peer identity)
2836  * @param value value in the hash map (struct ConnectedPeer)
2837  * @return GNUNET_YES if we should continue to
2838  *         iterate,
2839  *         GNUNET_NO if not.
2840  */
2841 static int
2842 target_peer_select_cb (void *cls,
2843                        const GNUNET_HashCode * key,
2844                        void *value)
2845 {
2846   struct PeerSelectionContext *psc = cls;
2847   struct ConnectedPeer *cp = value;
2848   struct PendingRequest *pr = psc->pr;
2849   struct GNUNET_TIME_Relative delay;
2850   double score;
2851   unsigned int i;
2852   unsigned int pc;
2853
2854   /* 1) check that this peer is not the initiator */
2855   if (cp == pr->cp)     
2856     {
2857 #if DEBUG_FS
2858       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859                   "Skipping initiator in forwarding selection\n");
2860 #endif
2861       return GNUNET_YES; /* skip */        
2862     }
2863   if (cp->irc != NULL)
2864     {
2865       psc->fast_retry = GNUNET_YES;
2866       return GNUNET_YES; /* skip: already querying core about this peer for other reasons */
2867     }
2868
2869   /* 2) check if we have already (recently) forwarded to this peer */
2870   /* 2a) this particular request */
2871   pc = 0;
2872   for (i=0;i<pr->used_targets_off;i++)
2873     if (pr->used_targets[i].pid == cp->pid) 
2874       {
2875         pc = pr->used_targets[i].num_requests;
2876         GNUNET_assert (pc > 0);
2877         /* FIXME: make re-enabling a peer independent of how often
2878            this function is called??? */
2879         if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2880                                            RETRY_PROBABILITY_INV * pc))
2881           {
2882 #if DEBUG_FS
2883             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2884                         "NOT re-trying query that was previously transmitted %u times\n",
2885                         (unsigned int) pc);
2886 #endif
2887             return GNUNET_YES; /* skip */
2888           }
2889         break;
2890       }
2891 #if DEBUG_FS
2892   if (0 < pc)
2893     {
2894       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2895                   "Re-trying query that was previously transmitted %u times to this peer\n",
2896                   (unsigned int) pc);
2897     }
2898 #endif
2899   /* 2b) many other requests to this peer */
2900   delay = GNUNET_TIME_absolute_get_duration (cp->last_request_times[cp->last_request_times_off % MAX_QUEUE_PER_PEER]);
2901   if (delay.rel_value <= cp->avg_delay.rel_value)
2902     {
2903 #if DEBUG_FS
2904       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2905                   "NOT sending query since we send %u others to this peer in the last %llums\n",
2906                   MAX_QUEUE_PER_PEER,
2907                   cp->avg_delay.rel_value);
2908 #endif
2909       return GNUNET_YES; /* skip */      
2910     }
2911
2912   /* 3) calculate how much we'd like to forward to this peer,
2913      starting with a random value that is strong enough
2914      to at least give any peer a chance sometimes 
2915      (compared to the other factors that come later) */
2916   /* 3a) count successful (recent) routes from cp for same source */
2917   if (pr->cp != NULL)
2918     {
2919       score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2920                                         P2P_SUCCESS_LIST_SIZE);
2921       for (i=0;i<P2P_SUCCESS_LIST_SIZE;i++)
2922         if (cp->last_p2p_replies[i] == pr->cp->pid)
2923           score += 1.0; /* likely successful based on hot path */
2924     }
2925   else
2926     {
2927       score = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2928                                         CS2P_SUCCESS_LIST_SIZE);
2929       for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
2930         if (cp->last_client_replies[i] == pr->client_request_list->client_list->client)
2931           score += 1.0; /* likely successful based on hot path */
2932     }
2933   /* 3b) include latency */
2934   if (cp->avg_delay.rel_value < 4 * TTL_DECREMENT)
2935     score += 1.0; /* likely fast based on latency */
2936   /* 3c) include priorities */
2937   if (cp->avg_priority <= pr->remaining_priority / 2.0)
2938     score += 1.0; /* likely successful based on priorities */
2939   /* 3d) penalize for queue size */  
2940   score -= (2.0 * cp->pending_requests / (double) MAX_QUEUE_PER_PEER); 
2941   /* 3e) include peer proximity */
2942   score -= (2.0 * (GNUNET_CRYPTO_hash_distance_u32 (key,
2943                                                     &pr->query)) / (double) UINT32_MAX);
2944   /* 4) super-bonus for being the known target */
2945   if (pr->target_pid == cp->pid)
2946     score += 100.0;
2947   /* store best-fit in closure */
2948   score++; /* avoid zero */
2949   if (score > psc->target_score)
2950     {
2951       psc->target_score = score;
2952       psc->target.hashPubKey = *key; 
2953     }
2954 #if DEBUG_FS
2955   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2956               "Peer `%s' gets score %f for forwarding query, max is %8f\n",
2957               GNUNET_h2s (key),
2958               score,
2959               psc->target_score);
2960 #endif
2961   return GNUNET_YES;
2962 }
2963   
2964
2965 /**
2966  * The priority level imposes a bound on the maximum
2967  * value for the ttl that can be requested.
2968  *
2969  * @param ttl_in requested ttl
2970  * @param prio given priority
2971  * @return ttl_in if ttl_in is below the limit,
2972  *         otherwise the ttl-limit for the given priority
2973  */
2974 static int32_t
2975 bound_ttl (int32_t ttl_in, uint32_t prio)
2976 {
2977   unsigned long long allowed;
2978
2979   if (ttl_in <= 0)
2980     return ttl_in;
2981   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2982   if (ttl_in > allowed)      
2983     {
2984       if (allowed >= (1 << 30))
2985         return 1 << 30;
2986       return allowed;
2987     }
2988   return ttl_in;
2989 }
2990
2991
2992 /**
2993  * Iterator called on each result obtained for a DHT
2994  * operation that expects a reply
2995  *
2996  * @param cls closure
2997  * @param exp when will this value expire
2998  * @param key key of the result
2999  * @param get_path NULL-terminated array of pointers
3000  *                 to the peers on reverse GET path (or NULL if not recorded)
3001  * @param put_path NULL-terminated array of pointers
3002  *                 to the peers on the PUT path (or NULL if not recorded)
3003  * @param type type of the result
3004  * @param size number of bytes in data
3005  * @param data pointer to the result data
3006  */
3007 static void
3008 process_dht_reply (void *cls,
3009                    struct GNUNET_TIME_Absolute exp,
3010                    const GNUNET_HashCode * key,
3011                    const struct GNUNET_PeerIdentity * const *get_path,
3012                    const struct GNUNET_PeerIdentity * const *put_path,
3013                    enum GNUNET_BLOCK_Type type,
3014                    size_t size,
3015                    const void *data);
3016
3017
3018 /**
3019  * We're processing a GET request and have decided
3020  * to forward it to other peers.  This function is called periodically
3021  * and should forward the request to other peers until we have all
3022  * possible replies.  If we have transmitted the *only* reply to
3023  * the initiator we should destroy the pending request.  If we have
3024  * many replies in the queue to the initiator, we should delay sending
3025  * out more queries until the reply queue has shrunk some.
3026  *
3027  * @param cls our "struct ProcessGetContext *"
3028  * @param tc unused
3029  */
3030 static void
3031 forward_request_task (void *cls,
3032                      const struct GNUNET_SCHEDULER_TaskContext *tc)
3033 {
3034   struct PendingRequest *pr = cls;
3035   struct PeerSelectionContext psc;
3036   struct ConnectedPeer *cp; 
3037   struct GNUNET_TIME_Relative delay;
3038
3039   pr->task = GNUNET_SCHEDULER_NO_TASK;
3040   if (pr->pirc != NULL)
3041     {
3042 #if DEBUG_FS
3043       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3044                   "Forwarding of query `%s' not attempted due to pending local lookup!\n",
3045                   GNUNET_h2s (&pr->query));
3046 #endif
3047       return; /* already pending */
3048     }
3049   if (GNUNET_YES == pr->local_only)
3050     return; /* configured to not do P2P search */
3051   /* (0) try DHT */
3052   if ( (0 == pr->anonymity_level) &&
3053        (GNUNET_YES != pr->forward_only) &&
3054        (pr->type != GNUNET_BLOCK_TYPE_FS_DBLOCK) &&
3055        (pr->type != GNUNET_BLOCK_TYPE_FS_IBLOCK) )
3056     {
3057       pr->dht_get = GNUNET_DHT_get_start (dht_handle,
3058                                           GNUNET_TIME_UNIT_FOREVER_REL,
3059                                           pr->type,
3060                                           &pr->query,
3061                                           DEFAULT_GET_REPLICATION,
3062                                           GNUNET_DHT_RO_NONE,
3063                                           pr->bf,
3064                                           pr->mingle,
3065                                           pr->namespace,
3066                                           (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3067                                           &process_dht_reply,
3068                                           pr);
3069     }
3070
3071   if ( (pr->anonymity_level > 1) &&
3072        (cover_query_count < pr->anonymity_level - 1) )
3073     {
3074       delay = get_processing_delay ();
3075 #if DEBUG_FS 
3076       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3077                   "Not enough cover traffic to forward query `%s', will try again in %llu ms!\n",
3078                   GNUNET_h2s (&pr->query),
3079                   delay.rel_value);
3080 #endif
3081       pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3082                                                &forward_request_task,
3083                                                pr);
3084       return;
3085     }
3086   /* consume cover traffic */
3087   if (pr->anonymity_level > 1) 
3088     cover_query_count -= pr->anonymity_level - 1;
3089
3090   /* (1) select target */
3091   psc.pr = pr;
3092   psc.target_score = -DBL_MAX;
3093   psc.fast_retry = GNUNET_NO;
3094   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
3095                                          &target_peer_select_cb,
3096                                          &psc);  
3097   if (psc.target_score == -DBL_MAX)
3098     {
3099       if (psc.fast_retry == GNUNET_YES)
3100         delay = GNUNET_TIME_UNIT_MILLISECONDS; /* FIXME: store adaptive fast-retry value in 'pr' */
3101       else
3102         delay = get_processing_delay ();
3103 #if DEBUG_FS 
3104       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3105                   "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
3106                   GNUNET_h2s (&pr->query),
3107                   delay.rel_value);
3108 #endif
3109       pr->task = GNUNET_SCHEDULER_add_delayed (delay,
3110                                                &forward_request_task,
3111                                                pr);
3112       return; /* nobody selected */
3113     }
3114   /* (3) update TTL/priority */
3115   if (pr->client_request_list != NULL)
3116     {
3117       /* FIXME: use better algorithm!? */
3118       if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3119                                          4))
3120         pr->priority++;
3121       /* bound priority we use by priorities we see from other peers
3122          rounded up (must round up so that we can see non-zero
3123          priorities, but round up as little as possible to make it
3124          plausible that we forwarded another peers request) */
3125       if (pr->priority > current_priorities + 1.0)
3126         pr->priority = (uint32_t) current_priorities + 1.0;
3127       pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
3128                            pr->priority);
3129 #if DEBUG_FS
3130       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3131                   "Trying query `%s' with priority %u and TTL %d.\n",
3132                   GNUNET_h2s (&pr->query),
3133                   pr->priority,
3134                   pr->ttl);
3135 #endif
3136     }
3137
3138   /* (3) reserve reply bandwidth */
3139   if (GNUNET_NO == pr->forward_only)
3140     {
3141       cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3142                                               &psc.target.hashPubKey);
3143       GNUNET_assert (NULL != cp);
3144       GNUNET_assert (cp->irc == NULL);
3145       pr->pirc = cp;
3146       cp->pr = pr;
3147       cp->irc = GNUNET_CORE_peer_change_preference (core,
3148                                                     &psc.target,
3149                                                     GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
3150                                                     GNUNET_BANDWIDTH_value_init (UINT32_MAX),
3151                                                     DBLOCK_SIZE * 2, 
3152                                                     cp->inc_preference,
3153                                                     &target_reservation_cb,
3154                                                     pr);
3155       GNUNET_assert (cp->irc != NULL);
3156       cp->inc_preference = 0;
3157     }
3158   else
3159     {
3160       /* force forwarding */
3161       static struct GNUNET_BANDWIDTH_Value32NBO zerobw;
3162       target_reservation_cb (pr, &psc.target,
3163                              zerobw, 0, 0.0);
3164     }
3165 }
3166
3167
3168 /* **************************** P2P PUT Handling ************************ */
3169
3170
3171 /**
3172  * Function called after we either failed or succeeded
3173  * at transmitting a reply to a peer.  
3174  *
3175  * @param cls the requests "struct PendingRequest*"
3176  * @param tpid ID of receiving peer, 0 on transmission error
3177  */
3178 static void
3179 transmit_reply_continuation (void *cls,
3180                              GNUNET_PEER_Id tpid)
3181 {
3182   struct PendingRequest *pr = cls;
3183   
3184   switch (pr->type)
3185     {
3186     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
3187     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
3188       /* only one reply expected, done with the request! */
3189       destroy_pending_request (pr);
3190       break;
3191     case GNUNET_BLOCK_TYPE_ANY:
3192     case GNUNET_BLOCK_TYPE_FS_KBLOCK:
3193     case GNUNET_BLOCK_TYPE_FS_SBLOCK:
3194       break;
3195     default:
3196       GNUNET_break (0);
3197       break;
3198     }
3199 }
3200
3201
3202 /**
3203  * Transmit the given message by copying it to the target buffer
3204  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
3205  * for writing in the meantime.  In that case, do nothing
3206  * (the disconnect or shutdown handler will take care of the rest).
3207  * If we were able to transmit messages and there are still more
3208  * pending, ask core again for further calls to this function.
3209  *
3210  * @param cls closure, pointer to the 'struct ClientList*'
3211  * @param size number of bytes available in buf
3212  * @param buf where the callee should write the message
3213  * @return number of bytes written to buf
3214  */
3215 static size_t
3216 transmit_to_client (void *cls,
3217                   size_t size, void *buf)
3218 {
3219   struct ClientList *cl = cls;
3220   char *cbuf = buf;
3221   struct ClientResponseMessage *creply;
3222   size_t msize;
3223   
3224   cl->th = NULL;
3225   if (NULL == buf)
3226     {
3227 #if DEBUG_FS
3228       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3229                   "Not sending reply, client communication problem.\n");
3230 #endif
3231       return 0;
3232     }
3233   msize = 0;
3234   while ( (NULL != (creply = cl->res_head) ) &&
3235           (creply->msize <= size) )
3236     {
3237       memcpy (&cbuf[msize], &creply[1], creply->msize);
3238       msize += creply->msize;
3239       size -= creply->msize;
3240       GNUNET_CONTAINER_DLL_remove (cl->res_head,
3241                                    cl->res_tail,
3242                                    creply);
3243       GNUNET_free (creply);
3244     }
3245   if (NULL != creply)
3246     cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3247                                                   creply->msize,
3248                                                   GNUNET_TIME_UNIT_FOREVER_REL,
3249                                                   &transmit_to_client,
3250                                                   cl);
3251 #if DEBUG_FS
3252   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3253               "Transmitted %u bytes to client\n",
3254               (unsigned int) msize);
3255 #endif
3256   return msize;
3257 }
3258
3259
3260 /**
3261  * Closure for "process_reply" function.
3262  */
3263 struct ProcessReplyClosure
3264 {
3265   /**
3266    * The data for the reply.
3267    */
3268   const void *data;
3269
3270   /**
3271    * Who gave us this reply? NULL for local host (or DHT)
3272    */
3273   struct ConnectedPeer *sender;
3274
3275   /**
3276    * When the reply expires.
3277    */
3278   struct GNUNET_TIME_Absolute expiration;
3279
3280   /**
3281    * Size of data.
3282    */
3283   size_t size;
3284
3285   /**
3286    * Type of the block.
3287    */
3288   enum GNUNET_BLOCK_Type type;
3289
3290   /**
3291    * How much was this reply worth to us?
3292    */
3293   uint32_t priority;
3294
3295   /**
3296    * Anonymity requirements for this reply.
3297    */
3298   uint32_t anonymity_level;
3299
3300   /**
3301    * Evaluation result (returned).
3302    */
3303   enum GNUNET_BLOCK_EvaluationResult eval;
3304
3305   /**
3306    * Did we finish processing the associated request?
3307    */ 
3308   int finished;
3309
3310   /**
3311    * Did we find a matching request?
3312    */
3313   int request_found;
3314 };
3315
3316
3317 /**
3318  * We have received a reply; handle it!
3319  *
3320  * @param cls response (struct ProcessReplyClosure)
3321  * @param key our query
3322  * @param value value in the hash map (info about the query)
3323  * @return GNUNET_YES (we should continue to iterate)
3324  */
3325 static int
3326 process_reply (void *cls,
3327                const GNUNET_HashCode * key,
3328                void *value)
3329 {
3330   struct ProcessReplyClosure *prq = cls;
3331   struct PendingRequest *pr = value;
3332   struct PendingMessage *reply;
3333   struct ClientResponseMessage *creply;
3334   struct ClientList *cl;
3335   struct PutMessage *pm;
3336   struct ConnectedPeer *cp;
3337   struct GNUNET_TIME_Relative cur_delay;
3338 #if SUPPORT_DELAYS  
3339 struct GNUNET_TIME_Relative art_delay;
3340 #endif
3341   size_t msize;
3342   unsigned int i;
3343
3344   if (NULL == pr->client_request_list)
3345     {
3346       /* reply will go over the network, check for cover traffic */
3347       if ( (prq->anonymity_level >  1) &&
3348            (cover_content_count < prq->anonymity_level - 1) )
3349         {
3350           /* insufficient cover traffic, skip */
3351           GNUNET_STATISTICS_update (stats,
3352                                     gettext_noop ("# replies suppressed due to lack of cover traffic"),
3353                                     1,
3354                                     GNUNET_NO);
3355           return GNUNET_YES;
3356         }       
3357       if (prq->anonymity_level >  1) 
3358         cover_content_count -= prq->anonymity_level - 1;
3359     }
3360 #if DEBUG_FS
3361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3362               "Matched result (type %u) for query `%s' with pending request\n",
3363               (unsigned int) prq->type,
3364               GNUNET_h2s (key));
3365 #endif  
3366   GNUNET_STATISTICS_update (stats,
3367                             gettext_noop ("# replies received and matched"),
3368                             1,
3369                             GNUNET_NO);
3370   if (prq->sender != NULL)
3371     {
3372       for (i=0;i<pr->used_targets_off;i++)
3373         if (pr->used_targets[i].pid == prq->sender->pid)
3374           break;
3375       if (i < pr->used_targets_off)
3376         {
3377           cur_delay = GNUNET_TIME_absolute_get_duration (pr->used_targets[i].last_request_time);      
3378           prq->sender->avg_delay.rel_value
3379             = (prq->sender->avg_delay.rel_value * 
3380                (RUNAVG_DELAY_N - 1) + cur_delay.rel_value) / RUNAVG_DELAY_N; 
3381           prq->sender->avg_priority
3382             = (prq->sender->avg_priority * 
3383                (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
3384         }
3385       if (pr->cp != NULL)
3386         {
3387           GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
3388                                  [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], 
3389                                  -1);
3390           GNUNET_PEER_change_rc (pr->cp->pid, 1);
3391           prq->sender->last_p2p_replies
3392             [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
3393             = pr->cp->pid;
3394         }
3395       else
3396         {
3397           if (NULL != prq->sender->last_client_replies
3398               [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
3399             GNUNET_SERVER_client_drop (prq->sender->last_client_replies
3400                                        [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
3401           prq->sender->last_client_replies
3402             [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
3403             = pr->client_request_list->client_list->client;
3404           GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
3405         }
3406     }
3407   prq->eval = GNUNET_BLOCK_evaluate (block_ctx,
3408                                      prq->type,
3409                                      key,
3410                                      &pr->bf,
3411                                      pr->mingle,
3412                                      pr->namespace, (pr->namespace != NULL) ? sizeof (GNUNET_HashCode) : 0,
3413                                      prq->data,
3414                                      prq->size);
3415   switch (prq->eval)
3416     {
3417     case GNUNET_BLOCK_EVALUATION_OK_MORE:
3418       break;
3419     case GNUNET_BLOCK_EVALUATION_OK_LAST:
3420       while (NULL != pr->pending_head)
3421         destroy_pending_message_list_entry (pr->pending_head);
3422       if (pr->qe != NULL)
3423         {
3424           if (pr->client_request_list != NULL)
3425             GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
3426                                         GNUNET_YES);
3427           GNUNET_DATASTORE_cancel (pr->qe);
3428           pr->qe = NULL;
3429         }
3430       pr->do_remove = GNUNET_YES;
3431       if (pr->task != GNUNET_SCHEDULER_NO_TASK)
3432         {
3433           GNUNET_SCHEDULER_cancel (pr->task);
3434           pr->task = GNUNET_SCHEDULER_NO_TASK;
3435         }
3436       GNUNET_break (GNUNET_YES ==
3437                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
3438                                                           key,
3439                                                           pr));
3440       GNUNET_LOAD_update (rt_entry_lifetime,
3441                           GNUNET_TIME_absolute_get_duration (pr->start_time).rel_value);
3442       break;
3443     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
3444       GNUNET_STATISTICS_update (stats,
3445                                 gettext_noop ("# duplicate replies discarded (bloomfilter)"),
3446                                 1,
3447                                 GNUNET_NO);
3448 #if DEBUG_FS
3449 /*      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3450                   "Duplicate response `%s', discarding.\n",
3451                   GNUNET_h2s (&mhash));*/
3452 #endif
3453       return GNUNET_YES; /* duplicate */
3454     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
3455       return GNUNET_YES; /* wrong namespace */  
3456     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
3457       GNUNET_break (0);
3458       return GNUNET_YES;
3459     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
3460       GNUNET_break (0);
3461       return GNUNET_YES;
3462     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
3463       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3464                   _("Unsupported block type %u\n"),
3465                   prq->type);
3466       return GNUNET_NO;
3467     }
3468   if (pr->client_request_list != NULL)
3469     {
3470       if (pr->replies_seen_size == pr->replies_seen_off)
3471         GNUNET_array_grow (pr->replies_seen,
3472                            pr->replies_seen_size,
3473                            pr->replies_seen_size * 2 + 4);      
3474       GNUNET_CRYPTO_hash (prq->data,
3475                           prq->size,
3476                           &pr->replies_seen[pr->replies_seen_off++]);         
3477       refresh_bloomfilter (pr);
3478     }
3479   if (NULL == prq->sender)
3480     {
3481 #if DEBUG_FS
3482       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3483                   "Found result for query `%s' in local datastore\n",
3484                   GNUNET_h2s (key));
3485 #endif
3486       GNUNET_STATISTICS_update (stats,
3487                                 gettext_noop ("# results found locally"),
3488                                 1,
3489                                 GNUNET_NO);      
3490     }
3491   prq->priority += pr->remaining_priority;
3492   pr->remaining_priority = 0;
3493   pr->results_found++;
3494   prq->request_found = GNUNET_YES;
3495   if (NULL != pr->client_request_list)
3496     {
3497       GNUNET_STATISTICS_update (stats,
3498                                 gettext_noop ("# replies received for local clients"),
3499                                 1,
3500                                 GNUNET_NO);
3501       cl = pr->client_request_list->client_list;
3502       msize = sizeof (struct PutMessage) + prq->size;
3503       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
3504       creply->msize = msize;
3505       creply->client_list = cl;
3506       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
3507                                          cl->res_tail,
3508                                          cl->res_tail,
3509                                          creply);      
3510       pm = (struct PutMessage*) &creply[1];
3511       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3512       pm->header.size = htons (msize);
3513       pm->type = htonl (prq->type);
3514       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3515       memcpy (&pm[1], prq->data, prq->size);      
3516       if (NULL == cl->th)
3517         {
3518 #if DEBUG_FS
3519           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3520                       "Transmitting result for query `%s' to client\n",
3521                       GNUNET_h2s (key));
3522 #endif  
3523           cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
3524                                                         msize,
3525                                                         GNUNET_TIME_UNIT_FOREVER_REL,
3526                                                         &transmit_to_client,
3527                                                         cl);
3528         }
3529       GNUNET_break (cl->th != NULL);
3530       if (pr->do_remove)                
3531         {
3532           prq->finished = GNUNET_YES;
3533           destroy_pending_request (pr);         
3534         }
3535     }
3536   else
3537     {
3538       cp = pr->cp;
3539 #if DEBUG_FS
3540       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3541                   "Transmitting result for query `%s' to other peer (PID=%u)\n",
3542                   GNUNET_h2s (key),
3543                   (unsigned int) cp->pid);
3544 #endif  
3545       GNUNET_STATISTICS_update (stats,
3546                                 gettext_noop ("# replies received for other peers"),
3547                                 1,
3548                                 GNUNET_NO);
3549       msize = sizeof (struct PutMessage) + prq->size;
3550       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
3551       reply->cont = &transmit_reply_continuation;
3552       reply->cont_cls = pr;
3553 #if SUPPORT_DELAYS
3554       art_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3555                                                  GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3556                                                                            TTL_DECREMENT));
3557       reply->delay_until 
3558         = GNUNET_TIME_relative_to_absolute (art_delay);
3559       GNUNET_STATISTICS_update (stats,
3560                                 gettext_noop ("cummulative artificial delay introduced (ms)"),
3561                                 art_delay.abs_value,
3562                                 GNUNET_NO);
3563 #endif
3564       reply->msize = msize;
3565       reply->priority = UINT32_MAX; /* send replies first! */
3566       pm = (struct PutMessage*) &reply[1];
3567       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3568       pm->header.size = htons (msize);
3569       pm->type = htonl (prq->type);
3570       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3571       memcpy (&pm[1], prq->data, prq->size);
3572       add_to_pending_messages_for_peer (cp, reply, pr);
3573     }
3574   return GNUNET_YES;
3575 }
3576
3577
3578 /**
3579  * Iterator called on each result obtained for a DHT
3580  * operation that expects a reply
3581  *
3582  * @param cls closure
3583  * @param exp when will this value expire
3584  * @param key key of the result
3585  * @param get_path NULL-terminated array of pointers
3586  *                 to the peers on reverse GET path (or NULL if not recorded)
3587  * @param put_path NULL-terminated array of pointers
3588  *                 to the peers on the PUT path (or NULL if not recorded)
3589  * @param type type of the result
3590  * @param size number of bytes in data
3591  * @param data pointer to the result data
3592  */
3593 static void
3594 process_dht_reply (void *cls,
3595                    struct GNUNET_TIME_Absolute exp,
3596                    const GNUNET_HashCode * key,
3597                    const struct GNUNET_PeerIdentity * const *get_path,
3598                    const struct GNUNET_PeerIdentity * const *put_path,
3599                    enum GNUNET_BLOCK_Type type,
3600                    size_t size,
3601                    const void *data)
3602 {
3603   struct PendingRequest *pr = cls;
3604   struct ProcessReplyClosure prq;
3605
3606   memset (&prq, 0, sizeof (prq));
3607   prq.data = data;
3608   prq.expiration = exp;
3609   prq.size = size;  
3610   prq.type = type;
3611   process_reply (&prq, key, pr);
3612 }
3613
3614
3615
3616 /**
3617  * Continuation called to notify client about result of the
3618  * operation.
3619  *
3620  * @param cls closure
3621  * @param success GNUNET_SYSERR on failure
3622  * @param msg NULL on success, otherwise an error message
3623  */
3624 static void 
3625 put_migration_continuation (void *cls,
3626                             int success,
3627                             const char *msg)
3628 {
3629   struct GNUNET_TIME_Absolute *start = cls;
3630   struct GNUNET_TIME_Relative delay;
3631   
3632   delay = GNUNET_TIME_absolute_get_duration (*start);
3633   GNUNET_free (start);
3634   GNUNET_LOAD_update (datastore_put_load,
3635                       delay.rel_value);
3636   if (GNUNET_OK == success)
3637     return;
3638   GNUNET_STATISTICS_update (stats,
3639                             gettext_noop ("# datastore 'put' failures"),
3640                             1,
3641                             GNUNET_NO);
3642 }
3643
3644
3645 /**
3646  * Handle P2P "PUT" message.
3647  *
3648  * @param cls closure, always NULL
3649  * @param other the other peer involved (sender or receiver, NULL
3650  *        for loopback messages where we are both sender and receiver)
3651  * @param message the actual message
3652  * @param atsi performance information
3653  * @return GNUNET_OK to keep the connection open,
3654  *         GNUNET_SYSERR to close it (signal serious error)
3655  */
3656 static int
3657 handle_p2p_put (void *cls,
3658                 const struct GNUNET_PeerIdentity *other,
3659                 const struct GNUNET_MessageHeader *message,
3660                 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3661 {
3662   const struct PutMessage *put;
3663   uint16_t msize;
3664   size_t dsize;
3665   enum GNUNET_BLOCK_Type type;
3666   struct GNUNET_TIME_Absolute expiration;
3667   GNUNET_HashCode query;
3668   struct ProcessReplyClosure prq;
3669   struct GNUNET_TIME_Absolute *start;
3670   struct GNUNET_TIME_Relative block_time;  
3671   double putl;
3672   struct ConnectedPeer *cp; 
3673   struct PendingMessage *pm;
3674   struct MigrationStopMessage *msm;
3675
3676   msize = ntohs (message->size);
3677   if (msize < sizeof (struct PutMessage))
3678     {
3679       GNUNET_break_op(0);
3680       return GNUNET_SYSERR;
3681     }
3682   put = (const struct PutMessage*) message;
3683   dsize = msize - sizeof (struct PutMessage);
3684   type = ntohl (put->type);
3685   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
3686
3687   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3688     return GNUNET_SYSERR;
3689   if (GNUNET_OK !=
3690       GNUNET_BLOCK_get_key (block_ctx,
3691                             type,
3692                             &put[1],
3693                             dsize,
3694                             &query))
3695     {
3696       GNUNET_break_op (0);
3697       return GNUNET_SYSERR;
3698     }
3699   cover_content_count++;
3700 #if DEBUG_FS
3701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3702               "Received result for query `%s' from peer `%4s'\n",
3703               GNUNET_h2s (&query),
3704               GNUNET_i2s (other));
3705 #endif
3706   GNUNET_STATISTICS_update (stats,
3707                             gettext_noop ("# replies received (overall)"),
3708                             1,
3709                             GNUNET_NO);
3710   /* now, lookup 'query' */
3711   prq.data = (const void*) &put[1];
3712   if (other != NULL)
3713     prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3714                                                     &other->hashPubKey);
3715   else
3716     prq.sender = NULL;
3717   prq.size = dsize;
3718   prq.type = type;
3719   prq.expiration = expiration;
3720   prq.priority = 0;
3721   prq.anonymity_level = 1;
3722   prq.finished = GNUNET_NO;
3723   prq.request_found = GNUNET_NO;
3724   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3725                                               &query,
3726                                               &process_reply,
3727                                               &prq);
3728   if (prq.sender != NULL)
3729     {
3730       prq.sender->inc_preference += CONTENT_BANDWIDTH_VALUE + 1000 * prq.priority;
3731       change_host_trust (prq.sender, prq.priority);
3732     }
3733   if ( (GNUNET_YES == active_to_migration) &&
3734        (GNUNET_NO == test_put_load_too_high (prq.priority)) )
3735     {      
3736 #if DEBUG_FS
3737       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3738                   "Replicating result for query `%s' with priority %u\n",
3739                   GNUNET_h2s (&query),
3740                   prq.priority);
3741 #endif
3742       start = GNUNET_malloc (sizeof (struct GNUNET_TIME_Absolute));
3743       *start = GNUNET_TIME_absolute_get ();
3744       GNUNET_DATASTORE_put (dsh,
3745                             0, &query, dsize, &put[1],
3746                             type, prq.priority, 1 /* anonymity */, 
3747                             expiration, 
3748                             1 + prq.priority, MAX_DATASTORE_QUEUE,
3749                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
3750                             &put_migration_continuation, 
3751                             start);
3752     }
3753   putl = GNUNET_LOAD_get_load (datastore_put_load);
3754   if ( (NULL != (cp = prq.sender)) &&
3755        (GNUNET_NO == prq.request_found) &&
3756        ( (GNUNET_YES != active_to_migration) ||
3757          (putl > 2.5 * (1 + prq.priority)) ) ) 
3758     {
3759       if (GNUNET_TIME_absolute_get_duration (cp->last_migration_block).rel_value < 5000)
3760         return GNUNET_OK; /* already blocked */
3761       /* We're too busy; send MigrationStop message! */
3762       if (GNUNET_YES != active_to_migration) 
3763         putl = 1.0 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 5);
3764       block_time = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
3765                                                   5000 + GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3766                                                                                    (unsigned int) (60000 * putl * putl)));
3767       
3768       cp->last_migration_block = GNUNET_TIME_relative_to_absolute (block_time);
3769       pm = GNUNET_malloc (sizeof (struct PendingMessage) + 
3770                           sizeof (struct MigrationStopMessage));
3771       pm->msize = sizeof (struct MigrationStopMessage);
3772       pm->priority = UINT32_MAX;
3773       msm = (struct MigrationStopMessage*) &pm[1];
3774       msm->header.size = htons (sizeof (struct MigrationStopMessage));
3775       msm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP);
3776       msm->duration = GNUNET_TIME_relative_hton (block_time);
3777       add_to_pending_messages_for_peer (cp,
3778                                         pm,
3779                                         NULL);
3780     }
3781   return GNUNET_OK;
3782 }
3783
3784
3785 /**
3786  * Handle P2P "MIGRATION_STOP" message.
3787  *
3788  * @param cls closure, always NULL
3789  * @param other the other peer involved (sender or receiver, NULL
3790  *        for loopback messages where we are both sender and receiver)
3791  * @param message the actual message
3792  * @param atsi performance information
3793  * @return GNUNET_OK to keep the connection open,
3794  *         GNUNET_SYSERR to close it (signal serious error)
3795  */
3796 static int
3797 handle_p2p_migration_stop (void *cls,
3798                            const struct GNUNET_PeerIdentity *other,
3799                            const struct GNUNET_MessageHeader *message,
3800                            const struct GNUNET_TRANSPORT_ATS_Information *atsi)
3801 {
3802   struct ConnectedPeer *cp; 
3803   const struct MigrationStopMessage *msm;
3804
3805   msm = (const struct MigrationStopMessage*) message;
3806   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
3807                                           &other->hashPubKey);
3808   if (cp == NULL)
3809     {
3810       GNUNET_break (0);
3811       return GNUNET_OK;
3812     }
3813   cp->migration_blocked = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (msm->duration));
3814   return GNUNET_OK;
3815 }
3816
3817
3818
3819 /* **************************** P2P GET Handling ************************ */
3820
3821
3822 /**
3823  * Closure for 'check_duplicate_request_{peer,client}'.
3824  */
3825 struct CheckDuplicateRequestClosure
3826 {
3827   /**
3828    * The new request we should check if it already exists.
3829    */
3830   const struct PendingRequest *pr;
3831
3832   /**
3833    * Existing request found by the checker, NULL if none.
3834    */
3835   struct PendingRequest *have;
3836 };
3837
3838
3839 /**
3840  * Iterator over entries in the 'query_request_map' that
3841  * tries to see if we have the same request pending from
3842  * the same client already.
3843  *
3844  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
3845  * @param key current key code (query, ignored, must match)
3846  * @param value value in the hash map (a 'struct PendingRequest' 
3847  *              that already exists)
3848  * @return GNUNET_YES if we should continue to
3849  *         iterate (no match yet)
3850  *         GNUNET_NO if not (match found).
3851  */
3852 static int
3853 check_duplicate_request_client (void *cls,
3854                                 const GNUNET_HashCode * key,
3855                                 void *value)
3856 {
3857   struct CheckDuplicateRequestClosure *cdc = cls;
3858   struct PendingRequest *have = value;
3859
3860   if (have->client_request_list == NULL)
3861     return GNUNET_YES;
3862   if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
3863        (cdc->pr != have) )
3864     {
3865       cdc->have = have;
3866       return GNUNET_NO;
3867     }
3868   return GNUNET_YES;
3869 }
3870
3871
3872 /**
3873  * We're processing (local) results for a search request
3874  * from another peer.  Pass applicable results to the
3875  * peer and if we are done either clean up (operation
3876  * complete) or forward to other peers (more results possible).
3877  *
3878  * @param cls our closure (struct LocalGetContext)
3879  * @param key key for the content
3880  * @param size number of bytes in data
3881  * @param data content stored
3882  * @param type type of the content
3883  * @param priority priority of the content
3884  * @param anonymity anonymity-level for the content
3885  * @param expiration expiration time for the content
3886  * @param uid unique identifier for the datum;
3887  *        maybe 0 if no unique identifier is available
3888  */
3889 static void
3890 process_local_reply (void *cls,
3891                      const GNUNET_HashCode * key,
3892                      size_t size,
3893                      const void *data,
3894                      enum GNUNET_BLOCK_Type type,
3895                      uint32_t priority,
3896                      uint32_t anonymity,
3897                      struct GNUNET_TIME_Absolute
3898                      expiration, 
3899                      uint64_t uid)
3900 {
3901   struct PendingRequest *pr = cls;
3902   struct ProcessReplyClosure prq;
3903   struct CheckDuplicateRequestClosure cdrc;
3904   GNUNET_HashCode query;
3905   unsigned int old_rf;
3906   
3907   if (NULL == key)
3908     {
3909 #if DEBUG_FS > 1
3910       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3911                   "Done processing local replies, forwarding request to other peers.\n");
3912 #endif
3913       pr->qe = NULL;
3914       if (pr->client_request_list != NULL)
3915         {
3916           GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
3917                                       GNUNET_YES);
3918           /* Figure out if this is a duplicate request and possibly
3919              merge 'struct PendingRequest' entries */
3920           cdrc.have = NULL;
3921           cdrc.pr = pr;
3922           GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3923                                                       &pr->query,
3924                                                       &check_duplicate_request_client,
3925                                                       &cdrc);
3926           if (cdrc.have != NULL)
3927             {
3928 #if DEBUG_FS
3929               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3930                           "Received request for block `%s' twice from client, will only request once.\n",
3931                           GNUNET_h2s (&pr->query));
3932 #endif
3933               
3934               destroy_pending_request (pr);
3935               return;
3936             }
3937         }
3938       if (pr->local_only == GNUNET_YES)
3939         {
3940           destroy_pending_request (pr);
3941           return;
3942         }
3943       /* no more results */
3944       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3945         pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
3946                                              pr);      
3947       return;
3948     }
3949 #if DEBUG_FS
3950   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3951               "New local response to `%s' of type %u.\n",
3952               GNUNET_h2s (key),
3953               type);
3954 #endif
3955   if (type == GNUNET_BLOCK_TYPE_FS_ONDEMAND)
3956     {
3957 #if DEBUG_FS
3958       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3959                   "Found ONDEMAND block, performing on-demand encoding\n");
3960 #endif
3961       GNUNET_STATISTICS_update (stats,
3962                                 gettext_noop ("# on-demand blocks matched requests"),
3963                                 1,
3964                                 GNUNET_NO);
3965       if (GNUNET_OK != 
3966           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
3967                                             anonymity, expiration, uid, 
3968                                             &process_local_reply,
3969                                             pr))
3970       if (pr->qe != NULL)
3971         {
3972           GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3973         }
3974       return;
3975     }
3976   old_rf = pr->results_found;
3977   memset (&prq, 0, sizeof (prq));
3978   prq.data = data;
3979   prq.expiration = expiration;
3980   prq.size = size;  
3981   if (GNUNET_OK != 
3982       GNUNET_BLOCK_get_key (block_ctx,
3983                             type,
3984                             data,
3985                             size,
3986                             &query))
3987     {
3988       GNUNET_break (0);
3989       GNUNET_DATASTORE_remove (dsh,
3990                                key,
3991                                size, data,
3992                                -1, -1, 
3993                                GNUNET_TIME_UNIT_FOREVER_REL,
3994                                NULL, NULL);
3995       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
3996       return;
3997     }
3998   prq.type = type;
3999   prq.priority = priority;  
4000   prq.finished = GNUNET_NO;
4001   prq.request_found = GNUNET_NO;
4002   prq.anonymity_level = anonymity;
4003   if ( (old_rf == 0) &&
4004        (pr->results_found == 0) )
4005     update_datastore_delays (pr->start_time);
4006   process_reply (&prq, key, pr);
4007   if (prq.finished == GNUNET_YES)
4008     return;
4009   if (pr->qe == NULL)
4010     return; /* done here */
4011   if (prq.eval == GNUNET_BLOCK_EVALUATION_OK_LAST)
4012     {
4013       pr->local_only = GNUNET_YES; /* do not forward */
4014       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4015       return;
4016     }
4017   if ( (pr->client_request_list == NULL) &&
4018        ( (GNUNET_YES == test_get_load_too_high (0)) ||
4019          (pr->results_found > 5 + 2 * pr->priority) ) )
4020     {
4021 #if DEBUG_FS > 2
4022       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4023                   "Load too high, done with request\n");
4024 #endif
4025       GNUNET_STATISTICS_update (stats,
4026                                 gettext_noop ("# processing result set cut short due to load"),
4027                                 1,
4028                                 GNUNET_NO);
4029       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
4030       return;
4031     }
4032   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
4033 }
4034
4035
4036 /**
4037  * We've received a request with the specified priority.  Bound it
4038  * according to how much we trust the given peer.
4039  * 
4040  * @param prio_in requested priority
4041  * @param cp the peer making the request
4042  * @return effective priority
4043  */
4044 static int32_t
4045 bound_priority (uint32_t prio_in,
4046                 struct ConnectedPeer *cp)
4047 {
4048 #define N ((double)128.0)
4049   uint32_t ret;
4050   double rret;
4051   int ld;
4052
4053   ld = test_get_load_too_high (0);
4054   if (ld == GNUNET_SYSERR)
4055     {
4056       GNUNET_STATISTICS_update (stats,
4057                                 gettext_noop ("# requests done for free (low load)"),
4058                                 1,
4059                                 GNUNET_NO);
4060       return 0; /* excess resources */
4061     }
4062   if (prio_in > INT32_MAX)
4063     prio_in = INT32_MAX;
4064   ret = - change_host_trust (cp, - (int) prio_in);
4065   if (ret > 0)
4066     {
4067       if (ret > current_priorities + N)
4068         rret = current_priorities + N;
4069       else
4070         rret = ret;
4071       current_priorities 
4072         = (current_priorities * (N-1) + rret)/N;
4073     }
4074   if ( (ld == GNUNET_YES) && (ret > 0) )
4075     {
4076       /* try with charging */
4077       ld = test_get_load_too_high (ret);
4078     }
4079   if (ld == GNUNET_YES)
4080     {
4081       GNUNET_STATISTICS_update (stats,
4082                                 gettext_noop ("# request dropped, priority insufficient"),
4083                                 1,
4084                                 GNUNET_NO);
4085       /* undo charge */
4086       change_host_trust (cp, (int) ret);
4087       return -1; /* not enough resources */
4088     }
4089   else
4090     {
4091       GNUNET_STATISTICS_update (stats,
4092                                 gettext_noop ("# requests done for a price (normal load)"),
4093                                 1,
4094                                 GNUNET_NO);
4095     }
4096 #undef N
4097   return ret;
4098 }
4099
4100
4101 /**
4102  * Iterator over entries in the 'query_request_map' that
4103  * tries to see if we have the same request pending from
4104  * the same peer already.
4105  *
4106  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
4107  * @param key current key code (query, ignored, must match)
4108  * @param value value in the hash map (a 'struct PendingRequest' 
4109  *              that already exists)
4110  * @return GNUNET_YES if we should continue to
4111  *         iterate (no match yet)
4112  *         GNUNET_NO if not (match found).
4113  */
4114 static int
4115 check_duplicate_request_peer (void *cls,
4116                               const GNUNET_HashCode * key,
4117                               void *value)
4118 {
4119   struct CheckDuplicateRequestClosure *cdc = cls;
4120   struct PendingRequest *have = value;
4121
4122   if (cdc->pr->target_pid == have->target_pid)
4123     {
4124       cdc->have = have;
4125       return GNUNET_NO;
4126     }
4127   return GNUNET_YES;
4128 }
4129
4130
4131 /**
4132  * Handle P2P "GET" request.
4133  *
4134  * @param cls closure, always NULL
4135  * @param other the other peer involved (sender or receiver, NULL
4136  *        for loopback messages where we are both sender and receiver)
4137  * @param message the actual message
4138  * @param atsi performance information
4139  * @return GNUNET_OK to keep the connection open,
4140  *         GNUNET_SYSERR to close it (signal serious error)
4141  */
4142 static int
4143 handle_p2p_get (void *cls,
4144                 const struct GNUNET_PeerIdentity *other,
4145                 const struct GNUNET_MessageHeader *message,
4146                 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4147 {
4148   struct PendingRequest *pr;
4149   struct ConnectedPeer *cp;
4150   struct ConnectedPeer *cps;
4151   struct CheckDuplicateRequestClosure cdc;
4152   struct GNUNET_TIME_Relative timeout;
4153   uint16_t msize;
4154   const struct GetMessage *gm;
4155   unsigned int bits;
4156   const GNUNET_HashCode *opt;
4157   uint32_t bm;
4158   size_t bfsize;
4159   uint32_t ttl_decrement;
4160   int32_t priority;
4161   enum GNUNET_BLOCK_Type type;
4162   int have_ns;
4163
4164   msize = ntohs(message->size);
4165   if (msize < sizeof (struct GetMessage))
4166     {
4167       GNUNET_break_op (0);
4168       return GNUNET_SYSERR;
4169     }
4170   gm = (const struct GetMessage*) message;
4171 #if DEBUG_FS
4172   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4173               "Received request for `%s'\n",
4174               GNUNET_h2s (&gm->query));
4175 #endif
4176   type = ntohl (gm->type);
4177   bm = ntohl (gm->hash_bitmap);
4178   bits = 0;
4179   while (bm > 0)
4180     {
4181       if (1 == (bm & 1))
4182         bits++;
4183       bm >>= 1;
4184     }
4185   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
4186     {
4187       GNUNET_break_op (0);
4188       return GNUNET_SYSERR;
4189     }  
4190   opt = (const GNUNET_HashCode*) &gm[1];
4191   bfsize = msize - sizeof (struct GetMessage) - bits * sizeof (GNUNET_HashCode);
4192   /* bfsize must be power of 2, check! */
4193   if (0 != ( (bfsize - 1) & bfsize))
4194     {
4195       GNUNET_break_op (0);
4196       return GNUNET_SYSERR;
4197     }
4198   cover_query_count++;
4199   bm = ntohl (gm->hash_bitmap);
4200   bits = 0;
4201   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4202                                            &other->hashPubKey);
4203   if (NULL == cps)
4204     {
4205       /* peer must have just disconnected */
4206       GNUNET_STATISTICS_update (stats,
4207                                 gettext_noop ("# requests dropped due to initiator not being connected"),
4208                                 1,
4209                                 GNUNET_NO);
4210       return GNUNET_SYSERR;
4211     }
4212   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4213     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
4214                                             &opt[bits++]);
4215   else
4216     cp = cps;
4217   if (cp == NULL)
4218     {
4219 #if DEBUG_FS
4220       if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
4221         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4222                     "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
4223                     GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
4224       
4225       else
4226         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4227                     "Failed to find peer `%4s' in connection set. Dropping query.\n",
4228                     GNUNET_i2s (other));
4229 #endif
4230       GNUNET_STATISTICS_update (stats,
4231                                 gettext_noop ("# requests dropped due to missing reverse route"),
4232                                 1,
4233                                 GNUNET_NO);
4234      /* FIXME: try connect? */
4235       return GNUNET_OK;
4236     }
4237   /* note that we can really only check load here since otherwise
4238      peers could find out that we are overloaded by not being
4239      disconnected after sending us a malformed query... */
4240   priority = bound_priority (ntohl (gm->priority), cps);
4241   if (priority < 0)
4242     {
4243 #if DEBUG_FS
4244       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4245                   "Dropping query from `%s', this peer is too busy.\n",
4246                   GNUNET_i2s (other));
4247 #endif
4248       return GNUNET_OK;
4249     }
4250 #if DEBUG_FS 
4251   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4252               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
4253               GNUNET_h2s (&gm->query),
4254               (unsigned int) type,
4255               GNUNET_i2s (other),
4256               (unsigned int) bm);
4257 #endif
4258   have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
4259   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
4260                       (have_ns ? sizeof(GNUNET_HashCode) : 0));
4261   if (have_ns)
4262     {
4263       pr->namespace = (GNUNET_HashCode*) &pr[1];
4264       memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
4265     }
4266   if ( (GNUNET_LOAD_get_load (cp->transmission_delay) > 3 * (1 + priority)) ||
4267        (GNUNET_LOAD_get_average (cp->transmission_delay) > 
4268         GNUNET_CONSTANTS_MAX_CORK_DELAY.rel_value * 2 + GNUNET_LOAD_get_average (rt_entry_lifetime)) )
4269     {
4270       /* don't have BW to send to peer, or would likely take longer than we have for it,
4271          so at best indirect the query */
4272       priority = 0;
4273       pr->forward_only = GNUNET_YES;
4274     }
4275   pr->type = type;
4276   pr->mingle = ntohl (gm->filter_mutator);
4277   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
4278     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
4279   pr->anonymity_level = 1;
4280   pr->priority = (uint32_t) priority;
4281   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
4282   pr->query = gm->query;
4283   /* decrement ttl (always) */
4284   ttl_decrement = 2 * TTL_DECREMENT +
4285     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
4286                               TTL_DECREMENT);
4287   if ( (pr->ttl < 0) &&
4288        (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
4289     {
4290 #if DEBUG_FS
4291       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4292                   "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
4293                   GNUNET_i2s (other),
4294                   pr->ttl,
4295                   ttl_decrement);
4296 #endif
4297       GNUNET_STATISTICS_update (stats,
4298                                 gettext_noop ("# requests dropped due TTL underflow"),
4299                                 1,
4300                                 GNUNET_NO);
4301       /* integer underflow => drop (should be very rare)! */      
4302       GNUNET_free (pr);
4303       return GNUNET_OK;
4304     } 
4305   pr->ttl -= ttl_decrement;
4306   pr->start_time = GNUNET_TIME_absolute_get ();
4307
4308   /* get bloom filter */
4309   if (bfsize > 0)
4310     {
4311       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
4312                                                   bfsize,
4313                                                   BLOOMFILTER_K);
4314       pr->bf_size = bfsize;
4315     }
4316   cdc.have = NULL;
4317   cdc.pr = pr;
4318   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
4319                                               &gm->query,
4320                                               &check_duplicate_request_peer,
4321                                               &cdc);
4322   if (cdc.have != NULL)
4323     {
4324       if (cdc.have->start_time.abs_value + cdc.have->ttl >=
4325           pr->start_time.abs_value + pr->ttl)
4326         {
4327           /* existing request has higher TTL, drop new one! */
4328           cdc.have->priority += pr->priority;
4329           destroy_pending_request (pr);
4330 #if DEBUG_FS
4331           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332                       "Have existing request with higher TTL, dropping new request.\n",
4333                       GNUNET_i2s (other));
4334 #endif
4335           GNUNET_STATISTICS_update (stats,
4336                                     gettext_noop ("# requests dropped due to higher-TTL request"),
4337                                     1,
4338                                     GNUNET_NO);
4339           return GNUNET_OK;
4340         }
4341       else
4342         {
4343           /* existing request has lower TTL, drop old one! */
4344           pr->priority += cdc.have->priority;
4345           /* Possible optimization: if we have applicable pending
4346              replies in 'cdc.have', we might want to move those over
4347              (this is a really rare special-case, so it is not clear
4348              that this would be worth it) */
4349           destroy_pending_request (cdc.have);
4350           /* keep processing 'pr'! */
4351         }
4352     }
4353
4354   pr->cp = cp;
4355   GNUNET_break (GNUNET_OK ==
4356                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4357                                                    &gm->query,
4358                                                    pr,
4359                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4360   GNUNET_break (GNUNET_OK ==
4361                 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
4362                                                    &other->hashPubKey,
4363                                                    pr,
4364                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4365   
4366   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
4367                                             pr,
4368                                             pr->start_time.abs_value + pr->ttl);
4369
4370   GNUNET_STATISTICS_update (stats,
4371                             gettext_noop ("# P2P searches received"),
4372                             1,
4373                             GNUNET_NO);
4374   GNUNET_STATISTICS_update (stats,
4375                             gettext_noop ("# P2P searches active"),
4376                             1,
4377                             GNUNET_NO);
4378
4379   /* calculate change in traffic preference */
4380   cps->inc_preference += pr->priority * 1000 + QUERY_BANDWIDTH_VALUE;
4381   /* process locally */
4382   if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4383     type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
4384   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
4385                                            (pr->priority + 1)); 
4386   if (GNUNET_YES != pr->forward_only)
4387     {
4388 #if DEBUG_FS
4389       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4390                   "Handing request for `%s' to datastore\n",
4391                   GNUNET_h2s (&gm->query));
4392 #endif
4393       pr->qe = GNUNET_DATASTORE_get (dsh,
4394                                      &gm->query,
4395                                      type,                             
4396                                      pr->priority + 1,
4397                                      MAX_DATASTORE_QUEUE,                                
4398                                      timeout,
4399                                      &process_local_reply,
4400                                      pr);
4401       if (NULL == pr->qe)
4402         {
4403           GNUNET_STATISTICS_update (stats,
4404                                     gettext_noop ("# requests dropped by datastore (queue length limit)"),
4405                                     1,
4406                                     GNUNET_NO);
4407         }
4408     }
4409   else
4410     {
4411       GNUNET_STATISTICS_update (stats,
4412                                 gettext_noop ("# requests forwarded due to high load"),
4413                                 1,
4414                                 GNUNET_NO);
4415     }
4416
4417   /* Are multiple results possible (and did we look locally)?  If so, start processing remotely now! */
4418   switch (pr->type)
4419     {
4420     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4421     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4422       /* only one result, wait for datastore */
4423       if (GNUNET_YES != pr->forward_only)
4424         {
4425           GNUNET_STATISTICS_update (stats,
4426                                     gettext_noop ("# requests not instantly forwarded (waiting for datastore)"),
4427                                     1,
4428                                     GNUNET_NO);
4429           break;
4430         }
4431     default:
4432       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
4433         pr->task = GNUNET_SCHEDULER_add_now (&forward_request_task,
4434                                              pr);
4435     }
4436
4437   /* make sure we don't track too many requests */
4438   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
4439     {
4440       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
4441       GNUNET_assert (pr != NULL);
4442       destroy_pending_request (pr);
4443     }
4444   return GNUNET_OK;
4445 }
4446
4447
4448 /* **************************** CS GET Handling ************************ */
4449
4450
4451 /**
4452  * Handle START_SEARCH-message (search request from client).
4453  *
4454  * @param cls closure
4455  * @param client identification of the client
4456  * @param message the actual message
4457  */
4458 static void
4459 handle_start_search (void *cls,
4460                      struct GNUNET_SERVER_Client *client,
4461                      const struct GNUNET_MessageHeader *message)
4462 {
4463   static GNUNET_HashCode all_zeros;
4464   const struct SearchMessage *sm;
4465   struct ClientList *cl;
4466   struct ClientRequestList *crl;
4467   struct PendingRequest *pr;
4468   uint16_t msize;
4469   unsigned int sc;
4470   enum GNUNET_BLOCK_Type type;
4471
4472   msize = ntohs (message->size);
4473   if ( (msize < sizeof (struct SearchMessage)) ||
4474        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
4475     {
4476       GNUNET_break (0);
4477       GNUNET_SERVER_receive_done (client,
4478                                   GNUNET_SYSERR);
4479       return;
4480     }
4481   GNUNET_STATISTICS_update (stats,
4482                             gettext_noop ("# client searches received"),
4483                             1,
4484                             GNUNET_NO);
4485   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
4486   sm = (const struct SearchMessage*) message;
4487   type = ntohl (sm->type);
4488 #if DEBUG_FS
4489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4490               "Received request for `%s' of type %u from local client\n",
4491               GNUNET_h2s (&sm->query),
4492               (unsigned int) type);
4493 #endif
4494   cl = client_list;
4495   while ( (cl != NULL) &&
4496           (cl->client != client) )
4497     cl = cl->next;
4498   if (cl == NULL)
4499     {
4500       cl = GNUNET_malloc (sizeof (struct ClientList));
4501       cl->client = client;
4502       GNUNET_SERVER_client_keep (client);
4503       cl->next = client_list;
4504       client_list = cl;
4505     }
4506   /* detect duplicate KBLOCK requests */
4507   if ( (type == GNUNET_BLOCK_TYPE_FS_KBLOCK) ||
4508        (type == GNUNET_BLOCK_TYPE_FS_NBLOCK) ||
4509        (type == GNUNET_BLOCK_TYPE_ANY) )
4510     {
4511       crl = cl->rl_head;
4512       while ( (crl != NULL) &&
4513               ( (0 != memcmp (&crl->req->query,
4514                               &sm->query,
4515                               sizeof (GNUNET_HashCode))) ||
4516                 (crl->req->type != type) ) )
4517         crl = crl->next;
4518       if (crl != NULL)  
4519         { 
4520 #if DEBUG_FS
4521           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4522                       "Have existing request, merging content-seen lists.\n");
4523 #endif
4524           pr = crl->req;
4525           /* Duplicate request (used to send long list of
4526              known/blocked results); merge 'pr->replies_seen'
4527              and update bloom filter */
4528           GNUNET_array_grow (pr->replies_seen,
4529                              pr->replies_seen_size,
4530                              pr->replies_seen_off + sc);
4531           memcpy (&pr->replies_seen[pr->replies_seen_off],
4532                   &sm[1],
4533                   sc * sizeof (GNUNET_HashCode));
4534           pr->replies_seen_off += sc;
4535           refresh_bloomfilter (pr);
4536           GNUNET_STATISTICS_update (stats,
4537                                     gettext_noop ("# client searches updated (merged content seen list)"),
4538                                     1,
4539                                     GNUNET_NO);
4540           GNUNET_SERVER_receive_done (client,
4541                                       GNUNET_OK);
4542           return;
4543         }
4544     }
4545   GNUNET_STATISTICS_update (stats,
4546                             gettext_noop ("# client searches active"),
4547                             1,
4548                             GNUNET_NO);
4549   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
4550                       ((type == GNUNET_BLOCK_TYPE_FS_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
4551   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
4552   memset (crl, 0, sizeof (struct ClientRequestList));
4553   crl->client_list = cl;
4554   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
4555                                cl->rl_tail,
4556                                crl);  
4557   crl->req = pr;
4558   pr->type = type;
4559   pr->client_request_list = crl;
4560   GNUNET_array_grow (pr->replies_seen,
4561                      pr->replies_seen_size,
4562                      sc);
4563   memcpy (pr->replies_seen,
4564           &sm[1],
4565           sc * sizeof (GNUNET_HashCode));
4566   pr->replies_seen_off = sc;
4567   pr->anonymity_level = ntohl (sm->anonymity_level); 
4568   pr->start_time = GNUNET_TIME_absolute_get ();
4569   refresh_bloomfilter (pr);
4570   pr->query = sm->query;
4571   if (0 == (1 & ntohl (sm->options)))
4572     pr->local_only = GNUNET_NO;
4573   else
4574     pr->local_only = GNUNET_YES;
4575   switch (type)
4576     {
4577     case GNUNET_BLOCK_TYPE_FS_DBLOCK:
4578     case GNUNET_BLOCK_TYPE_FS_IBLOCK:
4579       if (0 != memcmp (&sm->target,
4580                        &all_zeros,
4581                        sizeof (GNUNET_HashCode)))
4582         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
4583       break;
4584     case GNUNET_BLOCK_TYPE_FS_SBLOCK:
4585       pr->namespace = (GNUNET_HashCode*) &pr[1];
4586       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
4587       break;
4588     default:
4589       break;
4590     }
4591   GNUNET_break (GNUNET_OK ==
4592                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
4593                                                    &sm->query,
4594                                                    pr,
4595                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
4596   if (type == GNUNET_BLOCK_TYPE_FS_DBLOCK)
4597     type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
4598   pr->qe = GNUNET_DATASTORE_get (dsh,
4599                                  &sm->query,
4600                                  type,
4601                                  -3, -1,
4602                                  GNUNET_CONSTANTS_SERVICE_TIMEOUT,                             
4603                                  &process_local_reply,
4604                                  pr);
4605 }
4606
4607
4608 /* **************************** Startup ************************ */
4609
4610
4611
4612 /**
4613  * Function called after GNUNET_CORE_connect has succeeded
4614  * (or failed for good).  Note that the private key of the
4615  * peer is intentionally not exposed here; if you need it,
4616  * your process should try to read the private key file
4617  * directly (which should work if you are authorized...).
4618  *
4619  * @param cls closure
4620  * @param server handle to the server, NULL if we failed
4621  * @param my_identity ID of this peer, NULL if we failed
4622  * @param publicKey public key of this peer, NULL if we failed
4623  */
4624 static void
4625 peer_init_handler (void *cls,
4626                    struct GNUNET_CORE_Handle * server,
4627                    const struct GNUNET_PeerIdentity *
4628                    my_identity,
4629                    const struct
4630                    GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
4631                    publicKey)
4632 {
4633   my_id = *my_identity;
4634 }
4635
4636
4637
4638
4639 /**
4640  * Process fs requests.
4641  *
4642  * @param server the initialized server
4643  * @param c configuration to use
4644  */
4645 static int
4646 main_init (struct GNUNET_SERVER_Handle *server,
4647            const struct GNUNET_CONFIGURATION_Handle *c)
4648 {
4649   static const struct GNUNET_CORE_MessageHandler p2p_handlers[] =
4650     {
4651       { &handle_p2p_get, 
4652         GNUNET_MESSAGE_TYPE_FS_GET, 0 },
4653       { &handle_p2p_put, 
4654         GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
4655       { &handle_p2p_migration_stop, 
4656         GNUNET_MESSAGE_TYPE_FS_MIGRATION_STOP,
4657         sizeof (struct MigrationStopMessage) },
4658       { NULL, 0, 0 }
4659     };
4660   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
4661     {&GNUNET_FS_handle_index_start, NULL, 
4662      GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
4663     {&GNUNET_FS_handle_index_list_get, NULL, 
4664      GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
4665     {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
4666      sizeof (struct UnindexMessage) },
4667     {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
4668      0 },
4669     {NULL, NULL, 0, 0}
4670   };
4671   unsigned long long enc = 128;
4672
4673   cfg = c;
4674   stats = GNUNET_STATISTICS_create ("fs", cfg);
4675   min_migration_delay = GNUNET_TIME_UNIT_SECONDS;
4676   if ( (GNUNET_OK !=
4677         GNUNET_CONFIGURATION_get_value_number (cfg,
4678                                                "fs",
4679                                                "MAX_PENDING_REQUESTS",
4680                                                &max_pending_requests)) ||
4681        (GNUNET_OK !=
4682         GNUNET_CONFIGURATION_get_value_number (cfg,
4683                                                "fs",
4684                                                "EXPECTED_NEIGHBOUR_COUNT",
4685                                                &enc)) ||
4686        (GNUNET_OK != 
4687         GNUNET_CONFIGURATION_get_value_time (cfg,
4688                                              "fs",
4689                                              "MIN_MIGRATION_DELAY",
4690                                              &min_migration_delay)) )
4691     {
4692       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4693                   _("Configuration fails to specify certain parameters, assuming default values."));
4694     }
4695   connected_peers = GNUNET_CONTAINER_multihashmap_create (enc); 
4696   query_request_map = GNUNET_CONTAINER_multihashmap_create (max_pending_requests);
4697   rt_entry_lifetime = GNUNET_LOAD_value_init (GNUNET_TIME_UNIT_FOREVER_REL);
4698   peer_request_map = GNUNET_CONTAINER_multihashmap_create (enc);
4699   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
4700   core = GNUNET_CORE_connect (cfg,
4701                               1, /* larger? */
4702                               NULL,
4703                               &peer_init_handler,
4704                               &peer_connect_handler,
4705                               &peer_disconnect_handler,
4706                               &peer_status_handler,
4707                               NULL, GNUNET_NO,
4708                               NULL, GNUNET_NO,
4709                               p2p_handlers);
4710   if (NULL == core)
4711     {
4712       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
4713                   _("Failed to connect to `%s' service.\n"),
4714                   "core");
4715       GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
4716       connected_peers = NULL;
4717       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
4718       query_request_map = NULL;
4719       GNUNET_LOAD_value_free (rt_entry_lifetime);
4720       rt_entry_lifetime = NULL;
4721       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
4722       requests_by_expiration_heap = NULL;
4723       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
4724       peer_request_map = NULL;
4725       if (dsh != NULL)
4726         {
4727           GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4728           dsh = NULL;
4729         }
4730       return GNUNET_SYSERR;
4731     }
4732   if (active_from_migration) 
4733     {
4734       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
4735                   _("Content migration is enabled, will start to gather data\n"));
4736       consider_migration_gathering ();
4737     }
4738   consider_dht_put_gathering (NULL);
4739   GNUNET_SERVER_disconnect_notify (server, 
4740                                    &handle_client_disconnect,
4741                                    NULL);
4742   GNUNET_assert (GNUNET_OK ==
4743                  GNUNET_CONFIGURATION_get_value_filename (cfg,
4744                                                           "fs",
4745                                                           "TRUST",
4746                                                           &trustDirectory));
4747   GNUNET_DISK_directory_create (trustDirectory);
4748   GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_HIGH,
4749                                       &cron_flush_trust, NULL);
4750
4751
4752   GNUNET_SERVER_add_handlers (server, handlers);
4753   cover_age_task = GNUNET_SCHEDULER_add_delayed (COVER_AGE_FREQUENCY,
4754                                                  &age_cover_counters,
4755                                                  NULL);
4756   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4757                                 &shutdown_task,
4758                                 NULL);
4759   return GNUNET_OK;
4760 }
4761
4762
4763 /**
4764  * Process fs requests.
4765  *
4766  * @param cls closure
4767  * @param server the initialized server
4768  * @param cfg configuration to use
4769  */
4770 static void
4771 run (void *cls,
4772      struct GNUNET_SERVER_Handle *server,
4773      const struct GNUNET_CONFIGURATION_Handle *cfg)
4774 {
4775   active_to_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4776                                                               "FS",
4777                                                               "CONTENT_CACHING");
4778   active_from_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
4779                                                                 "FS",
4780                                                                 "CONTENT_PUSHING");
4781   dsh = GNUNET_DATASTORE_connect (cfg);
4782   if (dsh == NULL)
4783     {
4784       GNUNET_SCHEDULER_shutdown ();
4785       return;
4786     }
4787   datastore_get_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4788   datastore_put_load = GNUNET_LOAD_value_init (DATASTORE_LOAD_AUTODECLINE);
4789   block_cfg = GNUNET_CONFIGURATION_create ();
4790   GNUNET_CONFIGURATION_set_value_string (block_cfg,
4791                                          "block",
4792                                          "PLUGINS",
4793                                          "fs");
4794   block_ctx = GNUNET_BLOCK_context_create (block_cfg);
4795   GNUNET_assert (NULL != block_ctx);
4796   dht_handle = GNUNET_DHT_connect (cfg,
4797                                    FS_DHT_HT_SIZE);
4798   if ( (GNUNET_OK != GNUNET_FS_indexing_init (cfg, dsh)) ||
4799        (GNUNET_OK != main_init (server, cfg)) )
4800     {    
4801       GNUNET_SCHEDULER_shutdown ();
4802       GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
4803       dsh = NULL;
4804       GNUNET_DHT_disconnect (dht_handle);
4805       dht_handle = NULL;
4806       GNUNET_BLOCK_context_destroy (block_ctx);
4807       block_ctx = NULL;
4808       GNUNET_CONFIGURATION_destroy (block_cfg);
4809       block_cfg = NULL;
4810       GNUNET_LOAD_value_free (datastore_get_load);
4811       datastore_get_load = NULL;
4812       GNUNET_LOAD_value_free (datastore_put_load);
4813       datastore_put_load = NULL;
4814       return;   
4815     }
4816 }
4817
4818
4819 /**
4820  * The main function for the fs service.
4821  *
4822  * @param argc number of arguments from the command line
4823  * @param argv command line arguments
4824  * @return 0 ok, 1 on error
4825  */
4826 int
4827 main (int argc, char *const *argv)
4828 {
4829   return (GNUNET_OK ==
4830           GNUNET_SERVICE_run (argc,
4831                               argv,
4832                               "fs",
4833                               GNUNET_SERVICE_OPTION_NONE,
4834                               &run, NULL)) ? 0 : 1;
4835 }
4836
4837 /* end of gnunet-service-fs.c */