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