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