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