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