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