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