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