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