better
[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)2
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   cp->cth 
846     = GNUNET_CORE_notify_transmit_ready (core,
847                                          0, GNUNET_TIME_UNIT_FOREVER_REL,
848                                          (const struct GNUNET_PeerIdentity*) key,
849                                          msize + sizeof (struct PutMessage),
850                                          &transmit_to_peer,
851                                          cp);
852   return GNUNET_YES;
853 }
854
855
856 /**
857  * Task that is run periodically to obtain blocks for content
858  * migration
859  * 
860  * @param cls unused
861  * @param tc scheduler context (also unused)
862  */
863 static void
864 gather_migration_blocks (void *cls,
865                          const struct GNUNET_SCHEDULER_TaskContext *tc);
866
867
868 /**
869  * If the migration task is not currently running, consider
870  * (re)scheduling it with the appropriate delay.
871  */
872 static void
873 consider_migration_gathering ()
874 {
875   struct GNUNET_TIME_Relative delay;
876
877   if (mig_qe != NULL)
878     return;
879   if (mig_task != GNUNET_SCHEDULER_NO_TASK)
880     return;
881   delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
882                                          mig_size);
883   delay = GNUNET_TIME_relative_divide (GNUNET_TIME_UNIT_SECONDS,
884                                        MAX_MIGRATION_QUEUE);
885   delay = GNUNET_TIME_relative_max (delay,
886                                     min_migration_delay);
887   mig_task = GNUNET_SCHEDULER_add_delayed (sched,
888                                            delay,
889                                            &gather_migration_blocks,
890                                            NULL);
891 }
892
893
894 /**
895  * Process content offered for migration.
896  *
897  * @param cls closure
898  * @param key key for the content
899  * @param size number of bytes in data
900  * @param data content stored
901  * @param type type of the content
902  * @param priority priority of the content
903  * @param anonymity anonymity-level for the content
904  * @param expiration expiration time for the content
905  * @param uid unique identifier for the datum;
906  *        maybe 0 if no unique identifier is available
907  */
908 static void
909 process_migration_content (void *cls,
910                            const GNUNET_HashCode * key,
911                            uint32_t size,
912                            const void *data,
913                            enum GNUNET_BLOCK_Type type,
914                            uint32_t priority,
915                            uint32_t anonymity,
916                            struct GNUNET_TIME_Absolute
917                            expiration, uint64_t uid)
918 {
919   struct MigrationReadyBlock *mb;
920   
921   if (key == NULL)
922     {
923       mig_qe = NULL;
924       if (mig_size < MAX_MIGRATION_QUEUE)  
925         consider_migration_gathering ();
926       return;
927     }
928   if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
929     {
930       if (GNUNET_OK !=
931           GNUNET_FS_handle_on_demand_block (key, size, data,
932                                             type, priority, anonymity,
933                                             expiration, uid, 
934                                             &process_migration_content,
935                                             NULL))
936         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
937       return;
938     }
939   mb = GNUNET_malloc (sizeof (struct MigrationReadyBlock) + size);
940   mb->query = *key;
941   mb->expiration = expiration;
942   mb->size = size;
943   mb->type = type;
944   memcpy (&mb[1], data, size);
945   GNUNET_CONTAINER_DLL_insert_after (mig_head,
946                                      mig_tail,
947                                      mig_tail,
948                                      mb);
949   mig_size++;
950   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
951                                          &consider_migration,
952                                          mb);
953   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
954 }
955
956
957 /**
958  * Task that is run periodically to obtain blocks for content
959  * migration
960  * 
961  * @param cls unused
962  * @param tc scheduler context (also unused)
963  */
964 static void
965 gather_migration_blocks (void *cls,
966                          const struct GNUNET_SCHEDULER_TaskContext *tc)
967 {
968   mig_task = GNUNET_SCHEDULER_NO_TASK;
969   mig_qe = GNUNET_DATASTORE_get_random (dsh, 0, -1,
970                                         GNUNET_TIME_UNIT_FOREVER_REL,
971                                         &process_migration_content, NULL);
972   GNUNET_assert (mig_qe != NULL);
973 }
974
975
976 /**
977  * We're done with a particular message list entry.
978  * Free all associated resources.
979  * 
980  * @param pml entry to destroy
981  */
982 static void
983 destroy_pending_message_list_entry (struct PendingMessageList *pml)
984 {
985   GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
986                                pml->req->pending_tail,
987                                pml);
988   GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
989                                pml->target->pending_messages_tail,
990                                pml->pm);
991   pml->target->pending_requests--;
992   GNUNET_free (pml->pm);
993   GNUNET_free (pml);
994 }
995
996
997 /**
998  * Destroy the given pending message (and call the respective
999  * continuation).
1000  *
1001  * @param pm message to destroy
1002  * @param tpid id of peer that the message was delivered to, or 0 for none
1003  */
1004 static void
1005 destroy_pending_message (struct PendingMessage *pm,
1006                          GNUNET_PEER_Id tpid)
1007 {
1008   struct PendingMessageList *pml = pm->pml;
1009   TransmissionContinuation cont;
1010   void *cont_cls;
1011
1012   GNUNET_assert (pml->pm == pm);
1013   GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
1014   cont = pm->cont;
1015   cont_cls = pm->cont_cls;
1016   destroy_pending_message_list_entry (pml);
1017   cont (cont_cls, tpid);  
1018 }
1019
1020
1021 /**
1022  * We're done processing a particular request.
1023  * Free all associated resources.
1024  *
1025  * @param pr request to destroy
1026  */
1027 static void
1028 destroy_pending_request (struct PendingRequest *pr)
1029 {
1030   struct GNUNET_PeerIdentity pid;
1031
1032   if (pr->hnode != NULL)
1033     {
1034       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
1035                                          pr->hnode);
1036       pr->hnode = NULL;
1037     }
1038   if (NULL == pr->client_request_list)
1039     {
1040       GNUNET_STATISTICS_update (stats,
1041                                 gettext_noop ("# P2P searches active"),
1042                                 -1,
1043                                 GNUNET_NO);
1044     }
1045   else
1046     {
1047       GNUNET_STATISTICS_update (stats,
1048                                 gettext_noop ("# client searches active"),
1049                                 -1,
1050                                 GNUNET_NO);
1051     }
1052   /* might have already been removed from map in 'process_reply' (if
1053      there was a unique reply) or never inserted if it was a
1054      duplicate; hence ignore the return value here */
1055   (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1056                                                &pr->query,
1057                                                pr);
1058   if (pr->qe != NULL)
1059      {
1060       GNUNET_DATASTORE_cancel (pr->qe);
1061       pr->qe = NULL;
1062     }
1063   if (pr->client_request_list != NULL)
1064     {
1065       GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
1066                                    pr->client_request_list->client_list->rl_tail,
1067                                    pr->client_request_list);
1068       GNUNET_free (pr->client_request_list);
1069       pr->client_request_list = NULL;
1070     }
1071   if (pr->cp != NULL)
1072     {
1073       GNUNET_PEER_resolve (pr->cp->pid,
1074                            &pid);
1075       (void) GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1076                                                    &pid.hashPubKey,
1077                                                    pr);
1078       pr->cp = NULL;
1079     }
1080   if (pr->bf != NULL)
1081     {
1082       GNUNET_CONTAINER_bloomfilter_free (pr->bf);                                        
1083       pr->bf = NULL;
1084     }
1085   if (pr->irc != NULL)
1086     {
1087       GNUNET_CORE_peer_change_preference_cancel (pr->irc);
1088       pr->irc = NULL;
1089     }
1090   if (pr->replies_seen != NULL)
1091     {
1092       GNUNET_free (pr->replies_seen);
1093       pr->replies_seen = NULL;
1094     }
1095   if (pr->task != GNUNET_SCHEDULER_NO_TASK)
1096     {
1097       GNUNET_SCHEDULER_cancel (sched,
1098                                pr->task);
1099       pr->task = GNUNET_SCHEDULER_NO_TASK;
1100     }
1101   while (NULL != pr->pending_head)    
1102     destroy_pending_message_list_entry (pr->pending_head);
1103   GNUNET_PEER_change_rc (pr->target_pid, -1);
1104   if (pr->used_pids != NULL)
1105     {
1106       GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
1107       GNUNET_free (pr->used_pids);
1108       pr->used_pids_off = 0;
1109       pr->used_pids_size = 0;
1110       pr->used_pids = NULL;
1111     }
1112   GNUNET_free (pr);
1113 }
1114
1115
1116 /**
1117  * Method called whenever a given peer connects.
1118  *
1119  * @param cls closure, not used
1120  * @param peer peer identity this notification is about
1121  * @param latency reported latency of the connection with 'other'
1122  * @param distance reported distance (DV) to 'other' 
1123  */
1124 static void 
1125 peer_connect_handler (void *cls,
1126                       const struct
1127                       GNUNET_PeerIdentity * peer,
1128                       struct GNUNET_TIME_Relative latency,
1129                       uint32_t distance)
1130 {
1131   struct ConnectedPeer *cp;
1132   struct MigrationReadyBlock *pos;
1133   
1134   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
1135   cp->pid = GNUNET_PEER_intern (peer);
1136   GNUNET_break (GNUNET_OK ==
1137                 GNUNET_CONTAINER_multihashmap_put (connected_peers,
1138                                                    &peer->hashPubKey,
1139                                                    cp,
1140                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1141
1142   pos = mig_head;
1143   while (NULL != pos)
1144     {
1145       (void) consider_migration (pos, &peer->hashPubKey, cp);
1146       pos = pos->next;
1147     }
1148 }
1149
1150
1151
1152 /**
1153  * Free (each) request made by the peer.
1154  *
1155  * @param cls closure, points to peer that the request belongs to
1156  * @param key current key code
1157  * @param value value in the hash map
1158  * @return GNUNET_YES (we should continue to iterate)
1159  */
1160 static int
1161 destroy_request (void *cls,
1162                  const GNUNET_HashCode * key,
1163                  void *value)
1164 {
1165   const struct GNUNET_PeerIdentity * peer = cls;
1166   struct PendingRequest *pr = value;
1167   
1168   GNUNET_break (GNUNET_YES ==
1169                 GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
1170                                                       &peer->hashPubKey,
1171                                                       pr));
1172   destroy_pending_request (pr);
1173   return GNUNET_YES;
1174 }
1175
1176
1177 /**
1178  * Method called whenever a peer disconnects.
1179  *
1180  * @param cls closure, not used
1181  * @param peer peer identity this notification is about
1182  */
1183 static void
1184 peer_disconnect_handler (void *cls,
1185                          const struct
1186                          GNUNET_PeerIdentity * peer)
1187 {
1188   struct ConnectedPeer *cp;
1189   struct PendingMessage *pm;
1190   unsigned int i;
1191   struct MigrationReadyBlock *pos;
1192   struct MigrationReadyBlock *next;
1193
1194   GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
1195                                               &peer->hashPubKey,
1196                                               &destroy_request,
1197                                               (void*) peer);
1198   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1199                                           &peer->hashPubKey);
1200   if (cp == NULL)
1201     return;
1202   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1203     {
1204       if (NULL != cp->last_client_replies[i])
1205         {
1206           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1207           cp->last_client_replies[i] = NULL;
1208         }
1209     }
1210   GNUNET_break (GNUNET_YES ==
1211                 GNUNET_CONTAINER_multihashmap_remove (connected_peers,
1212                                                       &peer->hashPubKey,
1213                                                       cp));
1214   /* remove this peer from migration considerations; schedule
1215      alternatives */
1216   next = mig_head;
1217   while (NULL != (pos = next))
1218     {
1219       next = pos->next;
1220       for (i=0;i<MIGRATION_LIST_SIZE;i++)
1221         {
1222           if (pos->target_list[i] == cp->pid)
1223             {
1224               GNUNET_PEER_change_rc (pos->target_list[i], -1);
1225               pos->target_list[i] = 0;
1226             }
1227          }
1228       if (pos->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers))
1229         {
1230           delete_migration_block (pos);
1231           consider_migration_gathering ();
1232           continue;
1233         }
1234       GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1235                                              &consider_migration,
1236                                              pos);
1237     }
1238
1239   GNUNET_PEER_change_rc (cp->pid, -1);
1240   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
1241   if (NULL != cp->cth)
1242     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1243   while (NULL != (pm = cp->pending_messages_head))
1244     destroy_pending_message (pm, 0 /* delivery failed */);
1245   GNUNET_break (0 == cp->pending_requests);
1246   GNUNET_free (cp);
1247 }
1248
1249
1250 /**
1251  * Iterator over hash map entries that removes all occurences
1252  * of the given 'client' from the 'last_client_replies' of the
1253  * given connected peer.
1254  *
1255  * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
1256  * @param key current key code (unused)
1257  * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
1258  * @return GNUNET_YES (we should continue to iterate)
1259  */
1260 static int
1261 remove_client_from_last_client_replies (void *cls,
1262                                         const GNUNET_HashCode * key,
1263                                         void *value)
1264 {
1265   struct GNUNET_SERVER_Client *client = cls;
1266   struct ConnectedPeer *cp = value;
1267   unsigned int i;
1268
1269   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
1270     {
1271       if (cp->last_client_replies[i] == client)
1272         {
1273           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
1274           cp->last_client_replies[i] = NULL;
1275         }
1276     }  
1277   return GNUNET_YES;
1278 }
1279
1280
1281 /**
1282  * A client disconnected.  Remove all of its pending queries.
1283  *
1284  * @param cls closure, NULL
1285  * @param client identification of the client
1286  */
1287 static void
1288 handle_client_disconnect (void *cls,
1289                           struct GNUNET_SERVER_Client
1290                           * client)
1291 {
1292   struct ClientList *pos;
1293   struct ClientList *prev;
1294   struct ClientRequestList *rcl;
1295   struct ClientResponseMessage *creply;
1296
1297   if (client == NULL)
1298     return;
1299   prev = NULL;
1300   pos = client_list;
1301   while ( (NULL != pos) &&
1302           (pos->client != client) )
1303     {
1304       prev = pos;
1305       pos = pos->next;
1306     }
1307   if (pos == NULL)
1308     return; /* no requests pending for this client */
1309   while (NULL != (rcl = pos->rl_head))
1310     {
1311       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1312                   "Destroying pending request `%s' on disconnect\n",
1313                   GNUNET_h2s (&rcl->req->query));
1314       destroy_pending_request (rcl->req);
1315     }
1316   if (prev == NULL)
1317     client_list = pos->next;
1318   else
1319     prev->next = pos->next;
1320   if (pos->th != NULL)
1321     {
1322       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
1323       pos->th = NULL;
1324     }
1325   while (NULL != (creply = pos->res_head))
1326     {
1327       GNUNET_CONTAINER_DLL_remove (pos->res_head,
1328                                    pos->res_tail,
1329                                    creply);
1330       GNUNET_free (creply);
1331     }    
1332   GNUNET_SERVER_client_drop (pos->client);
1333   GNUNET_free (pos);
1334   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1335                                          &remove_client_from_last_client_replies,
1336                                          client);
1337 }
1338
1339
1340 /**
1341  * Iterator to free peer entries.
1342  *
1343  * @param cls closure, unused
1344  * @param key current key code
1345  * @param value value in the hash map (peer entry)
1346  * @return GNUNET_YES (we should continue to iterate)
1347  */
1348 static int 
1349 clean_peer (void *cls,
1350             const GNUNET_HashCode * key,
1351             void *value)
1352 {
1353   peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
1354   return GNUNET_YES;
1355 }
1356
1357
1358 /**
1359  * Task run during shutdown.
1360  *
1361  * @param cls unused
1362  * @param tc unused
1363  */
1364 static void
1365 shutdown_task (void *cls,
1366                const struct GNUNET_SCHEDULER_TaskContext *tc)
1367 {
1368   if (mig_qe != NULL)
1369     {
1370       GNUNET_DATASTORE_cancel (mig_qe);
1371       mig_qe = NULL;
1372     }
1373   if (GNUNET_SCHEDULER_NO_TASK != mig_task)
1374     {
1375       GNUNET_SCHEDULER_cancel (sched, mig_task);
1376       mig_task = GNUNET_SCHEDULER_NO_TASK;
1377     }
1378   while (client_list != NULL)
1379     handle_client_disconnect (NULL,
1380                               client_list->client);
1381   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1382                                          &clean_peer,
1383                                          NULL);
1384   GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
1385   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
1386   requests_by_expiration_heap = 0;
1387   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
1388   connected_peers = NULL;
1389   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
1390   GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
1391   query_request_map = NULL;
1392   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
1393   GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
1394   peer_request_map = NULL;
1395   GNUNET_assert (NULL != core);
1396   GNUNET_CORE_disconnect (core);
1397   core = NULL;
1398   if (stats != NULL)
1399     {
1400       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1401       stats = NULL;
1402     }
1403   GNUNET_DATASTORE_disconnect (dsh,
1404                                GNUNET_NO);
1405   while (mig_head != NULL)
1406     delete_migration_block (mig_head);
1407   GNUNET_assert (0 == mig_size);
1408   dsh = NULL;
1409   sched = NULL;
1410   cfg = NULL;  
1411 }
1412
1413
1414 /* ******************* Utility functions  ******************** */
1415
1416
1417 /**
1418  * Transmit messages by copying it to the target buffer
1419  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
1420  * for writing in the meantime.  In that case, do nothing
1421  * (the disconnect or shutdown handler will take care of the rest).
1422  * If we were able to transmit messages and there are still more
1423  * pending, ask core again for further calls to this function.
1424  *
1425  * @param cls closure, pointer to the 'struct ConnectedPeer*'
1426  * @param size number of bytes available in buf
1427  * @param buf where the callee should write the message
1428  * @return number of bytes written to buf
1429  */
1430 static size_t
1431 transmit_to_peer (void *cls,
1432                   size_t size, void *buf)
1433 {
1434   struct ConnectedPeer *cp = cls;
1435   char *cbuf = buf;
1436   struct GNUNET_PeerIdentity pid;
1437   struct PendingMessage *pm;
1438   struct MigrationReadyBlock *mb;
1439   struct MigrationReadyBlock *next;
1440   struct PutMessage migm;
1441   size_t msize;
1442   unsigned int i;
1443  
1444   cp->cth = NULL;
1445   if (NULL == buf)
1446     {
1447 #if DEBUG_FS
1448       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1449                   "Dropping message, core too busy.\n");
1450 #endif
1451       return 0;
1452     }
1453   msize = 0;
1454   while ( (NULL != (pm = cp->pending_messages_head) ) &&
1455           (pm->msize <= size) )
1456     {
1457       memcpy (&cbuf[msize], &pm[1], pm->msize);
1458       msize += pm->msize;
1459       size -= pm->msize;
1460       destroy_pending_message (pm, cp->pid);
1461     }
1462   if (NULL != pm)
1463     {
1464       GNUNET_PEER_resolve (cp->pid,
1465                            &pid);
1466       cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1467                                                    pm->priority,
1468                                                    GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1469                                                    &pid,
1470                                                    pm->msize,
1471                                                    &transmit_to_peer,
1472                                                    cp);
1473     }
1474   else
1475     {      
1476       next = mig_head;
1477       while (NULL != (mb = next))
1478         {
1479           next = mb->next;
1480           for (i=0;i<MIGRATION_LIST_SIZE;i++)
1481             {
1482               if ( (cp->pid == mb->target_list[i]) &&
1483                    (mb->size + sizeof (migm) <= size) )
1484                 {
1485                   GNUNET_PEER_change_rc (mb->target_list[i], -1);
1486                   mb->target_list[i] = 0;
1487                   mb->used_targets++;
1488                   migm.header.size = htons (sizeof (migm) + mb->size);
1489                   migm.header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1490                   migm.type = htonl (mb->type);
1491                   migm.expiration = GNUNET_TIME_absolute_hton (mb->expiration);
1492                   memcpy (&cbuf[msize], &migm, sizeof (migm));
1493                   msize += sizeof (migm);
1494                   size -= sizeof (migm);
1495                   memcpy (&cbuf[msize], &mb[1], mb->size);
1496                   msize += mb->size;
1497                   size -= mb->size;               
1498                   break;
1499                 }
1500             }
1501           if ( (mb->used_targets >= MIGRATION_TARGET_COUNT) ||
1502                (mb->used_targets >= GNUNET_CONTAINER_multihashmap_size (connected_peers)) )
1503             {
1504               delete_migration_block (mb);
1505               consider_migration_gathering ();
1506             }
1507         }
1508       consider_migration (NULL, 
1509                           &pid.hashPubKey,
1510                           cp);
1511     }
1512 #if DEBUG_FS
1513   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514               "Transmitting %u bytes to peer %u\n",
1515               msize,
1516               cp->pid);
1517 #endif
1518   return msize;
1519 }
1520
1521
1522 /**
1523  * Add a message to the set of pending messages for the given peer.
1524  *
1525  * @param cp peer to send message to
1526  * @param pm message to queue
1527  * @param pr request on which behalf this message is being queued
1528  */
1529 static void
1530 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1531                                   struct PendingMessage *pm,
1532                                   struct PendingRequest *pr)
1533 {
1534   struct PendingMessage *pos;
1535   struct PendingMessageList *pml;
1536   struct GNUNET_PeerIdentity pid;
1537
1538   GNUNET_assert (pm->next == NULL);
1539   GNUNET_assert (pm->pml == NULL);    
1540   pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1541   pml->req = pr;
1542   pml->target = cp;
1543   pml->pm = pm;
1544   pm->pml = pml;  
1545   GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1546                                pr->pending_tail,
1547                                pml);
1548   pos = cp->pending_messages_head;
1549   while ( (pos != NULL) &&
1550           (pm->priority < pos->priority) )
1551     pos = pos->next;    
1552   GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1553                                      cp->pending_messages_tail,
1554                                      pos,
1555                                      pm);
1556   cp->pending_requests++;
1557   if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1558     destroy_pending_message (cp->pending_messages_tail, 0);  
1559   GNUNET_PEER_resolve (cp->pid, &pid);
1560   if (NULL != cp->cth)
1561     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
1562   /* need to schedule transmission */
1563   cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1564                                                cp->pending_messages_head->priority,
1565                                                MAX_TRANSMIT_DELAY,
1566                                                &pid,
1567                                                cp->pending_messages_head->msize,
1568                                                &transmit_to_peer,
1569                                                cp);
1570   if (cp->cth == NULL)
1571     {
1572 #if DEBUG_FS
1573       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1574                   "Failed to schedule transmission with core!\n");
1575 #endif
1576       /* FIXME: call stats (rare, bad case) */
1577     }
1578 }
1579
1580
1581 /**
1582  * Mingle hash with the mingle_number to produce different bits.
1583  */
1584 static void
1585 mingle_hash (const GNUNET_HashCode * in,
1586              int32_t mingle_number, 
1587              GNUNET_HashCode * hc)
1588 {
1589   GNUNET_HashCode m;
1590
1591   GNUNET_CRYPTO_hash (&mingle_number, 
1592                       sizeof (int32_t), 
1593                       &m);
1594   GNUNET_CRYPTO_hash_xor (&m, in, hc);
1595 }
1596
1597
1598 /**
1599  * Test if the load on this peer is too high
1600  * to even consider processing the query at
1601  * all.
1602  * 
1603  * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1604  */
1605 static int
1606 test_load_too_high ()
1607 {
1608   return GNUNET_NO; // FIXME
1609 }
1610
1611
1612 /* ******************* Pending Request Refresh Task ******************** */
1613
1614
1615
1616 /**
1617  * We use a random delay to make the timing of requests less
1618  * predictable.  This function returns such a random delay.  We add a base
1619  * delay of MAX_CORK_DELAY (1s).
1620  *
1621  * FIXME: make schedule dependent on the specifics of the request?
1622  * Or bandwidth and number of connected peers and load?
1623  *
1624  * @return random delay to use for some request, between 1s and 1000+TTL_DECREMENT ms
1625  */
1626 static struct GNUNET_TIME_Relative
1627 get_processing_delay ()
1628 {
1629   return 
1630     GNUNET_TIME_relative_add (GNUNET_CONSTANTS_MAX_CORK_DELAY,
1631                               GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1632                                                              GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1633                                                                                        TTL_DECREMENT)));
1634 }
1635
1636
1637 /**
1638  * We're processing a GET request from another peer and have decided
1639  * to forward it to other peers.  This function is called periodically
1640  * and should forward the request to other peers until we have all
1641  * possible replies.  If we have transmitted the *only* reply to
1642  * the initiator we should destroy the pending request.  If we have
1643  * many replies in the queue to the initiator, we should delay sending
1644  * out more queries until the reply queue has shrunk some.
1645  *
1646  * @param cls our "struct ProcessGetContext *"
1647  * @param tc unused
1648  */
1649 static void
1650 forward_request_task (void *cls,
1651                       const struct GNUNET_SCHEDULER_TaskContext *tc);
1652
1653
1654 /**
1655  * Function called after we either failed or succeeded
1656  * at transmitting a query to a peer.  
1657  *
1658  * @param cls the requests "struct PendingRequest*"
1659  * @param tpid ID of receiving peer, 0 on transmission error
1660  */
1661 static void
1662 transmit_query_continuation (void *cls,
1663                              GNUNET_PEER_Id tpid)
1664 {
1665   struct PendingRequest *pr = cls;
1666
1667   GNUNET_STATISTICS_update (stats,
1668                             gettext_noop ("# queries scheduled for forwarding"),
1669                             -1,
1670                             GNUNET_NO);
1671   if (tpid == 0)   
1672     {
1673 #if DEBUG_FS
1674       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1675                   "Transmission of request failed, will try again later.\n");
1676 #endif
1677       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1678         pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1679                                                  get_processing_delay (),
1680                                                  &forward_request_task,
1681                                                  pr); 
1682       return;    
1683     }
1684   GNUNET_STATISTICS_update (stats,
1685                             gettext_noop ("# queries forwarded"),
1686                             1,
1687                             GNUNET_NO);
1688   GNUNET_PEER_change_rc (tpid, 1);
1689   if (pr->used_pids_off == pr->used_pids_size)
1690     GNUNET_array_grow (pr->used_pids,
1691                        pr->used_pids_size,
1692                        pr->used_pids_size * 2 + 2);
1693   pr->used_pids[pr->used_pids_off++] = tpid;
1694   if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1695     pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1696                                              get_processing_delay (),
1697                                              &forward_request_task,
1698                                              pr);
1699 }
1700
1701
1702 /**
1703  * How many bytes should a bloomfilter be if we have already seen
1704  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
1705  * of bits set per entry.  Furthermore, we should not re-size the
1706  * filter too often (to keep it cheap).
1707  *
1708  * Since other peers will also add entries but not resize the filter,
1709  * we should generally pick a slightly larger size than what the
1710  * strict math would suggest.
1711  *
1712  * @return must be a power of two and smaller or equal to 2^15.
1713  */
1714 static size_t
1715 compute_bloomfilter_size (unsigned int entry_count)
1716 {
1717   size_t size;
1718   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1719   uint16_t max = 1 << 15;
1720
1721   if (entry_count > max)
1722     return max;
1723   size = 8;
1724   while ((size < max) && (size < ideal))
1725     size *= 2;
1726   if (size > max)
1727     return max;
1728   return size;
1729 }
1730
1731
1732 /**
1733  * Recalculate our bloom filter for filtering replies.  This function
1734  * will create a new bloom filter from scratch, so it should only be
1735  * called if we have no bloomfilter at all (and hence can create a
1736  * fresh one of minimal size without problems) OR if our peer is the
1737  * initiator (in which case we may resize to larger than mimimum size).
1738  *
1739  * @param pr request for which the BF is to be recomputed
1740  */
1741 static void
1742 refresh_bloomfilter (struct PendingRequest *pr)
1743 {
1744   unsigned int i;
1745   size_t nsize;
1746   GNUNET_HashCode mhash;
1747
1748   nsize = compute_bloomfilter_size (pr->replies_seen_off);
1749   if (nsize == pr->bf_size)
1750     return; /* size not changed */
1751   if (pr->bf != NULL)
1752     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1753   pr->bf_size = nsize;
1754   pr->mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1755   pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
1756                                               pr->bf_size,
1757                                               BLOOMFILTER_K);
1758   for (i=0;i<pr->replies_seen_off;i++)
1759     {
1760       mingle_hash (&pr->replies_seen[i], pr->mingle, &mhash);
1761       GNUNET_CONTAINER_bloomfilter_add (pr->bf, &mhash);
1762     }
1763 }
1764
1765
1766 /**
1767  * Function called after we've tried to reserve a certain amount of
1768  * bandwidth for a reply.  Check if we succeeded and if so send our
1769  * query.
1770  *
1771  * @param cls the requests "struct PendingRequest*"
1772  * @param peer identifies the peer
1773  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1774  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1775  * @param amount set to the amount that was actually reserved or unreserved
1776  * @param preference current traffic preference for the given peer
1777  */
1778 static void
1779 target_reservation_cb (void *cls,
1780                        const struct
1781                        GNUNET_PeerIdentity * peer,
1782                        struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1783                        struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1784                        int amount,
1785                        uint64_t preference)
1786 {
1787   struct PendingRequest *pr = cls;
1788   struct ConnectedPeer *cp;
1789   struct PendingMessage *pm;
1790   struct GetMessage *gm;
1791   GNUNET_HashCode *ext;
1792   char *bfdata;
1793   size_t msize;
1794   unsigned int k;
1795   int no_route;
1796   uint32_t bm;
1797
1798   pr->irc = NULL;
1799   if (peer == NULL)
1800     {
1801       /* error in communication with core, try again later */
1802       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1803         pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1804                                                  get_processing_delay (),
1805                                                  &forward_request_task,
1806                                                  pr);
1807       return;
1808     }
1809   // (3) transmit, update ttl/priority
1810   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1811                                           &peer->hashPubKey);
1812   if (cp == NULL)
1813     {
1814       /* Peer must have just left */
1815 #if DEBUG_FS
1816       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1817                   "Selected peer disconnected!\n");
1818 #endif
1819       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1820         pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1821                                                  get_processing_delay (),
1822                                                  &forward_request_task,
1823                                                  pr);
1824       return;
1825     }
1826   no_route = GNUNET_NO;
1827   /* FIXME: check against DBLOCK_SIZE and possibly return
1828      amount to reserve; however, this also needs to work
1829      with testcases which currently start out with a far
1830      too low per-peer bw limit, so they would never send
1831      anything.  Big issue. */
1832   if (amount == 0)
1833     {
1834       if (pr->cp == NULL)
1835         {
1836 #if DEBUG_FS > 1
1837           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1838                       "Failed to reserve bandwidth for reply (got %d/%u bytes only)!\n",
1839                       amount,
1840                       DBLOCK_SIZE);
1841 #endif
1842           GNUNET_STATISTICS_update (stats,
1843                                     gettext_noop ("# reply bandwidth reservation requests failed"),
1844                                     1,
1845                                     GNUNET_NO);
1846           if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1847             pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1848                                                      get_processing_delay (),
1849                                                      &forward_request_task,
1850                                                      pr);
1851           return;  /* this target round failed */
1852         }
1853       /* FIXME: if we are "quite" busy, we may still want to skip
1854          this round; need more load detection code! */
1855       no_route = GNUNET_YES;
1856     }
1857   
1858   GNUNET_STATISTICS_update (stats,
1859                             gettext_noop ("# queries scheduled for forwarding"),
1860                             1,
1861                             GNUNET_NO);
1862   /* build message and insert message into priority queue */
1863 #if DEBUG_FS
1864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865               "Forwarding request `%s' to `%4s'!\n",
1866               GNUNET_h2s (&pr->query),
1867               GNUNET_i2s (peer));
1868 #endif
1869   k = 0;
1870   bm = 0;
1871   if (GNUNET_YES == no_route)
1872     {
1873       bm |= GET_MESSAGE_BIT_RETURN_TO;
1874       k++;      
1875     }
1876   if (pr->namespace != NULL)
1877     {
1878       bm |= GET_MESSAGE_BIT_SKS_NAMESPACE;
1879       k++;
1880     }
1881   if (pr->target_pid != 0)
1882     {
1883       bm |= GET_MESSAGE_BIT_TRANSMIT_TO;
1884       k++;
1885     }
1886   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1887   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1888   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1889   pm->msize = msize;
1890   gm = (struct GetMessage*) &pm[1];
1891   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1892   gm->header.size = htons (msize);
1893   gm->type = htonl (pr->type);
1894   pr->remaining_priority /= 2;
1895   gm->priority = htonl (pr->remaining_priority);
1896   gm->ttl = htonl (pr->ttl);
1897   gm->filter_mutator = htonl(pr->mingle); 
1898   gm->hash_bitmap = htonl (bm);
1899   gm->query = pr->query;
1900   ext = (GNUNET_HashCode*) &gm[1];
1901   k = 0;
1902   if (GNUNET_YES == no_route)
1903     GNUNET_PEER_resolve (pr->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1904   if (pr->namespace != NULL)
1905     memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1906   if (pr->target_pid != 0)
1907     GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1908   bfdata = (char *) &ext[k];
1909   if (pr->bf != NULL)
1910     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1911                                                bfdata,
1912                                                pr->bf_size);
1913   pm->cont = &transmit_query_continuation;
1914   pm->cont_cls = pr;
1915   add_to_pending_messages_for_peer (cp, pm, pr);
1916 }
1917
1918
1919 /**
1920  * Closure used for "target_peer_select_cb".
1921  */
1922 struct PeerSelectionContext 
1923 {
1924   /**
1925    * The request for which we are selecting
1926    * peers.
1927    */
1928   struct PendingRequest *pr;
1929
1930   /**
1931    * Current "prime" target.
1932    */
1933   struct GNUNET_PeerIdentity target;
1934
1935   /**
1936    * How much do we like this target?
1937    */
1938   double target_score;
1939
1940 };
1941
1942
1943 /**
1944  * Function called for each connected peer to determine
1945  * which one(s) would make good targets for forwarding.
1946  *
1947  * @param cls closure (struct PeerSelectionContext)
1948  * @param key current key code (peer identity)
1949  * @param value value in the hash map (struct ConnectedPeer)
1950  * @return GNUNET_YES if we should continue to
1951  *         iterate,
1952  *         GNUNET_NO if not.
1953  */
1954 static int
1955 target_peer_select_cb (void *cls,
1956                        const GNUNET_HashCode * key,
1957                        void *value)
1958 {
1959   struct PeerSelectionContext *psc = cls;
1960   struct ConnectedPeer *cp = value;
1961   struct PendingRequest *pr = psc->pr;
1962   double score;
1963   unsigned int i;
1964   unsigned int pc;
1965
1966   /* 1) check that this peer is not the initiator */
1967   if (cp == pr->cp)
1968     return GNUNET_YES; /* skip */          
1969
1970   /* 2) check if we have already (recently) forwarded to this peer */
1971   pc = 0;
1972   for (i=0;i<pr->used_pids_off;i++)
1973     if (pr->used_pids[i] == cp->pid) 
1974       {
1975         pc++;
1976         if (0 != GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1977                                            RETRY_PROBABILITY_INV))
1978           {
1979 #if DEBUG_FS
1980             GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981                         "NOT re-trying query that was previously transmitted %u times\n",
1982                         (unsigned int) pr->used_pids_off);
1983 #endif
1984             return GNUNET_YES; /* skip */
1985           }
1986       }
1987 #if DEBUG_FS
1988   if (0 < pc)
1989     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1990                 "Re-trying query that was previously transmitted %u times to this peer\n",
1991                 (unsigned int) pc);
1992 #endif
1993   // 3) calculate how much we'd like to forward to this peer
1994   score = 42; // FIXME!
1995   // FIXME: also need API to gather data on responsiveness
1996   // of this peer (we have fields for that in 'cp', but
1997   // they are never set!)
1998   
1999   /* store best-fit in closure */
2000   if (score > psc->target_score)
2001     {
2002       psc->target_score = score;
2003       psc->target.hashPubKey = *key; 
2004     }
2005   return GNUNET_YES;
2006 }
2007   
2008
2009 /**
2010  * The priority level imposes a bound on the maximum
2011  * value for the ttl that can be requested.
2012  *
2013  * @param ttl_in requested ttl
2014  * @param prio given priority
2015  * @return ttl_in if ttl_in is below the limit,
2016  *         otherwise the ttl-limit for the given priority
2017  */
2018 static int32_t
2019 bound_ttl (int32_t ttl_in, uint32_t prio)
2020 {
2021   unsigned long long allowed;
2022
2023   if (ttl_in <= 0)
2024     return ttl_in;
2025   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2026   if (ttl_in > allowed)      
2027     {
2028       if (allowed >= (1 << 30))
2029         return 1 << 30;
2030       return allowed;
2031     }
2032   return ttl_in;
2033 }
2034
2035
2036 /**
2037  * We're processing a GET request from another peer and have decided
2038  * to forward it to other peers.  This function is called periodically
2039  * and should forward the request to other peers until we have all
2040  * possible replies.  If we have transmitted the *only* reply to
2041  * the initiator we should destroy the pending request.  If we have
2042  * many replies in the queue to the initiator, we should delay sending
2043  * out more queries until the reply queue has shrunk some.
2044  *
2045  * @param cls our "struct ProcessGetContext *"
2046  * @param tc unused
2047  */
2048 static void
2049 forward_request_task (void *cls,
2050                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2051 {
2052   struct PendingRequest *pr = cls;
2053   struct PeerSelectionContext psc;
2054   struct ConnectedPeer *cp; 
2055   struct GNUNET_TIME_Relative delay;
2056
2057   pr->task = GNUNET_SCHEDULER_NO_TASK;
2058   if (pr->irc != NULL)
2059     {
2060 #if DEBUG_FS
2061       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062                   "Forwarding of query `%s' not attempted due to pending local lookup!\n",
2063                   GNUNET_h2s (&pr->query));
2064 #endif
2065       return; /* already pending */
2066     }
2067   if (GNUNET_YES == pr->local_only)
2068     return; /* configured to not do P2P search */
2069   /* (1) select target */
2070   psc.pr = pr;
2071   psc.target_score = DBL_MIN;
2072   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
2073                                          &target_peer_select_cb,
2074                                          &psc);  
2075   if (psc.target_score == DBL_MIN)
2076     {
2077       delay = get_processing_delay ();
2078 #if DEBUG_FS 
2079       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2080                   "No peer selected for forwarding of query `%s', will try again in %llu ms!\n",
2081                   GNUNET_h2s (&pr->query),
2082                   delay.value);
2083 #endif
2084       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2085                                                delay,
2086                                                &forward_request_task,
2087                                                pr);
2088       return; /* nobody selected */
2089     }
2090   /* (3) update TTL/priority */
2091   
2092   if (pr->client_request_list != NULL)
2093     {
2094       /* FIXME: use better algorithm!? */
2095       if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2096                                          4))
2097         pr->priority++;
2098       /* FIXME: bound priority by "customary" priority used by other peers
2099          at this time! */
2100       pr->ttl = bound_ttl (pr->ttl + TTL_DECREMENT * 2,
2101                            pr->priority);
2102 #if DEBUG_FS
2103       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104                   "Trying query `%s' with priority %u and TTL %d.\n",
2105                   GNUNET_h2s (&pr->query),
2106                   pr->priority,
2107                   pr->ttl);
2108 #endif
2109     }
2110   else
2111     {
2112       /* FIXME: should we do something here as well!? */
2113     }
2114
2115   /* (3) reserve reply bandwidth */
2116   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2117                                           &psc.target.hashPubKey);
2118   GNUNET_assert (NULL != cp);
2119   pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
2120                                                 &psc.target,
2121                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
2122                                                 GNUNET_BANDWIDTH_value_init ((uint32_t) -1 /* no limit */), 
2123                                                 DBLOCK_SIZE * 2, 
2124                                                 (uint64_t) cp->inc_preference,
2125                                                 &target_reservation_cb,
2126                                                 pr);
2127   cp->inc_preference = 0.0;
2128 }
2129
2130
2131 /* **************************** P2P PUT Handling ************************ */
2132
2133
2134 /**
2135  * Function called after we either failed or succeeded
2136  * at transmitting a reply to a peer.  
2137  *
2138  * @param cls the requests "struct PendingRequest*"
2139  * @param tpid ID of receiving peer, 0 on transmission error
2140  */
2141 static void
2142 transmit_reply_continuation (void *cls,
2143                              GNUNET_PEER_Id tpid)
2144 {
2145   struct PendingRequest *pr = cls;
2146   
2147   switch (pr->type)
2148     {
2149     case GNUNET_BLOCK_TYPE_DBLOCK:
2150     case GNUNET_BLOCK_TYPE_IBLOCK:
2151       /* only one reply expected, done with the request! */
2152       destroy_pending_request (pr);
2153       break;
2154     case GNUNET_BLOCK_TYPE_ANY:
2155     case GNUNET_BLOCK_TYPE_KBLOCK:
2156     case GNUNET_BLOCK_TYPE_SBLOCK:
2157       break;
2158     default:
2159       GNUNET_break (0);
2160       break;
2161     }
2162 }
2163
2164
2165 /**
2166  * Transmit the given message by copying it to the target buffer
2167  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
2168  * for writing in the meantime.  In that case, do nothing
2169  * (the disconnect or shutdown handler will take care of the rest).
2170  * If we were able to transmit messages and there are still more
2171  * pending, ask core again for further calls to this function.
2172  *
2173  * @param cls closure, pointer to the 'struct ClientList*'
2174  * @param size number of bytes available in buf
2175  * @param buf where the callee should write the message
2176  * @return number of bytes written to buf
2177  */
2178 static size_t
2179 transmit_to_client (void *cls,
2180                   size_t size, void *buf)
2181 {
2182   struct ClientList *cl = cls;
2183   char *cbuf = buf;
2184   struct ClientResponseMessage *creply;
2185   size_t msize;
2186   
2187   cl->th = NULL;
2188   if (NULL == buf)
2189     {
2190 #if DEBUG_FS
2191       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192                   "Not sending reply, client communication problem.\n");
2193 #endif
2194       return 0;
2195     }
2196   msize = 0;
2197   while ( (NULL != (creply = cl->res_head) ) &&
2198           (creply->msize <= size) )
2199     {
2200       memcpy (&cbuf[msize], &creply[1], creply->msize);
2201       msize += creply->msize;
2202       size -= creply->msize;
2203       GNUNET_CONTAINER_DLL_remove (cl->res_head,
2204                                    cl->res_tail,
2205                                    creply);
2206       GNUNET_free (creply);
2207     }
2208   if (NULL != creply)
2209     cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2210                                                   creply->msize,
2211                                                   GNUNET_TIME_UNIT_FOREVER_REL,
2212                                                   &transmit_to_client,
2213                                                   cl);
2214 #if DEBUG_FS
2215   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216               "Transmitted %u bytes to client\n",
2217               (unsigned int) msize);
2218 #endif
2219   return msize;
2220 }
2221
2222
2223 /**
2224  * Closure for "process_reply" function.
2225  */
2226 struct ProcessReplyClosure
2227 {
2228   /**
2229    * The data for the reply.
2230    */
2231   const void *data;
2232
2233   /**
2234    * Who gave us this reply? NULL for local host.
2235    */
2236   struct ConnectedPeer *sender;
2237
2238   /**
2239    * When the reply expires.
2240    */
2241   struct GNUNET_TIME_Absolute expiration;
2242
2243   /**
2244    * Size of data.
2245    */
2246   size_t size;
2247
2248   /**
2249    * Namespace that this reply belongs to
2250    * (if it is of type SBLOCK).
2251    */
2252   GNUNET_HashCode namespace;
2253
2254   /**
2255    * Type of the block.
2256    */
2257   enum GNUNET_BLOCK_Type type;
2258
2259   /**
2260    * How much was this reply worth to us?
2261    */
2262   uint32_t priority;
2263 };
2264
2265
2266 /**
2267  * We have received a reply; handle it!
2268  *
2269  * @param cls response (struct ProcessReplyClosure)
2270  * @param key our query
2271  * @param value value in the hash map (info about the query)
2272  * @return GNUNET_YES (we should continue to iterate)
2273  */
2274 static int
2275 process_reply (void *cls,
2276                const GNUNET_HashCode * key,
2277                void *value)
2278 {
2279   struct ProcessReplyClosure *prq = cls;
2280   struct PendingRequest *pr = value;
2281   struct PendingMessage *reply;
2282   struct ClientResponseMessage *creply;
2283   struct ClientList *cl;
2284   struct PutMessage *pm;
2285   struct ConnectedPeer *cp;
2286   struct GNUNET_TIME_Relative cur_delay;
2287   GNUNET_HashCode chash;
2288   GNUNET_HashCode mhash;
2289   size_t msize;
2290
2291 #if DEBUG_FS
2292   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2293               "Matched result (type %u) for query `%s' with pending request\n",
2294               (unsigned int) prq->type,
2295               GNUNET_h2s (key));
2296 #endif  
2297   GNUNET_STATISTICS_update (stats,
2298                             gettext_noop ("# replies received and matched"),
2299                             1,
2300                             GNUNET_NO);
2301   if (prq->sender != NULL)
2302     {
2303       /* FIXME: should we be more precise here and not use
2304          "start_time" but a peer-specific time stamp? */
2305       cur_delay = GNUNET_TIME_absolute_get_duration (pr->start_time);
2306       prq->sender->avg_delay.value
2307         = (prq->sender->avg_delay.value * 
2308            (RUNAVG_DELAY_N - 1) + cur_delay.value) / RUNAVG_DELAY_N; 
2309       prq->sender->avg_priority
2310         = (prq->sender->avg_priority * 
2311            (RUNAVG_DELAY_N - 1) + pr->priority) / (double) RUNAVG_DELAY_N;
2312       if (pr->cp != NULL)
2313         {
2314           GNUNET_PEER_change_rc (prq->sender->last_p2p_replies
2315                                  [prq->sender->last_p2p_replies_woff % P2P_SUCCESS_LIST_SIZE], -1);
2316           GNUNET_PEER_change_rc (pr->cp->pid, 1);
2317           prq->sender->last_p2p_replies
2318             [(prq->sender->last_p2p_replies_woff++) % P2P_SUCCESS_LIST_SIZE]
2319             = pr->cp->pid;
2320         }
2321       else
2322         {
2323           if (NULL != prq->sender->last_client_replies
2324               [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE])
2325             GNUNET_SERVER_client_drop (prq->sender->last_client_replies
2326                                        [(prq->sender->last_client_replies_woff) % CS2P_SUCCESS_LIST_SIZE]);
2327           prq->sender->last_client_replies
2328             [(prq->sender->last_client_replies_woff++) % CS2P_SUCCESS_LIST_SIZE]
2329             = pr->client_request_list->client_list->client;
2330           GNUNET_SERVER_client_keep (pr->client_request_list->client_list->client);
2331         }
2332     }
2333   GNUNET_CRYPTO_hash (prq->data,
2334                       prq->size,
2335                       &chash);
2336   switch (prq->type)
2337     {
2338     case GNUNET_BLOCK_TYPE_DBLOCK:
2339     case GNUNET_BLOCK_TYPE_IBLOCK:
2340       /* only possible reply, stop requesting! */
2341       while (NULL != pr->pending_head)
2342         destroy_pending_message_list_entry (pr->pending_head);
2343       if (pr->qe != NULL)
2344         {
2345           if (pr->client_request_list != NULL)
2346             GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
2347                                         GNUNET_YES);
2348           GNUNET_DATASTORE_cancel (pr->qe);
2349           pr->qe = NULL;
2350         }
2351       pr->do_remove = GNUNET_YES;
2352       if (pr->task != GNUNET_SCHEDULER_NO_TASK)
2353         {
2354           GNUNET_SCHEDULER_cancel (sched,
2355                                    pr->task);
2356           pr->task = GNUNET_SCHEDULER_NO_TASK;
2357         }
2358       GNUNET_break (GNUNET_YES ==
2359                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
2360                                                           key,
2361                                                           pr));
2362       break;
2363     case GNUNET_BLOCK_TYPE_SBLOCK:
2364       if (pr->namespace == NULL)
2365         {
2366           GNUNET_break (0);
2367           return GNUNET_YES;
2368         }
2369       if (0 != memcmp (pr->namespace,
2370                        &prq->namespace,
2371                        sizeof (GNUNET_HashCode)))
2372         {
2373           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2374                       _("Reply mismatched in terms of namespace.  Discarded.\n"));
2375           return GNUNET_YES; /* wrong namespace */      
2376         }
2377       /* then: fall-through! */
2378     case GNUNET_BLOCK_TYPE_KBLOCK:
2379     case GNUNET_BLOCK_TYPE_NBLOCK:
2380       if (pr->bf != NULL) 
2381         {
2382           mingle_hash (&chash, pr->mingle, &mhash);
2383           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2384                                                                &mhash))
2385             {
2386               GNUNET_STATISTICS_update (stats,
2387                                         gettext_noop ("# duplicate replies discarded (bloomfilter)"),
2388                                         1,
2389                                         GNUNET_NO);
2390 #if DEBUG_FS
2391               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392                           "Duplicate response `%s', discarding.\n",
2393                           GNUNET_h2s (&mhash));
2394 #endif
2395               return GNUNET_YES; /* duplicate */
2396             }
2397 #if DEBUG_FS
2398           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399                       "New response `%s', adding to filter.\n",
2400                       GNUNET_h2s (&mhash));
2401 #endif
2402         }
2403       if (pr->client_request_list != NULL)
2404         {
2405           if (pr->replies_seen_size == pr->replies_seen_off)
2406             GNUNET_array_grow (pr->replies_seen,
2407                                pr->replies_seen_size,
2408                                pr->replies_seen_size * 2 + 4);  
2409             pr->replies_seen[pr->replies_seen_off++] = chash;         
2410         }
2411       if ( (pr->bf == NULL) ||
2412            (pr->client_request_list != NULL) )
2413         refresh_bloomfilter (pr);
2414       GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2415                                         &mhash);
2416       break;
2417     default:
2418       GNUNET_break (0);
2419       return GNUNET_YES;
2420     }
2421   prq->priority += pr->remaining_priority;
2422   pr->remaining_priority = 0;
2423   if (pr->client_request_list != NULL)
2424     {
2425       GNUNET_STATISTICS_update (stats,
2426                                 gettext_noop ("# replies received for local clients"),
2427                                 1,
2428                                 GNUNET_NO);
2429       cl = pr->client_request_list->client_list;
2430       msize = sizeof (struct PutMessage) + prq->size;
2431       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
2432       creply->msize = msize;
2433       creply->client_list = cl;
2434       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
2435                                          cl->res_tail,
2436                                          cl->res_tail,
2437                                          creply);      
2438       pm = (struct PutMessage*) &creply[1];
2439       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2440       pm->header.size = htons (msize);
2441       pm->type = htonl (prq->type);
2442       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2443       memcpy (&pm[1], prq->data, prq->size);      
2444       if (NULL == cl->th)
2445         {
2446 #if DEBUG_FS
2447           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448                       "Transmitting result for query `%s' to client\n",
2449                       GNUNET_h2s (key));
2450 #endif  
2451           cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
2452                                                         msize,
2453                                                         GNUNET_TIME_UNIT_FOREVER_REL,
2454                                                         &transmit_to_client,
2455                                                         cl);
2456         }
2457       GNUNET_break (cl->th != NULL);
2458       if (pr->do_remove)                
2459         destroy_pending_request (pr);           
2460     }
2461   else
2462     {
2463       cp = pr->cp;
2464 #if DEBUG_FS
2465       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2466                   "Transmitting result for query `%s' to other peer (PID=%u)\n",
2467                   GNUNET_h2s (key),
2468                   (unsigned int) cp->pid);
2469 #endif  
2470       GNUNET_STATISTICS_update (stats,
2471                                 gettext_noop ("# replies received for other peers"),
2472                                 1,
2473                                 GNUNET_NO);
2474       msize = sizeof (struct PutMessage) + prq->size;
2475       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
2476       reply->cont = &transmit_reply_continuation;
2477       reply->cont_cls = pr;
2478       reply->msize = msize;
2479       reply->priority = (uint32_t) -1; /* send replies first! */
2480       pm = (struct PutMessage*) &reply[1];
2481       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2482       pm->header.size = htons (msize);
2483       pm->type = htonl (prq->type);
2484       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2485       memcpy (&pm[1], prq->data, prq->size);
2486       add_to_pending_messages_for_peer (cp, reply, pr);
2487     }
2488   return GNUNET_YES;
2489 }
2490
2491
2492 /**
2493  * Continuation called to notify client about result of the
2494  * operation.
2495  *
2496  * @param cls closure
2497  * @param success GNUNET_SYSERR on failure
2498  * @param msg NULL on success, otherwise an error message
2499  */
2500 static void 
2501 put_migration_continuation (void *cls,
2502                             int success,
2503                             const char *msg)
2504 {
2505   /* FIXME */
2506 }
2507
2508
2509 /**
2510  * Handle P2P "PUT" message.
2511  *
2512  * @param cls closure, always NULL
2513  * @param other the other peer involved (sender or receiver, NULL
2514  *        for loopback messages where we are both sender and receiver)
2515  * @param message the actual message
2516  * @param latency reported latency of the connection with 'other'
2517  * @param distance reported distance (DV) to 'other' 
2518  * @return GNUNET_OK to keep the connection open,
2519  *         GNUNET_SYSERR to close it (signal serious error)
2520  */
2521 static int
2522 handle_p2p_put (void *cls,
2523                 const struct GNUNET_PeerIdentity *other,
2524                 const struct GNUNET_MessageHeader *message,
2525                 struct GNUNET_TIME_Relative latency,
2526                 uint32_t distance)
2527 {
2528   const struct PutMessage *put;
2529   uint16_t msize;
2530   size_t dsize;
2531   enum GNUNET_BLOCK_Type type;
2532   struct GNUNET_TIME_Absolute expiration;
2533   GNUNET_HashCode query;
2534   struct ProcessReplyClosure prq;
2535   const struct SBlock *sb;
2536
2537   msize = ntohs (message->size);
2538   if (msize < sizeof (struct PutMessage))
2539     {
2540       GNUNET_break_op(0);
2541       return GNUNET_SYSERR;
2542     }
2543   put = (const struct PutMessage*) message;
2544   dsize = msize - sizeof (struct PutMessage);
2545   type = ntohl (put->type);
2546   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
2547
2548   if (GNUNET_OK !=
2549       GNUNET_BLOCK_check_block (type,
2550                                 &put[1],
2551                                 dsize,
2552                                 &query))
2553     {
2554       GNUNET_break_op (0);
2555       return GNUNET_SYSERR;
2556     }
2557   if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2558     return GNUNET_SYSERR;
2559   if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2560     { 
2561       sb = (const struct SBlock*) &put[1];
2562       GNUNET_CRYPTO_hash (&sb->subspace,
2563                           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2564                           &prq.namespace);
2565     }
2566
2567 #if DEBUG_FS
2568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2569               "Received result for query `%s' from peer `%4s'\n",
2570               GNUNET_h2s (&query),
2571               GNUNET_i2s (other));
2572 #endif
2573   GNUNET_STATISTICS_update (stats,
2574                             gettext_noop ("# replies received (overall)"),
2575                             1,
2576                             GNUNET_NO);
2577   /* now, lookup 'query' */
2578   prq.data = (const void*) &put[1];
2579   if (other != NULL)
2580     prq.sender = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2581                                                     &other->hashPubKey);
2582   prq.size = dsize;
2583   prq.type = type;
2584   prq.expiration = expiration;
2585   prq.priority = 0;
2586   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2587                                               &query,
2588                                               &process_reply,
2589                                               &prq);
2590   if (GNUNET_YES == active_migration)
2591     {
2592       GNUNET_DATASTORE_put (dsh,
2593                             0, &query, dsize, &put[1],
2594                             type, prq.priority, 1 /* anonymity */, 
2595                             expiration, 
2596                             1 + prq.priority, MAX_DATASTORE_QUEUE,
2597                             GNUNET_CONSTANTS_SERVICE_TIMEOUT,
2598                             &put_migration_continuation, 
2599                             NULL);
2600     }
2601   return GNUNET_OK;
2602 }
2603
2604
2605 /* **************************** P2P GET Handling ************************ */
2606
2607
2608 /**
2609  * Closure for 'check_duplicate_request_{peer,client}'.
2610  */
2611 struct CheckDuplicateRequestClosure
2612 {
2613   /**
2614    * The new request we should check if it already exists.
2615    */
2616   const struct PendingRequest *pr;
2617
2618   /**
2619    * Existing request found by the checker, NULL if none.
2620    */
2621   struct PendingRequest *have;
2622 };
2623
2624
2625 /**
2626  * Iterator over entries in the 'query_request_map' that
2627  * tries to see if we have the same request pending from
2628  * the same client already.
2629  *
2630  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2631  * @param key current key code (query, ignored, must match)
2632  * @param value value in the hash map (a 'struct PendingRequest' 
2633  *              that already exists)
2634  * @return GNUNET_YES if we should continue to
2635  *         iterate (no match yet)
2636  *         GNUNET_NO if not (match found).
2637  */
2638 static int
2639 check_duplicate_request_client (void *cls,
2640                                 const GNUNET_HashCode * key,
2641                                 void *value)
2642 {
2643   struct CheckDuplicateRequestClosure *cdc = cls;
2644   struct PendingRequest *have = value;
2645
2646   if (have->client_request_list == NULL)
2647     return GNUNET_YES;
2648   if ( (cdc->pr->client_request_list->client_list->client == have->client_request_list->client_list->client) &&
2649        (cdc->pr != have) )
2650     {
2651       cdc->have = have;
2652       return GNUNET_NO;
2653     }
2654   return GNUNET_YES;
2655 }
2656
2657
2658 /**
2659  * We're processing (local) results for a search request
2660  * from another peer.  Pass applicable results to the
2661  * peer and if we are done either clean up (operation
2662  * complete) or forward to other peers (more results possible).
2663  *
2664  * @param cls our closure (struct LocalGetContext)
2665  * @param key key for the content
2666  * @param size number of bytes in data
2667  * @param data content stored
2668  * @param type type of the content
2669  * @param priority priority of the content
2670  * @param anonymity anonymity-level for the content
2671  * @param expiration expiration time for the content
2672  * @param uid unique identifier for the datum;
2673  *        maybe 0 if no unique identifier is available
2674  */
2675 static void
2676 process_local_reply (void *cls,
2677                      const GNUNET_HashCode * key,
2678                      uint32_t size,
2679                      const void *data,
2680                      enum GNUNET_BLOCK_Type type,
2681                      uint32_t priority,
2682                      uint32_t anonymity,
2683                      struct GNUNET_TIME_Absolute
2684                      expiration, 
2685                      uint64_t uid)
2686 {
2687   struct PendingRequest *pr = cls;
2688   struct ProcessReplyClosure prq;
2689   struct CheckDuplicateRequestClosure cdrc;
2690   const struct SBlock *sb;
2691   GNUNET_HashCode dhash;
2692   GNUNET_HashCode mhash;
2693   GNUNET_HashCode query;
2694   
2695   if (NULL == key)
2696     {
2697 #if DEBUG_FS > 1
2698       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699                   "Done processing local replies, forwarding request to other peers.\n");
2700 #endif
2701       pr->qe = NULL;
2702       if (pr->client_request_list != NULL)
2703         {
2704           GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
2705                                       GNUNET_YES);
2706           /* Figure out if this is a duplicate request and possibly
2707              merge 'struct PendingRequest' entries */
2708           cdrc.have = NULL;
2709           cdrc.pr = pr;
2710           GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2711                                                       &pr->query,
2712                                                       &check_duplicate_request_client,
2713                                                       &cdrc);
2714           if (cdrc.have != NULL)
2715             {
2716 #if DEBUG_FS
2717               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2718                           "Received request for block `%s' twice from client, will only request once.\n",
2719                           GNUNET_h2s (&pr->query));
2720 #endif
2721               
2722               destroy_pending_request (pr);
2723               return;
2724             }
2725         }
2726
2727       /* no more results */
2728       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
2729         pr->task = GNUNET_SCHEDULER_add_now (sched,
2730                                              &forward_request_task,
2731                                              pr);      
2732       return;
2733     }
2734 #if DEBUG_FS
2735   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2736               "New local response to `%s' of type %u.\n",
2737               GNUNET_h2s (key),
2738               type);
2739 #endif
2740   if (type == GNUNET_BLOCK_TYPE_ONDEMAND)
2741     {
2742 #if DEBUG_FS
2743       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2744                   "Found ONDEMAND block, performing on-demand encoding\n");
2745 #endif
2746       GNUNET_STATISTICS_update (stats,
2747                                 gettext_noop ("# on-demand blocks matched requests"),
2748                                 1,
2749                                 GNUNET_NO);
2750       if (GNUNET_OK != 
2751           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
2752                                             anonymity, expiration, uid, 
2753                                             &process_local_reply,
2754                                             pr))
2755       if (pr->qe != NULL)
2756         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2757       return;
2758     }
2759   /* check for duplicates */
2760   GNUNET_CRYPTO_hash (data, size, &dhash);
2761   mingle_hash (&dhash, 
2762                pr->mingle,
2763                &mhash);
2764   if ( (pr->bf != NULL) &&
2765        (GNUNET_YES ==
2766         GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2767                                            &mhash)) )
2768     {      
2769 #if DEBUG_FS
2770       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2771                   "Result from datastore filtered by bloomfilter (duplicate).\n");
2772 #endif
2773       GNUNET_STATISTICS_update (stats,
2774                                 gettext_noop ("# results filtered by query bloomfilter"),
2775                                 1,
2776                                 GNUNET_NO);
2777       if (pr->qe != NULL)
2778         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2779       return;
2780     }
2781 #if DEBUG_FS
2782   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2783               "Found result for query `%s' in local datastore\n",
2784               GNUNET_h2s (key));
2785 #endif
2786   GNUNET_STATISTICS_update (stats,
2787                             gettext_noop ("# results found locally"),
2788                             1,
2789                             GNUNET_NO);
2790   pr->results_found++;
2791   memset (&prq, 0, sizeof (prq));
2792   prq.data = data;
2793   prq.expiration = expiration;
2794   prq.size = size;  
2795   if (GNUNET_BLOCK_TYPE_SBLOCK == type)
2796     { 
2797       sb = (const struct SBlock*) data;
2798       GNUNET_CRYPTO_hash (&sb->subspace,
2799                           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
2800                           &prq.namespace);
2801     }
2802   if (GNUNET_OK != GNUNET_BLOCK_check_block (type,
2803                                              data,
2804                                              size,
2805                                              &query))
2806     {
2807       GNUNET_break (0);
2808       GNUNET_DATASTORE_remove (dsh,
2809                                key,
2810                                size, data,
2811                                -1, -1, 
2812                                GNUNET_TIME_UNIT_FOREVER_REL,
2813                                NULL, NULL);
2814       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2815       return;
2816     }
2817   if ( (type == GNUNET_BLOCK_TYPE_DBLOCK) ||
2818        (type == GNUNET_BLOCK_TYPE_IBLOCK) ) 
2819     {
2820       if (pr->qe != NULL)
2821         GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2822     }
2823   else if ( (pr->client_request_list == NULL) &&
2824        ( (GNUNET_YES == test_load_too_high()) ||
2825          (pr->results_found > 5 + 2 * pr->priority) ) )
2826     {
2827 #if DEBUG_FS > 2
2828       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2829                   "Load too high, done with request\n");
2830 #endif
2831       GNUNET_STATISTICS_update (stats,
2832                                 gettext_noop ("# processing result set cut short due to load"),
2833                                 1,
2834                                 GNUNET_NO);
2835       if (pr->qe != NULL)
2836         GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2837     }
2838   else if (pr->qe != NULL)
2839     GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2840   prq.type = type;
2841   prq.priority = priority;  
2842   process_reply (&prq, key, pr);
2843 }
2844
2845
2846 /**
2847  * We've received a request with the specified priority.  Bound it
2848  * according to how much we trust the given peer.
2849  * 
2850  * @param prio_in requested priority
2851  * @param cp the peer making the request
2852  * @return effective priority
2853  */
2854 static uint32_t
2855 bound_priority (uint32_t prio_in,
2856                 struct ConnectedPeer *cp)
2857 {
2858   return 0; // FIXME!
2859 }
2860
2861
2862 /**
2863  * Iterator over entries in the 'query_request_map' that
2864  * tries to see if we have the same request pending from
2865  * the same peer already.
2866  *
2867  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2868  * @param key current key code (query, ignored, must match)
2869  * @param value value in the hash map (a 'struct PendingRequest' 
2870  *              that already exists)
2871  * @return GNUNET_YES if we should continue to
2872  *         iterate (no match yet)
2873  *         GNUNET_NO if not (match found).
2874  */
2875 static int
2876 check_duplicate_request_peer (void *cls,
2877                               const GNUNET_HashCode * key,
2878                               void *value)
2879 {
2880   struct CheckDuplicateRequestClosure *cdc = cls;
2881   struct PendingRequest *have = value;
2882
2883   if (cdc->pr->target_pid == have->target_pid)
2884     {
2885       cdc->have = have;
2886       return GNUNET_NO;
2887     }
2888   return GNUNET_YES;
2889 }
2890
2891
2892 /**
2893  * Handle P2P "GET" request.
2894  *
2895  * @param cls closure, always NULL
2896  * @param other the other peer involved (sender or receiver, NULL
2897  *        for loopback messages where we are both sender and receiver)
2898  * @param message the actual message
2899  * @param latency reported latency of the connection with 'other'
2900  * @param distance reported distance (DV) to 'other' 
2901  * @return GNUNET_OK to keep the connection open,
2902  *         GNUNET_SYSERR to close it (signal serious error)
2903  */
2904 static int
2905 handle_p2p_get (void *cls,
2906                 const struct GNUNET_PeerIdentity *other,
2907                 const struct GNUNET_MessageHeader *message,
2908                 struct GNUNET_TIME_Relative latency,
2909                 uint32_t distance)
2910 {
2911   struct PendingRequest *pr;
2912   struct ConnectedPeer *cp;
2913   struct ConnectedPeer *cps;
2914   struct CheckDuplicateRequestClosure cdc;
2915   struct GNUNET_TIME_Relative timeout;
2916   uint16_t msize;
2917   const struct GetMessage *gm;
2918   unsigned int bits;
2919   const GNUNET_HashCode *opt;
2920   uint32_t bm;
2921   size_t bfsize;
2922   uint32_t ttl_decrement;
2923   enum GNUNET_BLOCK_Type type;
2924   double preference;
2925   int have_ns;
2926
2927   msize = ntohs(message->size);
2928   if (msize < sizeof (struct GetMessage))
2929     {
2930       GNUNET_break_op (0);
2931       return GNUNET_SYSERR;
2932     }
2933   gm = (const struct GetMessage*) message;
2934   type = ntohl (gm->type);
2935   switch (type)
2936     {
2937     case GNUNET_BLOCK_TYPE_ANY:
2938     case GNUNET_BLOCK_TYPE_DBLOCK:
2939     case GNUNET_BLOCK_TYPE_IBLOCK:
2940     case GNUNET_BLOCK_TYPE_KBLOCK:
2941     case GNUNET_BLOCK_TYPE_SBLOCK:
2942       break;
2943     default:
2944       GNUNET_break_op (0);
2945       return GNUNET_SYSERR;
2946     }
2947   bm = ntohl (gm->hash_bitmap);
2948   bits = 0;
2949   while (bm > 0)
2950     {
2951       if (1 == (bm & 1))
2952         bits++;
2953       bm >>= 1;
2954     }
2955   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2956     {
2957       GNUNET_break_op (0);
2958       return GNUNET_SYSERR;
2959     }  
2960   opt = (const GNUNET_HashCode*) &gm[1];
2961   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2962   bm = ntohl (gm->hash_bitmap);
2963   if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2964        (type != GNUNET_BLOCK_TYPE_SBLOCK) )
2965     {
2966       GNUNET_break_op (0);
2967       return GNUNET_SYSERR;      
2968     }
2969   bits = 0;
2970   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2971                                            &other->hashPubKey);
2972   if (NULL == cps)
2973     {
2974       /* peer must have just disconnected */
2975       GNUNET_STATISTICS_update (stats,
2976                                 gettext_noop ("# requests dropped due to initiator not being connected"),
2977                                 1,
2978                                 GNUNET_NO);
2979       return GNUNET_SYSERR;
2980     }
2981   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2982     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2983                                             &opt[bits++]);
2984   else
2985     cp = cps;
2986   if (cp == NULL)
2987     {
2988 #if DEBUG_FS
2989       if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2990         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2991                     "Failed to find RETURN-TO peer `%4s' in connection set. Dropping query.\n",
2992                     GNUNET_i2s ((const struct GNUNET_PeerIdentity*) &opt[bits-1]));
2993       
2994       else
2995         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2996                     "Failed to find peer `%4s' in connection set. Dropping query.\n",
2997                     GNUNET_i2s (other));
2998 #endif
2999       GNUNET_STATISTICS_update (stats,
3000                                 gettext_noop ("# requests dropped due to missing reverse route"),
3001                                 1,
3002                                 GNUNET_NO);
3003      /* FIXME: try connect? */
3004       return GNUNET_OK;
3005     }
3006   /* note that we can really only check load here since otherwise
3007      peers could find out that we are overloaded by not being
3008      disconnected after sending us a malformed query... */
3009   if (GNUNET_YES == test_load_too_high ())
3010     {
3011 #if DEBUG_FS
3012       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3013                   "Dropping query from `%s', this peer is too busy.\n",
3014                   GNUNET_i2s (other));
3015 #endif
3016       GNUNET_STATISTICS_update (stats,
3017                                 gettext_noop ("# requests dropped due to high load"),
3018                                 1,
3019                                 GNUNET_NO);
3020       return GNUNET_OK;
3021     }
3022
3023 #if DEBUG_FS 
3024   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3025               "Received request for `%s' of type %u from peer `%4s' with flags %u\n",
3026               GNUNET_h2s (&gm->query),
3027               (unsigned int) type,
3028               GNUNET_i2s (other),
3029               (unsigned int) bm);
3030 #endif
3031   have_ns = (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE));
3032   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
3033                       (have_ns ? sizeof(GNUNET_HashCode) : 0));
3034   if (have_ns)
3035     pr->namespace = (GNUNET_HashCode*) &pr[1];
3036   pr->type = type;
3037   pr->mingle = ntohl (gm->filter_mutator);
3038   if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))    
3039     memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
3040   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
3041     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
3042
3043   pr->anonymity_level = 1;
3044   pr->priority = bound_priority (ntohl (gm->priority), cps);
3045   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
3046   pr->query = gm->query;
3047   /* decrement ttl (always) */
3048   ttl_decrement = 2 * TTL_DECREMENT +
3049     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
3050                               TTL_DECREMENT);
3051   if ( (pr->ttl < 0) &&
3052        (((int32_t)(pr->ttl - ttl_decrement)) > 0) )
3053     {
3054 #if DEBUG_FS
3055       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3056                   "Dropping query from `%s' due to TTL underflow (%d - %u).\n",
3057                   GNUNET_i2s (other),
3058                   pr->ttl,
3059                   ttl_decrement);
3060 #endif
3061       GNUNET_STATISTICS_update (stats,
3062                                 gettext_noop ("# requests dropped due TTL underflow"),
3063                                 1,
3064                                 GNUNET_NO);
3065       /* integer underflow => drop (should be very rare)! */
3066       GNUNET_free (pr);
3067       return GNUNET_OK;
3068     } 
3069   pr->ttl -= ttl_decrement;
3070   pr->start_time = GNUNET_TIME_absolute_get ();
3071
3072   /* get bloom filter */
3073   if (bfsize > 0)
3074     {
3075       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
3076                                                   bfsize,
3077                                                   BLOOMFILTER_K);
3078       pr->bf_size = bfsize;
3079     }
3080
3081   cdc.have = NULL;
3082   cdc.pr = pr;
3083   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
3084                                               &gm->query,
3085                                               &check_duplicate_request_peer,
3086                                               &cdc);
3087   if (cdc.have != NULL)
3088     {
3089       if (cdc.have->start_time.value + cdc.have->ttl >=
3090           pr->start_time.value + pr->ttl)
3091         {
3092           /* existing request has higher TTL, drop new one! */
3093           cdc.have->priority += pr->priority;
3094           destroy_pending_request (pr);
3095 #if DEBUG_FS
3096           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3097                       "Have existing request with higher TTL, dropping new request.\n",
3098                       GNUNET_i2s (other));
3099 #endif
3100           GNUNET_STATISTICS_update (stats,
3101                                     gettext_noop ("# requests dropped due to higher-TTL request"),
3102                                     1,
3103                                     GNUNET_NO);
3104           return GNUNET_OK;
3105         }
3106       else
3107         {
3108           /* existing request has lower TTL, drop old one! */
3109           pr->priority += cdc.have->priority;
3110           /* Possible optimization: if we have applicable pending
3111              replies in 'cdc.have', we might want to move those over
3112              (this is a really rare special-case, so it is not clear
3113              that this would be worth it) */
3114           destroy_pending_request (cdc.have);
3115           /* keep processing 'pr'! */
3116         }
3117     }
3118
3119   pr->cp = cp;
3120   GNUNET_break (GNUNET_OK ==
3121                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3122                                                    &gm->query,
3123                                                    pr,
3124                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3125   GNUNET_break (GNUNET_OK ==
3126                 GNUNET_CONTAINER_multihashmap_put (peer_request_map,
3127                                                    &other->hashPubKey,
3128                                                    pr,
3129                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3130   
3131   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
3132                                             pr,
3133                                             pr->start_time.value + pr->ttl);
3134
3135   GNUNET_STATISTICS_update (stats,
3136                             gettext_noop ("# P2P searches received"),
3137                             1,
3138                             GNUNET_NO);
3139   GNUNET_STATISTICS_update (stats,
3140                             gettext_noop ("# P2P searches active"),
3141                             1,
3142                             GNUNET_NO);
3143
3144   /* calculate change in traffic preference */
3145   preference = (double) pr->priority;
3146   if (preference < QUERY_BANDWIDTH_VALUE)
3147     preference = QUERY_BANDWIDTH_VALUE;
3148   cps->inc_preference += preference;
3149
3150   /* process locally */
3151   if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3152     type = GNUNET_BLOCK_TYPE_ANY; /* to get on-demand as well */
3153   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
3154                                            (pr->priority + 1)); 
3155   pr->qe = GNUNET_DATASTORE_get (dsh,
3156                                  &gm->query,
3157                                  type,                         
3158                                  pr->priority + 1,
3159                                  MAX_DATASTORE_QUEUE,                            
3160                                  timeout,
3161                                  &process_local_reply,
3162                                  pr);
3163
3164   /* Are multiple results possible?  If so, start processing remotely now! */
3165   switch (pr->type)
3166     {
3167     case GNUNET_BLOCK_TYPE_DBLOCK:
3168     case GNUNET_BLOCK_TYPE_IBLOCK:
3169       /* only one result, wait for datastore */
3170       break;
3171     default:
3172       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
3173         pr->task = GNUNET_SCHEDULER_add_now (sched,
3174                                              &forward_request_task,
3175                                              pr);
3176     }
3177
3178   /* make sure we don't track too many requests */
3179   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
3180     {
3181       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
3182       destroy_pending_request (pr);
3183     }
3184   return GNUNET_OK;
3185 }
3186
3187
3188 /* **************************** CS GET Handling ************************ */
3189
3190
3191 /**
3192  * Handle START_SEARCH-message (search request from client).
3193  *
3194  * @param cls closure
3195  * @param client identification of the client
3196  * @param message the actual message
3197  */
3198 static void
3199 handle_start_search (void *cls,
3200                      struct GNUNET_SERVER_Client *client,
3201                      const struct GNUNET_MessageHeader *message)
3202 {
3203   static GNUNET_HashCode all_zeros;
3204   const struct SearchMessage *sm;
3205   struct ClientList *cl;
3206   struct ClientRequestList *crl;
3207   struct PendingRequest *pr;
3208   uint16_t msize;
3209   unsigned int sc;
3210   enum GNUNET_BLOCK_Type type;
3211
3212   msize = ntohs (message->size);
3213   if ( (msize < sizeof (struct SearchMessage)) ||
3214        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
3215     {
3216       GNUNET_break (0);
3217       GNUNET_SERVER_receive_done (client,
3218                                   GNUNET_SYSERR);
3219       return;
3220     }
3221   GNUNET_STATISTICS_update (stats,
3222                             gettext_noop ("# client searches received"),
3223                             1,
3224                             GNUNET_NO);
3225   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
3226   sm = (const struct SearchMessage*) message;
3227   type = ntohl (sm->type);
3228 #if DEBUG_FS
3229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3230               "Received request for `%s' of type %u from local client\n",
3231               GNUNET_h2s (&sm->query),
3232               (unsigned int) type);
3233 #endif
3234   switch (type)
3235     {
3236     case GNUNET_BLOCK_TYPE_ANY:
3237     case GNUNET_BLOCK_TYPE_DBLOCK:
3238     case GNUNET_BLOCK_TYPE_IBLOCK:
3239     case GNUNET_BLOCK_TYPE_KBLOCK:
3240     case GNUNET_BLOCK_TYPE_SBLOCK:
3241     case GNUNET_BLOCK_TYPE_NBLOCK:
3242       break;
3243     default:
3244       GNUNET_break (0);
3245       GNUNET_SERVER_receive_done (client,
3246                                   GNUNET_SYSERR);
3247       return;
3248     }  
3249
3250   cl = client_list;
3251   while ( (cl != NULL) &&
3252           (cl->client != client) )
3253     cl = cl->next;
3254   if (cl == NULL)
3255     {
3256       cl = GNUNET_malloc (sizeof (struct ClientList));
3257       cl->client = client;
3258       GNUNET_SERVER_client_keep (client);
3259       cl->next = client_list;
3260       client_list = cl;
3261     }
3262   /* detect duplicate KBLOCK requests */
3263   if ( (type == GNUNET_BLOCK_TYPE_KBLOCK) ||
3264        (type == GNUNET_BLOCK_TYPE_NBLOCK) ||
3265        (type == GNUNET_BLOCK_TYPE_ANY) )
3266     {
3267       crl = cl->rl_head;
3268       while ( (crl != NULL) &&
3269               ( (0 != memcmp (&crl->req->query,
3270                               &sm->query,
3271                               sizeof (GNUNET_HashCode))) ||
3272                 (crl->req->type != type) ) )
3273         crl = crl->next;
3274       if (crl != NULL)  
3275         { 
3276 #if DEBUG_FS
3277           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3278                       "Have existing request, merging content-seen lists.\n");
3279 #endif
3280           pr = crl->req;
3281           /* Duplicate request (used to send long list of
3282              known/blocked results); merge 'pr->replies_seen'
3283              and update bloom filter */
3284           GNUNET_array_grow (pr->replies_seen,
3285                              pr->replies_seen_size,
3286                              pr->replies_seen_off + sc);
3287           memcpy (&pr->replies_seen[pr->replies_seen_off],
3288                   &sm[1],
3289                   sc * sizeof (GNUNET_HashCode));
3290           pr->replies_seen_off += sc;
3291           refresh_bloomfilter (pr);
3292           GNUNET_STATISTICS_update (stats,
3293                                     gettext_noop ("# client searches updated (merged content seen list)"),
3294                                     1,
3295                                     GNUNET_NO);
3296           GNUNET_SERVER_receive_done (client,
3297                                       GNUNET_OK);
3298           return;
3299         }
3300     }
3301   GNUNET_STATISTICS_update (stats,
3302                             gettext_noop ("# client searches active"),
3303                             1,
3304                             GNUNET_NO);
3305   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
3306                       ((type == GNUNET_BLOCK_TYPE_SBLOCK) ? sizeof(GNUNET_HashCode) : 0));
3307   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
3308   memset (crl, 0, sizeof (struct ClientRequestList));
3309   crl->client_list = cl;
3310   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
3311                                cl->rl_tail,
3312                                crl);  
3313   crl->req = pr;
3314   pr->type = type;
3315   pr->client_request_list = crl;
3316   GNUNET_array_grow (pr->replies_seen,
3317                      pr->replies_seen_size,
3318                      sc);
3319   memcpy (pr->replies_seen,
3320           &sm[1],
3321           sc * sizeof (GNUNET_HashCode));
3322   pr->replies_seen_off = sc;
3323   pr->anonymity_level = ntohl (sm->anonymity_level); 
3324   refresh_bloomfilter (pr);
3325   pr->query = sm->query;
3326   if (0 == (1 & ntohl (sm->options)))
3327     pr->local_only = GNUNET_NO;
3328   else
3329     pr->local_only = GNUNET_YES;
3330   switch (type)
3331     {
3332     case GNUNET_BLOCK_TYPE_DBLOCK:
3333     case GNUNET_BLOCK_TYPE_IBLOCK:
3334       if (0 != memcmp (&sm->target,
3335                        &all_zeros,
3336                        sizeof (GNUNET_HashCode)))
3337         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
3338       break;
3339     case GNUNET_BLOCK_TYPE_SBLOCK:
3340       pr->namespace = (GNUNET_HashCode*) &pr[1];
3341       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
3342       break;
3343     default:
3344       break;
3345     }
3346   GNUNET_break (GNUNET_OK ==
3347                 GNUNET_CONTAINER_multihashmap_put (query_request_map,
3348                                                    &sm->query,
3349                                                    pr,
3350                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
3351   if (type == GNUNET_BLOCK_TYPE_DBLOCK)
3352     type = GNUNET_BLOCK_TYPE_ANY; /* get on-demand blocks too! */
3353   pr->qe = GNUNET_DATASTORE_get (dsh,
3354                                  &sm->query,
3355                                  type,
3356                                  -3, -1,
3357                                  GNUNET_CONSTANTS_SERVICE_TIMEOUT,                             
3358                                  &process_local_reply,
3359                                  pr);
3360 }
3361
3362
3363 /* **************************** Startup ************************ */
3364
3365
3366 /**
3367  * List of handlers for P2P messages
3368  * that we care about.
3369  */
3370 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3371   {
3372     { &handle_p2p_get, 
3373       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3374     { &handle_p2p_put, 
3375       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3376     { NULL, 0, 0 }
3377   };
3378
3379
3380 /**
3381  * List of handlers for the messages understood by this
3382  * service.
3383  */
3384 static struct GNUNET_SERVER_MessageHandler handlers[] = {
3385   {&GNUNET_FS_handle_index_start, NULL, 
3386    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
3387   {&GNUNET_FS_handle_index_list_get, NULL, 
3388    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
3389   {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
3390    sizeof (struct UnindexMessage) },
3391   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
3392    0 },
3393   {NULL, NULL, 0, 0}
3394 };
3395
3396
3397 /**
3398  * Process fs requests.
3399  *
3400  * @param s scheduler to use
3401  * @param server the initialized server
3402  * @param c configuration to use
3403  */
3404 static int
3405 main_init (struct GNUNET_SCHEDULER_Handle *s,
3406            struct GNUNET_SERVER_Handle *server,
3407            const struct GNUNET_CONFIGURATION_Handle *c)
3408 {
3409   sched = s;
3410   cfg = c;
3411   stats = GNUNET_STATISTICS_create (sched, "fs", cfg);
3412   min_migration_delay = GNUNET_TIME_UNIT_SECONDS; // FIXME: get from config
3413   connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3414   query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3415   peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3416   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
3417   core = GNUNET_CORE_connect (sched,
3418                               cfg,
3419                               GNUNET_TIME_UNIT_FOREVER_REL,
3420                               NULL,
3421                               NULL,
3422                               &peer_connect_handler,
3423                               &peer_disconnect_handler,
3424                               NULL, GNUNET_NO,
3425                               NULL, GNUNET_NO,
3426                               p2p_handlers);
3427   if (NULL == core)
3428     {
3429       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3430                   _("Failed to connect to `%s' service.\n"),
3431                   "core");
3432       GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
3433       connected_peers = NULL;
3434       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
3435       query_request_map = NULL;
3436       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
3437       requests_by_expiration_heap = NULL;
3438       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
3439       peer_request_map = NULL;
3440       if (dsh != NULL)
3441         {
3442           GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3443           dsh = NULL;
3444         }
3445       return GNUNET_SYSERR;
3446     }
3447   /* FIXME: distinguish between sending and storing in options? */
3448   if (active_migration) 
3449     consider_migration_gathering ();
3450   GNUNET_SERVER_disconnect_notify (server, 
3451                                    &handle_client_disconnect,
3452                                    NULL);
3453   GNUNET_SERVER_add_handlers (server, handlers);
3454   GNUNET_SCHEDULER_add_delayed (sched,
3455                                 GNUNET_TIME_UNIT_FOREVER_REL,
3456                                 &shutdown_task,
3457                                 NULL);
3458   return GNUNET_OK;
3459 }
3460
3461
3462 /**
3463  * Process fs requests.
3464  *
3465  * @param cls closure
3466  * @param sched scheduler to use
3467  * @param server the initialized server
3468  * @param cfg configuration to use
3469  */
3470 static void
3471 run (void *cls,
3472      struct GNUNET_SCHEDULER_Handle *sched,
3473      struct GNUNET_SERVER_Handle *server,
3474      const struct GNUNET_CONFIGURATION_Handle *cfg)
3475 {
3476   active_migration = GNUNET_CONFIGURATION_get_value_yesno (cfg,
3477                                                            "FS",
3478                                                            "ACTIVEMIGRATION");
3479   dsh = GNUNET_DATASTORE_connect (cfg,
3480                                   sched);
3481   if (dsh == NULL)
3482     {
3483       GNUNET_SCHEDULER_shutdown (sched);
3484       return;
3485     }
3486   if ( (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg, dsh)) ||
3487        (GNUNET_OK != main_init (sched, server, cfg)) )
3488     {    
3489       GNUNET_SCHEDULER_shutdown (sched);
3490       GNUNET_DATASTORE_disconnect (dsh, GNUNET_NO);
3491       dsh = NULL;
3492       return;   
3493     }
3494 }
3495
3496
3497 /**
3498  * The main function for the fs service.
3499  *
3500  * @param argc number of arguments from the command line
3501  * @param argv command line arguments
3502  * @return 0 ok, 1 on error
3503  */
3504 int
3505 main (int argc, char *const *argv)
3506 {
3507   return (GNUNET_OK ==
3508           GNUNET_SERVICE_run (argc,
3509                               argv,
3510                               "fs",
3511                               GNUNET_SERVICE_OPTION_NONE,
3512                               &run, NULL)) ? 0 : 1;
3513 }
3514
3515 /* end of gnunet-service-fs.c */