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