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