stuff
[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_change_preference 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_data (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_data (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_data (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 IndexInfo *pos;
1114
1115   tc = GNUNET_SERVER_transmit_context_create (client);
1116   iim = (struct IndexInfoMessage*) buf;
1117   pos = indexed_files;
1118   while (NULL != pos)
1119     {
1120       fn = pos->filename;
1121       slen = strlen (fn) + 1;
1122       if (slen + sizeof (struct IndexInfoMessage) > 
1123           GNUNET_SERVER_MAX_MESSAGE_SIZE)
1124         {
1125           GNUNET_break (0);
1126           break;
1127         }
1128       iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1129       iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
1130       iim->reserved = 0;
1131       iim->file_id = pos->file_id;
1132       memcpy (&iim[1], fn, slen);
1133       GNUNET_SERVER_transmit_context_append_message (tc,
1134                                                      &iim->header);
1135       pos = pos->next;
1136     }
1137   GNUNET_SERVER_transmit_context_append_data (tc,
1138                                               NULL, 0,
1139                                               GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1140   GNUNET_SERVER_transmit_context_run (tc,
1141                                       GNUNET_TIME_UNIT_MINUTES);
1142 }
1143
1144
1145 /**
1146  * Handle UNINDEX-message.
1147  *
1148  * @param cls closure
1149  * @param client identification of the client
1150  * @param message the actual message
1151  */
1152 static void
1153 handle_unindex (void *cls,
1154                 struct GNUNET_SERVER_Client *client,
1155                 const struct GNUNET_MessageHeader *message)
1156 {
1157   const struct UnindexMessage *um;
1158   struct IndexInfo *pos;
1159   struct IndexInfo *prev;
1160   struct IndexInfo *next;
1161   struct GNUNET_SERVER_TransmitContext *tc;
1162   int found;
1163   
1164   um = (const struct UnindexMessage*) message;
1165   found = GNUNET_NO;
1166   prev = NULL;
1167   pos = indexed_files;
1168   while (NULL != pos)
1169     {
1170       next = pos->next;
1171       if (0 == memcmp (&pos->file_id,
1172                        &um->file_id,
1173                        sizeof (GNUNET_HashCode)))
1174         {
1175           if (prev == NULL)
1176             indexed_files = next;
1177           else
1178             prev->next = next;
1179           GNUNET_free (pos);
1180           found = GNUNET_YES;
1181         }
1182       else
1183         {
1184           prev = pos;
1185         }
1186       pos = next;
1187     }
1188 #if DEBUG_FS
1189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190               "Client requested unindexing of file `%s': %s\n",
1191               GNUNET_h2s (&um->file_id),
1192               found ? "found" : "not found");
1193 #endif
1194   if (GNUNET_YES == found)    
1195     write_index_list ();
1196   tc = GNUNET_SERVER_transmit_context_create (client);
1197   GNUNET_SERVER_transmit_context_append_data (tc,
1198                                               NULL, 0,
1199                                               GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1200   GNUNET_SERVER_transmit_context_run (tc,
1201                                       GNUNET_TIME_UNIT_MINUTES);
1202 }
1203
1204
1205 /**
1206  * Run the next DS request in our
1207  * queue, we're done with the current one.
1208  */
1209 static void
1210 next_ds_request ()
1211 {
1212   struct DatastoreRequestQueue *e;
1213   
1214   while (NULL != (e = drq_head))
1215     {
1216       if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1217         break;
1218       if (e->task != GNUNET_SCHEDULER_NO_TASK)
1219         GNUNET_SCHEDULER_cancel (sched, e->task);
1220       GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1221       e->req (e->req_cls, GNUNET_NO);
1222       GNUNET_free (e);  
1223     }
1224   if (e == NULL)
1225     return;
1226   if (e->task != GNUNET_SCHEDULER_NO_TASK)
1227     GNUNET_SCHEDULER_cancel (sched, e->task);
1228   e->task = GNUNET_SCHEDULER_NO_TASK;
1229   e->req (e->req_cls, GNUNET_YES);
1230   GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1231   GNUNET_free (e);  
1232 }
1233
1234
1235 /**
1236  * A datastore request had to be timed out. 
1237  *
1238  * @param cls closure (of type "struct DatastoreRequestQueue*")
1239  * @param tc task context, unused
1240  */
1241 static void
1242 timeout_ds_request (void *cls,
1243                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1244 {
1245   struct DatastoreRequestQueue *e = cls;
1246
1247   e->task = GNUNET_SCHEDULER_NO_TASK;
1248   GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1249   e->req (e->req_cls, GNUNET_NO);
1250   GNUNET_free (e);  
1251 }
1252
1253
1254 /**
1255  * Queue a request for the datastore.
1256  *
1257  * @param deadline by when the request should run
1258  * @param fun function to call once the request can be run
1259  * @param fun_cls closure for fun
1260  */
1261 static struct DatastoreRequestQueue *
1262 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1263                   RequestFunction fun,
1264                   void *fun_cls)
1265 {
1266   struct DatastoreRequestQueue *e;
1267   struct DatastoreRequestQueue *bef;
1268
1269   if (drq_head == NULL)
1270     {
1271       /* no other requests pending, run immediately */
1272       fun (fun_cls, GNUNET_OK);
1273       return NULL;
1274     }
1275   e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1276   e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1277   e->req = fun;
1278   e->req_cls = fun_cls;
1279   if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1280     {
1281       /* local request, highest prio, put at head of queue
1282          regardless of deadline */
1283       bef = NULL;
1284     }
1285   else
1286     {
1287       bef = drq_tail;
1288       while ( (NULL != bef) &&
1289               (e->timeout.value < bef->timeout.value) )
1290         bef = bef->prev;
1291     }
1292   GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1293   if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1294     return e;
1295   e->task = GNUNET_SCHEDULER_add_delayed (sched,
1296                                           deadline,
1297                                           &timeout_ds_request,
1298                                           e);
1299   return e;                                    
1300 }
1301
1302
1303 /**
1304  * Free the state associated with a local get context.
1305  *
1306  * @param lgc the lgc to free
1307  */
1308 static void
1309 local_get_context_free (struct LocalGetContext *lgc) 
1310 {
1311   GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1312   GNUNET_SERVER_client_drop (lgc->client); 
1313   GNUNET_free_non_null (lgc->results);
1314   if (lgc->results_bf != NULL)
1315     GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1316   if (lgc->req != NULL)
1317     {
1318       if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1319         GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1320       GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1321       GNUNET_free (lgc->req);
1322     }
1323   GNUNET_free (lgc);
1324 }
1325
1326
1327 /**
1328  * We're able to transmit the next (local) result to the client.
1329  * Do it and ask the datastore for more.  Or, on error, tell
1330  * the datastore to stop giving us more.
1331  *
1332  * @param cls our closure (struct LocalGetContext)
1333  * @param max maximum number of bytes we can transmit
1334  * @param buf where to copy our message
1335  * @return number of bytes copied to buf
1336  */
1337 static size_t
1338 transmit_local_result (void *cls,
1339                        size_t max,
1340                        void *buf)
1341 {
1342   struct LocalGetContext *lgc = cls;  
1343   uint16_t msize;
1344
1345   if (NULL == buf)
1346     {
1347 #if DEBUG_FS
1348       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349                   "Failed to transmit result to local client, aborting datastore iteration.\n");
1350 #endif
1351       /* error, abort! */
1352       GNUNET_free (lgc->result);
1353       lgc->result = NULL;
1354       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1355       return 0;
1356     }
1357   msize = ntohs (lgc->result->header.size);
1358 #if DEBUG_FS
1359   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360               "Transmitting %u bytes of result to local client.\n",
1361               msize);
1362 #endif
1363   GNUNET_assert (max >= msize);
1364   memcpy (buf, lgc->result, msize);
1365   GNUNET_free (lgc->result);
1366   lgc->result = NULL;
1367   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1368   return msize;
1369 }
1370
1371
1372 /**
1373  * Continuation called from datastore's remove
1374  * function.
1375  *
1376  * @param cls unused
1377  * @param success did the deletion work?
1378  * @param msg error message
1379  */
1380 static void
1381 remove_cont (void *cls,
1382              int success,
1383              const char *msg)
1384 {
1385   if (GNUNET_OK != success)
1386     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1387                 _("Failed to delete bogus block: %s\n"),
1388                 msg);
1389   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1390 }
1391
1392
1393 /**
1394  * Mingle hash with the mingle_number to
1395  * produce different bits.
1396  */
1397 static void
1398 mingle_hash (const GNUNET_HashCode * in,
1399              int32_t mingle_number, 
1400              GNUNET_HashCode * hc)
1401 {
1402   GNUNET_HashCode m;
1403
1404   GNUNET_CRYPTO_hash (&mingle_number, 
1405                       sizeof (int32_t), 
1406                       &m);
1407   GNUNET_CRYPTO_hash_xor (&m, in, hc);
1408 }
1409
1410
1411 /**
1412  * We've received an on-demand encoded block
1413  * from the datastore.  Attempt to do on-demand
1414  * encoding and (if successful), call the 
1415  * continuation with the resulting block.  On
1416  * error, clean up and ask the datastore for
1417  * more results.
1418  *
1419  * @param key key for the content
1420  * @param size number of bytes in data
1421  * @param data content stored
1422  * @param type type of the content
1423  * @param priority priority of the content
1424  * @param anonymity anonymity-level for the content
1425  * @param expiration expiration time for the content
1426  * @param uid unique identifier for the datum;
1427  *        maybe 0 if no unique identifier is available
1428  * @param cont function to call with the actual block
1429  * @param cont_cls closure for cont
1430  */
1431 static void
1432 handle_on_demand_block (const GNUNET_HashCode * key,
1433                         uint32_t size,
1434                         const void *data,
1435                         uint32_t type,
1436                         uint32_t priority,
1437                         uint32_t anonymity,
1438                         struct GNUNET_TIME_Absolute
1439                         expiration, uint64_t uid,
1440                         GNUNET_DATASTORE_Iterator cont,
1441                         void *cont_cls)
1442 {
1443   const struct OnDemandBlock *odb;
1444   GNUNET_HashCode nkey;
1445   struct GNUNET_CRYPTO_AesSessionKey skey;
1446   struct GNUNET_CRYPTO_AesInitializationVector iv;
1447   GNUNET_HashCode query;
1448   ssize_t nsize;
1449   char ndata[DBLOCK_SIZE];
1450   char edata[DBLOCK_SIZE];
1451   const char *fn;
1452   struct GNUNET_DISK_FileHandle *fh;
1453   uint64_t off;
1454
1455   if (size != sizeof (struct OnDemandBlock))
1456     {
1457       GNUNET_break (0);
1458       GNUNET_DATASTORE_remove (dsh, 
1459                                key,
1460                                size,
1461                                data,
1462                                &remove_cont,
1463                                NULL,
1464                                GNUNET_TIME_UNIT_FOREVER_REL);     
1465       return;
1466     }
1467   odb = (const struct OnDemandBlock*) data;
1468   off = GNUNET_ntohll (odb->offset);
1469   fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1470                                                         &odb->file_id);
1471   fh = NULL;
1472   if ( (NULL == fn) ||
1473        (NULL == (fh = GNUNET_DISK_file_open (fn, 
1474                                              GNUNET_DISK_OPEN_READ,
1475                                              GNUNET_DISK_PERM_NONE))) ||
1476        (off !=
1477         GNUNET_DISK_file_seek (fh,
1478                                off,
1479                                GNUNET_DISK_SEEK_SET)) ||
1480        (-1 ==
1481         (nsize = GNUNET_DISK_file_read (fh,
1482                                         ndata,
1483                                         sizeof (ndata)))) )
1484     {
1485       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1486                   _("Could not access indexed file `%s' at offset %llu: %s\n"),
1487                   GNUNET_h2s (&odb->file_id),
1488                   (unsigned long long) off,
1489                   STRERROR (errno));
1490       if (fh != NULL)
1491         GNUNET_DISK_file_close (fh);
1492       /* FIXME: if this happens often, we need
1493          to remove the OnDemand block from the DS! */
1494       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);        
1495       return;
1496     }
1497   GNUNET_DISK_file_close (fh);
1498   GNUNET_CRYPTO_hash (ndata,
1499                       nsize,
1500                       &nkey);
1501   GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1502   GNUNET_CRYPTO_aes_encrypt (ndata,
1503                              nsize,
1504                              &skey,
1505                              &iv,
1506                              edata);
1507   GNUNET_CRYPTO_hash (edata,
1508                       nsize,
1509                       &query);
1510   if (0 != memcmp (&query, 
1511                    key,
1512                    sizeof (GNUNET_HashCode)))
1513     {
1514       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1515                   _("Indexed file `%s' changed at offset %llu\n"),
1516                   fn,
1517                   (unsigned long long) off);
1518       /* FIXME: if this happens often, we need
1519          to remove the OnDemand block from the DS! */
1520       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1521       return;
1522     }
1523   cont (cont_cls,
1524         key,
1525         nsize,
1526         edata,
1527         GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1528         priority,
1529         anonymity,
1530         expiration,
1531         uid);
1532 }
1533
1534
1535 /**
1536  * How many bytes should a bloomfilter be if we have already seen
1537  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
1538  * of bits set per entry.  Furthermore, we should not re-size the
1539  * filter too often (to keep it cheap).
1540  *
1541  * Since other peers will also add entries but not resize the filter,
1542  * we should generally pick a slightly larger size than what the
1543  * strict math would suggest.
1544  *
1545  * @return must be a power of two and smaller or equal to 2^15.
1546  */
1547 static size_t
1548 compute_bloomfilter_size (unsigned int entry_count)
1549 {
1550   size_t size;
1551   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1552   uint16_t max = 1 << 15;
1553
1554   if (entry_count > max)
1555     return max;
1556   size = 8;
1557   while ((size < max) && (size < ideal))
1558     size *= 2;
1559   if (size > max)
1560     return max;
1561   return size;
1562 }
1563
1564
1565 /**
1566  * Recalculate our bloom filter for filtering replies.
1567  *
1568  * @param count number of entries we are filtering right now
1569  * @param mingle set to our new mingling value
1570  * @param bf_size set to the size of the bloomfilter
1571  * @param entries the entries to filter
1572  * @return updated bloomfilter, NULL for none
1573  */
1574 static struct GNUNET_CONTAINER_BloomFilter *
1575 refresh_bloomfilter (unsigned int count,
1576                      int32_t * mingle,
1577                      size_t *bf_size,
1578                      const GNUNET_HashCode *entries)
1579 {
1580   struct GNUNET_CONTAINER_BloomFilter *bf;
1581   size_t nsize;
1582   unsigned int i;
1583   GNUNET_HashCode mhash;
1584
1585   if (0 == count)
1586     return NULL;
1587   nsize = compute_bloomfilter_size (count);
1588   *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1589   *bf_size = nsize;
1590   bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
1591                                           nsize,
1592                                           BLOOMFILTER_K);
1593   for (i=0;i<count;i++)
1594     {
1595       mingle_hash (&entries[i], *mingle, &mhash);
1596       GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1597     }
1598   return bf;
1599 }
1600
1601
1602 /**
1603  * Closure used for "target_peer_select_cb".
1604  */
1605 struct PeerSelectionContext 
1606 {
1607   /**
1608    * The request for which we are selecting
1609    * peers.
1610    */
1611   struct PendingRequest *pr;
1612
1613   /**
1614    * Current "prime" target.
1615    */
1616   struct GNUNET_PeerIdentity target;
1617
1618   /**
1619    * How much do we like this target?
1620    */
1621   double target_score;
1622
1623 };
1624
1625
1626 /**
1627  * Function called for each connected peer to determine
1628  * which one(s) would make good targets for forwarding.
1629  *
1630  * @param cls closure (struct PeerSelectionContext)
1631  * @param key current key code (peer identity)
1632  * @param value value in the hash map (struct ConnectedPeer)
1633  * @return GNUNET_YES if we should continue to
1634  *         iterate,
1635  *         GNUNET_NO if not.
1636  */
1637 static int
1638 target_peer_select_cb (void *cls,
1639                        const GNUNET_HashCode * key,
1640                        void *value)
1641 {
1642   struct PeerSelectionContext *psc = cls;
1643   struct ConnectedPeer *cp = value;
1644   struct PendingRequest *pr = psc->pr;
1645   double score;
1646   unsigned int i;
1647
1648   /* 1) check if we have already (recently) forwarded to this peer */
1649   for (i=0;i<pr->used_pids_off;i++)
1650     if (pr->used_pids[i] == cp->pid)
1651       return GNUNET_YES; /* skip */
1652   // 2) calculate how much we'd like to forward to this peer
1653   score = 0; // FIXME!
1654   
1655   /* store best-fit in closure */
1656   if (score > psc->target_score)
1657     {
1658       psc->target_score = score;
1659       psc->target.hashPubKey = *key; 
1660     }
1661   return GNUNET_YES;
1662 }
1663
1664
1665 /**
1666  * We use a random delay to make the timing of requests
1667  * less predictable.  This function returns such a random
1668  * delay.
1669  *
1670  * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1671  */
1672 static struct GNUNET_TIME_Relative
1673 get_processing_delay ()
1674 {
1675   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1676                                         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1677                                                                   TTL_DECREMENT));
1678 }
1679
1680
1681 /**
1682  * Task that is run for each request with the
1683  * goal of forwarding the associated query to
1684  * other peers.  The task should re-schedule
1685  * itself to be re-run once the TTL has expired.
1686  * (or at a later time if more peers should
1687  * be queried earlier).
1688  *
1689  * @param cls the requests "struct PendingRequest*"
1690  * @param tc task context (unused)
1691  */
1692 static void
1693 forward_request_task (void *cls,
1694                       const struct GNUNET_SCHEDULER_TaskContext *tc);
1695
1696
1697 /**
1698  * We've selected a peer for forwarding of a query.
1699  * Construct the message and then re-schedule the
1700  * task to forward again to (other) peers.
1701  *
1702  * @param cls closure
1703  * @param size number of bytes available in buf
1704  * @param buf where the callee should write the message
1705  * @return number of bytes written to buf
1706  */
1707 static size_t
1708 transmit_request_cb (void *cls,
1709                      size_t size, 
1710                      void *buf)
1711 {
1712   struct PendingRequest *pr = cls;
1713   struct GetMessage *gm;
1714   GNUNET_HashCode *ext;
1715   char *bfdata;
1716   size_t msize;
1717   unsigned int k;
1718
1719   pr->cth = NULL;
1720   /* (1) check for timeout */
1721   if (NULL == buf)
1722     {
1723       /* timeout, try another peer immediately again */
1724       pr->task = GNUNET_SCHEDULER_add_with_priority (sched,
1725                                                      GNUNET_SCHEDULER_PRIORITY_IDLE,
1726                                                      &forward_request_task,
1727                                                      pr);
1728       return 0;
1729     }
1730   /* (2) build query message */
1731   k = 0; // FIXME: count hash codes!
1732   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1733   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1734   gm = (struct GetMessage*) buf;
1735   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1736   gm->header.size = htons (msize);
1737   gm->type = htonl (pr->type);
1738   pr->remaining_priority /= 2;
1739   gm->priority = htonl (pr->remaining_priority);
1740   gm->ttl = htonl (pr->ttl);
1741   gm->filter_mutator = htonl(pr->mingle);
1742   gm->hash_bitmap = htonl (42);
1743   gm->query = pr->query;
1744   ext = (GNUNET_HashCode*) &gm[1];
1745   // FIXME: setup "ext[0]..[k-1]"
1746   bfdata = (char *) &ext[k];
1747   if (pr->bf != NULL)
1748     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1749                                                bfdata,
1750                                                pr->bf_size);
1751   
1752   /* (3) schedule job to do it again (or another peer, etc.) */
1753   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1754                                            get_processing_delay (), // FIXME!
1755                                            &forward_request_task,
1756                                            pr);
1757
1758   return msize;
1759 }
1760
1761
1762 /**
1763  * Function called after we've tried to reserve
1764  * a certain amount of bandwidth for a reply.
1765  * Check if we succeeded and if so send our query.
1766  *
1767  * @param cls the requests "struct PendingRequest*"
1768  * @param peer identifies the peer
1769  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1770  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1771  * @param amount set to the amount that was actually reserved or unreserved
1772  * @param preference current traffic preference for the given peer
1773  */
1774 static void
1775 target_reservation_cb (void *cls,
1776                        const struct
1777                        GNUNET_PeerIdentity * peer,
1778                        unsigned int bpm_in,
1779                        unsigned int bpm_out,
1780                        int amount,
1781                        uint64_t preference)
1782 {
1783   struct PendingRequest *pr = cls;
1784   uint32_t priority;
1785   uint16_t size;
1786   struct GNUNET_TIME_Relative maxdelay;
1787
1788   pr->irc = NULL;
1789   GNUNET_assert (peer != NULL);
1790   if ( (amount != DBLOCK_SIZE) ||
1791        (pr->cth != NULL) )
1792     {
1793       /* try again later; FIXME: we may need to un-reserve "amount"? */
1794       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1795                                                get_processing_delay (), // FIXME: longer?
1796                                                &forward_request_task,
1797                                                pr);
1798       return;
1799     }
1800   // (2) transmit, update ttl/priority
1801   // FIXME: calculate priority, maxdelay, size properly!
1802   priority = 0;
1803   size = 60000;
1804   maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1805   pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1806                                                priority,
1807                                                maxdelay,
1808                                                peer,
1809                                                size,
1810                                                &transmit_request_cb,
1811                                                pr);
1812   if (pr->cth == NULL)
1813     {
1814       /* try again later */
1815       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1816                                                get_processing_delay (), // FIXME: longer?
1817                                                &forward_request_task,
1818                                                pr);
1819     }
1820 }
1821
1822
1823 /**
1824  * Task that is run for each request with the
1825  * goal of forwarding the associated query to
1826  * other peers.  The task should re-schedule
1827  * itself to be re-run once the TTL has expired.
1828  * (or at a later time if more peers should
1829  * be queried earlier).
1830  *
1831  * @param cls the requests "struct PendingRequest*"
1832  * @param tc task context (unused)
1833  */
1834 static void
1835 forward_request_task (void *cls,
1836                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1837 {
1838   struct PendingRequest *pr = cls;
1839   struct PeerSelectionContext psc;
1840
1841   pr->task = GNUNET_SCHEDULER_NO_TASK;
1842   if (pr->cth != NULL) 
1843     {
1844       /* we're busy transmitting a result, wait a bit */
1845       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1846                                                get_processing_delay (), 
1847                                                &forward_request_task,
1848                                                pr);
1849       return;
1850     }
1851   /* (1) select target */
1852   psc.pr = pr;
1853   psc.target_score = DBL_MIN;
1854   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1855                                          &target_peer_select_cb,
1856                                          &psc);
1857   if (psc.target_score == DBL_MIN)
1858     {
1859       /* no possible target found, wait some time */
1860       pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1861                                                get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1862                                                &forward_request_task,
1863                                                pr);
1864       return;
1865     }
1866   /* (2) reserve reply bandwidth */
1867   GNUNET_assert (NULL == pr->irc);
1868   pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1869                                        &psc.target,
1870                                        GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
1871                                        -1,
1872                                        DBLOCK_SIZE, // FIXME: make dependent on type?
1873                                        0,
1874                                        &target_reservation_cb,
1875                                        pr);
1876 }
1877
1878
1879 /**
1880  * We're processing (local) results for a search request
1881  * from a (local) client.  Pass applicable results to the
1882  * client and if we are done either clean up (operation
1883  * complete) or switch to P2P search (more results possible).
1884  *
1885  * @param cls our closure (struct LocalGetContext)
1886  * @param key key for the content
1887  * @param size number of bytes in data
1888  * @param data content stored
1889  * @param type type of the content
1890  * @param priority priority of the content
1891  * @param anonymity anonymity-level for the content
1892  * @param expiration expiration time for the content
1893  * @param uid unique identifier for the datum;
1894  *        maybe 0 if no unique identifier is available
1895  */
1896 static void
1897 process_local_get_result (void *cls,
1898                           const GNUNET_HashCode * key,
1899                           uint32_t size,
1900                           const void *data,
1901                           uint32_t type,
1902                           uint32_t priority,
1903                           uint32_t anonymity,
1904                           struct GNUNET_TIME_Absolute
1905                           expiration, 
1906                           uint64_t uid)
1907 {
1908   struct LocalGetContext *lgc = cls;
1909   struct PendingRequest *pr;
1910   struct ClientRequestList *crl;
1911   struct ClientList *cl;
1912   size_t msize;
1913   unsigned int i;
1914
1915   if (key == NULL)
1916     {
1917 #if DEBUG_FS
1918       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919                   "Received last result for `%s' from local datastore, deciding what to do next.\n",
1920                   GNUNET_h2s (&lgc->query));
1921 #endif
1922       /* no further results from datastore; continue
1923          processing further requests from the client and
1924          allow the next task to use the datastore; also,
1925          switch to P2P requests or clean up our state. */
1926       next_ds_request ();
1927       GNUNET_SERVER_receive_done (lgc->client,
1928                                   GNUNET_OK);
1929       if ( (lgc->results_used == 0) ||
1930            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1931            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1932            (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1933         {
1934 #if DEBUG_FS
1935           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1936                       "Forwarding query for `%s' to network.\n",
1937                       GNUNET_h2s (&lgc->query));
1938 #endif
1939           cl = clients;
1940           while ( (NULL != cl) &&
1941                   (cl->client != lgc->client) )
1942             cl = cl->next;
1943           if (cl == NULL)
1944             {
1945               cl = GNUNET_malloc (sizeof (struct ClientList));
1946               cl->client = lgc->client;
1947               cl->next = clients;
1948               clients = cl;
1949             }
1950           crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1951           crl->cl = cl;
1952           GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1953           pr = GNUNET_malloc (sizeof (struct PendingRequest));
1954           pr->client = lgc->client;
1955           GNUNET_SERVER_client_keep (pr->client);
1956           pr->crl_entry = crl;
1957           crl->req = pr;
1958           if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1959             {
1960               pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1961               *pr->namespace = lgc->namespace;
1962             }
1963           pr->replies_seen = lgc->results;
1964           lgc->results = NULL;
1965           pr->start_time = GNUNET_TIME_absolute_get ();
1966           pr->query = lgc->query;
1967           pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1968           pr->replies_seen_off = lgc->results_used;
1969           pr->replies_seen_size = lgc->results_size;
1970           lgc->results_size = 0;
1971           pr->type = lgc->type;
1972           pr->anonymity_level = lgc->anonymity_level;
1973           pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1974                                         &pr->mingle,
1975                                         &pr->bf_size,
1976                                         pr->replies_seen);
1977           GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1978                                              &pr->query,
1979                                              pr,
1980                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1981           pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1982                                                    get_processing_delay (),
1983                                                    &forward_request_task,
1984                                                    pr);
1985           local_get_context_free (lgc);
1986           return;
1987         }
1988       /* got all possible results, clean up! */
1989 #if DEBUG_FS
1990       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1991                   "Found all possible results for query for `%s', done!\n",
1992                   GNUNET_h2s (&lgc->query));
1993 #endif
1994       local_get_context_free (lgc);
1995       return;
1996     }
1997   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1998     {
1999 #if DEBUG_FS
2000       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001                   "Received on-demand block for `%s' from local datastore, fetching data.\n",
2002                   GNUNET_h2s (&lgc->query));
2003 #endif
2004       handle_on_demand_block (key, size, data, type, priority, 
2005                               anonymity, expiration, uid,
2006                               &process_local_get_result,
2007                               lgc);
2008       return;
2009     }
2010   if ( (type != lgc->type) &&
2011        (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2012     {
2013       /* this should be virtually impossible to reach (DBLOCK 
2014          query hash being identical to KBLOCK/SBLOCK query hash);
2015          nevertheless, if it happens, the correct thing is to
2016          simply skip the result. */
2017 #if DEBUG_FS
2018       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2019                   "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2020                   type,
2021                   lgc->type,
2022                   GNUNET_h2s (&lgc->query));
2023 #endif
2024       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);        
2025       return;
2026     }
2027   /* check if this is a result we've alredy
2028      received */
2029   for (i=0;i<lgc->results_used;i++)
2030     if (0 == memcmp (key,
2031                      &lgc->results[i],
2032                      sizeof (GNUNET_HashCode)))
2033       {
2034 #if DEBUG_FS
2035         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2036                     "Received duplicate result for `%s' from local datastore, ignoring.\n",
2037                     GNUNET_h2s (&lgc->query));
2038 #endif
2039         GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2040         return; 
2041       }
2042   if (lgc->results_used == lgc->results_size)
2043     GNUNET_array_grow (lgc->results,
2044                        lgc->results_size,
2045                        lgc->results_size * 2 + 2);
2046   GNUNET_CRYPTO_hash (data, 
2047                       size, 
2048                       &lgc->results[lgc->results_used++]);    
2049   msize = size + sizeof (struct ContentMessage);
2050   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2051   lgc->result = GNUNET_malloc (msize);
2052   lgc->result->header.size = htons (msize);
2053   lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2054   lgc->result->type = htonl (type);
2055   lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2056   memcpy (&lgc->result[1],
2057           data,
2058           size);
2059 #if DEBUG_FS
2060   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061               "Received new result for `%s' from local datastore, passing to client.\n",
2062               GNUNET_h2s (&lgc->query));
2063 #endif
2064   GNUNET_SERVER_notify_transmit_ready (lgc->client,
2065                                        msize,
2066                                        GNUNET_TIME_UNIT_FOREVER_REL,
2067                                        &transmit_local_result,
2068                                        lgc);
2069 }
2070
2071
2072 /**
2073  * We're processing a search request from a local
2074  * client.  Now it is our turn to query the datastore.
2075  * 
2076  * @param cls our closure (struct LocalGetContext)
2077  * @param tc unused
2078  */
2079 static void
2080 transmit_local_get (void *cls,
2081                     const struct GNUNET_SCHEDULER_TaskContext *tc)
2082 {
2083   struct LocalGetContext *lgc = cls;
2084   uint32_t type;
2085   
2086   type = lgc->type;
2087   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2088     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2089   GNUNET_DATASTORE_get (dsh,
2090                         &lgc->query,
2091                         type,
2092                         &process_local_get_result,
2093                         lgc,
2094                         GNUNET_TIME_UNIT_FOREVER_REL);
2095 }
2096
2097
2098 /**
2099  * We're processing a search request from a local
2100  * client.  Now it is our turn to query the datastore.
2101  * 
2102  * @param cls our closure (struct LocalGetContext)
2103  * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2104  */
2105 static void 
2106 transmit_local_get_ready (void *cls,
2107                           int ok)
2108 {
2109   struct LocalGetContext *lgc = cls;
2110
2111   GNUNET_assert (GNUNET_OK == ok);
2112   GNUNET_SCHEDULER_add_continuation (sched,
2113                                      &transmit_local_get,
2114                                      lgc,
2115                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2116 }
2117
2118
2119 /**
2120  * Handle START_SEARCH-message (search request from client).
2121  *
2122  * @param cls closure
2123  * @param client identification of the client
2124  * @param message the actual message
2125  */
2126 static void
2127 handle_start_search (void *cls,
2128                      struct GNUNET_SERVER_Client *client,
2129                      const struct GNUNET_MessageHeader *message)
2130 {
2131   const struct SearchMessage *sm;
2132   struct LocalGetContext *lgc;
2133   uint16_t msize;
2134   unsigned int sc;
2135   
2136   msize = ntohs (message->size);
2137   if ( (msize < sizeof (struct SearchMessage)) ||
2138        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2139     {
2140       GNUNET_break (0);
2141       GNUNET_SERVER_receive_done (client,
2142                                   GNUNET_SYSERR);
2143       return;
2144     }
2145   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2146   sm = (const struct SearchMessage*) message;
2147   GNUNET_SERVER_client_keep (client);
2148   lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2149   if  (sc > 0)
2150     {
2151       lgc->results_used = sc;
2152       GNUNET_array_grow (lgc->results,
2153                          lgc->results_size,
2154                          sc * 2);
2155       memcpy (lgc->results,
2156               &sm[1],
2157               sc * sizeof (GNUNET_HashCode));
2158     }
2159   lgc->client = client;
2160   lgc->type = ntohl (sm->type);
2161   lgc->anonymity_level = ntohl (sm->anonymity_level);
2162   switch (lgc->type)
2163     {
2164     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2165     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2166       lgc->target.hashPubKey = sm->target;
2167       break;
2168     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2169       lgc->namespace = sm->target;
2170       break;
2171     default:
2172       break;
2173     }
2174   lgc->query = sm->query;
2175   GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2176   lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2177                                &transmit_local_get_ready,
2178                                lgc);
2179 }
2180
2181
2182 /**
2183  * List of handlers for the messages understood by this
2184  * service.
2185  */
2186 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2187   {&handle_index_start, NULL, 
2188    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2189   {&handle_index_list_get, NULL, 
2190    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2191   {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
2192    sizeof (struct UnindexMessage) },
2193   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
2194    0 },
2195   {NULL, NULL, 0, 0}
2196 };
2197
2198
2199 /**
2200  * Clean up the memory used by the PendingRequest structure (except
2201  * for the client or peer list that the request may be part of).
2202  *
2203  * @param pr request to clean up
2204  */
2205 static void
2206 destroy_pending_request (struct PendingRequest *pr)
2207 {
2208   struct PendingReply *reply;
2209   struct ClientList *cl;
2210
2211   GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2212                                         &pr->query,
2213                                         pr);
2214   // FIXME: not sure how this can work (efficiently)
2215   // also, what does the return value mean?
2216   if (pr->irc != NULL)
2217     {
2218       GNUNET_CORE_peer_change_preference_cancel (pr->irc);
2219       pr->irc = NULL;
2220     }
2221   if (pr->client == NULL)
2222     {
2223       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2224                                          pr->hnode);
2225     }
2226   else
2227     {
2228       cl = pr->crl_entry->cl;
2229       GNUNET_CONTAINER_DLL_remove (cl->head,
2230                                    cl->tail,
2231                                    pr->crl_entry);
2232     }
2233   if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2234     GNUNET_SCHEDULER_cancel (sched, pr->task);
2235   if (NULL != pr->cth)
2236     GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2237   if (NULL != pr->bf)
2238     GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2239   if (NULL != pr->th)
2240     GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2241   while (NULL != (reply = pr->replies_pending))
2242     {
2243       pr->replies_pending = reply->next;
2244       GNUNET_free (reply);
2245     }
2246   GNUNET_PEER_change_rc (pr->source_pid, -1);
2247   GNUNET_PEER_change_rc (pr->target_pid, -1);
2248   GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2249   GNUNET_free_non_null (pr->used_pids);
2250   GNUNET_free_non_null (pr->replies_seen);
2251   GNUNET_free_non_null (pr->namespace);
2252   GNUNET_free (pr);
2253 }
2254
2255
2256 /**
2257  * A client disconnected.  Remove all of its pending queries.
2258  *
2259  * @param cls closure, NULL
2260  * @param client identification of the client
2261  */
2262 static void
2263 handle_client_disconnect (void *cls,
2264                           struct GNUNET_SERVER_Client
2265                           * client)
2266 {
2267   struct LocalGetContext *lgc;
2268   struct ClientList *cpos;
2269   struct ClientList *cprev;
2270   struct ClientRequestList *rl;
2271
2272   if (client == NULL)
2273     return;
2274   lgc = lgc_head;
2275   while ( (NULL != lgc) &&
2276           (lgc->client != client) )
2277     lgc = lgc->next;
2278   if (lgc != NULL)
2279     local_get_context_free (lgc);
2280   cprev = NULL;
2281   cpos = clients;
2282   while ( (NULL != cpos) &&
2283           (clients->client != client) )
2284     {
2285       cprev = cpos;
2286       cpos = cpos->next;
2287     }
2288   if (cpos != NULL)
2289     {
2290       if (cprev == NULL)
2291         clients = cpos->next;
2292       else
2293         cprev->next = cpos->next;
2294       while (NULL != (rl = cpos->head))
2295         {
2296           cpos->head = rl->next;
2297           destroy_pending_request (rl->req);
2298           GNUNET_free (rl);
2299         }
2300       GNUNET_free (cpos);
2301     }
2302 }
2303
2304
2305 /**
2306  * Iterator over entries in the "requests_by_query" map
2307  * that frees all the entries.
2308  *
2309  * @param cls closure, NULL
2310  * @param key current key code (the query, unused) 
2311  * @param value value in the hash map, of type "struct PendingRequest*"
2312  * @return GNUNET_YES (we should continue to  iterate)
2313  */
2314 static int 
2315 destroy_pending_request_cb (void *cls,
2316                             const GNUNET_HashCode * key,
2317                             void *value)
2318 {
2319   struct PendingRequest *pr = value;
2320
2321   destroy_pending_request (pr);
2322   return GNUNET_YES;
2323 }
2324
2325
2326 /**
2327  * Task run during shutdown.
2328  *
2329  * @param cls unused
2330  * @param tc unused
2331  */
2332 static void
2333 shutdown_task (void *cls,
2334                const struct GNUNET_SCHEDULER_TaskContext *tc)
2335 {
2336   struct IndexInfo *pos;  
2337
2338   if (NULL != core)
2339     {
2340       GNUNET_CORE_disconnect (core);
2341       core = NULL;
2342     }
2343   if (NULL != dsh)
2344     {
2345       GNUNET_DATASTORE_disconnect (dsh,
2346                                    GNUNET_NO);
2347       dsh = NULL;
2348     }
2349   GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2350                                          &destroy_pending_request_cb,
2351                                          NULL);
2352   while (clients != NULL)
2353     handle_client_disconnect (NULL,
2354                               clients->client);
2355   GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2356   requests_by_query = NULL;
2357   GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2358   requests_by_peer = NULL;
2359   GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2360   requests_by_expiration = NULL;
2361   // FIXME: iterate over entries and free individually?
2362   // (or do we get disconnect notifications?)
2363   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2364   connected_peers = NULL;
2365   GNUNET_CONTAINER_multihashmap_destroy (ifm);
2366   ifm = NULL;
2367   while (NULL != (pos = indexed_files))
2368     {
2369       indexed_files = pos->next;
2370       GNUNET_free (pos);
2371     }
2372 }
2373
2374
2375 /**
2376  * Free (each) request made by the peer.
2377  *
2378  * @param cls closure, points to peer that the request belongs to
2379  * @param key current key code
2380  * @param value value in the hash map
2381  * @return GNUNET_YES (we should continue to iterate)
2382  */
2383 static int
2384 destroy_request (void *cls,
2385                  const GNUNET_HashCode * key,
2386                  void *value)
2387 {
2388   const struct GNUNET_PeerIdentity * peer = cls;
2389   struct PendingRequest *pr = value;
2390   
2391   GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2392                                         &peer->hashPubKey,
2393                                         pr);
2394   destroy_pending_request (pr);
2395   return GNUNET_YES;
2396 }
2397
2398
2399
2400 /**
2401  * Method called whenever a given peer connects.
2402  *
2403  * @param cls closure, not used
2404  * @param peer peer identity this notification is about
2405  * @param latency reported latency of the connection with 'other'
2406  * @param distance reported distance (DV) to 'other' 
2407  */
2408 static void 
2409 peer_connect_handler (void *cls,
2410                       const struct
2411                       GNUNET_PeerIdentity * peer,
2412                       struct GNUNET_TIME_Relative latency,
2413                       uint32_t distance)
2414 {
2415   struct ConnectedPeer *cp;
2416
2417   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2418   cp->pid = GNUNET_PEER_intern (peer);
2419   GNUNET_CONTAINER_multihashmap_put (connected_peers,
2420                                      &peer->hashPubKey,
2421                                      cp,
2422                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2423 }
2424
2425
2426 /**
2427  * Method called whenever a peer disconnects.
2428  *
2429  * @param cls closure, not used
2430  * @param peer peer identity this notification is about
2431  */
2432 static void
2433 peer_disconnect_handler (void *cls,
2434                          const struct
2435                          GNUNET_PeerIdentity * peer)
2436 {
2437   struct ConnectedPeer *cp;
2438
2439   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2440                                           &peer->hashPubKey);
2441   GNUNET_PEER_change_rc (cp->pid, -1);
2442   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2443   GNUNET_free (cp);
2444   GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2445                                               &peer->hashPubKey,
2446                                               &destroy_request,
2447                                               (void*) peer);
2448 }
2449
2450
2451 /**
2452  * We're processing a GET request from
2453  * another peer and have decided to forward
2454  * it to other peers.
2455  *
2456  * @param cls our "struct ProcessGetContext *"
2457  * @param tc unused
2458  */
2459 static void
2460 forward_get_request (void *cls,
2461                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2462 {
2463   struct ProcessGetContext *pgc = cls;
2464   struct PendingRequest *pr;
2465   struct PendingRequest *eer;
2466   struct GNUNET_PeerIdentity target;
2467
2468   pr = GNUNET_malloc (sizeof (struct PendingRequest));
2469   if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2470     {
2471       pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2472       *pr->namespace = pgc->namespace;
2473     }
2474   pr->bf = pgc->bf;
2475   pr->bf_size = pgc->bf_size;
2476   pgc->bf = NULL;
2477   pr->start_time = pgc->start_time;
2478   pr->query = pgc->query;
2479   pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2480   if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2481     pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2482   pr->anonymity_level = 1; /* default */
2483   pr->priority = pgc->priority;
2484   pr->remaining_priority = pr->priority;
2485   pr->mingle = pgc->mingle;
2486   pr->ttl = pgc->ttl; 
2487   pr->type = pgc->type;
2488   GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2489                                      &pr->query,
2490                                      pr,
2491                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2492   GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2493                                      &pgc->reply_to.hashPubKey,
2494                                      pr,
2495                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2496   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2497                                             pr,
2498                                             pr->start_time.value + pr->ttl);
2499   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2500     {
2501       /* expire oldest request! */
2502       eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2503       GNUNET_PEER_resolve (eer->source_pid,
2504                            &target);    
2505       GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2506                                             &target.hashPubKey,
2507                                             eer);
2508       destroy_pending_request (eer);     
2509     }
2510   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2511                                            get_processing_delay (),
2512                                            &forward_request_task,
2513                                            pr);
2514   GNUNET_free (pgc); 
2515 }
2516 /**
2517  * Transmit the given message by copying it to
2518  * the target buffer "buf".  "buf" will be
2519  * NULL and "size" zero if the socket was closed for
2520  * writing in the meantime.  In that case, only
2521
2522  * free the message
2523  *
2524  * @param cls closure, pointer to the message
2525  * @param size number of bytes available in buf
2526  * @param buf where the callee should write the message
2527  * @return number of bytes written to buf
2528  */
2529 static size_t
2530 transmit_message (void *cls,
2531                   size_t size, void *buf)
2532 {
2533   struct GNUNET_MessageHeader *msg = cls;
2534   uint16_t msize;
2535   
2536   if (NULL == buf)
2537     {
2538 #if DEBUG_FS
2539       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540                   "Dropping reply, core too busy.\n");
2541 #endif
2542       GNUNET_free (msg);
2543       return 0;
2544     }
2545   msize = ntohs (msg->size);
2546   GNUNET_assert (size >= msize);
2547   memcpy (buf, msg, msize);
2548   GNUNET_free (msg);
2549   return msize;
2550 }
2551
2552
2553 /**
2554  * Test if the load on this peer is too high
2555  * to even consider processing the query at
2556  * all.
2557  * 
2558  * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2559  */
2560 static int
2561 test_load_too_high ()
2562 {
2563   return GNUNET_NO; // FIXME
2564 }
2565
2566
2567 /**
2568  * We're processing (local) results for a search request
2569  * from another peer.  Pass applicable results to the
2570  * peer and if we are done either clean up (operation
2571  * complete) or forward to other peers (more results possible).
2572  *
2573  * @param cls our closure (struct LocalGetContext)
2574  * @param key key for the content
2575  * @param size number of bytes in data
2576  * @param data content stored
2577  * @param type type of the content
2578  * @param priority priority of the content
2579  * @param anonymity anonymity-level for the content
2580  * @param expiration expiration time for the content
2581  * @param uid unique identifier for the datum;
2582  *        maybe 0 if no unique identifier is available
2583  */
2584 static void
2585 process_p2p_get_result (void *cls,
2586                         const GNUNET_HashCode * key,
2587                         uint32_t size,
2588                         const void *data,
2589                         uint32_t type,
2590                         uint32_t priority,
2591                         uint32_t anonymity,
2592                         struct GNUNET_TIME_Absolute
2593                         expiration, 
2594                         uint64_t uid)
2595 {
2596   struct ProcessGetContext *pgc = cls;
2597   GNUNET_HashCode dhash;
2598   GNUNET_HashCode mhash;
2599   struct PutMessage *reply;
2600   
2601   if (NULL == key)
2602     {
2603       /* no more results */
2604       if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) ==  ROUTING_POLICY_FORWARD) &&
2605            ( (0 == pgc->results_found) ||
2606              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2607              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2608              (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2609         {
2610           GNUNET_SCHEDULER_add_continuation (sched,
2611                                              &forward_get_request,
2612                                              pgc,
2613                                              GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2614         }
2615       else
2616         {
2617           if (pgc->bf != NULL)
2618             GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2619           GNUNET_free (pgc); 
2620         }
2621       next_ds_request ();
2622       return;
2623     }
2624   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2625     {
2626       handle_on_demand_block (key, size, data, type, priority, 
2627                               anonymity, expiration, uid,
2628                               &process_p2p_get_result,
2629                               pgc);
2630       return;
2631     }
2632   /* check for duplicates */
2633   GNUNET_CRYPTO_hash (data, size, &dhash);
2634   mingle_hash (&dhash, 
2635                pgc->mingle,
2636                &mhash);
2637   if ( (pgc->bf != NULL) &&
2638        (GNUNET_YES ==
2639         GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2640                                            &mhash)) )
2641     {      
2642 #if DEBUG_FS
2643       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2644                   "Result from datastore filtered by bloomfilter.\n");
2645 #endif
2646       GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2647       return;
2648     }
2649   pgc->results_found++;
2650   if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2651        (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2652        (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2653     {
2654       if (pgc->bf == NULL)
2655         {
2656           pgc->bf_size = 32;
2657           pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2658                                                        pgc->bf_size, 
2659                                                        BLOOMFILTER_K);
2660         }
2661       GNUNET_CONTAINER_bloomfilter_add (pgc->bf, 
2662                                         &mhash);
2663     }
2664
2665   reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2666   reply->header.size = htons (sizeof (struct PutMessage) + size);
2667   reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2668   reply->type = htonl (type);
2669   reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2670   memcpy (&reply[1], data, size);
2671   GNUNET_CORE_notify_transmit_ready (core,
2672                                      pgc->priority,
2673                                      ACCEPTABLE_REPLY_DELAY,
2674                                      &pgc->reply_to,
2675                                      sizeof (struct PutMessage) + size,
2676                                      &transmit_message,
2677                                      reply);
2678   if ( (GNUNET_YES == test_load_too_high()) ||
2679        (pgc->results_found > 5 + 2 * pgc->priority) )
2680     {
2681       GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2682       pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2683       return;
2684     }
2685   GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2686 }
2687   
2688
2689 /**
2690  * We're processing a GET request from another peer.  Give it to our
2691  * local datastore.
2692  *
2693  * @param cls our "struct ProcessGetContext"
2694  * @param ok did we get a datastore slice or not?
2695  */
2696 static void
2697 ds_get_request (void *cls, 
2698                 int ok)
2699 {
2700   struct ProcessGetContext *pgc = cls;
2701   uint32_t type;
2702   struct GNUNET_TIME_Relative timeout;
2703
2704   if (GNUNET_OK != ok)
2705     {
2706       /* no point in doing P2P stuff if we can't even do local */
2707       GNUNET_free (dsh);
2708       return;
2709     }
2710   type = pgc->type;
2711   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2712     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2713   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2714                                            (pgc->priority + 1));
2715   GNUNET_DATASTORE_get (dsh,
2716                         &pgc->query,
2717                         type,
2718                         &process_p2p_get_result,
2719                         pgc,
2720                         timeout);
2721 }
2722
2723
2724 /**
2725  * The priority level imposes a bound on the maximum
2726  * value for the ttl that can be requested.
2727  *
2728  * @param ttl_in requested ttl
2729  * @param prio given priority
2730  * @return ttl_in if ttl_in is below the limit,
2731  *         otherwise the ttl-limit for the given priority
2732  */
2733 static int32_t
2734 bound_ttl (int32_t ttl_in, uint32_t prio)
2735 {
2736   unsigned long long allowed;
2737
2738   if (ttl_in <= 0)
2739     return ttl_in;
2740   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2741   if (ttl_in > allowed)      
2742     {
2743       if (allowed >= (1 << 30))
2744         return 1 << 30;
2745       return allowed;
2746     }
2747   return ttl_in;
2748 }
2749
2750
2751 /**
2752  * We've received a request with the specified
2753  * priority.  Bound it according to how much
2754  * we trust the given peer.
2755  * 
2756  * @param prio_in requested priority
2757  * @param peer the peer making the request
2758  * @return effective priority
2759  */
2760 static uint32_t
2761 bound_priority (uint32_t prio_in,
2762                 const struct GNUNET_PeerIdentity *peer)
2763 {
2764   return 0; // FIXME!
2765 }
2766
2767
2768 /**
2769  * Handle P2P "GET" request.
2770  *
2771  * @param cls closure, always NULL
2772  * @param other the other peer involved (sender or receiver, NULL
2773  *        for loopback messages where we are both sender and receiver)
2774  * @param message the actual message
2775  * @param latency reported latency of the connection with 'other'
2776  * @param distance reported distance (DV) to 'other' 
2777  * @return GNUNET_OK to keep the connection open,
2778  *         GNUNET_SYSERR to close it (signal serious error)
2779  */
2780 static int
2781 handle_p2p_get (void *cls,
2782                 const struct GNUNET_PeerIdentity *other,
2783                 const struct GNUNET_MessageHeader *message,
2784                                   struct GNUNET_TIME_Relative latency,
2785                                   uint32_t distance)
2786 {
2787   uint16_t msize;
2788   const struct GetMessage *gm;
2789   unsigned int bits;
2790   const GNUNET_HashCode *opt;
2791   struct ProcessGetContext *pgc;
2792   uint32_t bm;
2793   size_t bfsize;
2794   uint32_t ttl_decrement;
2795   double preference;
2796   int net_load_up;
2797   int net_load_down;
2798
2799   msize = ntohs(message->size);
2800   if (msize < sizeof (struct GetMessage))
2801     {
2802       GNUNET_break_op (0);
2803       return GNUNET_SYSERR;
2804     }
2805   gm = (const struct GetMessage*) message;
2806   bm = ntohl (gm->hash_bitmap);
2807   bits = 0;
2808   while (bm > 0)
2809     {
2810       if (1 == (bm & 1))
2811         bits++;
2812       bm >>= 1;
2813     }
2814   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2815     {
2816       GNUNET_break_op (0);
2817       return GNUNET_SYSERR;
2818     }  
2819   opt = (const GNUNET_HashCode*) &gm[1];
2820   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2821   pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2822   if (bfsize > 0)
2823     {
2824       pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2825                                                    bfsize,
2826                                                    BLOOMFILTER_K);
2827       pgc->bf_size = bfsize;
2828     }
2829   pgc->type = ntohl (gm->type);
2830   pgc->bm = ntohl (gm->hash_bitmap);
2831   pgc->mingle = gm->filter_mutator;
2832   bits = 0;
2833   if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2834     pgc->reply_to.hashPubKey = opt[bits++];
2835   else
2836     pgc->reply_to = *other;
2837   if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2838     pgc->namespace = opt[bits++];
2839   else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2840     {
2841       GNUNET_break_op (0);
2842       GNUNET_free (pgc);
2843       return GNUNET_SYSERR;
2844     }
2845   if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2846     pgc->prime_target.hashPubKey = opt[bits++];
2847   /* note that we can really only check load here since otherwise
2848      peers could find out that we are overloaded by being disconnected
2849      after sending us a malformed query... */
2850   if (GNUNET_YES == test_load_too_high ())
2851     {
2852       if (NULL != pgc->bf)
2853         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2854       GNUNET_free (pgc);
2855 #if DEBUG_FS
2856       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857                   "Dropping query from `%s', this peer is too busy.\n",
2858                   GNUNET_i2s (other));
2859 #endif
2860       return GNUNET_OK;
2861     }
2862   net_load_up = 50; // FIXME
2863   net_load_down = 50; // FIXME
2864   pgc->policy = ROUTING_POLICY_NONE;
2865   if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2866        (net_load_down < IDLE_LOAD_THRESHOLD) )
2867     {
2868       pgc->policy |= ROUTING_POLICY_ALL;
2869       pgc->priority = 0; /* no charge */
2870     }
2871   else
2872     {
2873       pgc->priority = bound_priority (ntohl (gm->priority), other);
2874       if ( (net_load_up < 
2875             IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2876            (net_load_down < 
2877             IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2878         {
2879           pgc->policy |= ROUTING_POLICY_ALL;
2880         }
2881       else
2882         {
2883           // FIXME: is this sound?
2884           if (net_load_up < 90 + 10 * pgc->priority)
2885             pgc->policy |= ROUTING_POLICY_FORWARD;
2886           if (net_load_down < 90 + 10 * pgc->priority)
2887             pgc->policy |= ROUTING_POLICY_ANSWER;
2888         }
2889     }
2890   if (pgc->policy == ROUTING_POLICY_NONE)
2891     {
2892 #if DEBUG_FS
2893       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894                   "Dropping query from `%s', network saturated.\n",
2895                   GNUNET_i2s (other));
2896 #endif
2897       if (NULL != pgc->bf)
2898         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2899       GNUNET_free (pgc);
2900       return GNUNET_OK;     /* drop */
2901     }
2902   if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2903     pgc->priority = 0;  /* kill the priority (we cannot benefit) */
2904   pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2905   /* decrement ttl (always) */
2906   ttl_decrement = 2 * TTL_DECREMENT +
2907     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2908                               TTL_DECREMENT);
2909   if ( (pgc->ttl < 0) &&
2910        (pgc->ttl - ttl_decrement > 0) )
2911     {
2912 #if DEBUG_FS
2913       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914                   "Dropping query from `%s' due to TTL underflow.\n",
2915                   GNUNET_i2s (other));
2916 #endif
2917       /* integer underflow => drop (should be very rare)! */
2918       if (NULL != pgc->bf)
2919         GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2920       GNUNET_free (pgc);
2921       return GNUNET_OK;
2922     }
2923   pgc->ttl -= ttl_decrement;
2924   pgc->start_time = GNUNET_TIME_absolute_get ();
2925   preference = (double) pgc->priority;
2926   if (preference < QUERY_BANDWIDTH_VALUE)
2927     preference = QUERY_BANDWIDTH_VALUE;
2928   // FIXME: also reserve bandwidth for reply?
2929   (void) GNUNET_CORE_peer_change_preference (sched, cfg,
2930                                              other,
2931                                              GNUNET_TIME_UNIT_FOREVER_REL,
2932                                              0, 0, preference, NULL, NULL);
2933   if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2934     pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2935                                  &ds_get_request,
2936                                  pgc);
2937   else
2938     GNUNET_SCHEDULER_add_continuation (sched,
2939                                        &forward_get_request,
2940                                        pgc,
2941                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2942   return GNUNET_OK;
2943 }
2944
2945
2946 /**
2947  * Function called to notify us that we can now transmit a reply to a
2948  * client or peer.  "buf" will be NULL and "size" zero if the socket was
2949  * closed for writing in the meantime.
2950  *
2951  * @param cls closure, points to a "struct PendingRequest*" with
2952  *            one or more pending replies
2953  * @param size number of bytes available in buf
2954  * @param buf where the callee should write the message
2955  * @return number of bytes written to buf
2956  */
2957 static size_t
2958 transmit_result (void *cls,
2959                  size_t size, 
2960                  void *buf)
2961 {
2962   struct PendingRequest *pr = cls;
2963   char *cbuf = buf;
2964   struct PendingReply *reply;
2965   size_t ret;
2966
2967   ret = 0;
2968   while (NULL != (reply = pr->replies_pending))
2969     {
2970       if ( (reply->msize + ret < ret) ||
2971            (reply->msize + ret > size) )
2972         break;
2973       pr->replies_pending = reply->next;
2974       memcpy (&cbuf[ret], &reply[1], reply->msize);
2975       ret += reply->msize;
2976       GNUNET_free (reply);
2977     }
2978   return ret;
2979 }
2980
2981
2982 /**
2983  * Iterator over pending requests.
2984  *
2985  * @param cls response (struct ProcessReplyClosure)
2986  * @param key our query
2987  * @param value value in the hash map (meta-info about the query)
2988  * @return GNUNET_YES (we should continue to iterate)
2989  */
2990 static int
2991 process_reply (void *cls,
2992                const GNUNET_HashCode * key,
2993                void *value)
2994 {
2995   struct ProcessReplyClosure *prq = cls;
2996   struct PendingRequest *pr = value;
2997   struct PendingRequest *eer;
2998   struct PendingReply *reply;
2999   struct PutMessage *pm;
3000   struct ContentMessage *cm;
3001   GNUNET_HashCode chash;
3002   GNUNET_HashCode mhash;
3003   struct GNUNET_PeerIdentity target;
3004   size_t msize;
3005   uint32_t prio;
3006   struct GNUNET_TIME_Relative max_delay;
3007   
3008   GNUNET_CRYPTO_hash (prq->data,
3009                       prq->size,
3010                       &chash);
3011   switch (prq->type)
3012     {
3013     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3014     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3015       break;
3016     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3017       /* FIXME: does prq->namespace match our expectations? */
3018       /* then: fall-through??? */
3019     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3020       if (pr->bf != NULL) 
3021         {
3022           mingle_hash (&chash, pr->mingle, &mhash);
3023           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3024                                                                &mhash))
3025             return GNUNET_YES; /* duplicate */
3026           GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3027                                             &mhash);
3028         }
3029       break;
3030     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3031       // FIXME: any checks against duplicates for SKBlocks?
3032       break;
3033     }
3034   prio = pr->priority;
3035   prq->priority += pr->remaining_priority;
3036   pr->remaining_priority = 0;
3037   if (pr->client != NULL)
3038     {
3039       if (pr->replies_seen_size == pr->replies_seen_off)
3040         GNUNET_array_grow (pr->replies_seen,
3041                            pr->replies_seen_size,
3042                            pr->replies_seen_size * 2 + 4);
3043       pr->replies_seen[pr->replies_seen_off++] = chash;
3044       // FIXME: possibly recalculate BF!
3045     }
3046   if (pr->client == NULL)
3047     {
3048       msize = sizeof (struct ContentMessage) + prq->size;
3049       reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3050       reply->msize = msize;
3051       cm = (struct ContentMessage*) &reply[1];
3052       cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3053       cm->header.size = htons (msize);
3054       cm->type = htonl (prq->type);
3055       cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3056       reply->next = pr->replies_pending;
3057       pr->replies_pending = reply;
3058       memcpy (&reply[1], prq->data, prq->size);
3059       if (pr->cth != NULL)
3060         return GNUNET_YES;
3061       max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3062       if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3063         {
3064           /* estimate expiration time from time difference between
3065              first request that will be discarded and this request */
3066           eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3067           max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3068                                                            eer->start_time);
3069         }
3070       GNUNET_PEER_resolve (pr->source_pid,
3071                            &target);
3072       pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3073                                                    prio,
3074                                                    max_delay,
3075                                                    &target,
3076                                                    msize,
3077                                                    &transmit_result,
3078                                                    pr);
3079       if (NULL == pr->cth)
3080         {
3081           // FIXME: now what? discard?
3082         }
3083     }
3084   else
3085     {
3086       msize = sizeof (struct PutMessage) + prq->size;
3087       reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3088       reply->msize = msize;
3089       reply->next = pr->replies_pending;
3090       pm = (struct PutMessage*) &reply[1];
3091       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3092       pm->header.size = htons (msize);
3093       pm->type = htonl (prq->type);
3094       pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3095       pr->replies_pending = reply;
3096       memcpy (&reply[1], prq->data, prq->size);
3097       if (pr->th != NULL)
3098         return GNUNET_YES;
3099       pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3100                                                     msize,
3101                                                     GNUNET_TIME_UNIT_FOREVER_REL,
3102                                                     &transmit_result,
3103                                                     pr);
3104       if (pr->th == NULL)
3105         {
3106           // FIXME: need to try again later (not much
3107           // to do here specifically, but we need to
3108           // check somewhere else to handle this case!)
3109         }
3110     }
3111   // FIXME: implement hot-path routing statistics keeping!
3112   return GNUNET_YES;
3113 }
3114
3115
3116 /**
3117  * Check if the given KBlock is well-formed.
3118  *
3119  * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3120  * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3121  * @param query where to store the query that this block answers
3122  * @return GNUNET_OK if this is actually a well-formed KBlock
3123  */
3124 static int
3125 check_kblock (const struct KBlock *kb,
3126               size_t dsize,
3127               GNUNET_HashCode *query)
3128 {
3129   if (dsize < sizeof (struct KBlock))
3130     {
3131       GNUNET_break_op (0);
3132       return GNUNET_SYSERR;
3133     }
3134   if (dsize - sizeof (struct KBlock) !=
3135       ntohs (kb->purpose.size) 
3136       - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) 
3137       - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) ) 
3138     {
3139       GNUNET_break_op (0);
3140       return GNUNET_SYSERR;
3141     }
3142   if (GNUNET_OK !=
3143       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3144                                 &kb->purpose,
3145                                 &kb->signature,
3146                                 &kb->keyspace)) 
3147     {
3148       GNUNET_break_op (0);
3149       return GNUNET_SYSERR;
3150     }
3151   if (query != NULL)
3152     GNUNET_CRYPTO_hash (&kb->keyspace,
3153                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3154                         query);
3155   return GNUNET_OK;
3156 }
3157
3158
3159 /**
3160  * Check if the given SBlock is well-formed.
3161  *
3162  * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3163  * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3164  * @param query where to store the query that this block answers
3165  * @param namespace where to store the namespace that this block belongs to
3166  * @return GNUNET_OK if this is actually a well-formed SBlock
3167  */
3168 static int
3169 check_sblock (const struct SBlock *sb,
3170               size_t dsize,
3171               GNUNET_HashCode *query,   
3172               GNUNET_HashCode *namespace)
3173 {
3174   if (dsize < sizeof (struct SBlock))
3175     {
3176       GNUNET_break_op (0);
3177       return GNUNET_SYSERR;
3178     }
3179   if (dsize !=
3180       ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3181     {
3182       GNUNET_break_op (0);
3183       return GNUNET_SYSERR;
3184     }
3185   if (GNUNET_OK !=
3186       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3187                                 &sb->purpose,
3188                                 &sb->signature,
3189                                 &sb->subspace)) 
3190     {
3191       GNUNET_break_op (0);
3192       return GNUNET_SYSERR;
3193     }
3194   if (query != NULL)
3195     *query = sb->identifier;
3196   if (namespace != NULL)
3197     GNUNET_CRYPTO_hash (&sb->subspace,
3198                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3199                         namespace);
3200   return GNUNET_OK;
3201 }
3202
3203
3204 /**
3205  * Handle P2P "PUT" request.
3206  *
3207  * @param cls closure, always NULL
3208  * @param other the other peer involved (sender or receiver, NULL
3209  *        for loopback messages where we are both sender and receiver)
3210  * @param message the actual message
3211  * @param latency reported latency of the connection with 'other'
3212  * @param distance reported distance (DV) to 'other' 
3213  * @return GNUNET_OK to keep the connection open,
3214  *         GNUNET_SYSERR to close it (signal serious error)
3215  */
3216 static int
3217 handle_p2p_put (void *cls,
3218                 const struct GNUNET_PeerIdentity *other,
3219                 const struct GNUNET_MessageHeader *message,
3220                 struct GNUNET_TIME_Relative latency,
3221                 uint32_t distance)
3222 {
3223   const struct PutMessage *put;
3224   uint16_t msize;
3225   size_t dsize;
3226   uint32_t type;
3227   struct GNUNET_TIME_Absolute expiration;
3228   GNUNET_HashCode query;
3229   struct ProcessReplyClosure prq;
3230
3231   msize = ntohs (message->size);
3232   if (msize < sizeof (struct PutMessage))
3233     {
3234       GNUNET_break_op(0);
3235       return GNUNET_SYSERR;
3236     }
3237   put = (const struct PutMessage*) message;
3238   dsize = msize - sizeof (struct PutMessage);
3239   type = ntohl (put->type);
3240   expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3241
3242   /* first, validate! */
3243   switch (type)
3244     {
3245     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3246     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3247       GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3248       break;
3249     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3250       if (GNUNET_OK !=
3251           check_kblock ((const struct KBlock*) &put[1],
3252                         dsize,
3253                         &query))
3254         return GNUNET_SYSERR;
3255       break;
3256     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3257       if (GNUNET_OK !=
3258           check_sblock ((const struct SBlock*) &put[1],
3259                         dsize,
3260                         &query,
3261                         &prq.namespace))
3262         return GNUNET_SYSERR;
3263       break;
3264     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3265       // FIXME -- validate SKBLOCK!
3266       GNUNET_break (0);
3267       return GNUNET_OK;
3268     default:
3269       /* unknown block type */
3270       GNUNET_break_op (0);
3271       return GNUNET_SYSERR;
3272     }
3273
3274   /* now, lookup 'query' */
3275   prq.data = (const void*) &put[1];
3276   prq.size = dsize;
3277   prq.type = type;
3278   prq.expiration = expiration;
3279   prq.priority = 0;
3280   GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3281                                               &query,
3282                                               &process_reply,
3283                                               &prq);
3284   // FIXME: if migration is on and load is low,
3285   // queue to store data in datastore;
3286   // use "prq.priority" for that!
3287   return GNUNET_OK;
3288 }
3289
3290
3291 /**
3292  * List of handlers for P2P messages
3293  * that we care about.
3294  */
3295 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3296   {
3297     { &handle_p2p_get, 
3298       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3299     { &handle_p2p_put, 
3300       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3301     { NULL, 0, 0 }
3302   };
3303
3304
3305 /**
3306  * Process fs requests.
3307  *
3308  * @param cls closure
3309  * @param s scheduler to use
3310  * @param server the initialized server
3311  * @param c configuration to use
3312  */
3313 static void
3314 run (void *cls,
3315      struct GNUNET_SCHEDULER_Handle *s,
3316      struct GNUNET_SERVER_Handle *server,
3317      const struct GNUNET_CONFIGURATION_Handle *c)
3318 {
3319   sched = s;
3320   cfg = c;
3321
3322   ifm = GNUNET_CONTAINER_multihashmap_create (128);
3323   requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3324   requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3325   connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3326   requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
3327   read_index_list ();
3328   dsh = GNUNET_DATASTORE_connect (cfg,
3329                                   sched);
3330   core = GNUNET_CORE_connect (sched,
3331                               cfg,
3332                               GNUNET_TIME_UNIT_FOREVER_REL,
3333                               NULL,
3334                               NULL,
3335                               NULL,
3336                               &peer_connect_handler,
3337                               &peer_disconnect_handler,
3338                               NULL, GNUNET_NO,
3339                               NULL, GNUNET_NO,
3340                               p2p_handlers);
3341
3342   GNUNET_SERVER_disconnect_notify (server, 
3343                                    &handle_client_disconnect,
3344                                    NULL);
3345   GNUNET_SERVER_add_handlers (server, handlers);
3346   GNUNET_SCHEDULER_add_delayed (sched,
3347                                 GNUNET_TIME_UNIT_FOREVER_REL,
3348                                 &shutdown_task,
3349                                 NULL);
3350   if (NULL == dsh)
3351     {
3352       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3353                   _("Failed to connect to `%s' service.\n"),
3354                   "datastore");
3355       GNUNET_SCHEDULER_shutdown (sched);
3356       return;
3357     }
3358   if (NULL == core)
3359     {
3360       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3361                   _("Failed to connect to `%s' service.\n"),
3362                   "core");
3363       GNUNET_SCHEDULER_shutdown (sched);
3364       return;
3365     }
3366 }
3367
3368
3369 /**
3370  * The main function for the fs service.
3371  *
3372  * @param argc number of arguments from the command line
3373  * @param argv command line arguments
3374  * @return 0 ok, 1 on error
3375  */
3376 int
3377 main (int argc, char *const *argv)
3378 {
3379   return (GNUNET_OK ==
3380           GNUNET_SERVICE_run (argc,
3381                               argv,
3382                               "fs",
3383                               GNUNET_SERVICE_OPTION_NONE,
3384                               &run, NULL)) ? 0 : 1;
3385 }
3386
3387 /* end of gnunet-service-fs.c */