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