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