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