fixing core API issues
[oweals/gnunet.git] / src / fs / gnunet-service-fs.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 program that provides the file-sharing service
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - fix gazillion of minor FIXME's
28  * - possible major issue: we may queue "gazillions" of (K|S)Blocks for the
29  *   core to transmit to another peer; need to make sure this is bounded overall...
30  * - randomly delay processing for improved anonymity (can wait)
31  * - content migration (put in local DS) (can wait)
32  * - handle some special cases when forwarding replies based on tracked requests (can wait)
33  * - tracking of success correlations for hot-path routing (can wait)
34  * - various load-based actions (can wait)
35  * - validation of KSBLOCKS (can wait)
36  * - remove on-demand blocks if they keep failing (can wait)
37  * - check that we decrement PIDs always where necessary (can wait)
38  * - find out how to use core-pulling instead of pushing (at least for some cases)
39  */
40 #include "platform.h"
41 #include <float.h>
42 #include "gnunet_core_service.h"
43 #include "gnunet_datastore_service.h"
44 #include "gnunet_peer_lib.h"
45 #include "gnunet_protocols.h"
46 #include "gnunet_signatures.h"
47 #include "gnunet_util_lib.h"
48 #include "fs.h"
49
50 #define DEBUG_FS GNUNET_NO
51
52
53 /**
54  * In-memory information about indexed files (also available
55  * on-disk).
56  */
57 struct IndexInfo
58 {
59   
60   /**
61    * This is a linked list.
62    */
63   struct IndexInfo *next;
64
65   /**
66    * Name of the indexed file.  Memory allocated
67    * at the end of this struct (do not free).
68    */
69   const char *filename;
70
71   /**
72    * Context for transmitting confirmation to client,
73    * NULL if we've done this already.
74    */
75   struct GNUNET_SERVER_TransmitContext *tc;
76   
77   /**
78    * Hash of the contents of the file.
79    */
80   GNUNET_HashCode file_id;
81
82 };
83
84
85 /**
86  * Signature of a function that is called whenever a datastore
87  * request can be processed (or an entry put on the queue times out).
88  *
89  * @param cls closure
90  * @param ok GNUNET_OK if DS is ready, GNUNET_SYSERR on timeout
91  */
92 typedef void (*RequestFunction)(void *cls,
93                                 int ok);
94
95
96 /**
97  * Doubly-linked list of our requests for the datastore.
98  */
99 struct DatastoreRequestQueue
100 {
101
102   /**
103    * This is a doubly-linked list.
104    */
105   struct DatastoreRequestQueue *next;
106
107   /**
108    * This is a doubly-linked list.
109    */
110   struct DatastoreRequestQueue *prev;
111
112   /**
113    * Function to call (will issue the request).
114    */
115   RequestFunction req;
116
117   /**
118    * Closure for req.
119    */
120   void *req_cls;
121
122   /**
123    * When should this request time-out because we don't care anymore?
124    */
125   struct GNUNET_TIME_Absolute timeout;
126     
127   /**
128    * ID of task used for signaling timeout.
129    */
130   GNUNET_SCHEDULER_TaskIdentifier task;
131
132 };
133
134
135 /**
136  * Closure for processing START_SEARCH messages from a client.
137  */
138 struct LocalGetContext
139 {
140
141   /**
142    * This is a doubly-linked list.
143    */
144   struct LocalGetContext *next;
145
146   /**
147    * This is a doubly-linked list.
148    */
149   struct LocalGetContext *prev;
150
151   /**
152    * Client that initiated the search.
153    */
154   struct GNUNET_SERVER_Client *client;
155
156   /**
157    * Array of results that we've already received 
158    * (can be NULL).
159    */
160   GNUNET_HashCode *results; 
161
162   /**
163    * Bloomfilter over all results (for fast query construction);
164    * NULL if we don't have any results.
165    *
166    * FIXME: this member is not used, is that OK? If so, it should
167    * be removed!
168    */
169   struct GNUNET_CONTAINER_BloomFilter *results_bf; 
170
171   /**
172    * DS request associated with this operation.
173    */
174   struct DatastoreRequestQueue *req;
175
176   /**
177    * Current result message to transmit to client (or NULL).
178    */
179   struct ContentMessage *result;
180   
181   /**
182    * Type of the content that we're looking for.
183    * 0 for any.
184    */
185   uint32_t type;
186
187   /**
188    * Desired anonymity level.
189    */
190   uint32_t anonymity_level;
191
192   /**
193    * Number of results actually stored in the results array.
194    */
195   unsigned int results_used;
196   
197   /**
198    * Size of the results array in memory.
199    */
200   unsigned int results_size;
201   
202   /**
203    * Size (in bytes) of the 'results_bf' bloomfilter.
204    *
205    * FIXME: this member is not used, is that OK? If so, it should
206    * be removed!
207    */
208   size_t results_bf_size;
209
210   /**
211    * If the request is for a DBLOCK or IBLOCK, this is the identity of
212    * the peer that is known to have a response.  Set to all-zeros if
213    * such a target is not known (note that even if OUR anonymity
214    * level is >0 we may happen to know the responder's identity;
215    * nevertheless, we should probably not use it for a DHT-lookup
216    * or similar blunt actions in order to avoid exposing ourselves).
217    */
218   struct GNUNET_PeerIdentity target;
219
220   /**
221    * If the request is for an SBLOCK, this is the identity of the
222    * pseudonym to which the SBLOCK belongs. 
223    */
224   GNUNET_HashCode namespace;
225
226   /**
227    * Hash of the keyword (aka query) for KBLOCKs; Hash of
228    * the CHK-encoded block for DBLOCKS and IBLOCKS (aka query)
229    * and hash of the identifier XORed with the target for
230    * SBLOCKS (aka query).
231    */
232   GNUNET_HashCode query;
233
234 };
235
236
237 /**
238  * Possible routing policies for an FS-GET request.
239  */
240 enum RoutingPolicy
241   {
242     /**
243      * Simply drop the request.
244      */
245     ROUTING_POLICY_NONE = 0,
246     
247     /**
248      * Answer it if we can from local datastore.
249      */
250     ROUTING_POLICY_ANSWER = 1,
251
252     /**
253      * Forward the request to other peers (if possible).
254      */
255     ROUTING_POLICY_FORWARD = 2,
256
257     /**
258      * Forward to other peers, and ask them to route
259      * the response via ourselves.
260      */
261     ROUTING_POLICY_INDIRECT = 6,
262     
263     /**
264      * Do everything we could possibly do (that would
265      * make sense).
266      */
267     ROUTING_POLICY_ALL = 7
268   };
269
270
271 /**
272  * Internal context we use for our initial processing
273  * of a GET request.
274  */
275 struct ProcessGetContext
276 {
277   /**
278    * The search query (used for datastore lookup).
279    */
280   GNUNET_HashCode query;
281   
282   /**
283    * Which peer we should forward the response to.
284    */
285   struct GNUNET_PeerIdentity reply_to;
286
287   /**
288    * Namespace for the result (only set for SKS requests)
289    */
290   GNUNET_HashCode namespace;
291
292   /**
293    * Peer that we should forward the query to if possible
294    * (since that peer likely has the content).
295    */
296   struct GNUNET_PeerIdentity prime_target;
297
298   /**
299    * When did we receive this request?
300    */
301   struct GNUNET_TIME_Absolute start_time;
302
303   /**
304    * Our entry in the DRQ (non-NULL while we wait for our
305    * turn to interact with the local database).
306    */
307   struct DatastoreRequestQueue *drq;
308
309   /**
310    * Filter used to eliminate duplicate results.  Can be NULL if we
311    * are not yet filtering any results.
312    */
313   struct GNUNET_CONTAINER_BloomFilter *bf;
314
315   /**
316    * Bitmap describing which of the optional
317    * hash codes / peer identities were given to us.
318    */
319   uint32_t bm;
320
321   /**
322    * Desired block type.
323    */
324   uint32_t type;
325
326   /**
327    * Priority of the request.
328    */
329   uint32_t priority;
330
331   /**
332    * Size of the 'bf' (in bytes).
333    */
334   size_t bf_size;
335
336   /**
337    * In what ways are we going to process
338    * the request?
339    */
340   enum RoutingPolicy policy;
341
342   /**
343    * Time-to-live for the request (value
344    * we use).
345    */
346   int32_t ttl;
347
348   /**
349    * Number to mingle hashes for bloom-filter
350    * tests with.
351    */
352   int32_t mingle;
353
354   /**
355    * Number of results that were found so far.
356    */
357   unsigned int results_found;
358 };
359
360
361 /**
362  * Information we keep for each pending reply.
363  */
364 struct PendingReply
365 {
366   /**
367    * This is a linked list.
368    */
369   struct PendingReply *next;
370
371   /**
372    * Size of the reply; actual reply message follows
373    * at the end of this struct.
374    */
375   size_t msize;
376
377 };
378
379
380 /**
381  * All requests from a client are kept in a doubly-linked list.
382  */
383 struct ClientRequestList;
384
385
386 /**
387  * Information we keep for each pending request.  We should try to
388  * keep this struct as small as possible since its memory consumption
389  * is key to how many requests we can have pending at once.
390  */
391 struct PendingRequest
392 {
393
394   /**
395    * ID of a client making a request, NULL if this entry is for a
396    * peer.
397    */
398   struct GNUNET_SERVER_Client *client;
399
400   /**
401    * If this request was made by a client,
402    * this is our entry in the client request
403    * list; otherwise NULL.
404    */
405   struct ClientRequestList *crl_entry;
406
407   /**
408    * If this is a namespace query, pointer to the hash of the public
409    * key of the namespace; otherwise NULL.
410    */
411   GNUNET_HashCode *namespace;
412
413   /**
414    * Bloomfilter we use to filter out replies that we don't care about
415    * (anymore).  NULL as long as we are interested in all replies.
416    */
417   struct GNUNET_CONTAINER_BloomFilter *bf;
418
419   /**
420    * Context of our GNUNET_CORE_peer_get_info call.
421    */
422   struct GNUNET_CORE_InformationRequestContext *irc;
423
424   /**
425    * Replies that we have received but were unable to forward yet
426    * (typically non-null only if we have a pending transmission
427    * request with the client or the respective peer).
428    */
429   struct PendingReply *replies_pending;
430
431   /**
432    * Pending transmission request with the core service for the target
433    * peer (for processing of 'replies_pending') or Handle for a
434    * pending query-request for P2P-transmission with the core service.
435    * If non-NULL, this request must be cancelled should this struct be
436    * destroyed!
437    */
438   struct GNUNET_CORE_TransmitHandle *cth;
439
440   /**
441    * Pending transmission request for the target client (for processing of
442    * 'replies_pending').
443    */
444   struct GNUNET_CONNECTION_TransmitHandle *th;
445
446   /**
447    * Hash code of all replies that we have seen so far (only valid
448    * if client is not NULL since we only track replies like this for
449    * our own clients).
450    */
451   GNUNET_HashCode *replies_seen;
452
453   /**
454    * Node in the heap representing this entry.
455    */
456   struct GNUNET_CONTAINER_HeapNode *hnode;
457
458   /**
459    * When did we first see this request (form this peer), or, if our
460    * client is initiating, when did we last initiate a search?
461    */
462   struct GNUNET_TIME_Absolute start_time;
463
464   /**
465    * The query that this request is for.
466    */
467   GNUNET_HashCode query;
468
469   /**
470    * The task responsible for transmitting queries
471    * for this request.
472    */
473   GNUNET_SCHEDULER_TaskIdentifier task;
474
475   /**
476    * (Interned) Peer identifier (only valid if "client" is NULL)
477    * that identifies a peer that gave us this request.
478    */
479   GNUNET_PEER_Id source_pid;
480
481   /**
482    * (Interned) Peer identifier that identifies a preferred target
483    * for requests.
484    */
485   GNUNET_PEER_Id target_pid;
486
487   /**
488    * (Interned) Peer identifiers of peers that have already
489    * received our query for this content.
490    */
491   GNUNET_PEER_Id *used_pids;
492
493   /**
494    * Size of the 'bf' (in bytes).
495    */
496   size_t bf_size;
497
498   /**
499    * Desired anonymity level; only valid for requests from a local client.
500    */
501   uint32_t anonymity_level;
502
503   /**
504    * How many entries in "used_pids" are actually valid?
505    */
506   unsigned int used_pids_off;
507
508   /**
509    * How long is the "used_pids" array?
510    */
511   unsigned int used_pids_size;
512
513   /**
514    * How many entries in "replies_seen" are actually valid?
515    */
516   unsigned int replies_seen_off;
517
518   /**
519    * How long is the "replies_seen" array?
520    */
521   unsigned int replies_seen_size;
522   
523   /**
524    * Priority with which this request was made.  If one of our clients
525    * made the request, then this is the current priority that we are
526    * using when initiating the request.  This value is used when
527    * we decide to reward other peers with trust for providing a reply.
528    */
529   uint32_t priority;
530
531   /**
532    * Priority points left for us to spend when forwarding this request
533    * to other peers.
534    */
535   uint32_t remaining_priority;
536
537   /**
538    * Number to mingle hashes for bloom-filter
539    * tests with.
540    */
541   int32_t mingle;
542
543   /**
544    * TTL with which we saw this request (or, if we initiated, TTL that
545    * we used for the request).
546    */
547   int32_t ttl;
548   
549   /**
550    * Type of the content that this request is for.
551    */
552   uint32_t type;
553
554 };
555
556
557 /**
558  * All requests from a client are kept in a doubly-linked list.
559  */
560 struct ClientRequestList
561 {
562   /**
563    * This is a doubly-linked list.
564    */
565   struct ClientRequestList *next;
566
567   /**
568    * This is a doubly-linked list.
569    */ 
570   struct ClientRequestList *prev;
571
572   /**
573    * A request from this client.
574    */
575   struct PendingRequest *req;
576
577   /**
578    * Client list with the head and tail of this DLL.
579    */
580   struct ClientList *cl;
581 };
582
583
584 /**
585  * Linked list of all clients that we are 
586  * currently processing requests for.
587  */
588 struct ClientList
589 {
590
591   /**
592    * This is a linked list.
593    */
594   struct ClientList *next;
595
596   /**
597    * What client is this entry for?
598    */
599   struct GNUNET_SERVER_Client* client;
600
601   /**
602    * Head of the DLL of requests from this client.
603    */
604   struct ClientRequestList *head;
605
606   /**
607    * Tail of the DLL of requests from this client.
608    */
609   struct ClientRequestList *tail;
610
611 };
612
613
614 /**
615  * Closure for "process_reply" function.
616  */
617 struct ProcessReplyClosure
618 {
619   /**
620    * The data for the reply.
621    */
622   const void *data;
623
624   /**
625    * When the reply expires.
626    */
627   struct GNUNET_TIME_Absolute expiration;
628
629   /**
630    * Size of data.
631    */
632   size_t size;
633
634   /**
635    * Namespace that this reply belongs to
636    * (if it is of type SBLOCK).
637    */
638   GNUNET_HashCode namespace;
639
640   /**
641    * Type of the block.
642    */
643   uint32_t type;
644
645   /**
646    * How much was this reply worth to us?
647    */
648   uint32_t priority;
649 };
650
651
652 /**
653  * Information about a peer that we are connected to.
654  * We track data that is useful for determining which
655  * peers should receive our requests.
656  */
657 struct ConnectedPeer
658 {
659
660   /**
661    * List of the last clients for which this peer
662    * successfully answered a query. 
663    */
664   struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
665
666   /**
667    * List of the last PIDs for which
668    * this peer successfully answered a query;
669    * We use 0 to indicate no successful reply.
670    */
671   GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
672
673   /**
674    * Average delay between sending the peer a request and
675    * getting a reply (only calculated over the requests for
676    * which we actually got a reply).   Calculated
677    * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
678    */ 
679   struct GNUNET_TIME_Relative avg_delay;
680
681   /**
682    * Average priority of successful replies.  Calculated
683    * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
684    */
685   double avg_priority;
686
687   /**
688    * The peer's identity.
689    */
690   GNUNET_PEER_Id pid;  
691
692   /**
693    * Number of requests we have currently pending
694    * with this peer (that is, requests that were
695    * transmitted so recently that we would not retransmit
696    * them right now).
697    */
698   unsigned int pending_requests;
699
700   /**
701    * Which offset in "last_p2p_replies" will be updated next?
702    * (we go round-robin).
703    */
704   unsigned int last_p2p_replies_woff;
705
706   /**
707    * Which offset in "last_client_replies" will be updated next?
708    * (we go round-robin).
709    */
710   unsigned int last_client_replies_woff;
711
712 };
713
714
715 /**
716  * Our connection to the datastore.
717  */
718 static struct GNUNET_DATASTORE_Handle *dsh;
719
720 /**
721  * Our scheduler.
722  */
723 static struct GNUNET_SCHEDULER_Handle *sched;
724
725 /**
726  * Our configuration.
727  */
728 const struct GNUNET_CONFIGURATION_Handle *cfg;
729
730 /**
731  * Handle to the core service (NULL until we've connected to it).
732  */
733 struct GNUNET_CORE_Handle *core;
734
735 /**
736  * Head of doubly-linked LGC list.
737  */
738 static struct LocalGetContext *lgc_head;
739
740 /**
741  * Tail of doubly-linked LGC list.
742  */
743 static struct LocalGetContext *lgc_tail;
744
745 /**
746  * Head of request queue for the datastore, sorted by timeout.
747  */
748 static struct DatastoreRequestQueue *drq_head;
749
750 /**
751  * Tail of request queue for the datastore.
752  */
753 static struct DatastoreRequestQueue *drq_tail;
754
755 /**
756  * Linked list of indexed files.
757  */
758 static struct IndexInfo *indexed_files;
759
760 /**
761  * Maps hash over content of indexed files to the respective filename.
762  * The filenames are pointers into the indexed_files linked list and
763  * do not need to be freed.
764  */
765 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
766
767 /**
768  * Map of query hash codes to requests.
769  */
770 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_query;
771
772 /**
773  * Map of peer IDs to requests (for those requests coming
774  * from other peers).
775  */
776 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_peer;
777
778 /**
779  * Linked list of all of our clients and their requests.
780  */
781 static struct ClientList *clients;
782
783 /**
784  * Heap with the request that will expire next at the top.  Contains
785  * pointers of type "struct PendingRequest*"; these will *also* be
786  * aliased from the "requests_by_peer" data structures and the
787  * "requests_by_query" table.  Note that requests from our clients
788  * don't expire and are thus NOT in the "requests_by_expiration"
789  * (or the "requests_by_peer" tables).
790  */
791 static struct GNUNET_CONTAINER_Heap *requests_by_expiration;
792
793 /**
794  * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
795  */
796 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
797
798 /**
799  * Maximum number of requests (from other peers) that we're
800  * willing to have pending at any given point in time.
801  * FIXME: set from configuration (and 32 is a tiny value for testing only).
802  */
803 static uint64_t max_pending_requests = 32;
804
805
806 /**
807  * Write the current index information list to disk.
808  */ 
809 static void
810 write_index_list ()
811 {
812   struct GNUNET_BIO_WriteHandle *wh;
813   char *fn;
814   struct IndexInfo *pos;  
815
816   if (GNUNET_OK !=
817       GNUNET_CONFIGURATION_get_value_filename (cfg,
818                                                "FS",
819                                                "INDEXDB",
820                                                &fn))
821     {
822       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
823                   _("Configuration option `%s' in section `%s' missing.\n"),
824                   "INDEXDB",
825                   "FS");
826       return;
827     }
828   wh = GNUNET_BIO_write_open (fn);
829   if (NULL == wh)
830     {
831       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
832                   _("Could not open `%s'.\n"),
833                   fn);
834       GNUNET_free (fn);
835       return;
836     }
837   pos = indexed_files;
838   while (pos != NULL)
839     {
840       if ( (GNUNET_OK !=
841             GNUNET_BIO_write (wh,
842                               &pos->file_id,
843                               sizeof (GNUNET_HashCode))) ||
844            (GNUNET_OK !=
845             GNUNET_BIO_write_string (wh,
846                                      pos->filename)) )
847         break;
848       pos = pos->next;
849     }
850   if (GNUNET_OK != 
851       GNUNET_BIO_write_close (wh))
852     {
853       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
854                   _("Error writing `%s'.\n"),
855                   fn);
856       GNUNET_free (fn);
857       return;
858     }
859   GNUNET_free (fn);
860 }
861
862
863 /**
864  * Read index information from disk.
865  */
866 static void
867 read_index_list ()
868 {
869   struct GNUNET_BIO_ReadHandle *rh;
870   char *fn;
871   struct IndexInfo *pos;  
872   char *fname;
873   GNUNET_HashCode hc;
874   size_t slen;
875   char *emsg;
876
877   if (GNUNET_OK !=
878       GNUNET_CONFIGURATION_get_value_filename (cfg,
879                                                "FS",
880                                                "INDEXDB",
881                                                &fn))
882     {
883       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
884                   _("Configuration option `%s' in section `%s' missing.\n"),
885                   "INDEXDB",
886                   "FS");
887       return;
888     }
889   if (GNUNET_NO == GNUNET_DISK_file_test (fn))
890     {
891       /* no index info  yet */
892       GNUNET_free (fn);
893       return;
894     }
895   rh = GNUNET_BIO_read_open (fn);
896   if (NULL == rh)
897     {
898       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
899                   _("Could not open `%s'.\n"),
900                   fn);
901       GNUNET_free (fn);
902       return;
903     }
904
905   while ( (GNUNET_OK ==
906            GNUNET_BIO_read (rh,
907                             "Hash of indexed file",
908                             &hc,
909                             sizeof (GNUNET_HashCode))) &&
910           (GNUNET_OK ==
911            GNUNET_BIO_read_string (rh, 
912                                    "Name of indexed file",
913                                    &fname,
914                                    1024 * 16)) )
915     {
916       slen = strlen (fname) + 1;
917       pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
918       pos->file_id = hc;
919       pos->filename = (const char *) &pos[1];
920       memcpy (&pos[1], fname, slen);
921       if (GNUNET_SYSERR ==
922           GNUNET_CONTAINER_multihashmap_put (ifm,
923                                              &hc,
924                                              (void*) pos->filename,
925                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
926         {
927           GNUNET_free (pos);
928         }
929       else
930         {
931           pos->next = indexed_files;
932           indexed_files = pos;
933         }
934       GNUNET_free (fname);
935     }
936   if (GNUNET_OK != 
937       GNUNET_BIO_read_close (rh, &emsg))
938     GNUNET_free (emsg);
939   GNUNET_free (fn);
940 }
941
942
943 /**
944  * We've validated the hash of the file we're about to
945  * index.  Signal success to the client and update
946  * our internal data structures.
947  *
948  * @param ii the index info entry for the request
949  */
950 static void
951 signal_index_ok (struct IndexInfo *ii)
952 {
953   if (GNUNET_SYSERR ==
954       GNUNET_CONTAINER_multihashmap_put (ifm,
955                                          &ii->file_id,
956                                          (void*) ii->filename,
957                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
958     {
959       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
960                   _("Index request received for file `%s' is indexed as `%s'.  Permitting anyway.\n"),
961                   ii->filename,
962                   (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
963                                                                    &ii->file_id));
964       GNUNET_SERVER_transmit_context_append (ii->tc,
965                                              NULL, 0,
966                                              GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
967       GNUNET_SERVER_transmit_context_run (ii->tc,
968                                           GNUNET_TIME_UNIT_MINUTES);
969       GNUNET_free (ii);
970       return;
971     }
972   ii->next = indexed_files;
973   indexed_files = ii;
974   write_index_list ();
975   GNUNET_SERVER_transmit_context_append (ii->tc,
976                                          NULL, 0,
977                                          GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
978   GNUNET_SERVER_transmit_context_run (ii->tc,
979                                       GNUNET_TIME_UNIT_MINUTES);
980   ii->tc = NULL;
981 }
982
983
984 /**
985  * Function called once the hash computation over an
986  * indexed file has completed.
987  *
988  * @param cls closure, our publishing context
989  * @param res resulting hash, NULL on error
990  */
991 static void 
992 hash_for_index_val (void *cls,
993                     const GNUNET_HashCode *
994                     res)
995 {
996   struct IndexInfo *ii = cls;
997   
998   if ( (res == NULL) ||
999        (0 != memcmp (res,
1000                      &ii->file_id,
1001                      sizeof(GNUNET_HashCode))) )
1002     {
1003       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1004                   _("Hash mismatch trying to index file `%s' which has hash `%s'\n"),
1005                   ii->filename,
1006                   GNUNET_h2s (res));
1007 #if DEBUG_FS
1008       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1009                   "Wanted `%s'\n",
1010                   GNUNET_h2s (&ii->file_id));
1011 #endif
1012       GNUNET_SERVER_transmit_context_append (ii->tc,
1013                                              NULL, 0,
1014                                              GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
1015       GNUNET_SERVER_transmit_context_run (ii->tc,
1016                                           GNUNET_TIME_UNIT_MINUTES);
1017       GNUNET_free (ii);
1018       return;
1019     }
1020   signal_index_ok (ii);
1021 }
1022
1023
1024 /**
1025  * Handle INDEX_START-message.
1026  *
1027  * @param cls closure
1028  * @param client identification of the client
1029  * @param message the actual message
1030  */
1031 static void
1032 handle_index_start (void *cls,
1033                     struct GNUNET_SERVER_Client *client,
1034                     const struct GNUNET_MessageHeader *message)
1035 {
1036   const struct IndexStartMessage *ism;
1037   const char *fn;
1038   uint16_t msize;
1039   struct IndexInfo *ii;
1040   size_t slen;
1041   uint32_t dev;
1042   uint64_t ino;
1043   uint32_t mydev;
1044   uint64_t myino;
1045
1046   msize = ntohs(message->size);
1047   if ( (msize <= sizeof (struct IndexStartMessage)) ||
1048        ( ((const char *)message)[msize-1] != '\0') )
1049     {
1050       GNUNET_break (0);
1051       GNUNET_SERVER_receive_done (client,
1052                                   GNUNET_SYSERR);
1053       return;
1054     }
1055   ism = (const struct IndexStartMessage*) message;
1056   fn = (const char*) &ism[1];
1057   dev = ntohl (ism->device);
1058   ino = GNUNET_ntohll (ism->inode);
1059   ism = (const struct IndexStartMessage*) message;
1060   slen = strlen (fn) + 1;
1061   ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
1062   ii->filename = (const char*) &ii[1];
1063   memcpy (&ii[1], fn, slen);
1064   ii->file_id = ism->file_id;  
1065   ii->tc = GNUNET_SERVER_transmit_context_create (client);
1066   if ( ( (dev != 0) ||
1067          (ino != 0) ) &&
1068        (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
1069                                                        &mydev,
1070                                                        &myino)) &&
1071        ( (dev == mydev) &&
1072          (ino == myino) ) )
1073     {      
1074       /* fast validation OK! */
1075       signal_index_ok (ii);
1076       return;
1077     }
1078 #if DEBUG_FS
1079   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080               "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
1081               (unsigned long long) ino,
1082               (unsigned long long) myino,
1083               (unsigned int) dev,
1084               (unsigned int) mydev);
1085 #endif
1086   /* slow validation, need to hash full file (again) */
1087   GNUNET_CRYPTO_hash_file (sched,
1088                            GNUNET_SCHEDULER_PRIORITY_IDLE,
1089                            fn,
1090                            HASHING_BLOCKSIZE,
1091                            &hash_for_index_val,
1092                            ii);
1093 }
1094
1095
1096 /**
1097  * Handle INDEX_LIST_GET-message.
1098  *
1099  * @param cls closure
1100  * @param client identification of the client
1101  * @param message the actual message
1102  */
1103 static void
1104 handle_index_list_get (void *cls,
1105                        struct GNUNET_SERVER_Client *client,
1106                        const struct GNUNET_MessageHeader *message)
1107 {
1108   struct GNUNET_SERVER_TransmitContext *tc;
1109   struct IndexInfoMessage *iim;
1110   char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1111   size_t slen;
1112   const char *fn;
1113   struct GNUNET_MessageHeader *msg;
1114   struct IndexInfo *pos;
1115
1116   tc = GNUNET_SERVER_transmit_context_create (client);
1117   iim = (struct IndexInfoMessage*) buf;
1118   msg = &iim->header;
1119   pos = indexed_files;
1120   while (NULL != pos)
1121     {
1122       iim->reserved = 0;
1123       iim->file_id = pos->file_id;
1124       fn = pos->filename;
1125       slen = strlen (fn) + 1;
1126       if (slen + sizeof (struct IndexInfoMessage) > 
1127           GNUNET_SERVER_MAX_MESSAGE_SIZE)
1128         {
1129           GNUNET_break (0);
1130           break;
1131         }
1132       memcpy (&iim[1], fn, slen);
1133       GNUNET_SERVER_transmit_context_append
1134         (tc,
1135          &msg[1],
1136          sizeof (struct IndexInfoMessage) 
1137          - sizeof (struct GNUNET_MessageHeader) + slen,
1138          GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1139       pos = pos->next;
1140     }
1141   GNUNET_SERVER_transmit_context_append (tc,
1142                                          NULL, 0,
1143                                          GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1144   GNUNET_SERVER_transmit_context_run (tc,
1145                                       GNUNET_TIME_UNIT_MINUTES);
1146 }
1147
1148
1149 /**
1150  * Handle UNINDEX-message.
1151  *
1152  * @param cls closure
1153  * @param client identification of the client
1154  * @param message the actual message
1155  */
1156 static void
1157 handle_unindex (void *cls,
1158                 struct GNUNET_SERVER_Client *client,
1159                 const struct GNUNET_MessageHeader *message)
1160 {
1161   const struct UnindexMessage *um;
1162   struct IndexInfo *pos;
1163   struct IndexInfo *prev;
1164   struct IndexInfo *next;
1165   struct GNUNET_SERVER_TransmitContext *tc;
1166   int found;
1167   
1168   um = (const struct UnindexMessage*) message;
1169   found = GNUNET_NO;
1170   prev = NULL;
1171   pos = indexed_files;
1172   while (NULL != pos)
1173     {
1174       next = pos->next;
1175       if (0 == memcmp (&pos->file_id,
1176                        &um->file_id,
1177                        sizeof (GNUNET_HashCode)))
1178         {
1179           if (prev == NULL)
1180             indexed_files = next;
1181           else
1182             prev->next = next;
1183           GNUNET_free (pos);
1184           found = GNUNET_YES;
1185         }
1186       else
1187         {
1188           prev = pos;
1189         }
1190       pos = next;
1191     }
1192 #if DEBUG_FS
1193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1194               "Client requested unindexing of file `%s': %s\n",
1195               GNUNET_h2s (&um->file_id),
1196               found ? "found" : "not found");
1197 #endif
1198   if (GNUNET_YES == found)    
1199     write_index_list ();
1200   tc = GNUNET_SERVER_transmit_context_create (client);
1201   GNUNET_SERVER_transmit_context_append (tc,
1202                                          NULL, 0,
1203                                          GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1204   GNUNET_SERVER_transmit_context_run (tc,
1205                                       GNUNET_TIME_UNIT_MINUTES);
1206 }
1207
1208
1209 /**
1210  * Run the next DS request in our
1211  * queue, we're done with the current one.
1212  */
1213 static void
1214 next_ds_request ()
1215 {
1216   struct DatastoreRequestQueue *e;
1217   
1218   while (NULL != (e = drq_head))
1219     {
1220       if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1221         break;
1222       if (e->task != GNUNET_SCHEDULER_NO_TASK)
1223         GNUNET_SCHEDULER_cancel (sched, e->task);
1224       GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1225       e->req (e->req_cls, GNUNET_NO);
1226       GNUNET_free (e);  
1227     }
1228   if (e == NULL)
1229     return;
1230   if (e->task != GNUNET_SCHEDULER_NO_TASK)
1231     GNUNET_SCHEDULER_cancel (sched, e->task);
1232   e->task = GNUNET_SCHEDULER_NO_TASK;
1233   e->req (e->req_cls, GNUNET_YES);
1234   GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1235   GNUNET_free (e);  
1236 }
1237
1238
1239 /**
1240  * A datastore request had to be timed out. 
1241  *
1242  * @param cls closure (of type "struct DatastoreRequestQueue*")
1243  * @param tc task context, unused
1244  */
1245 static void
1246 timeout_ds_request (void *cls,
1247                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1248 {
1249   struct DatastoreRequestQueue *e = cls;
1250
1251   e->task = GNUNET_SCHEDULER_NO_TASK;
1252   GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1253   e->req (e->req_cls, GNUNET_NO);
1254   GNUNET_free (e);  
1255 }
1256
1257
1258 /**
1259  * Queue a request for the datastore.
1260  *
1261  * @param deadline by when the request should run
1262  * @param fun function to call once the request can be run
1263  * @param fun_cls closure for fun
1264  */
1265 static struct DatastoreRequestQueue *
1266 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1267                   RequestFunction fun,
1268                   void *fun_cls)
1269 {
1270   struct DatastoreRequestQueue *e;
1271   struct DatastoreRequestQueue *bef;
1272
1273   if (drq_head == NULL)
1274     {
1275       /* no other requests pending, run immediately */
1276       fun (fun_cls, GNUNET_OK);
1277       return NULL;
1278     }
1279   e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1280   e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1281   e->req = fun;
1282   e->req_cls = fun_cls;
1283   if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1284     {
1285       /* local request, highest prio, put at head of queue
1286          regardless of deadline */
1287       bef = NULL;
1288     }
1289   else
1290     {
1291       bef = drq_tail;
1292       while ( (NULL != bef) &&
1293               (e->timeout.value < bef->timeout.value) )
1294         bef = bef->prev;
1295     }
1296   GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1297   if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1298     return e;
1299   e->task = GNUNET_SCHEDULER_add_delayed (sched,
1300                                           deadline,
1301                                           &timeout_ds_request,
1302                                           e);
1303   return e;                                    
1304 }
1305
1306
1307 /**
1308  * Free the state associated with a local get context.
1309  *
1310  * @param lgc the lgc to free
1311  */
1312 static void
1313 local_get_context_free (struct LocalGetContext *lgc) 
1314 {
1315   GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1316   GNUNET_SERVER_client_drop (lgc->client); 
1317   GNUNET_free_non_null (lgc->results);
1318   if (lgc->results_bf != NULL)
1319     GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1320   if (lgc->req != NULL)
1321     {
1322       if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1323         GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1324       GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1325       GNUNET_free (lgc->req);
1326     }
1327   GNUNET_free (lgc);
1328 }
1329
1330
1331 /**
1332  * We're able to transmit the next (local) result to the client.
1333  * Do it and ask the datastore for more.  Or, on error, tell
1334  * the datastore to stop giving us more.
1335  *
1336  * @param cls our closure (struct LocalGetContext)
1337  * @param max maximum number of bytes we can transmit
1338  * @param buf where to copy our message
1339  * @return number of bytes copied to buf
1340  */
1341 static size_t
1342 transmit_local_result (void *cls,
1343                        size_t max,
1344                        void *buf)
1345 {
1346   struct LocalGetContext *lgc = cls;  
1347   uint16_t msize;
1348
1349   if (NULL == buf)
1350     {
1351 #if DEBUG_FS
1352       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353                   "Failed to transmit result to local client, aborting datastore iteration.\n");
1354 #endif
1355       /* error, abort! */
1356       GNUNET_free (lgc->result);
1357       lgc->result = NULL;
1358       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1359       return 0;
1360     }
1361   msize = ntohs (lgc->result->header.size);
1362 #if DEBUG_FS
1363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364               "Transmitting %u bytes of result to local client.\n",
1365               msize);
1366 #endif
1367   GNUNET_assert (max >= msize);
1368   memcpy (buf, lgc->result, msize);
1369   GNUNET_free (lgc->result);
1370   lgc->result = NULL;
1371   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1372   return msize;
1373 }
1374
1375
1376 /**
1377  * Continuation called from datastore's remove
1378  * function.
1379  *
1380  * @param cls unused
1381  * @param success did the deletion work?
1382  * @param msg error message
1383  */
1384 static void
1385 remove_cont (void *cls,
1386              int success,
1387              const char *msg)
1388 {
1389   if (GNUNET_OK != success)
1390     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1391                 _("Failed to delete bogus block: %s\n"),
1392                 msg);
1393   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1394 }
1395
1396
1397 /**
1398  * Mingle hash with the mingle_number to
1399  * produce different bits.
1400  */
1401 static void
1402 mingle_hash (const GNUNET_HashCode * in,
1403              int32_t mingle_number, 
1404              GNUNET_HashCode * hc)
1405 {
1406   GNUNET_HashCode m;
1407
1408   GNUNET_CRYPTO_hash (&mingle_number, 
1409                       sizeof (int32_t), 
1410                       &m);
1411   GNUNET_CRYPTO_hash_xor (&m, in, hc);
1412 }
1413
1414
1415 /**
1416  * We've received an on-demand encoded block
1417  * from the datastore.  Attempt to do on-demand
1418  * encoding and (if successful), call the 
1419  * continuation with the resulting block.  On
1420  * error, clean up and ask the datastore for
1421  * more results.
1422  *
1423  * @param key key for the content
1424  * @param size number of bytes in data
1425  * @param data content stored
1426  * @param type type of the content
1427  * @param priority priority of the content
1428  * @param anonymity anonymity-level for the content
1429  * @param expiration expiration time for the content
1430  * @param uid unique identifier for the datum;
1431  *        maybe 0 if no unique identifier is available
1432  * @param cont function to call with the actual block
1433  * @param cont_cls closure for cont
1434  */
1435 static void
1436 handle_on_demand_block (const GNUNET_HashCode * key,
1437                         uint32_t size,
1438                         const void *data,
1439                         uint32_t type,
1440                         uint32_t priority,
1441                         uint32_t anonymity,
1442                         struct GNUNET_TIME_Absolute
1443                         expiration, uint64_t uid,
1444                         GNUNET_DATASTORE_Iterator cont,
1445                         void *cont_cls)
1446 {
1447   const struct OnDemandBlock *odb;
1448   GNUNET_HashCode nkey;
1449   struct GNUNET_CRYPTO_AesSessionKey skey;
1450   struct GNUNET_CRYPTO_AesInitializationVector iv;
1451   GNUNET_HashCode query;
1452   ssize_t nsize;
1453   char ndata[DBLOCK_SIZE];
1454   char edata[DBLOCK_SIZE];
1455   const char *fn;
1456   struct GNUNET_DISK_FileHandle *fh;
1457   uint64_t off;
1458
1459   if (size != sizeof (struct OnDemandBlock))
1460     {
1461       GNUNET_break (0);
1462       GNUNET_DATASTORE_remove (dsh, 
1463                                key,
1464                                size,
1465                                data,
1466                                &remove_cont,
1467                                NULL,
1468                                GNUNET_TIME_UNIT_FOREVER_REL);     
1469       return;
1470     }
1471   odb = (const struct OnDemandBlock*) data;
1472   off = GNUNET_ntohll (odb->offset);
1473   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1474                                                         &odb->file_id);
1475   fh = NULL;
1476   if ( (NULL == fn) ||
1477        (NULL == (fh = GNUNET_DISK_file_open (fn, 
1478                                              GNUNET_DISK_OPEN_READ,
1479                                              GNUNET_DISK_PERM_NONE))) ||
1480        (off !=
1481         GNUNET_DISK_file_seek (fh,
1482                                off,
1483                                GNUNET_DISK_SEEK_SET)) ||
1484        (-1 ==
1485         (nsize = GNUNET_DISK_file_read (fh,
1486                                         ndata,
1487                                         sizeof (ndata)))) )
1488     {
1489       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1490                   _("Could not access indexed file `%s' at offset %llu: %s\n"),
1491                   GNUNET_h2s (&odb->file_id),
1492                   (unsigned long long) off,
1493                   STRERROR (errno));
1494       if (fh != NULL)
1495         GNUNET_DISK_file_close (fh);
1496       /* FIXME: if this happens often, we need
1497          to remove the OnDemand block from the DS! */
1498       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);        
1499       return;
1500     }
1501   GNUNET_DISK_file_close (fh);
1502   GNUNET_CRYPTO_hash (ndata,
1503                       nsize,
1504                       &nkey);
1505   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1506   GNUNET_CRYPTO_aes_encrypt (ndata,
1507                              nsize,
1508                              &skey,
1509                              &iv,
1510                              edata);
1511   GNUNET_CRYPTO_hash (edata,
1512                       nsize,
1513                       &query);
1514   if (0 != memcmp (&query, 
1515                    key,
1516                    sizeof (GNUNET_HashCode)))
1517     {
1518       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1519                   _("Indexed file `%s' changed at offset %llu\n"),
1520                   fn,
1521                   (unsigned long long) off);
1522       /* FIXME: if this happens often, we need
1523          to remove the OnDemand block from the DS! */
1524       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1525       return;
1526     }
1527   cont (cont_cls,
1528         key,
1529         nsize,
1530         edata,
1531         GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1532         priority,
1533         anonymity,
1534         expiration,
1535         uid);
1536 }
1537
1538
1539 /**
1540  * How many bytes should a bloomfilter be if we have already seen
1541  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
1542  * of bits set per entry.  Furthermore, we should not re-size the
1543  * filter too often (to keep it cheap).
1544  *
1545  * Since other peers will also add entries but not resize the filter,
1546  * we should generally pick a slightly larger size than what the
1547  * strict math would suggest.
1548  *
1549  * @return must be a power of two and smaller or equal to 2^15.
1550  */
1551 static size_t
1552 compute_bloomfilter_size (unsigned int entry_count)
1553 {
1554   size_t size;
1555   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1556   uint16_t max = 1 << 15;
1557
1558   if (entry_count > max)
1559     return max;
1560   size = 8;
1561   while ((size < max) && (size < ideal))
1562     size *= 2;
1563   if (size > max)
1564     return max;
1565   return size;
1566 }
1567
1568
1569 /**
1570  * Recalculate our bloom filter for filtering replies.
1571  *
1572  * @param count number of entries we are filtering right now
1573  * @param mingle set to our new mingling value
1574  * @param bf_size set to the size of the bloomfilter
1575  * @param entries the entries to filter
1576  * @return updated bloomfilter, NULL for none
1577  */
1578 static struct GNUNET_CONTAINER_BloomFilter *
1579 refresh_bloomfilter (unsigned int count,
1580                      int32_t * mingle,
1581                      size_t *bf_size,
1582                      const GNUNET_HashCode *entries)
1583 {
1584   struct GNUNET_CONTAINER_BloomFilter *bf;
1585   size_t nsize;
1586   unsigned int i;
1587   GNUNET_HashCode mhash;
1588
1589   if (0 == count)
1590     return NULL;
1591   nsize = compute_bloomfilter_size (count);
1592   *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1593   *bf_size = nsize;
1594   bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
1595                                           nsize,
1596                                           BLOOMFILTER_K);
1597   for (i=0;i<count;i++)
1598     {
1599       mingle_hash (&entries[i], *mingle, &mhash);
1600       GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1601     }
1602   return bf;
1603 }
1604
1605
1606 /**
1607  * Closure used for "target_peer_select_cb".
1608  */
1609 struct PeerSelectionContext 
1610 {
1611   /**
1612    * The request for which we are selecting
1613    * peers.
1614    */
1615   struct PendingRequest *pr;
1616
1617   /**
1618    * Current "prime" target.
1619    */
1620   struct GNUNET_PeerIdentity target;
1621
1622   /**
1623    * How much do we like this target?
1624    */
1625   double target_score;
1626
1627 };
1628
1629
1630 /**
1631  * Function called for each connected peer to determine
1632  * which one(s) would make good targets for forwarding.
1633  *
1634  * @param cls closure (struct PeerSelectionContext)
1635  * @param key current key code (peer identity)
1636  * @param value value in the hash map (struct ConnectedPeer)
1637  * @return GNUNET_YES if we should continue to
1638  *         iterate,
1639  *         GNUNET_NO if not.
1640  */
1641 static int
1642 target_peer_select_cb (void *cls,
1643                        const GNUNET_HashCode * key,
1644                        void *value)
1645 {
1646   struct PeerSelectionContext *psc = cls;
1647   struct ConnectedPeer *cp = value;
1648   struct PendingRequest *pr = psc->pr;
1649   double score;
1650   unsigned int i;
1651
1652   /* 1) check if we have already (recently) forwarded to this peer */
1653   for (i=0;i<pr->used_pids_off;i++)
1654     if (pr->used_pids[i] == cp->pid)
1655       return GNUNET_YES; /* skip */
1656   // 2) calculate how much we'd like to forward to this peer
1657   score = 0; // FIXME!
1658   
1659   /* store best-fit in closure */
1660   if (score > psc->target_score)
1661     {
1662       psc->target_score = score;
1663       psc->target.hashPubKey = *key; 
1664     }
1665   return GNUNET_YES;
1666 }
1667
1668
1669 /**
1670  * We use a random delay to make the timing of requests
1671  * less predictable.  This function returns such a random
1672  * delay.
1673  *
1674  * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1675  */
1676 static struct GNUNET_TIME_Relative
1677 get_processing_delay ()
1678 {
1679   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1680                                         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1681                                                                   TTL_DECREMENT));
1682 }
1683
1684
1685 /**
1686  * Task that is run for each request with the
1687  * goal of forwarding the associated query to
1688  * other peers.  The task should re-schedule
1689  * itself to be re-run once the TTL has expired.
1690  * (or at a later time if more peers should
1691  * be queried earlier).
1692  *
1693  * @param cls the requests "struct PendingRequest*"
1694  * @param tc task context (unused)
1695  */
1696 static void
1697 forward_request_task (void *cls,
1698                       const struct GNUNET_SCHEDULER_TaskContext *tc);
1699
1700
1701 /**
1702  * We've selected a peer for forwarding of a query.
1703  * Construct the message and then re-schedule the
1704  * task to forward again to (other) peers.
1705  *
1706  * @param cls closure
1707  * @param size number of bytes available in buf
1708  * @param buf where the callee should write the message
1709  * @return number of bytes written to buf
1710  */
1711 static size_t
1712 transmit_request_cb (void *cls,
1713                      size_t size, 
1714                      void *buf)
1715 {
1716   struct PendingRequest *pr = cls;
1717   struct GetMessage *gm;
1718   GNUNET_HashCode *ext;
1719   char *bfdata;
1720   size_t msize;
1721   unsigned int k;
1722
1723   pr->cth = NULL;
1724   /* (1) check for timeout */
1725   if (NULL == buf)
1726     {
1727       /* timeout, try another peer immediately again */
1728       pr->task = GNUNET_SCHEDULER_add_with_priority (sched,
1729                                                      GNUNET_SCHEDULER_PRIORITY_IDLE,
1730                                                      &forward_request_task,
1731                                                      pr);
1732       return 0;
1733     }
1734   /* (2) build query message */
1735   k = 0; // FIXME: count hash codes!
1736   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1737   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1738   gm = (struct GetMessage*) buf;
1739   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1740   gm->header.size = htons (msize);
1741   gm->type = htonl (pr->type);
1742   pr->remaining_priority /= 2;
1743   gm->priority = htonl (pr->remaining_priority);
1744   gm->ttl = htonl (pr->ttl);
1745   gm->filter_mutator = htonl(pr->mingle);
1746   gm->hash_bitmap = htonl (42);
1747   gm->query = pr->query;
1748   ext = (GNUNET_HashCode*) &gm[1];
1749   // FIXME: setup "ext[0]..[k-1]"
1750   bfdata = (char *) &ext[k];
1751   if (pr->bf != NULL)
1752     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1753                                                bfdata,
1754                                                pr->bf_size);
1755   
1756   /* (3) schedule job to do it again (or another peer, etc.) */
1757   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1758                                            get_processing_delay (), // FIXME!
1759                                            &forward_request_task,
1760                                            pr);
1761
1762   return msize;
1763 }
1764
1765
1766 /**
1767  * Function called after we've tried to reserve
1768  * a certain amount of bandwidth for a reply.
1769  * Check if we succeeded and if so send our query.
1770  *
1771  * @param cls the requests "struct PendingRequest*"
1772  * @param peer identifies the peer
1773  * @param latency current latency estimate, "FOREVER" if we have been
1774  *                disconnected
1775  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1776  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1777  * @param amount set to the amount that was actually reserved or unreserved
1778  * @param preference current traffic preference for the given peer
1779  */
1780 static void
1781 target_reservation_cb (void *cls,
1782                        const struct
1783                        GNUNET_PeerIdentity * peer,
1784                        unsigned int bpm_in,
1785                        unsigned int bpm_out,
1786                        struct GNUNET_TIME_Relative
1787                        latency, int amount,
1788                        unsigned long long preference)
1789 {
1790   struct PendingRequest *pr = cls;
1791   uint32_t priority;
1792   uint16_t size;
1793   struct GNUNET_TIME_Relative maxdelay;
1794
1795   pr->irc = NULL;
1796   GNUNET_assert (peer != NULL);
1797   if ( (amount != DBLOCK_SIZE) ||
1798        (pr->cth != NULL) )
1799     {
1800       /* try again later; FIXME: we may need to un-reserve "amount"? */
1801       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1802                                                get_processing_delay (), // FIXME: longer?
1803                                                &forward_request_task,
1804                                                pr);
1805       return;
1806     }
1807   // (2) transmit, update ttl/priority
1808   // FIXME: calculate priority, maxdelay, size properly!
1809   priority = 0;
1810   size = 60000;
1811   maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1812   pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1813                                                priority,
1814                                                maxdelay,
1815                                                peer,
1816                                                size,
1817                                                &transmit_request_cb,
1818                                                pr);
1819   if (pr->cth == NULL)
1820     {
1821       /* try again later */
1822       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1823                                                get_processing_delay (), // FIXME: longer?
1824                                                &forward_request_task,
1825                                                pr);
1826     }
1827 }
1828
1829
1830 /**
1831  * Task that is run for each request with the
1832  * goal of forwarding the associated query to
1833  * other peers.  The task should re-schedule
1834  * itself to be re-run once the TTL has expired.
1835  * (or at a later time if more peers should
1836  * be queried earlier).
1837  *
1838  * @param cls the requests "struct PendingRequest*"
1839  * @param tc task context (unused)
1840  */
1841 static void
1842 forward_request_task (void *cls,
1843                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1844 {
1845   struct PendingRequest *pr = cls;
1846   struct PeerSelectionContext psc;
1847
1848   pr->task = GNUNET_SCHEDULER_NO_TASK;
1849   if (pr->cth != NULL) 
1850     {
1851       /* we're busy transmitting a result, wait a bit */
1852       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1853                                                get_processing_delay (), 
1854                                                &forward_request_task,
1855                                                pr);
1856       return;
1857     }
1858   /* (1) select target */
1859   psc.pr = pr;
1860   psc.target_score = DBL_MIN;
1861   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1862                                          &target_peer_select_cb,
1863                                          &psc);
1864   if (psc.target_score == DBL_MIN)
1865     {
1866       /* no possible target found, wait some time */
1867       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1868                                                get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1869                                                &forward_request_task,
1870                                                pr);
1871       return;
1872     }
1873   /* (2) reserve reply bandwidth */
1874   GNUNET_assert (NULL == pr->irc);
1875   pr->irc = GNUNET_CORE_peer_get_info (sched, cfg,
1876                                        &psc.target,
1877                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
1878                                        -1,
1879                                        DBLOCK_SIZE, // FIXME: make dependent on type?
1880                                        0,
1881                                        &target_reservation_cb,
1882                                        pr);
1883 }
1884
1885
1886 /**
1887  * We're processing (local) results for a search request
1888  * from a (local) client.  Pass applicable results to the
1889  * client and if we are done either clean up (operation
1890  * complete) or switch to P2P search (more results possible).
1891  *
1892  * @param cls our closure (struct LocalGetContext)
1893  * @param key key for the content
1894  * @param size number of bytes in data
1895  * @param data content stored
1896  * @param type type of the content
1897  * @param priority priority of the content
1898  * @param anonymity anonymity-level for the content
1899  * @param expiration expiration time for the content
1900  * @param uid unique identifier for the datum;
1901  *        maybe 0 if no unique identifier is available
1902  */
1903 static void
1904 process_local_get_result (void *cls,
1905                           const GNUNET_HashCode * key,
1906                           uint32_t size,
1907                           const void *data,
1908                           uint32_t type,
1909                           uint32_t priority,
1910                           uint32_t anonymity,
1911                           struct GNUNET_TIME_Absolute
1912                           expiration, 
1913                           uint64_t uid)
1914 {
1915   struct LocalGetContext *lgc = cls;
1916   struct PendingRequest *pr;
1917   struct ClientRequestList *crl;
1918   struct ClientList *cl;
1919   size_t msize;
1920   unsigned int i;
1921
1922   if (key == NULL)
1923     {
1924 #if DEBUG_FS
1925       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926                   "Received last result for `%s' from local datastore, deciding what to do next.\n",
1927                   GNUNET_h2s (&lgc->query));
1928 #endif
1929       /* no further results from datastore; continue
1930          processing further requests from the client and
1931          allow the next task to use the datastore; also,
1932          switch to P2P requests or clean up our state. */
1933       next_ds_request ();
1934       GNUNET_SERVER_receive_done (lgc->client,
1935                                   GNUNET_OK);
1936       if ( (lgc->results_used == 0) ||
1937            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1938            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1939            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1940         {
1941 #if DEBUG_FS
1942           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943                       "Forwarding query for `%s' to network.\n",
1944                       GNUNET_h2s (&lgc->query));
1945 #endif
1946           cl = clients;
1947           while ( (NULL != cl) &&
1948                   (cl->client != lgc->client) )
1949             cl = cl->next;
1950           if (cl == NULL)
1951             {
1952               cl = GNUNET_malloc (sizeof (struct ClientList));
1953               cl->client = lgc->client;
1954               cl->next = clients;
1955               clients = cl;
1956             }
1957           crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1958           crl->cl = cl;
1959           GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1960           pr = GNUNET_malloc (sizeof (struct PendingRequest));
1961           pr->client = lgc->client;
1962           GNUNET_SERVER_client_keep (pr->client);
1963           pr->crl_entry = crl;
1964           crl->req = pr;
1965           if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1966             {
1967               pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1968               *pr->namespace = lgc->namespace;
1969             }
1970           pr->replies_seen = lgc->results;
1971           lgc->results = NULL;
1972           pr->start_time = GNUNET_TIME_absolute_get ();
1973           pr->query = lgc->query;
1974           pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1975           pr->replies_seen_off = lgc->results_used;
1976           pr->replies_seen_size = lgc->results_size;
1977           lgc->results_size = 0;
1978           pr->type = lgc->type;
1979           pr->anonymity_level = lgc->anonymity_level;
1980           pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1981                                         &pr->mingle,
1982                                         &pr->bf_size,
1983                                         pr->replies_seen);
1984           GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1985                                              &pr->query,
1986                                              pr,
1987                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1988           pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1989                                                    get_processing_delay (),
1990                                                    &forward_request_task,
1991                                                    pr);
1992           local_get_context_free (lgc);
1993           return;
1994         }
1995       /* got all possible results, clean up! */
1996 #if DEBUG_FS
1997       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998                   "Found all possible results for query for `%s', done!\n",
1999                   GNUNET_h2s (&lgc->query));
2000 #endif
2001       local_get_context_free (lgc);
2002       return;
2003     }
2004   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2005     {
2006 #if DEBUG_FS
2007       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008                   "Received on-demand block for `%s' from local datastore, fetching data.\n",
2009                   GNUNET_h2s (&lgc->query));
2010 #endif
2011       handle_on_demand_block (key, size, data, type, priority, 
2012                               anonymity, expiration, uid,
2013                               &process_local_get_result,
2014                               lgc);
2015       return;
2016     }
2017   if ( (type != lgc->type) &&
2018        (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2019     {
2020       /* this should be virtually impossible to reach (DBLOCK 
2021          query hash being identical to KBLOCK/SBLOCK query hash);
2022          nevertheless, if it happens, the correct thing is to
2023          simply skip the result. */
2024 #if DEBUG_FS
2025       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2026                   "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2027                   type,
2028                   lgc->type,
2029                   GNUNET_h2s (&lgc->query));
2030 #endif
2031       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);        
2032       return;
2033     }
2034   /* check if this is a result we've alredy
2035      received */
2036   for (i=0;i<lgc->results_used;i++)
2037     if (0 == memcmp (key,
2038                      &lgc->results[i],
2039                      sizeof (GNUNET_HashCode)))
2040       {
2041 #if DEBUG_FS
2042         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2043                     "Received duplicate result for `%s' from local datastore, ignoring.\n",
2044                     GNUNET_h2s (&lgc->query));
2045 #endif
2046         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2047         return; 
2048       }
2049   if (lgc->results_used == lgc->results_size)
2050     GNUNET_array_grow (lgc->results,
2051                        lgc->results_size,
2052                        lgc->results_size * 2 + 2);
2053   GNUNET_CRYPTO_hash (data, 
2054                       size, 
2055                       &lgc->results[lgc->results_used++]);    
2056   msize = size + sizeof (struct ContentMessage);
2057   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2058   lgc->result = GNUNET_malloc (msize);
2059   lgc->result->header.size = htons (msize);
2060   lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2061   lgc->result->type = htonl (type);
2062   lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2063   memcpy (&lgc->result[1],
2064           data,
2065           size);
2066 #if DEBUG_FS
2067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2068               "Received new result for `%s' from local datastore, passing to client.\n",
2069               GNUNET_h2s (&lgc->query));
2070 #endif
2071   GNUNET_SERVER_notify_transmit_ready (lgc->client,
2072                                        msize,
2073                                        GNUNET_TIME_UNIT_FOREVER_REL,
2074                                        &transmit_local_result,
2075                                        lgc);
2076 }
2077
2078
2079 /**
2080  * We're processing a search request from a local
2081  * client.  Now it is our turn to query the datastore.
2082  * 
2083  * @param cls our closure (struct LocalGetContext)
2084  * @param tc unused
2085  */
2086 static void
2087 transmit_local_get (void *cls,
2088                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2089 {
2090   struct LocalGetContext *lgc = cls;
2091   uint32_t type;
2092   
2093   type = lgc->type;
2094   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2095     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2096   GNUNET_DATASTORE_get (dsh,
2097                         &lgc->query,
2098                         type,
2099                         &process_local_get_result,
2100                         lgc,
2101                         GNUNET_TIME_UNIT_FOREVER_REL);
2102 }
2103
2104
2105 /**
2106  * We're processing a search request from a local
2107  * client.  Now it is our turn to query the datastore.
2108  * 
2109  * @param cls our closure (struct LocalGetContext)
2110  * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2111  */
2112 static void 
2113 transmit_local_get_ready (void *cls,
2114                           int ok)
2115 {
2116   struct LocalGetContext *lgc = cls;
2117
2118   GNUNET_assert (GNUNET_OK == ok);
2119   GNUNET_SCHEDULER_add_continuation (sched,
2120                                      &transmit_local_get,
2121                                      lgc,
2122                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2123 }
2124
2125
2126 /**
2127  * Handle START_SEARCH-message (search request from client).
2128  *
2129  * @param cls closure
2130  * @param client identification of the client
2131  * @param message the actual message
2132  */
2133 static void
2134 handle_start_search (void *cls,
2135                      struct GNUNET_SERVER_Client *client,
2136                      const struct GNUNET_MessageHeader *message)
2137 {
2138   const struct SearchMessage *sm;
2139   struct LocalGetContext *lgc;
2140   uint16_t msize;
2141   unsigned int sc;
2142   
2143   msize = ntohs (message->size);
2144   if ( (msize < sizeof (struct SearchMessage)) ||
2145        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2146     {
2147       GNUNET_break (0);
2148       GNUNET_SERVER_receive_done (client,
2149                                   GNUNET_SYSERR);
2150       return;
2151     }
2152   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2153   sm = (const struct SearchMessage*) message;
2154   GNUNET_SERVER_client_keep (client);
2155   lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2156   if  (sc > 0)
2157     {
2158       lgc->results_used = sc;
2159       GNUNET_array_grow (lgc->results,
2160                          lgc->results_size,
2161                          sc * 2);
2162       memcpy (lgc->results,
2163               &sm[1],
2164               sc * sizeof (GNUNET_HashCode));
2165     }
2166   lgc->client = client;
2167   lgc->type = ntohl (sm->type);
2168   lgc->anonymity_level = ntohl (sm->anonymity_level);
2169   switch (lgc->type)
2170     {
2171     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2172     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2173       lgc->target.hashPubKey = sm->target;
2174       break;
2175     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2176       lgc->namespace = sm->target;
2177       break;
2178     default:
2179       break;
2180     }
2181   lgc->query = sm->query;
2182   GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2183   lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2184                                &transmit_local_get_ready,
2185                                lgc);
2186 }
2187
2188
2189 /**
2190  * List of handlers for the messages understood by this
2191  * service.
2192  */
2193 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2194   {&handle_index_start, NULL, 
2195    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2196   {&handle_index_list_get, NULL, 
2197    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2198   {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
2199    sizeof (struct UnindexMessage) },
2200   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
2201    0 },
2202   {NULL, NULL, 0, 0}
2203 };
2204
2205
2206 /**
2207  * Clean up the memory used by the PendingRequest structure (except
2208  * for the client or peer list that the request may be part of).
2209  *
2210  * @param pr request to clean up
2211  */
2212 static void
2213 destroy_pending_request (struct PendingRequest *pr)
2214 {
2215   struct PendingReply *reply;
2216   struct ClientList *cl;
2217
2218   GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2219                                         &pr->query,
2220                                         pr);
2221   // FIXME: not sure how this can work (efficiently)
2222   // also, what does the return value mean?
2223   if (pr->irc != NULL)
2224     {
2225       GNUNET_CORE_peer_get_info_cancel (pr->irc);
2226       pr->irc = NULL;
2227     }
2228   if (pr->client == NULL)
2229     {
2230       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2231                                          pr->hnode);
2232     }
2233   else
2234     {
2235       cl = pr->crl_entry->cl;
2236       GNUNET_CONTAINER_DLL_remove (cl->head,
2237                                    cl->tail,
2238                                    pr->crl_entry);
2239     }
2240   if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2241     GNUNET_SCHEDULER_cancel (sched, pr->task);
2242   if (NULL != pr->cth)
2243     GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2244   if (NULL != pr->bf)
2245     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2246   if (NULL != pr->th)
2247     GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2248   while (NULL != (reply = pr->replies_pending))
2249     {
2250       pr->replies_pending = reply->next;
2251       GNUNET_free (reply);
2252     }
2253   GNUNET_PEER_change_rc (pr->source_pid, -1);
2254   GNUNET_PEER_change_rc (pr->target_pid, -1);
2255   GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2256   GNUNET_free_non_null (pr->used_pids);
2257   GNUNET_free_non_null (pr->replies_seen);
2258   GNUNET_free_non_null (pr->namespace);
2259   GNUNET_free (pr);
2260 }
2261
2262
2263 /**
2264  * A client disconnected.  Remove all of its pending queries.
2265  *
2266  * @param cls closure, NULL
2267  * @param client identification of the client
2268  */
2269 static void
2270 handle_client_disconnect (void *cls,
2271                           struct GNUNET_SERVER_Client
2272                           * client)
2273 {
2274   struct LocalGetContext *lgc;
2275   struct ClientList *cpos;
2276   struct ClientList *cprev;
2277   struct ClientRequestList *rl;
2278
2279   lgc = lgc_head;
2280   while ( (NULL != lgc) &&
2281           (lgc->client != client) )
2282     lgc = lgc->next;
2283   if (lgc != NULL)
2284     local_get_context_free (lgc);
2285   cprev = NULL;
2286   cpos = clients;
2287   while ( (NULL != cpos) &&
2288           (clients->client != client) )
2289     {
2290       cprev = cpos;
2291       cpos = cpos->next;
2292     }
2293   if (cpos != NULL)
2294     {
2295       if (cprev == NULL)
2296         clients = cpos->next;
2297       else
2298         cprev->next = cpos->next;
2299       while (NULL != (rl = cpos->head))
2300         {
2301           cpos->head = rl->next;
2302           destroy_pending_request (rl->req);
2303           GNUNET_free (rl);
2304         }
2305       GNUNET_free (cpos);
2306     }
2307 }
2308
2309
2310 /**
2311  * Iterator over entries in the "requests_by_query" map
2312  * that frees all the entries.
2313  *
2314  * @param cls closure, NULL
2315  * @param key current key code (the query, unused) 
2316  * @param value value in the hash map, of type "struct PendingRequest*"
2317  * @return GNUNET_YES (we should continue to  iterate)
2318  */
2319 static int 
2320 destroy_pending_request_cb (void *cls,
2321                             const GNUNET_HashCode * key,
2322                             void *value)
2323 {
2324   struct PendingRequest *pr = value;
2325
2326   destroy_pending_request (pr);
2327   return GNUNET_YES;
2328 }
2329
2330
2331 /**
2332  * Task run during shutdown.
2333  *
2334  * @param cls unused
2335  * @param tc unused
2336  */
2337 static void
2338 shutdown_task (void *cls,
2339                const struct GNUNET_SCHEDULER_TaskContext *tc)
2340 {
2341   struct IndexInfo *pos;  
2342
2343   if (NULL != core)
2344     {
2345       GNUNET_CORE_disconnect (core);
2346       core = NULL;
2347     }
2348   if (NULL != dsh)
2349     {
2350       GNUNET_DATASTORE_disconnect (dsh,
2351                                    GNUNET_NO);
2352       dsh = NULL;
2353     }
2354   GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2355                                          &destroy_pending_request_cb,
2356                                          NULL);
2357   while (clients != NULL)
2358     handle_client_disconnect (NULL,
2359                               clients->client);
2360   GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2361   requests_by_query = NULL;
2362   GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2363   requests_by_peer = NULL;
2364   GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2365   requests_by_expiration = NULL;
2366   // FIXME: iterate over entries and free individually?
2367   // (or do we get disconnect notifications?)
2368   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2369   connected_peers = NULL;
2370   GNUNET_CONTAINER_multihashmap_destroy (ifm);
2371   ifm = NULL;
2372   while (NULL != (pos = indexed_files))
2373     {
2374       indexed_files = pos->next;
2375       GNUNET_free (pos);
2376     }
2377 }
2378
2379
2380 /**
2381  * Free (each) request made by the peer.
2382  *
2383  * @param cls closure, points to peer that the request belongs to
2384  * @param key current key code
2385  * @param value value in the hash map
2386  * @return GNUNET_YES (we should continue to iterate)
2387  */
2388 static int
2389 destroy_request (void *cls,
2390                  const GNUNET_HashCode * key,
2391                  void *value)
2392 {
2393   const struct GNUNET_PeerIdentity * peer = cls;
2394   struct PendingRequest *pr = value;
2395   
2396   GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2397                                         &peer->hashPubKey,
2398                                         pr);
2399   destroy_pending_request (pr);
2400   return GNUNET_YES;
2401 }
2402
2403
2404
2405 /**
2406  * Method called whenever a given peer connects.
2407  *
2408  * @param cls closure, not used
2409  * @param peer peer identity this notification is about
2410  */
2411 static void 
2412 peer_connect_handler (void *cls,
2413                       const struct
2414                       GNUNET_PeerIdentity * peer)
2415 {
2416   struct ConnectedPeer *cp;
2417
2418   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2419   cp->pid = GNUNET_PEER_intern (peer);
2420   GNUNET_CONTAINER_multihashmap_put (connected_peers,
2421                                      &peer->hashPubKey,
2422                                      cp,
2423                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2424 }
2425
2426
2427 /**
2428  * Method called whenever a peer disconnects.
2429  *
2430  * @param cls closure, not used
2431  * @param peer peer identity this notification is about
2432  */
2433 static void
2434 peer_disconnect_handler (void *cls,
2435                          const struct
2436                          GNUNET_PeerIdentity * peer)
2437 {
2438   struct ConnectedPeer *cp;
2439
2440   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2441                                           &peer->hashPubKey);
2442   GNUNET_PEER_change_rc (cp->pid, -1);
2443   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2444   GNUNET_free (cp);
2445   GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2446                                               &peer->hashPubKey,
2447                                               &destroy_request,
2448                                               (void*) peer);
2449 }
2450
2451
2452 /**
2453  * We're processing a GET request from
2454  * another peer and have decided to forward
2455  * it to other peers.
2456  *
2457  * @param cls our "struct ProcessGetContext *"
2458  * @param tc unused
2459  */
2460 static void
2461 forward_get_request (void *cls,
2462                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2463 {
2464   struct ProcessGetContext *pgc = cls;
2465   struct PendingRequest *pr;
2466   struct PendingRequest *eer;
2467   struct GNUNET_PeerIdentity target;
2468
2469   pr = GNUNET_malloc (sizeof (struct PendingRequest));
2470   if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2471     {
2472       pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2473       *pr->namespace = pgc->namespace;
2474     }
2475   pr->bf = pgc->bf;
2476   pr->bf_size = pgc->bf_size;
2477   pgc->bf = NULL;
2478   pr->start_time = pgc->start_time;
2479   pr->query = pgc->query;
2480   pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2481   if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2482     pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2483   pr->anonymity_level = 1; /* default */
2484   pr->priority = pgc->priority;
2485   pr->remaining_priority = pr->priority;
2486   pr->mingle = pgc->mingle;
2487   pr->ttl = pgc->ttl; 
2488   pr->type = pgc->type;
2489   GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2490                                      &pr->query,
2491                                      pr,
2492                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2493   GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2494                                      &pgc->reply_to.hashPubKey,
2495                                      pr,
2496                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2497   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2498                                             pr,
2499                                             pr->start_time.value + pr->ttl);
2500   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2501     {
2502       /* expire oldest request! */
2503       eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2504       GNUNET_PEER_resolve (eer->source_pid,
2505                            &target);    
2506       GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2507                                             &target.hashPubKey,
2508                                             eer);
2509       destroy_pending_request (eer);     
2510     }
2511   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2512                                            get_processing_delay (),
2513                                            &forward_request_task,
2514                                            pr);
2515   GNUNET_free (pgc); 
2516 }
2517 /**
2518  * Transmit the given message by copying it to
2519  * the target buffer "buf".  "buf" will be
2520  * NULL and "size" zero if the socket was closed for
2521  * writing in the meantime.  In that case, only
2522
2523  * free the message
2524  *
2525  * @param cls closure, pointer to the message
2526  * @param size number of bytes available in buf
2527  * @param buf where the callee should write the message
2528  * @return number of bytes written to buf
2529  */
2530 static size_t
2531 transmit_message (void *cls,
2532                   size_t size, void *buf)
2533 {
2534   struct GNUNET_MessageHeader *msg = cls;
2535   uint16_t msize;
2536   
2537   if (NULL == buf)
2538     {
2539 #if DEBUG_FS
2540       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541                   "Dropping reply, core too busy.\n");
2542 #endif
2543       GNUNET_free (msg);
2544       return 0;
2545     }
2546   msize = ntohs (msg->size);
2547   GNUNET_assert (size >= msize);
2548   memcpy (buf, msg, msize);
2549   GNUNET_free (msg);
2550   return msize;
2551 }
2552
2553
2554 /**
2555  * Test if the load on this peer is too high
2556  * to even consider processing the query at
2557  * all.
2558  * 
2559  * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2560  */
2561 static int
2562 test_load_too_high ()
2563 {
2564   return GNUNET_NO; // FIXME
2565 }
2566
2567
2568 /**
2569  * We're processing (local) results for a search request
2570  * from another peer.  Pass applicable results to the
2571  * peer and if we are done either clean up (operation
2572  * complete) or forward to other peers (more results possible).
2573  *
2574  * @param cls our closure (struct LocalGetContext)
2575  * @param key key for the content
2576  * @param size number of bytes in data
2577  * @param data content stored
2578  * @param type type of the content
2579  * @param priority priority of the content
2580  * @param anonymity anonymity-level for the content
2581  * @param expiration expiration time for the content
2582  * @param uid unique identifier for the datum;
2583  *        maybe 0 if no unique identifier is available
2584  */
2585 static void
2586 process_p2p_get_result (void *cls,
2587                         const GNUNET_HashCode * key,
2588                         uint32_t size,
2589                         const void *data,
2590                         uint32_t type,
2591                         uint32_t priority,
2592                         uint32_t anonymity,
2593                         struct GNUNET_TIME_Absolute
2594                         expiration, 
2595                         uint64_t uid)
2596 {
2597   struct ProcessGetContext *pgc = cls;
2598   GNUNET_HashCode dhash;
2599   GNUNET_HashCode mhash;
2600   struct PutMessage *reply;
2601   
2602   if (NULL == key)
2603     {
2604       /* no more results */
2605       if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) ==  ROUTING_POLICY_FORWARD) &&
2606            ( (0 == pgc->results_found) ||
2607              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2608              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2609              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2610         {
2611           GNUNET_SCHEDULER_add_continuation (sched,
2612                                              &forward_get_request,
2613                                              pgc,
2614                                              GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2615         }
2616       else
2617         {
2618           if (pgc->bf != NULL)
2619             GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2620           GNUNET_free (pgc); 
2621         }
2622       next_ds_request ();
2623       return;
2624     }
2625   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2626     {
2627       handle_on_demand_block (key, size, data, type, priority, 
2628                               anonymity, expiration, uid,
2629                               &process_p2p_get_result,
2630                               pgc);
2631       return;
2632     }
2633   /* check for duplicates */
2634   GNUNET_CRYPTO_hash (data, size, &dhash);
2635   mingle_hash (&dhash, 
2636                pgc->mingle,
2637                &mhash);
2638   if ( (pgc->bf != NULL) &&
2639        (GNUNET_YES ==
2640         GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2641                                            &mhash)) )
2642     {      
2643 #if DEBUG_FS
2644       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645                   "Result from datastore filtered by bloomfilter.\n");
2646 #endif
2647       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2648       return;
2649     }
2650   pgc->results_found++;
2651   if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2652        (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2653        (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2654     {
2655       if (pgc->bf == NULL)
2656         {
2657           pgc->bf_size = 32;
2658           pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2659                                                        pgc->bf_size, 
2660                                                        BLOOMFILTER_K);
2661         }
2662       GNUNET_CONTAINER_bloomfilter_add (pgc->bf, 
2663                                         &mhash);
2664     }
2665
2666   reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2667   reply->header.size = htons (sizeof (struct PutMessage) + size);
2668   reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2669   reply->type = htonl (type);
2670   reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2671   memcpy (&reply[1], data, size);
2672   GNUNET_CORE_notify_transmit_ready (core,
2673                                      pgc->priority,
2674                                      ACCEPTABLE_REPLY_DELAY,
2675                                      &pgc->reply_to,
2676                                      sizeof (struct PutMessage) + size,
2677                                      &transmit_message,
2678                                      reply);
2679   if ( (GNUNET_YES == test_load_too_high()) ||
2680        (pgc->results_found > 5 + 2 * pgc->priority) )
2681     {
2682       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2683       pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2684       return;
2685     }
2686   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2687 }
2688   
2689
2690 /**
2691  * We're processing a GET request from another peer.  Give it to our
2692  * local datastore.
2693  *
2694  * @param cls our "struct ProcessGetContext"
2695  * @param ok did we get a datastore slice or not?
2696  */
2697 static void
2698 ds_get_request (void *cls, 
2699                 int ok)
2700 {
2701   struct ProcessGetContext *pgc = cls;
2702   uint32_t type;
2703   struct GNUNET_TIME_Relative timeout;
2704
2705   if (GNUNET_OK != ok)
2706     {
2707       /* no point in doing P2P stuff if we can't even do local */
2708       GNUNET_free (dsh);
2709       return;
2710     }
2711   type = pgc->type;
2712   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2713     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2714   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2715                                            (pgc->priority + 1));
2716   GNUNET_DATASTORE_get (dsh,
2717                         &pgc->query,
2718                         type,
2719                         &process_p2p_get_result,
2720                         pgc,
2721                         timeout);
2722 }
2723
2724
2725 /**
2726  * The priority level imposes a bound on the maximum
2727  * value for the ttl that can be requested.
2728  *
2729  * @param ttl_in requested ttl
2730  * @param prio given priority
2731  * @return ttl_in if ttl_in is below the limit,
2732  *         otherwise the ttl-limit for the given priority
2733  */
2734 static int32_t
2735 bound_ttl (int32_t ttl_in, uint32_t prio)
2736 {
2737   unsigned long long allowed;
2738
2739   if (ttl_in <= 0)
2740     return ttl_in;
2741   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2742   if (ttl_in > allowed)      
2743     {
2744       if (allowed >= (1 << 30))
2745         return 1 << 30;
2746       return allowed;
2747     }
2748   return ttl_in;
2749 }
2750
2751
2752 /**
2753  * We've received a request with the specified
2754  * priority.  Bound it according to how much
2755  * we trust the given peer.
2756  * 
2757  * @param prio_in requested priority
2758  * @param peer the peer making the request
2759  * @return effective priority
2760  */
2761 static uint32_t
2762 bound_priority (uint32_t prio_in,
2763                 const struct GNUNET_PeerIdentity *peer)
2764 {
2765   return 0; // FIXME!
2766 }
2767
2768
2769 /**
2770  * Handle P2P "GET" request.
2771  *
2772  * @param cls closure, always NULL
2773  * @param other the other peer involved (sender or receiver, NULL
2774  *        for loopback messages where we are both sender and receiver)
2775  * @param message the actual message
2776  * @return GNUNET_OK to keep the connection open,
2777  *         GNUNET_SYSERR to close it (signal serious error)
2778  */
2779 static int
2780 handle_p2p_get (void *cls,
2781                 const struct GNUNET_PeerIdentity *other,
2782                 const struct GNUNET_MessageHeader *message)
2783 {
2784   uint16_t msize;
2785   const struct GetMessage *gm;
2786   unsigned int bits;
2787   const GNUNET_HashCode *opt;
2788   struct ProcessGetContext *pgc;
2789   uint32_t bm;
2790   size_t bfsize;
2791   uint32_t ttl_decrement;
2792   double preference;
2793   int net_load_up;
2794   int net_load_down;
2795
2796   msize = ntohs(message->size);
2797   if (msize < sizeof (struct GetMessage))
2798     {
2799       GNUNET_break_op (0);
2800       return GNUNET_SYSERR;
2801     }
2802   gm = (const struct GetMessage*) message;
2803   bm = ntohl (gm->hash_bitmap);
2804   bits = 0;
2805   while (bm > 0)
2806     {
2807       if (1 == (bm & 1))
2808         bits++;
2809       bm >>= 1;
2810     }
2811   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2812     {
2813       GNUNET_break_op (0);
2814       return GNUNET_SYSERR;
2815     }  
2816   opt = (const GNUNET_HashCode*) &gm[1];
2817   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2818   pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2819   if (bfsize > 0)
2820     {
2821       pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2822                                                    bfsize,
2823                                                    BLOOMFILTER_K);
2824       pgc->bf_size = bfsize;
2825     }
2826   pgc->type = ntohl (gm->type);
2827   pgc->bm = ntohl (gm->hash_bitmap);
2828   pgc->mingle = gm->filter_mutator;
2829   bits = 0;
2830   if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2831     pgc->reply_to.hashPubKey = opt[bits++];
2832   else
2833     pgc->reply_to = *other;
2834   if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2835     pgc->namespace = opt[bits++];
2836   else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2837     {
2838       GNUNET_break_op (0);
2839       GNUNET_free (pgc);
2840       return GNUNET_SYSERR;
2841     }
2842   if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2843     pgc->prime_target.hashPubKey = opt[bits++];
2844   /* note that we can really only check load here since otherwise
2845      peers could find out that we are overloaded by being disconnected
2846      after sending us a malformed query... */
2847   if (GNUNET_YES == test_load_too_high ())
2848     {
2849       if (NULL != pgc->bf)
2850         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2851       GNUNET_free (pgc);
2852 #if DEBUG_FS
2853       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854                   "Dropping query from `%s', this peer is too busy.\n",
2855                   GNUNET_i2s (other));
2856 #endif
2857       return GNUNET_OK;
2858     }
2859   net_load_up = 50; // FIXME
2860   net_load_down = 50; // FIXME
2861   pgc->policy = ROUTING_POLICY_NONE;
2862   if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2863        (net_load_down < IDLE_LOAD_THRESHOLD) )
2864     {
2865       pgc->policy |= ROUTING_POLICY_ALL;
2866       pgc->priority = 0; /* no charge */
2867     }
2868   else
2869     {
2870       pgc->priority = bound_priority (ntohl (gm->priority), other);
2871       if ( (net_load_up < 
2872             IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2873            (net_load_down < 
2874             IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2875         {
2876           pgc->policy |= ROUTING_POLICY_ALL;
2877         }
2878       else
2879         {
2880           // FIXME: is this sound?
2881           if (net_load_up < 90 + 10 * pgc->priority)
2882             pgc->policy |= ROUTING_POLICY_FORWARD;
2883           if (net_load_down < 90 + 10 * pgc->priority)
2884             pgc->policy |= ROUTING_POLICY_ANSWER;
2885         }
2886     }
2887   if (pgc->policy == ROUTING_POLICY_NONE)
2888     {
2889 #if DEBUG_FS
2890       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891                   "Dropping query from `%s', network saturated.\n",
2892                   GNUNET_i2s (other));
2893 #endif
2894       if (NULL != pgc->bf)
2895         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2896       GNUNET_free (pgc);
2897       return GNUNET_OK;     /* drop */
2898     }
2899   if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2900     pgc->priority = 0;  /* kill the priority (we cannot benefit) */
2901   pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2902   /* decrement ttl (always) */
2903   ttl_decrement = 2 * TTL_DECREMENT +
2904     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2905                               TTL_DECREMENT);
2906   if ( (pgc->ttl < 0) &&
2907        (pgc->ttl - ttl_decrement > 0) )
2908     {
2909 #if DEBUG_FS
2910       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911                   "Dropping query from `%s' due to TTL underflow.\n",
2912                   GNUNET_i2s (other));
2913 #endif
2914       /* integer underflow => drop (should be very rare)! */
2915       if (NULL != pgc->bf)
2916         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2917       GNUNET_free (pgc);
2918       return GNUNET_OK;
2919     }
2920   pgc->ttl -= ttl_decrement;
2921   pgc->start_time = GNUNET_TIME_absolute_get ();
2922   preference = (double) pgc->priority;
2923   if (preference < QUERY_BANDWIDTH_VALUE)
2924     preference = QUERY_BANDWIDTH_VALUE;
2925   // FIXME: also reserve bandwidth for reply?
2926   (void) GNUNET_CORE_peer_get_info (sched, cfg,
2927                                     other,
2928                                     GNUNET_TIME_UNIT_FOREVER_REL,
2929                                     0, 0, preference, NULL, NULL);
2930   if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2931     pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2932                                  &ds_get_request,
2933                                  pgc);
2934   else
2935     GNUNET_SCHEDULER_add_continuation (sched,
2936                                        &forward_get_request,
2937                                        pgc,
2938                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2939   return GNUNET_OK;
2940 }
2941
2942
2943 /**
2944  * Function called to notify us that we can now transmit a reply to a
2945  * client or peer.  "buf" will be NULL and "size" zero if the socket was
2946  * closed for writing in the meantime.
2947  *
2948  * @param cls closure, points to a "struct PendingRequest*" with
2949  *            one or more pending replies
2950  * @param size number of bytes available in buf
2951  * @param buf where the callee should write the message
2952  * @return number of bytes written to buf
2953  */
2954 static size_t
2955 transmit_result (void *cls,
2956                  size_t size, 
2957                  void *buf)
2958 {
2959   struct PendingRequest *pr = cls;
2960   char *cbuf = buf;
2961   struct PendingReply *reply;
2962   size_t ret;
2963
2964   ret = 0;
2965   while (NULL != (reply = pr->replies_pending))
2966     {
2967       if ( (reply->msize + ret < ret) ||
2968            (reply->msize + ret > size) )
2969         break;
2970       pr->replies_pending = reply->next;
2971       memcpy (&cbuf[ret], &reply[1], reply->msize);
2972       ret += reply->msize;
2973       GNUNET_free (reply);
2974     }
2975   return ret;
2976 }
2977
2978
2979 /**
2980  * Iterator over pending requests.
2981  *
2982  * @param cls response (struct ProcessReplyClosure)
2983  * @param key our query
2984  * @param value value in the hash map (meta-info about the query)
2985  * @return GNUNET_YES (we should continue to iterate)
2986  */
2987 static int
2988 process_reply (void *cls,
2989                const GNUNET_HashCode * key,
2990                void *value)
2991 {
2992   struct ProcessReplyClosure *prq = cls;
2993   struct PendingRequest *pr = value;
2994   struct PendingRequest *eer;
2995   struct PendingReply *reply;
2996   struct PutMessage *pm;
2997   struct ContentMessage *cm;
2998   GNUNET_HashCode chash;
2999   GNUNET_HashCode mhash;
3000   struct GNUNET_PeerIdentity target;
3001   size_t msize;
3002   uint32_t prio;
3003   struct GNUNET_TIME_Relative max_delay;
3004   
3005   GNUNET_CRYPTO_hash (prq->data,
3006                       prq->size,
3007                       &chash);
3008   switch (prq->type)
3009     {
3010     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3011     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3012       break;
3013     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3014       /* FIXME: does prq->namespace match our expectations? */
3015       /* then: fall-through??? */
3016     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3017       if (pr->bf != NULL) 
3018         {
3019           mingle_hash (&chash, pr->mingle, &mhash);
3020           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3021                                                                &mhash))
3022             return GNUNET_YES; /* duplicate */
3023           GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3024                                             &mhash);
3025         }
3026       break;
3027     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3028       // FIXME: any checks against duplicates for SKBlocks?
3029       break;
3030     }
3031   prio = pr->priority;
3032   prq->priority += pr->remaining_priority;
3033   pr->remaining_priority = 0;
3034   if (pr->client != NULL)
3035     {
3036       if (pr->replies_seen_size == pr->replies_seen_off)
3037         GNUNET_array_grow (pr->replies_seen,
3038                            pr->replies_seen_size,
3039                            pr->replies_seen_size * 2 + 4);
3040       pr->replies_seen[pr->replies_seen_off++] = chash;
3041       // FIXME: possibly recalculate BF!
3042     }
3043   if (pr->client == NULL)
3044     {
3045       msize = sizeof (struct ContentMessage) + prq->size;
3046       reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3047       reply->msize = msize;
3048       cm = (struct ContentMessage*) &reply[1];
3049       cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3050       cm->header.size = htons (msize);
3051       cm->type = htonl (prq->type);
3052       cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3053       reply->next = pr->replies_pending;
3054       pr->replies_pending = reply;
3055       memcpy (&reply[1], prq->data, prq->size);
3056       if (pr->cth != NULL)
3057         return GNUNET_YES;
3058       max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3059       if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3060         {
3061           /* estimate expiration time from time difference between
3062              first request that will be discarded and this request */
3063           eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3064           max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3065                                                            eer->start_time);
3066         }
3067       GNUNET_PEER_resolve (pr->source_pid,
3068                            &target);
3069       pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3070                                                    prio,
3071                                                    max_delay,
3072                                                    &target,
3073                                                    msize,
3074                                                    &transmit_result,
3075                                                    pr);
3076       if (NULL == pr->cth)
3077         {
3078           // FIXME: now what? discard?
3079         }
3080     }
3081   else
3082     {
3083       msize = sizeof (struct PutMessage) + prq->size;
3084       reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3085       reply->msize = msize;
3086       reply->next = pr->replies_pending;
3087       pm = (struct PutMessage*) &reply[1];
3088       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3089       pm->header.size = htons (msize);
3090       pm->type = htonl (prq->type);
3091       pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3092       pr->replies_pending = reply;
3093       memcpy (&reply[1], prq->data, prq->size);
3094       if (pr->th != NULL)
3095         return GNUNET_YES;
3096       pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3097                                                     msize,
3098                                                     GNUNET_TIME_UNIT_FOREVER_REL,
3099                                                     &transmit_result,
3100                                                     pr);
3101       if (pr->th == NULL)
3102         {
3103           // FIXME: need to try again later (not much
3104           // to do here specifically, but we need to
3105           // check somewhere else to handle this case!)
3106         }
3107     }
3108   // FIXME: implement hot-path routing statistics keeping!
3109   return GNUNET_YES;
3110 }
3111
3112
3113 /**
3114  * Check if the given KBlock is well-formed.
3115  *
3116  * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3117  * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3118  * @param query where to store the query that this block answers
3119  * @return GNUNET_OK if this is actually a well-formed KBlock
3120  */
3121 static int
3122 check_kblock (const struct KBlock *kb,
3123               size_t dsize,
3124               GNUNET_HashCode *query)
3125 {
3126   if (dsize < sizeof (struct KBlock))
3127     {
3128       GNUNET_break_op (0);
3129       return GNUNET_SYSERR;
3130     }
3131   if (dsize - sizeof (struct KBlock) !=
3132       ntohs (kb->purpose.size) 
3133       - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) 
3134       - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) ) 
3135     {
3136       GNUNET_break_op (0);
3137       return GNUNET_SYSERR;
3138     }
3139   if (GNUNET_OK !=
3140       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3141                                 &kb->purpose,
3142                                 &kb->signature,
3143                                 &kb->keyspace)) 
3144     {
3145       GNUNET_break_op (0);
3146       return GNUNET_SYSERR;
3147     }
3148   if (query != NULL)
3149     GNUNET_CRYPTO_hash (&kb->keyspace,
3150                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3151                         query);
3152   return GNUNET_OK;
3153 }
3154
3155
3156 /**
3157  * Check if the given SBlock is well-formed.
3158  *
3159  * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3160  * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3161  * @param query where to store the query that this block answers
3162  * @param namespace where to store the namespace that this block belongs to
3163  * @return GNUNET_OK if this is actually a well-formed SBlock
3164  */
3165 static int
3166 check_sblock (const struct SBlock *sb,
3167               size_t dsize,
3168               GNUNET_HashCode *query,   
3169               GNUNET_HashCode *namespace)
3170 {
3171   if (dsize < sizeof (struct SBlock))
3172     {
3173       GNUNET_break_op (0);
3174       return GNUNET_SYSERR;
3175     }
3176   if (dsize !=
3177       ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3178     {
3179       GNUNET_break_op (0);
3180       return GNUNET_SYSERR;
3181     }
3182   if (GNUNET_OK !=
3183       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3184                                 &sb->purpose,
3185                                 &sb->signature,
3186                                 &sb->subspace)) 
3187     {
3188       GNUNET_break_op (0);
3189       return GNUNET_SYSERR;
3190     }
3191   if (query != NULL)
3192     *query = sb->identifier;
3193   if (namespace != NULL)
3194     GNUNET_CRYPTO_hash (&sb->subspace,
3195                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3196                         namespace);
3197   return GNUNET_OK;
3198 }
3199
3200
3201 /**
3202  * Handle P2P "PUT" request.
3203  *
3204  * @param cls closure, always NULL
3205  * @param other the other peer involved (sender or receiver, NULL
3206  *        for loopback messages where we are both sender and receiver)
3207  * @param message the actual message
3208  * @return GNUNET_OK to keep the connection open,
3209  *         GNUNET_SYSERR to close it (signal serious error)
3210  */
3211 static int
3212 handle_p2p_put (void *cls,
3213                 const struct GNUNET_PeerIdentity *other,
3214                 const struct GNUNET_MessageHeader *message)
3215 {
3216   const struct PutMessage *put;
3217   uint16_t msize;
3218   size_t dsize;
3219   uint32_t type;
3220   struct GNUNET_TIME_Absolute expiration;
3221   GNUNET_HashCode query;
3222   struct ProcessReplyClosure prq;
3223
3224   msize = ntohs (message->size);
3225   if (msize < sizeof (struct PutMessage))
3226     {
3227       GNUNET_break_op(0);
3228       return GNUNET_SYSERR;
3229     }
3230   put = (const struct PutMessage*) message;
3231   dsize = msize - sizeof (struct PutMessage);
3232   type = ntohl (put->type);
3233   expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3234
3235   /* first, validate! */
3236   switch (type)
3237     {
3238     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3239     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3240       GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3241       break;
3242     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3243       if (GNUNET_OK !=
3244           check_kblock ((const struct KBlock*) &put[1],
3245                         dsize,
3246                         &query))
3247         return GNUNET_SYSERR;
3248       break;
3249     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3250       if (GNUNET_OK !=
3251           check_sblock ((const struct SBlock*) &put[1],
3252                         dsize,
3253                         &query,
3254                         &prq.namespace))
3255         return GNUNET_SYSERR;
3256       break;
3257     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3258       // FIXME -- validate SKBLOCK!
3259       GNUNET_break (0);
3260       return GNUNET_OK;
3261     default:
3262       /* unknown block type */
3263       GNUNET_break_op (0);
3264       return GNUNET_SYSERR;
3265     }
3266
3267   /* now, lookup 'query' */
3268   prq.data = (const void*) &put[1];
3269   prq.size = dsize;
3270   prq.type = type;
3271   prq.expiration = expiration;
3272   prq.priority = 0;
3273   GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3274                                               &query,
3275                                               &process_reply,
3276                                               &prq);
3277   // FIXME: if migration is on and load is low,
3278   // queue to store data in datastore;
3279   // use "prq.priority" for that!
3280   return GNUNET_OK;
3281 }
3282
3283
3284 /**
3285  * List of handlers for P2P messages
3286  * that we care about.
3287  */
3288 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3289   {
3290     { &handle_p2p_get, 
3291       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3292     { &handle_p2p_put, 
3293       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3294     { NULL, 0, 0 }
3295   };
3296
3297
3298 /**
3299  * Process fs requests.
3300  *
3301  * @param cls closure
3302  * @param s scheduler to use
3303  * @param server the initialized server
3304  * @param c configuration to use
3305  */
3306 static void
3307 run (void *cls,
3308      struct GNUNET_SCHEDULER_Handle *s,
3309      struct GNUNET_SERVER_Handle *server,
3310      const struct GNUNET_CONFIGURATION_Handle *c)
3311 {
3312   sched = s;
3313   cfg = c;
3314
3315   ifm = GNUNET_CONTAINER_multihashmap_create (128);
3316   requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3317   requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3318   connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3319   requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
3320   read_index_list ();
3321   dsh = GNUNET_DATASTORE_connect (cfg,
3322                                   sched);
3323   core = GNUNET_CORE_connect (sched,
3324                               cfg,
3325                               GNUNET_TIME_UNIT_FOREVER_REL,
3326                               NULL,
3327                               NULL,
3328                               NULL,
3329                               &peer_connect_handler,
3330                               &peer_disconnect_handler,
3331                               NULL, GNUNET_NO,
3332                               NULL, GNUNET_NO,
3333                               p2p_handlers);
3334
3335   GNUNET_SERVER_disconnect_notify (server, 
3336                                    &handle_client_disconnect,
3337                                    NULL);
3338   GNUNET_SERVER_add_handlers (server, handlers);
3339   GNUNET_SCHEDULER_add_delayed (sched,
3340                                 GNUNET_TIME_UNIT_FOREVER_REL,
3341                                 &shutdown_task,
3342                                 NULL);
3343   if (NULL == dsh)
3344     {
3345       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3346                   _("Failed to connect to `%s' service.\n"),
3347                   "datastore");
3348       GNUNET_SCHEDULER_shutdown (sched);
3349       return;
3350     }
3351   if (NULL == core)
3352     {
3353       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3354                   _("Failed to connect to `%s' service.\n"),
3355                   "core");
3356       GNUNET_SCHEDULER_shutdown (sched);
3357       return;
3358     }
3359 }
3360
3361
3362 /**
3363  * The main function for the fs service.
3364  *
3365  * @param argc number of arguments from the command line
3366  * @param argv command line arguments
3367  * @return 0 ok, 1 on error
3368  */
3369 int
3370 main (int argc, char *const *argv)
3371 {
3372   return (GNUNET_OK ==
3373           GNUNET_SERVICE_run (argc,
3374                               argv,
3375                               "fs",
3376                               GNUNET_SERVICE_OPTION_NONE,
3377                               &run, NULL)) ? 0 : 1;
3378 }
3379
3380 /* end of gnunet-service-fs.c */