fixing drq code
[oweals/gnunet.git] / src / fs / gnunet-service-fs.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file fs/gnunet-service-fs.c
23  * @brief gnunet anonymity protocol implementation
24  * @author Christian Grothoff
25  *
26  * TODO:
27  * - forward_request_task (P2P forwarding!) 
28  * - track stats for hot-path routing
29  * - implement hot-path routing decision procedure
30  * - detect duplicate requests (P2P and CS)
31  * - implement: bound_priority, test_load_too_high, validate_skblock
32  * - add content migration support (store locally)
33  * - add random delay
34  * - statistics
35  * 
36  */
37 #include "platform.h"
38 #include <float.h>
39 #include "gnunet_constants.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_datastore_service.h"
42 #include "gnunet_peer_lib.h"
43 #include "gnunet_protocols.h"
44 #include "gnunet_signatures.h"
45 #include "gnunet_util_lib.h"
46 #include "gnunet-service-fs_drq.h"
47 #include "gnunet-service-fs_indexing.h"
48 #include "fs.h"
49
50 /**
51  * Maximum number of outgoing messages we queue per peer.
52  * FIXME: set to a tiny value for testing; make configurable.
53  */
54 #define MAX_QUEUE_PER_PEER 2
55
56
57
58 /**
59  * Maximum number of requests (from other peers) that we're
60  * willing to have pending at any given point in time.
61  * FIXME: set from configuration (and 32 is a tiny value for testing only).
62  */
63 static uint64_t max_pending_requests = 32;
64
65
66 /**
67  * Information we keep for each pending reply.  The
68  * actual message follows at the end of this struct.
69  */
70 struct PendingMessage;
71
72
73 /**
74  * Function called upon completion of a transmission.
75  *
76  * @param cls closure
77  * @param pid ID of receiving peer, 0 on transmission error
78  */
79 typedef void (*TransmissionContinuation)(void * cls, 
80                                          GNUNET_PEER_Id tpid);
81
82
83 /**
84  * Information we keep for each pending reply.  The
85  * actual message follows at the end of this struct.
86  */
87 struct PendingMessage
88 {
89   /**
90    * This is a doubly-linked list of messages to the same peer.
91    */
92   struct PendingMessage *next;
93
94   /**
95    * This is a doubly-linked list of messages to the same peer.
96    */
97   struct PendingMessage *prev;
98
99   /**
100    * Entry in pending message list for this pending message.
101    */ 
102   struct PendingMessageList *pml;  
103
104   /**
105    * Function to call immediately once we have transmitted this
106    * message.
107    */
108   TransmissionContinuation cont;
109
110   /**
111    * Closure for cont.
112    */
113   void *cont_cls;
114
115   /**
116    * Size of the reply; actual reply message follows
117    * at the end of this struct.
118    */
119   size_t msize;
120   
121   /**
122    * How important is this message for us?
123    */
124   uint32_t priority;
125  
126 };
127
128
129 /**
130  * Information about a peer that we are connected to.
131  * We track data that is useful for determining which
132  * peers should receive our requests.  We also keep
133  * a list of messages to transmit to this peer.
134  */
135 struct ConnectedPeer
136 {
137
138   /**
139    * List of the last clients for which this peer successfully
140    * answered a query.
141    */
142   struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
143
144   /**
145    * List of the last PIDs for which
146    * this peer successfully answered a query;
147    * We use 0 to indicate no successful reply.
148    */
149   GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
150
151   /**
152    * Average delay between sending the peer a request and
153    * getting a reply (only calculated over the requests for
154    * which we actually got a reply).   Calculated
155    * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
156    */ 
157   struct GNUNET_TIME_Relative avg_delay;
158
159   /**
160    * Handle for an active request for transmission to this
161    * peer, or NULL.
162    */
163   struct GNUNET_CORE_TransmitHandle *cth;
164
165   /**
166    * Messages (replies, queries, content migration) we would like to
167    * send to this peer in the near future.  Sorted by priority, head.
168    */
169   struct PendingMessage *pending_messages_head;
170
171   /**
172    * Messages (replies, queries, content migration) we would like to
173    * send to this peer in the near future.  Sorted by priority, tail.
174    */
175   struct PendingMessage *pending_messages_tail;
176
177   /**
178    * Average priority of successful replies.  Calculated
179    * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
180    */
181   double avg_priority;
182
183   /**
184    * Increase in traffic preference still to be submitted
185    * to the core service for this peer. FIXME: double or 'uint64_t'?
186    */
187   double inc_preference;
188
189   /**
190    * The peer's identity.
191    */
192   GNUNET_PEER_Id pid;  
193
194   /**
195    * Size of the linked list of 'pending_messages'.
196    */
197   unsigned int pending_requests;
198
199   /**
200    * Which offset in "last_p2p_replies" will be updated next?
201    * (we go round-robin).
202    */
203   unsigned int last_p2p_replies_woff;
204
205   /**
206    * Which offset in "last_client_replies" will be updated next?
207    * (we go round-robin).
208    */
209   unsigned int last_client_replies_woff;
210
211 };
212
213
214 /**
215  * Information we keep for each pending request.  We should try to
216  * keep this struct as small as possible since its memory consumption
217  * is key to how many requests we can have pending at once.
218  */
219 struct PendingRequest;
220
221
222 /**
223  * Doubly-linked list of requests we are performing
224  * on behalf of the same client.
225  */
226 struct ClientRequestList
227 {
228
229   /**
230    * This is a doubly-linked list.
231    */
232   struct ClientRequestList *next;
233
234   /**
235    * This is a doubly-linked list.
236    */
237   struct ClientRequestList *prev;
238
239   /**
240    * Request this entry represents.
241    */
242   struct PendingRequest *req;
243
244   /**
245    * Client list this request belongs to.
246    */
247   struct ClientList *client_list;
248
249 };
250
251
252 /**
253  * Replies to be transmitted to the client.  The actual
254  * response message is allocated after this struct.
255  */
256 struct ClientResponseMessage
257 {
258   /**
259    * This is a doubly-linked list.
260    */
261   struct ClientResponseMessage *next;
262
263   /**
264    * This is a doubly-linked list.
265    */
266   struct ClientResponseMessage *prev;
267
268   /**
269    * Client list entry this response belongs to.
270    */
271   struct ClientList *client_list;
272
273   /**
274    * Number of bytes in the response.
275    */
276   size_t msize;
277 };
278
279
280 /**
281  * Linked list of clients we are performing requests
282  * for right now.
283  */
284 struct ClientList
285 {
286   /**
287    * This is a linked list.
288    */
289   struct ClientList *next;
290
291   /**
292    * ID of a client making a request, NULL if this entry is for a
293    * peer.
294    */
295   struct GNUNET_SERVER_Client *client;
296
297   /**
298    * Head of list of requests performed on behalf
299    * of this client right now.
300    */
301   struct ClientRequestList *rl_head;
302
303   /**
304    * Tail of list of requests performed on behalf
305    * of this client right now.
306    */
307   struct ClientRequestList *rl_tail;
308
309   /**
310    * Head of linked list of responses.
311    */
312   struct ClientResponseMessage *res_head;
313
314   /**
315    * Tail of linked list of responses.
316    */
317   struct ClientResponseMessage *res_tail;
318
319   /**
320    * Context for sending replies.
321    */
322   struct GNUNET_CONNECTION_TransmitHandle *th;
323
324 };
325
326
327 /**
328  * Hash map entry of requests we are performing
329  * on behalf of the same peer.
330  */
331 struct PeerRequestEntry
332 {
333
334   /**
335    * Request this entry represents.
336    */
337   struct PendingRequest *req;
338
339   /**
340    * Entry of peer responsible for this entry.
341    */
342   struct ConnectedPeer *cp;
343
344 };
345
346
347 /**
348  * Doubly-linked list of messages we are performing
349  * due to a pending request.
350  */
351 struct PendingMessageList
352 {
353
354   /**
355    * This is a doubly-linked list of messages on behalf of the same request.
356    */
357   struct PendingMessageList *next;
358
359   /**
360    * This is a doubly-linked list of messages on behalf of the same request.
361    */
362   struct PendingMessageList *prev;
363
364   /**
365    * Message this entry represents.
366    */
367   struct PendingMessage *pm;
368
369   /**
370    * Request this entry belongs to.
371    */
372   struct PendingRequest *req;
373
374   /**
375    * Peer this message is targeted for.
376    */
377   struct ConnectedPeer *target;
378
379 };
380
381
382 /**
383  * Information we keep for each pending request.  We should try to
384  * keep this struct as small as possible since its memory consumption
385  * is key to how many requests we can have pending at once.
386  */
387 struct PendingRequest
388 {
389
390   /**
391    * If this request was made by a client, this is our entry in the
392    * client request list; otherwise NULL.
393    */
394   struct ClientRequestList *client_request_list;
395   
396   /**
397    * If this request was made by a peer, this is our entry in the
398    * per-peer multi-hash map; otherwise NULL.
399    */
400   struct PeerRequestEntry *pht_entry;
401
402   /**
403    * If this is a namespace query, pointer to the hash of the public
404    * key of the namespace; otherwise NULL.  Pointer will be to the 
405    * end of this struct (so no need to free it).
406    */
407   const GNUNET_HashCode *namespace;
408
409   /**
410    * Bloomfilter we use to filter out replies that we don't care about
411    * (anymore).  NULL as long as we are interested in all replies.
412    */
413   struct GNUNET_CONTAINER_BloomFilter *bf;
414
415   /**
416    * Context of our GNUNET_CORE_peer_change_preference call.
417    */
418   struct GNUNET_CORE_InformationRequestContext *irc;
419
420   /**
421    * Hash code of all replies that we have seen so far (only valid
422    * if client is not NULL since we only track replies like this for
423    * our own clients).
424    */
425   GNUNET_HashCode *replies_seen;
426
427   /**
428    * Node in the heap representing this entry; NULL
429    * if we have no heap node.
430    */
431   struct GNUNET_CONTAINER_HeapNode *hnode;
432
433   /**
434    * Head of list of messages being performed on behalf of this
435    * request.
436    */
437   struct PendingMessageList *pending_head;
438
439   /**
440    * Tail of list of messages being performed on behalf of this
441    * request.
442    */
443   struct PendingMessageList *pending_tail;
444
445   /**
446    * When did we first see this request (form this peer), or, if our
447    * client is initiating, when did we last initiate a search?
448    */
449   struct GNUNET_TIME_Absolute start_time;
450
451   /**
452    * The query that this request is for.
453    */
454   GNUNET_HashCode query;
455
456   /**
457    * The task responsible for transmitting queries
458    * for this request.
459    */
460   GNUNET_SCHEDULER_TaskIdentifier task;
461
462   /**
463    * (Interned) Peer identifier that identifies a preferred target
464    * for requests.
465    */
466   GNUNET_PEER_Id target_pid;
467
468   /**
469    * (Interned) Peer identifiers of peers that have already
470    * received our query for this content.
471    */
472   GNUNET_PEER_Id *used_pids;
473   
474   /**
475    * Our entry in the DRQ (non-NULL while we wait for our
476    * turn to interact with the local database).
477    */
478   struct DatastoreRequestQueue *drq;
479
480   /**
481    * Size of the 'bf' (in bytes).
482    */
483   size_t bf_size;
484
485   /**
486    * Desired anonymity level; only valid for requests from a local client.
487    */
488   uint32_t anonymity_level;
489
490   /**
491    * How many entries in "used_pids" are actually valid?
492    */
493   unsigned int used_pids_off;
494
495   /**
496    * How long is the "used_pids" array?
497    */
498   unsigned int used_pids_size;
499
500   /**
501    * Number of results found for this request.
502    */
503   unsigned int results_found;
504
505   /**
506    * How many entries in "replies_seen" are actually valid?
507    */
508   unsigned int replies_seen_off;
509
510   /**
511    * How long is the "replies_seen" array?
512    */
513   unsigned int replies_seen_size;
514   
515   /**
516    * Priority with which this request was made.  If one of our clients
517    * made the request, then this is the current priority that we are
518    * using when initiating the request.  This value is used when
519    * we decide to reward other peers with trust for providing a reply.
520    */
521   uint32_t priority;
522
523   /**
524    * Priority points left for us to spend when forwarding this request
525    * to other peers.
526    */
527   uint32_t remaining_priority;
528
529   /**
530    * Number to mingle hashes for bloom-filter
531    * tests with.
532    */
533   int32_t mingle;
534
535   /**
536    * TTL with which we saw this request (or, if we initiated, TTL that
537    * we used for the request).
538    */
539   int32_t ttl;
540   
541   /**
542    * Type of the content that this request is for.
543    */
544   uint32_t type;
545
546 };
547
548
549 /**
550  * Our scheduler.
551  */
552 static struct GNUNET_SCHEDULER_Handle *sched;
553
554 /**
555  * Our configuration.
556  */
557 const struct GNUNET_CONFIGURATION_Handle *cfg;
558
559 /**
560  * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
561  */
562 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
563
564 /**
565  * Map of peer identifiers to "struct PendingRequest" (for that peer).
566  */
567 static struct GNUNET_CONTAINER_MultiHashMap *peer_request_map;
568
569 /**
570  * Map of query identifiers to "struct PendingRequest" (for that query).
571  */
572 static struct GNUNET_CONTAINER_MultiHashMap *query_request_map;
573
574 /**
575  * Heap with the request that will expire next at the top.  Contains
576  * pointers of type "struct PendingRequest*"; these will *also* be
577  * aliased from the "requests_by_peer" data structures and the
578  * "requests_by_query" table.  Note that requests from our clients
579  * don't expire and are thus NOT in the "requests_by_expiration"
580  * (or the "requests_by_peer" tables).
581  */
582 static struct GNUNET_CONTAINER_Heap *requests_by_expiration_heap;
583
584 /**
585  * Linked list of clients we are currently processing requests for.
586  */
587 struct ClientList *client_list;
588
589 /**
590  * Pointer to handle to the core service (points to NULL until we've
591  * connected to it).
592  */
593 struct GNUNET_CORE_Handle *core;
594
595
596 /* ******************* clean up functions ************************ */
597
598
599 /**
600  * We're done with a particular message list entry.
601  * Free all associated resources.
602  * 
603  * @param pml entry to destroy
604  */
605 static void
606 destroy_pending_message_list_entry (struct PendingMessageList *pml)
607 {
608   GNUNET_CONTAINER_DLL_remove (pml->req->pending_head,
609                                pml->req->pending_tail,
610                                pml);
611   GNUNET_CONTAINER_DLL_remove (pml->target->pending_messages_head,
612                                pml->target->pending_messages_tail,
613                                pml->pm);
614   pml->target->pending_requests--;
615   GNUNET_free (pml->pm);
616   GNUNET_free (pml);
617 }
618
619
620 /**
621  * Destroy the given pending message (and call the respective
622  * continuation).
623  *
624  * @param pm message to destroy
625  * @param tpid id of peer that the message was delivered to, or 0 for none
626  */
627 static void
628 destroy_pending_message (struct PendingMessage *pm,
629                          GNUNET_PEER_Id tpid)
630 {
631   struct PendingMessageList *pml = pm->pml;
632
633   GNUNET_assert (pml->pm == pm);
634   GNUNET_assert ( (tpid == 0) || (tpid == pml->target->pid) );
635   pm->cont (pm->cont_cls, 0);  
636   destroy_pending_message_list_entry (pml);
637 }
638
639
640
641 /**
642  * We're done processing a particular request.
643  * Free all associated resources.
644  *
645  * @param pr request to destroy
646  */
647 static void
648 destroy_pending_request (struct PendingRequest *pr)
649 {
650   struct GNUNET_PeerIdentity pid;
651
652   if (pr->hnode != NULL)
653     {
654       GNUNET_CONTAINER_heap_remove_node (requests_by_expiration_heap,
655                                          pr->hnode);
656       pr->hnode = NULL;
657     }
658   /* might have already been removed from map
659      in 'process_reply' if there was a unique 
660      reply; hence ignore the return value here */
661   (void) GNUNET_CONTAINER_multihashmap_remove (query_request_map,
662                                                &pr->query,
663                                                pr);
664   if (pr->drq != NULL)
665     {
666       GNUNET_FS_drq_get_cancel (pr->drq);
667       pr->drq = NULL;
668     }
669   if (pr->client_request_list != NULL)
670     {
671       GNUNET_CONTAINER_DLL_remove (pr->client_request_list->client_list->rl_head,
672                                    pr->client_request_list->client_list->rl_tail,
673                                    pr->client_request_list);
674       GNUNET_free (pr->client_request_list);
675       pr->client_request_list = NULL;
676     }
677   if (pr->pht_entry != NULL)
678     {
679       GNUNET_PEER_resolve (pr->pht_entry->cp->pid,
680                            &pid);
681       GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
682                                             &pid.hashPubKey,
683                                             pr->pht_entry);
684       GNUNET_free (pr->pht_entry);
685       pr->pht_entry = NULL;
686     }
687   if (pr->bf != NULL)
688     {
689       GNUNET_CONTAINER_bloomfilter_free (pr->bf);                                        
690       pr->bf = NULL;
691     }
692   if (pr->irc != NULL)
693     {
694       GNUNET_CORE_peer_change_preference_cancel (pr->irc);
695       pr->irc = NULL;
696     }
697   if (pr->replies_seen != NULL)
698     {
699       GNUNET_free (pr->replies_seen);
700       pr->replies_seen = NULL;
701     }
702   if (pr->task != GNUNET_SCHEDULER_NO_TASK)
703     {
704       GNUNET_SCHEDULER_cancel (sched,
705                                pr->task);
706       pr->task = GNUNET_SCHEDULER_NO_TASK;
707     }
708   while (NULL != pr->pending_head)    
709     destroy_pending_message_list_entry (pr->pending_head);
710   GNUNET_PEER_change_rc (pr->target_pid, -1);
711   if (pr->used_pids != NULL)
712     {
713       GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
714       GNUNET_free (pr->used_pids);
715       pr->used_pids_off = 0;
716       pr->used_pids_size = 0;
717       pr->used_pids = NULL;
718     }
719   GNUNET_free (pr);
720 }
721
722
723 /**
724  * Method called whenever a given peer connects.
725  *
726  * @param cls closure, not used
727  * @param peer peer identity this notification is about
728  * @param latency reported latency of the connection with 'other'
729  * @param distance reported distance (DV) to 'other' 
730  */
731 static void 
732 peer_connect_handler (void *cls,
733                       const struct
734                       GNUNET_PeerIdentity * peer,
735                       struct GNUNET_TIME_Relative latency,
736                       uint32_t distance)
737 {
738   struct ConnectedPeer *cp;
739
740   cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
741   cp->pid = GNUNET_PEER_intern (peer);
742   GNUNET_CONTAINER_multihashmap_put (connected_peers,
743                                      &peer->hashPubKey,
744                                      cp,
745                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
746 }
747
748
749 /**
750  * Free (each) request made by the peer.
751  *
752  * @param cls closure, points to peer that the request belongs to
753  * @param key current key code
754  * @param value value in the hash map
755  * @return GNUNET_YES (we should continue to iterate)
756  */
757 static int
758 destroy_request (void *cls,
759                  const GNUNET_HashCode * key,
760                  void *value)
761 {
762   const struct GNUNET_PeerIdentity * peer = cls;
763   struct PendingRequest *pr = value;
764   
765   GNUNET_CONTAINER_multihashmap_remove (peer_request_map,
766                                         &peer->hashPubKey,
767                                         pr);
768   destroy_pending_request (pr);
769   return GNUNET_YES;
770 }
771
772
773 /**
774  * Method called whenever a peer disconnects.
775  *
776  * @param cls closure, not used
777  * @param peer peer identity this notification is about
778  */
779 static void
780 peer_disconnect_handler (void *cls,
781                          const struct
782                          GNUNET_PeerIdentity * peer)
783 {
784   struct ConnectedPeer *cp;
785   struct PendingMessage *pm;
786   unsigned int i;
787
788   GNUNET_CONTAINER_multihashmap_get_multiple (peer_request_map,
789                                               &peer->hashPubKey,
790                                               &destroy_request,
791                                               (void*) peer);
792   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
793                                           &peer->hashPubKey);
794   if (cp == NULL)
795     return;
796   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
797     {
798       if (NULL != cp->last_client_replies[i])
799         {
800           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
801           cp->last_client_replies[i] = NULL;
802         }
803     }
804   GNUNET_CONTAINER_multihashmap_remove (connected_peers,
805                                         &peer->hashPubKey,
806                                         cp);
807   GNUNET_PEER_change_rc (cp->pid, -1);
808   GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
809   if (NULL != cp->cth)
810     GNUNET_CORE_notify_transmit_ready_cancel (cp->cth);
811   while (NULL != (pm = cp->pending_messages_head))
812     destroy_pending_message (pm, 0 /* delivery failed */);
813   GNUNET_break (0 == cp->pending_requests);
814   GNUNET_free (cp);
815 }
816
817
818 /**
819  * Iterator over hash map entries that removes all occurences
820  * of the given 'client' from the 'last_client_replies' of the
821  * given connected peer.
822  *
823  * @param cls closure, the 'struct GNUNET_SERVER_Client*' to remove
824  * @param key current key code (unused)
825  * @param value value in the hash map (the 'struct ConnectedPeer*' to change)
826  * @return GNUNET_YES (we should continue to iterate)
827  */
828 static int
829 remove_client_from_last_client_replies (void *cls,
830                                         const GNUNET_HashCode * key,
831                                         void *value)
832 {
833   struct GNUNET_SERVER_Client *client = cls;
834   struct ConnectedPeer *cp = value;
835   unsigned int i;
836
837   for (i=0;i<CS2P_SUCCESS_LIST_SIZE;i++)
838     {
839       if (cp->last_client_replies[i] == client)
840         {
841           GNUNET_SERVER_client_drop (cp->last_client_replies[i]);
842           cp->last_client_replies[i] = NULL;
843         }
844     }  
845   return GNUNET_YES;
846 }
847
848
849 /**
850  * A client disconnected.  Remove all of its pending queries.
851  *
852  * @param cls closure, NULL
853  * @param client identification of the client
854  */
855 static void
856 handle_client_disconnect (void *cls,
857                           struct GNUNET_SERVER_Client
858                           * client)
859 {
860   struct ClientList *pos;
861   struct ClientList *prev;
862   struct ClientRequestList *rcl;
863   struct ClientResponseMessage *creply;
864
865   if (client == NULL)
866     return; /* huh? is this allowed? */
867   prev = NULL;
868   pos = client_list;
869   while ( (NULL != pos) &&
870           (pos->client != client) )
871     {
872       prev = pos;
873       pos = pos->next;
874     }
875   if (pos == NULL)
876     return; /* no requests pending for this client */
877   while (NULL != (rcl = pos->rl_head))
878     destroy_pending_request (rcl->req);
879   if (prev == NULL)
880     client_list = pos->next;
881   else
882     prev->next = pos->next;
883   if (pos->th != NULL)
884     {
885       GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->th);
886       pos->th = NULL;
887     }
888   while (NULL != (creply = pos->res_head))
889     {
890       GNUNET_CONTAINER_DLL_remove (pos->res_head,
891                                    pos->res_tail,
892                                    creply);
893       GNUNET_free (creply);
894     }    
895   GNUNET_SERVER_client_drop (pos->client);
896   GNUNET_free (pos);
897   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
898                                          &remove_client_from_last_client_replies,
899                                          client);
900 }
901
902
903 /**
904  * Iterator to free peer entries.
905  *
906  * @param cls closure, unused
907  * @param key current key code
908  * @param value value in the hash map (peer entry)
909  * @return GNUNET_YES (we should continue to iterate)
910  */
911 static int 
912 clean_peer (void *cls,
913             const GNUNET_HashCode * key,
914             void *value)
915 {
916   peer_disconnect_handler (NULL, (const struct GNUNET_PeerIdentity*) key);
917   return GNUNET_YES;
918 }
919
920
921 /**
922  * Task run during shutdown.
923  *
924  * @param cls unused
925  * @param tc unused
926  */
927 static void
928 shutdown_task (void *cls,
929                const struct GNUNET_SCHEDULER_TaskContext *tc)
930 {
931   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
932                                          &clean_peer,
933                                          NULL);
934   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
935   connected_peers = NULL;
936   while (client_list != NULL)
937     handle_client_disconnect (NULL,
938                               client_list->client);
939   GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
940   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
941   requests_by_expiration_heap = 0;
942   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (query_request_map));
943   GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
944   query_request_map = NULL;
945   GNUNET_break (0 == GNUNET_CONTAINER_multihashmap_size (peer_request_map));
946   GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
947   peer_request_map = NULL;
948   GNUNET_assert (NULL != core);
949   GNUNET_CORE_disconnect (core);
950   core = NULL;
951   sched = NULL;
952   cfg = NULL;  
953 }
954
955
956 /* ******************* Utility functions  ******************** */
957
958
959 /**
960  * Transmit the given message by copying it to the target buffer
961  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
962  * for writing in the meantime.  In that case, do nothing
963  * (the disconnect or shutdown handler will take care of the rest).
964  * If we were able to transmit messages and there are still more
965  * pending, ask core again for further calls to this function.
966  *
967  * @param cls closure, pointer to the 'struct ConnectedPeer*'
968  * @param size number of bytes available in buf
969  * @param buf where the callee should write the message
970  * @return number of bytes written to buf
971  */
972 static size_t
973 transmit_to_peer (void *cls,
974                   size_t size, void *buf)
975 {
976   struct ConnectedPeer *cp = cls;
977   char *cbuf = buf;
978   struct GNUNET_PeerIdentity pid;
979   struct PendingMessage *pm;
980   size_t msize;
981   
982   cp->cth = NULL;
983   if (NULL == buf)
984     {
985 #if DEBUG_FS
986       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987                   "Dropping reply, core too busy.\n");
988 #endif
989       return 0;
990     }
991   msize = 0;
992   while ( (NULL != (pm = cp->pending_messages_head) ) &&
993           (pm->msize <= size) )
994     {
995       memcpy (&cbuf[msize], &pm[1], pm->msize);
996       msize += pm->msize;
997       size -= pm->msize;
998       destroy_pending_message (pm, cp->pid);
999     }
1000   if (NULL != pm)
1001     {
1002       GNUNET_PEER_resolve (cp->pid,
1003                            &pid);
1004       cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1005                                                    pm->priority,
1006                                                    GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1007                                                    &pid,
1008                                                    pm->msize,
1009                                                    &transmit_to_peer,
1010                                                    pm);
1011     }
1012   return msize;
1013 }
1014
1015
1016 /**
1017  * Add a message to the set of pending messages for the given peer.
1018  *
1019  * @param cp peer to send message to
1020  * @param pm message to queue
1021  * @param pr request on which behalf this message is being queued
1022  */
1023 static void
1024 add_to_pending_messages_for_peer (struct ConnectedPeer *cp,
1025                                   struct PendingMessage *pm,
1026                                   struct PendingRequest *pr)
1027 {
1028   struct PendingMessage *pos;
1029   struct PendingMessageList *pml;
1030   struct GNUNET_PeerIdentity pid;
1031
1032   GNUNET_assert (pm->next == NULL);
1033   GNUNET_assert (pm->pml == NULL);    
1034   pml = GNUNET_malloc (sizeof (struct PendingMessageList));
1035   pml->req = pr;
1036   pml->target = cp;
1037   pml->pm = pm;
1038   pm->pml = pml;  
1039   GNUNET_CONTAINER_DLL_insert (pr->pending_head,
1040                                pr->pending_tail,
1041                                pml);
1042   pos = cp->pending_messages_head;
1043   while ( (pos != NULL) &&
1044           (pm->priority < pos->priority) )
1045     pos = pos->next;    
1046   GNUNET_CONTAINER_DLL_insert_after (cp->pending_messages_head,
1047                                      cp->pending_messages_tail,
1048                                      pos,
1049                                      pm);
1050   cp->pending_requests++;
1051   if (cp->pending_requests > MAX_QUEUE_PER_PEER)
1052     destroy_pending_message (cp->pending_messages_tail, 0);  
1053   if (cp->cth == NULL)
1054     {
1055       /* need to schedule transmission */
1056       GNUNET_PEER_resolve (cp->pid, &pid);
1057       cp->cth = GNUNET_CORE_notify_transmit_ready (core,
1058                                                    cp->pending_messages_head->priority,
1059                                                    GNUNET_TIME_UNIT_FOREVER_REL,
1060                                                    &pid,
1061                                                    cp->pending_messages_head->msize,
1062                                                    &transmit_to_peer,
1063                                                    cp);
1064     }
1065   if (cp->cth == NULL)
1066     {
1067       /* FIXME: call stats (rare, bad case) */
1068     }
1069 }
1070
1071
1072 /**
1073  * Mingle hash with the mingle_number to produce different bits.
1074  */
1075 static void
1076 mingle_hash (const GNUNET_HashCode * in,
1077              int32_t mingle_number, 
1078              GNUNET_HashCode * hc)
1079 {
1080   GNUNET_HashCode m;
1081
1082   GNUNET_CRYPTO_hash (&mingle_number, 
1083                       sizeof (int32_t), 
1084                       &m);
1085   GNUNET_CRYPTO_hash_xor (&m, in, hc);
1086 }
1087
1088
1089 /**
1090  * Test if the load on this peer is too high
1091  * to even consider processing the query at
1092  * all.
1093  * 
1094  * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
1095  */
1096 static int
1097 test_load_too_high ()
1098 {
1099   return GNUNET_NO; // FIXME
1100 }
1101
1102
1103 /* ******************* Pending Request Refresh Task ******************** */
1104
1105
1106 /**
1107  * Function called after we either failed or succeeded
1108  * at transmitting a query to a peer.  
1109  *
1110  * @param cls the requests "struct PendingRequest*"
1111  * @param pid ID of receiving peer, 0 on transmission error
1112  */
1113 static void
1114 transmit_query_continuation (void *cls,
1115                              GNUNET_PEER_Id tpid)
1116 {
1117   struct PendingRequest *pr = cls;
1118
1119   if (tpid == 0)    
1120     return;    
1121   GNUNET_PEER_change_rc (tpid, 1);
1122   if (pr->used_pids_off == pr->used_pids_size)
1123     GNUNET_array_grow (pr->used_pids,
1124                        pr->used_pids_size,
1125                        pr->used_pids_size * 2 + 2);
1126   pr->used_pids[pr->used_pids_off++] = tpid;
1127 }
1128
1129
1130 #if 0
1131 /**
1132  * How many bytes should a bloomfilter be if we have already seen
1133  * entry_count responses?  Note that BLOOMFILTER_K gives us the number
1134  * of bits set per entry.  Furthermore, we should not re-size the
1135  * filter too often (to keep it cheap).
1136  *
1137  * Since other peers will also add entries but not resize the filter,
1138  * we should generally pick a slightly larger size than what the
1139  * strict math would suggest.
1140  *
1141  * @return must be a power of two and smaller or equal to 2^15.
1142  */
1143 static size_t
1144 compute_bloomfilter_size (unsigned int entry_count)
1145 {
1146   size_t size;
1147   unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1148   uint16_t max = 1 << 15;
1149
1150   if (entry_count > max)
1151     return max;
1152   size = 8;
1153   while ((size < max) && (size < ideal))
1154     size *= 2;
1155   if (size > max)
1156     return max;
1157   return size;
1158 }
1159
1160
1161 /**
1162  * Recalculate our bloom filter for filtering replies.
1163  *
1164  * @param count number of entries we are filtering right now
1165  * @param mingle set to our new mingling value
1166  * @param bf_size set to the size of the bloomfilter
1167  * @param entries the entries to filter
1168  * @return updated bloomfilter, NULL for none
1169  */
1170 static struct GNUNET_CONTAINER_BloomFilter *
1171 refresh_bloomfilter (unsigned int count,
1172                      int32_t * mingle,
1173                      size_t *bf_size,
1174                      const GNUNET_HashCode *entries)
1175 {
1176   struct GNUNET_CONTAINER_BloomFilter *bf;
1177   size_t nsize;
1178   unsigned int i;
1179   GNUNET_HashCode mhash;
1180
1181   if (0 == count)
1182     return NULL;
1183   nsize = compute_bloomfilter_size (count);
1184   *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1185   *bf_size = nsize;
1186   bf = GNUNET_CONTAINER_bloomfilter_init (NULL, 
1187                                           nsize,
1188                                           BLOOMFILTER_K);
1189   for (i=0;i<count;i++)
1190     {
1191       mingle_hash (&entries[i], *mingle, &mhash);
1192       GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1193     }
1194   return bf;
1195 }
1196 #endif
1197
1198
1199 /**
1200  * We use a random delay to make the timing of requests less
1201  * predictable.  This function returns such a random delay.
1202  *
1203  * FIXME: make schedule dependent on the specifics of the request?
1204  * Or bandwidth and number of connected peers and load?
1205  *
1206  * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1207  */
1208 static struct GNUNET_TIME_Relative
1209 get_processing_delay ()
1210 {
1211   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1212                                         GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1213                                                                   TTL_DECREMENT));
1214 }
1215
1216
1217 /**
1218  * Function called after we've tried to reserve a certain amount of
1219  * bandwidth for a reply.  Check if we succeeded and if so send our
1220  * query.
1221  *
1222  * @param cls the requests "struct PendingRequest*"
1223  * @param peer identifies the peer
1224  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1225  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1226  * @param amount set to the amount that was actually reserved or unreserved
1227  * @param preference current traffic preference for the given peer
1228  */
1229 static void
1230 target_reservation_cb (void *cls,
1231                        const struct
1232                        GNUNET_PeerIdentity * peer,
1233                        unsigned int bpm_in,
1234                        unsigned int bpm_out,
1235                        int amount,
1236                        uint64_t preference)
1237 {
1238   struct PendingRequest *pr = cls;
1239   struct ConnectedPeer *cp;
1240   struct PendingMessage *pm;
1241   struct GetMessage *gm;
1242   GNUNET_HashCode *ext;
1243   char *bfdata;
1244   size_t msize;
1245   unsigned int k;
1246
1247   pr->irc = NULL;
1248   GNUNET_assert (peer != NULL);
1249   if (amount != DBLOCK_SIZE) 
1250     {
1251       /* FIXME: call stats... */
1252       return; /* this target round failed */    
1253     }
1254   // (3) transmit, update ttl/priority
1255   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1256                                           &peer->hashPubKey);
1257   if (cp == NULL)
1258     {
1259       /* Peer must have just left */
1260       return;
1261     }
1262   /* build message and insert message into priority queue */
1263   k = 0; // FIXME: count hash codes!
1264   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1265   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1266   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1267   pm->msize = msize;
1268   gm = (struct GetMessage*) &pm[1];
1269   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1270   gm->header.size = htons (msize);
1271   gm->type = htonl (pr->type);
1272   pr->remaining_priority /= 2;
1273   gm->priority = htonl (pr->remaining_priority);
1274   gm->ttl = htonl (pr->ttl);
1275   gm->filter_mutator = htonl(pr->mingle); // FIXME: bad endianess conversion?
1276   gm->hash_bitmap = htonl (42); // FIXME!
1277   gm->query = pr->query;
1278   ext = (GNUNET_HashCode*) &gm[1];
1279   // FIXME: setup "ext[0]..[k-1]"
1280   bfdata = (char *) &ext[k];
1281   if (pr->bf != NULL)
1282     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1283                                                bfdata,
1284                                                pr->bf_size);
1285   pm->cont = &transmit_query_continuation;
1286   pm->cont_cls = pr;
1287   add_to_pending_messages_for_peer (cp, pm, pr);
1288 }
1289
1290
1291
1292 /**
1293  * Closure used for "target_peer_select_cb".
1294  */
1295 struct PeerSelectionContext 
1296 {
1297   /**
1298    * The request for which we are selecting
1299    * peers.
1300    */
1301   struct PendingRequest *pr;
1302
1303   /**
1304    * Current "prime" target.
1305    */
1306   struct GNUNET_PeerIdentity target;
1307
1308   /**
1309    * How much do we like this target?
1310    */
1311   double target_score;
1312
1313 };
1314
1315
1316 /**
1317  * Function called for each connected peer to determine
1318  * which one(s) would make good targets for forwarding.
1319  *
1320  * @param cls closure (struct PeerSelectionContext)
1321  * @param key current key code (peer identity)
1322  * @param value value in the hash map (struct ConnectedPeer)
1323  * @return GNUNET_YES if we should continue to
1324  *         iterate,
1325  *         GNUNET_NO if not.
1326  */
1327 static int
1328 target_peer_select_cb (void *cls,
1329                        const GNUNET_HashCode * key,
1330                        void *value)
1331 {
1332   struct PeerSelectionContext *psc = cls;
1333   struct ConnectedPeer *cp = value;
1334   struct PendingRequest *pr = psc->pr;
1335   double score;
1336   unsigned int i;
1337   
1338   /* 1) check if we have already (recently) forwarded to this peer */
1339   for (i=0;i<pr->used_pids_off;i++)
1340     if (pr->used_pids[i] == cp->pid)
1341       return GNUNET_YES; /* skip */
1342   // 2) calculate how much we'd like to forward to this peer
1343   score = 42; // FIXME!
1344   // FIXME: also need API to gather data on responsiveness
1345   // of this peer (we have fields for that in 'cp', but
1346   // they are never set!)
1347   
1348   /* store best-fit in closure */
1349   if (score > psc->target_score)
1350     {
1351       psc->target_score = score;
1352       psc->target.hashPubKey = *key; 
1353     }
1354   return GNUNET_YES;
1355 }
1356   
1357
1358 /**
1359  * We're processing a GET request from another peer and have decided
1360  * to forward it to other peers.  This function is called periodically
1361  * and should forward the request to other peers until we have all
1362  * possible replies.  If we have transmitted the *only* reply to
1363  * the initiator we should destroy the pending request.  If we have
1364  * many replies in the queue to the initiator, we should delay sending
1365  * out more queries until the reply queue has shrunk some.
1366  *
1367  * @param cls our "struct ProcessGetContext *"
1368  * @param tc unused
1369  */
1370 static void
1371 forward_request_task (void *cls,
1372                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1373 {
1374   struct PendingRequest *pr = cls;
1375   struct PeerSelectionContext psc;
1376   struct ConnectedPeer *cp; 
1377
1378   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1379                                            get_processing_delay (),
1380                                            &forward_request_task,
1381                                            pr);
1382   if (pr->irc != NULL)
1383     return; /* previous request still pending */
1384   /* (1) select target */
1385   psc.pr = pr;
1386   psc.target_score = DBL_MIN;
1387   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1388                                          &target_peer_select_cb,
1389                                          &psc);  
1390   if (psc.target_score == DBL_MIN)
1391     return; /* nobody selected */
1392
1393   /* (2) reserve reply bandwidth */
1394   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1395                                           &psc.target.hashPubKey);
1396   pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1397                                                 &psc.target,
1398                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
1399                                                 (uint32_t) -1 /* no limit */, 
1400                                                 DBLOCK_SIZE, 
1401                                                 (uint64_t) cp->inc_preference,
1402                                                 &target_reservation_cb,
1403                                                 pr);
1404   cp->inc_preference = 0.0;
1405 }
1406
1407
1408 /* **************************** P2P PUT Handling ************************ */
1409
1410
1411 /**
1412  * Function called after we either failed or succeeded
1413  * at transmitting a reply to a peer.  
1414  *
1415  * @param cls the requests "struct PendingRequest*"
1416  * @param pid ID of receiving peer, 0 on transmission error
1417  */
1418 static void
1419 transmit_reply_continuation (void *cls,
1420                              GNUNET_PEER_Id tpid)
1421 {
1422   struct PendingRequest *pr = cls;
1423
1424   switch (pr->type)
1425     {
1426     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1427     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1428       /* only one reply expected, done with the request! */
1429       destroy_pending_request (pr);
1430       break;
1431     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1432     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1433       break;
1434     default:
1435       GNUNET_break (0);
1436       break;
1437     }
1438 }
1439
1440
1441 /**
1442  * Check if the given KBlock is well-formed.
1443  *
1444  * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1445  * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1446  * @param query where to store the query that this block answers
1447  * @return GNUNET_OK if this is actually a well-formed KBlock
1448  */
1449 static int
1450 check_kblock (const struct KBlock *kb,
1451               size_t dsize,
1452               GNUNET_HashCode *query)
1453 {
1454   if (dsize < sizeof (struct KBlock))
1455     {
1456       GNUNET_break_op (0);
1457       return GNUNET_SYSERR;
1458     }
1459   if (dsize - sizeof (struct KBlock) !=
1460       ntohs (kb->purpose.size) 
1461       - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) 
1462       - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) ) 
1463     {
1464       GNUNET_break_op (0);
1465       return GNUNET_SYSERR;
1466     }
1467   if (GNUNET_OK !=
1468       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1469                                 &kb->purpose,
1470                                 &kb->signature,
1471                                 &kb->keyspace)) 
1472     {
1473       GNUNET_break_op (0);
1474       return GNUNET_SYSERR;
1475     }
1476   if (query != NULL)
1477     GNUNET_CRYPTO_hash (&kb->keyspace,
1478                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1479                         query);
1480   return GNUNET_OK;
1481 }
1482
1483
1484 /**
1485  * Check if the given SBlock is well-formed.
1486  *
1487  * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1488  * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1489  * @param query where to store the query that this block answers
1490  * @param namespace where to store the namespace that this block belongs to
1491  * @return GNUNET_OK if this is actually a well-formed SBlock
1492  */
1493 static int
1494 check_sblock (const struct SBlock *sb,
1495               size_t dsize,
1496               GNUNET_HashCode *query,   
1497               GNUNET_HashCode *namespace)
1498 {
1499   if (dsize < sizeof (struct SBlock))
1500     {
1501       GNUNET_break_op (0);
1502       return GNUNET_SYSERR;
1503     }
1504   if (dsize !=
1505       ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1506     {
1507       GNUNET_break_op (0);
1508       return GNUNET_SYSERR;
1509     }
1510   if (GNUNET_OK !=
1511       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1512                                 &sb->purpose,
1513                                 &sb->signature,
1514                                 &sb->subspace)) 
1515     {
1516       GNUNET_break_op (0);
1517       return GNUNET_SYSERR;
1518     }
1519   if (query != NULL)
1520     *query = sb->identifier;
1521   if (namespace != NULL)
1522     GNUNET_CRYPTO_hash (&sb->subspace,
1523                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1524                         namespace);
1525   return GNUNET_OK;
1526 }
1527
1528
1529 /**
1530  * Transmit the given message by copying it to the target buffer
1531  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
1532  * for writing in the meantime.  In that case, do nothing
1533  * (the disconnect or shutdown handler will take care of the rest).
1534  * If we were able to transmit messages and there are still more
1535  * pending, ask core again for further calls to this function.
1536  *
1537  * @param cls closure, pointer to the 'struct ClientList*'
1538  * @param size number of bytes available in buf
1539  * @param buf where the callee should write the message
1540  * @return number of bytes written to buf
1541  */
1542 static size_t
1543 transmit_to_client (void *cls,
1544                   size_t size, void *buf)
1545 {
1546   struct ClientList *cl = cls;
1547   char *cbuf = buf;
1548   struct ClientResponseMessage *creply;
1549   size_t msize;
1550   
1551   cl->th = NULL;
1552   if (NULL == buf)
1553     {
1554 #if DEBUG_FS
1555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1556                   "Not sending reply, client communication problem.\n");
1557 #endif
1558       return 0;
1559     }
1560   msize = 0;
1561   while ( (NULL != (creply = cl->res_head) ) &&
1562           (creply->msize <= size) )
1563     {
1564       memcpy (&cbuf[msize], &creply[1], creply->msize);
1565       msize += creply->msize;
1566       size -= creply->msize;
1567       GNUNET_CONTAINER_DLL_remove (cl->res_head,
1568                                    cl->res_tail,
1569                                    creply);
1570       GNUNET_free (creply);
1571     }
1572   if (NULL != creply)
1573     cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1574                                                   creply->msize,
1575                                                   GNUNET_TIME_UNIT_FOREVER_REL,
1576                                                   &transmit_to_client,
1577                                                   cl);
1578   return msize;
1579 }
1580
1581
1582 /**
1583  * Closure for "process_reply" function.
1584  */
1585 struct ProcessReplyClosure
1586 {
1587   /**
1588    * The data for the reply.
1589    */
1590   const void *data;
1591
1592   // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1593
1594   /**
1595    * When the reply expires.
1596    */
1597   struct GNUNET_TIME_Absolute expiration;
1598
1599   /**
1600    * Size of data.
1601    */
1602   size_t size;
1603
1604   /**
1605    * Namespace that this reply belongs to
1606    * (if it is of type SBLOCK).
1607    */
1608   GNUNET_HashCode namespace;
1609
1610   /**
1611    * Type of the block.
1612    */
1613   uint32_t type;
1614
1615   /**
1616    * How much was this reply worth to us?
1617    */
1618   uint32_t priority;
1619 };
1620
1621
1622 /**
1623  * We have received a reply; handle it!
1624  *
1625  * @param cls response (struct ProcessReplyClosure)
1626  * @param key our query
1627  * @param value value in the hash map (info about the query)
1628  * @return GNUNET_YES (we should continue to iterate)
1629  */
1630 static int
1631 process_reply (void *cls,
1632                const GNUNET_HashCode * key,
1633                void *value)
1634 {
1635   struct ProcessReplyClosure *prq = cls;
1636   struct PendingRequest *pr = value;
1637   struct PendingMessage *reply;
1638   struct ClientResponseMessage *creply;
1639   struct ClientList *cl;
1640   struct PutMessage *pm;
1641   struct ContentMessage *cm;
1642   struct ConnectedPeer *cp;
1643   GNUNET_HashCode chash;
1644   GNUNET_HashCode mhash;
1645   size_t msize;
1646   uint32_t prio;
1647
1648   
1649   GNUNET_CRYPTO_hash (prq->data,
1650                       prq->size,
1651                       &chash);
1652   switch (prq->type)
1653     {
1654     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1655     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1656       /* only possible reply, stop requesting! */
1657       while (NULL != pr->pending_head)
1658         destroy_pending_message_list_entry (pr->pending_head);
1659       GNUNET_break (GNUNET_YES ==
1660                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1661                                                           key,
1662                                                           prq));
1663       break;
1664     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1665       if (0 != memcmp (pr->namespace,
1666                        &prq->namespace,
1667                        sizeof (GNUNET_HashCode)))
1668         return GNUNET_YES; /* wrong namespace */        
1669       /* then: fall-through! */
1670     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1671       if (pr->bf != NULL) 
1672         {
1673           mingle_hash (&chash, pr->mingle, &mhash);
1674           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1675                                                                &mhash))
1676             return GNUNET_YES; /* duplicate */
1677           GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1678                                             &mhash);
1679         }
1680       if (pr->client_request_list != NULL)
1681         {
1682           cl = pr->client_request_list->client_list;
1683           if (pr->replies_seen_size == pr->replies_seen_off)
1684             {
1685               GNUNET_array_grow (pr->replies_seen,
1686                                  pr->replies_seen_size,
1687                                  pr->replies_seen_size * 2 + 4);
1688               // FIXME: recalculate BF!
1689             }
1690           pr->replies_seen[pr->replies_seen_off++] = chash;
1691         }
1692       break;
1693     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1694       // FIXME: any checks against duplicates for SKBlocks?
1695       break;
1696     default:
1697       GNUNET_break (0);
1698       return GNUNET_YES;
1699     }
1700   prio = pr->priority;
1701   prq->priority += pr->remaining_priority;
1702   pr->remaining_priority = 0;
1703   if (pr->client_request_list != NULL)
1704     {
1705       msize = sizeof (struct PutMessage) + prq->size;
1706       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1707       creply->msize = msize;
1708       creply->client_list = cl;
1709       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1710                                          cl->res_tail,
1711                                          cl->res_tail,
1712                                          creply);      
1713       pm = (struct PutMessage*) &creply[1];
1714       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1715       pm->header.size = htons (msize);
1716       pm->type = htonl (prq->type);
1717       pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
1718       memcpy (&creply[1], prq->data, prq->size);      
1719       if (NULL == cl->th)
1720         cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1721                                                       msize,
1722                                                       GNUNET_TIME_UNIT_FOREVER_REL,
1723                                                       &transmit_to_client,
1724                                                       cl);
1725       GNUNET_break (cl->th != NULL);
1726     }
1727   else
1728     {
1729       cp = pr->pht_entry->cp;
1730       msize = sizeof (struct ContentMessage) + prq->size;
1731       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1732       reply->cont = &transmit_reply_continuation;
1733       reply->cont_cls = pr;
1734       reply->msize = msize;
1735       reply->priority = (uint32_t) -1; /* send replies first! */
1736       cm = (struct ContentMessage*) &reply[1];
1737       cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
1738       cm->header.size = htons (msize);
1739       cm->type = htonl (prq->type);
1740       cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1741       memcpy (&reply[1], prq->data, prq->size);
1742       add_to_pending_messages_for_peer (cp, reply, pr);
1743     }
1744
1745
1746   // FIXME: implement hot-path routing statistics keeping!
1747   return GNUNET_YES;
1748 }
1749
1750
1751 /**
1752  * Handle P2P "PUT" message.
1753  *
1754  * @param cls closure, always NULL
1755  * @param other the other peer involved (sender or receiver, NULL
1756  *        for loopback messages where we are both sender and receiver)
1757  * @param message the actual message
1758  * @param latency reported latency of the connection with 'other'
1759  * @param distance reported distance (DV) to 'other' 
1760  * @return GNUNET_OK to keep the connection open,
1761  *         GNUNET_SYSERR to close it (signal serious error)
1762  */
1763 static int
1764 handle_p2p_put (void *cls,
1765                 const struct GNUNET_PeerIdentity *other,
1766                 const struct GNUNET_MessageHeader *message,
1767                 struct GNUNET_TIME_Relative latency,
1768                 uint32_t distance)
1769 {
1770   const struct PutMessage *put;
1771   uint16_t msize;
1772   size_t dsize;
1773   uint32_t type;
1774   struct GNUNET_TIME_Absolute expiration;
1775   GNUNET_HashCode query;
1776   struct ProcessReplyClosure prq;
1777
1778   msize = ntohs (message->size);
1779   if (msize < sizeof (struct PutMessage))
1780     {
1781       GNUNET_break_op(0);
1782       return GNUNET_SYSERR;
1783     }
1784   put = (const struct PutMessage*) message;
1785   dsize = msize - sizeof (struct PutMessage);
1786   type = ntohl (put->type);
1787   expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
1788
1789   /* first, validate! */
1790   switch (type)
1791     {
1792     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1793     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1794       GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1795       break;
1796     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1797       if (GNUNET_OK !=
1798           check_kblock ((const struct KBlock*) &put[1],
1799                         dsize,
1800                         &query))
1801         return GNUNET_SYSERR;
1802       break;
1803     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1804       if (GNUNET_OK !=
1805           check_sblock ((const struct SBlock*) &put[1],
1806                         dsize,
1807                         &query,
1808                         &prq.namespace))
1809         return GNUNET_SYSERR;
1810       break;
1811     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1812       // FIXME -- validate SKBLOCK!
1813       GNUNET_break (0);
1814       return GNUNET_OK;
1815     default:
1816       /* unknown block type */
1817       GNUNET_break_op (0);
1818       return GNUNET_SYSERR;
1819     }
1820
1821   /* now, lookup 'query' */
1822   prq.data = (const void*) &put[1];
1823   prq.size = dsize;
1824   prq.type = type;
1825   prq.expiration = expiration;
1826   prq.priority = 0;
1827   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1828                                               &query,
1829                                               &process_reply,
1830                                               &prq);
1831   // FIXME: if migration is on and load is low,
1832   // queue to store data in datastore;
1833   // use "prq.priority" for that!
1834   return GNUNET_OK;
1835 }
1836
1837
1838 /* **************************** P2P GET Handling ************************ */
1839
1840
1841 /**
1842  * We're processing (local) results for a search request
1843  * from another peer.  Pass applicable results to the
1844  * peer and if we are done either clean up (operation
1845  * complete) or forward to other peers (more results possible).
1846  *
1847  * @param cls our closure (struct LocalGetContext)
1848  * @param key key for the content
1849  * @param size number of bytes in data
1850  * @param data content stored
1851  * @param type type of the content
1852  * @param priority priority of the content
1853  * @param anonymity anonymity-level for the content
1854  * @param expiration expiration time for the content
1855  * @param uid unique identifier for the datum;
1856  *        maybe 0 if no unique identifier is available
1857  */
1858 static void
1859 process_local_reply (void *cls,
1860                      const GNUNET_HashCode * key,
1861                      uint32_t size,
1862                      const void *data,
1863                      uint32_t type,
1864                      uint32_t priority,
1865                      uint32_t anonymity,
1866                      struct GNUNET_TIME_Absolute
1867                      expiration, 
1868                      uint64_t uid)
1869 {
1870   struct PendingRequest *pr = cls;
1871   struct ProcessReplyClosure prq;
1872   GNUNET_HashCode dhash;
1873   GNUNET_HashCode mhash;
1874   GNUNET_HashCode query;
1875   
1876   pr->drq = NULL;
1877   if (NULL == key)
1878     {
1879       /* no more results */
1880       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1881         pr->task = GNUNET_SCHEDULER_add_now (sched,
1882                                              &forward_request_task,
1883                                              pr);      
1884       return;
1885     }
1886   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1887     {
1888       if (GNUNET_OK != 
1889           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
1890                                             anonymity, expiration, uid, 
1891                                             &process_local_reply,
1892                                             pr))
1893         GNUNET_FS_drq_get_next (GNUNET_YES);
1894       return;
1895     }
1896   /* check for duplicates */
1897   GNUNET_CRYPTO_hash (data, size, &dhash);
1898   mingle_hash (&dhash, 
1899                pr->mingle,
1900                &mhash);
1901   if ( (pr->bf != NULL) &&
1902        (GNUNET_YES ==
1903         GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1904                                            &mhash)) )
1905     {      
1906 #if DEBUG_FS
1907       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908                   "Result from datastore filtered by bloomfilter.\n");
1909 #endif
1910       GNUNET_FS_drq_get_next (GNUNET_YES);
1911       return;
1912     }
1913   pr->results_found++;
1914   if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1915        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1916        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1917     {
1918       if (pr->bf == NULL)
1919         {
1920           pr->bf_size = 32;
1921           pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1922                                                       pr->bf_size, 
1923                                                       BLOOMFILTER_K);
1924         }
1925       GNUNET_CONTAINER_bloomfilter_add (pr->bf, 
1926                                         &mhash);
1927     }
1928   memset (&prq, 0, sizeof (prq));
1929   prq.data = data;
1930   prq.expiration = expiration;
1931   prq.size = size;  
1932   if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1933        (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1934                                    size,
1935                                    &query,
1936                                    &prq.namespace)) )
1937     {
1938       GNUNET_break (0);
1939       /* FIXME: consider removing the block? */
1940       GNUNET_FS_drq_get_next (GNUNET_YES);
1941       return;
1942     }
1943   prq.type = type;
1944   prq.priority = priority;  
1945   process_reply (&prq, key, pr);
1946   
1947   if ( (GNUNET_YES == test_load_too_high()) ||
1948        (pr->results_found > 5 + 2 * pr->priority) )
1949     {
1950       GNUNET_FS_drq_get_next (GNUNET_NO);
1951       return;
1952     }
1953   GNUNET_FS_drq_get_next (GNUNET_YES);
1954 }
1955
1956
1957 /**
1958  * The priority level imposes a bound on the maximum
1959  * value for the ttl that can be requested.
1960  *
1961  * @param ttl_in requested ttl
1962  * @param prio given priority
1963  * @return ttl_in if ttl_in is below the limit,
1964  *         otherwise the ttl-limit for the given priority
1965  */
1966 static int32_t
1967 bound_ttl (int32_t ttl_in, uint32_t prio)
1968 {
1969   unsigned long long allowed;
1970
1971   if (ttl_in <= 0)
1972     return ttl_in;
1973   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
1974   if (ttl_in > allowed)      
1975     {
1976       if (allowed >= (1 << 30))
1977         return 1 << 30;
1978       return allowed;
1979     }
1980   return ttl_in;
1981 }
1982
1983
1984 /**
1985  * We've received a request with the specified priority.  Bound it
1986  * according to how much we trust the given peer.
1987  * 
1988  * @param prio_in requested priority
1989  * @param cp the peer making the request
1990  * @return effective priority
1991  */
1992 static uint32_t
1993 bound_priority (uint32_t prio_in,
1994                 struct ConnectedPeer *cp)
1995 {
1996   return 0; // FIXME!
1997 }
1998
1999
2000 /**
2001  * Handle P2P "GET" request.
2002  *
2003  * @param cls closure, always NULL
2004  * @param other the other peer involved (sender or receiver, NULL
2005  *        for loopback messages where we are both sender and receiver)
2006  * @param message the actual message
2007  * @param latency reported latency of the connection with 'other'
2008  * @param distance reported distance (DV) to 'other' 
2009  * @return GNUNET_OK to keep the connection open,
2010  *         GNUNET_SYSERR to close it (signal serious error)
2011  */
2012 static int
2013 handle_p2p_get (void *cls,
2014                 const struct GNUNET_PeerIdentity *other,
2015                 const struct GNUNET_MessageHeader *message,
2016                 struct GNUNET_TIME_Relative latency,
2017                 uint32_t distance)
2018 {
2019   struct PendingRequest *pr;
2020   struct PeerRequestEntry *pre;
2021   struct ConnectedPeer *cp;
2022   struct ConnectedPeer *cps;
2023   struct GNUNET_TIME_Relative timeout;
2024   uint16_t msize;
2025   const struct GetMessage *gm;
2026   unsigned int bits;
2027   const GNUNET_HashCode *opt;
2028   uint32_t bm;
2029   size_t bfsize;
2030   uint32_t ttl_decrement;
2031   uint32_t type;
2032   double preference;
2033
2034   msize = ntohs(message->size);
2035   if (msize < sizeof (struct GetMessage))
2036     {
2037       GNUNET_break_op (0);
2038       return GNUNET_SYSERR;
2039     }
2040   gm = (const struct GetMessage*) message;
2041   bm = ntohl (gm->hash_bitmap);
2042   bits = 0;
2043   while (bm > 0)
2044     {
2045       if (1 == (bm & 1))
2046         bits++;
2047       bm >>= 1;
2048     }
2049   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2050     {
2051       GNUNET_break_op (0);
2052       return GNUNET_SYSERR;
2053     }  
2054   opt = (const GNUNET_HashCode*) &gm[1];
2055   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2056
2057   bm = ntohl (gm->hash_bitmap);
2058   if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2059        (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2060     {
2061       GNUNET_break_op (0);
2062       return GNUNET_SYSERR;      
2063     }
2064   bits = 0;
2065   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2066                                            &other->hashPubKey);
2067   GNUNET_assert (NULL != cps);
2068   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2069     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2070                                             &opt[bits++]);
2071   else
2072     cp = cps;
2073   if (cp == NULL)
2074     {
2075       /* FIXME: try connect? */
2076       return GNUNET_OK;
2077     }
2078   /* note that we can really only check load here since otherwise
2079      peers could find out that we are overloaded by not being
2080      disconnected after sending us a malformed query... */
2081   if (GNUNET_YES == test_load_too_high ())
2082     {
2083 #if DEBUG_FS
2084       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2085                   "Dropping query from `%s', this peer is too busy.\n",
2086                   GNUNET_i2s (other));
2087 #endif
2088       return GNUNET_OK;
2089     }
2090
2091   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2092                       (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2093   if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2094     pr->namespace = (GNUNET_HashCode*) &pr[1];
2095   pr->type = ntohl (gm->type);
2096   pr->mingle = gm->filter_mutator;
2097   if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2098     memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2099   else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2100     {
2101       GNUNET_break_op (0);
2102       GNUNET_free (pr);
2103       return GNUNET_SYSERR;
2104     }
2105   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2106     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2107
2108   pr->anonymity_level = 1;
2109   pr->priority = bound_priority (ntohl (gm->priority), cps);
2110   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2111   pr->query = gm->query;
2112   /* decrement ttl (always) */
2113   ttl_decrement = 2 * TTL_DECREMENT +
2114     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2115                               TTL_DECREMENT);
2116   if ( (pr->ttl < 0) &&
2117        (pr->ttl - ttl_decrement > 0) )
2118     {
2119 #if DEBUG_FS
2120       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2121                   "Dropping query from `%s' due to TTL underflow.\n",
2122                   GNUNET_i2s (other));
2123 #endif
2124       /* integer underflow => drop (should be very rare)! */
2125       GNUNET_free (pr);
2126       return GNUNET_OK;
2127     } 
2128   pr->ttl -= ttl_decrement;
2129   pr->start_time = GNUNET_TIME_absolute_get ();
2130
2131   /* get bloom filter */
2132   if (bfsize > 0)
2133     {
2134       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2135                                                   bfsize,
2136                                                   BLOOMFILTER_K);
2137       pr->bf_size = bfsize;
2138     }
2139
2140   /* FIXME: check somewhere if request already exists, and if so,
2141      recycle old state... */
2142   pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2143   pre->cp = cp;
2144   pre->req = pr;
2145   GNUNET_CONTAINER_multihashmap_put (query_request_map,
2146                                      &gm->query,
2147                                      pre,
2148                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2149   
2150   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2151                                             pr,
2152                                             GNUNET_TIME_absolute_get().value + pr->ttl);
2153
2154
2155   /* calculate change in traffic preference */
2156   preference = (double) pr->priority;
2157   if (preference < QUERY_BANDWIDTH_VALUE)
2158     preference = QUERY_BANDWIDTH_VALUE;
2159   cps->inc_preference += preference;
2160
2161   /* process locally */
2162   type = pr->type;
2163   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2164     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2165   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2166                                            (pr->priority + 1)); 
2167   pr->drq = GNUNET_FS_drq_get (&gm->query,
2168                                pr->type,                               
2169                                &process_local_reply,
2170                                pr,
2171                                timeout,
2172                                GNUNET_NO);
2173
2174   /* Are multiple results possible?  If so, start processing remotely now! */
2175   switch (pr->type)
2176     {
2177     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2178     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2179       /* only one result, wait for datastore */
2180       break;
2181     default:
2182       pr->task = GNUNET_SCHEDULER_add_now (sched,
2183                                            &forward_request_task,
2184                                            pr);
2185     }
2186
2187   /* make sure we don't track too many requests */
2188   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2189     {
2190       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2191       destroy_pending_request (pr);
2192     }
2193   return GNUNET_OK;
2194 }
2195
2196
2197 /* **************************** CS GET Handling ************************ */
2198
2199
2200 /**
2201  * Handle START_SEARCH-message (search request from client).
2202  *
2203  * @param cls closure
2204  * @param client identification of the client
2205  * @param message the actual message
2206  */
2207 static void
2208 handle_start_search (void *cls,
2209                      struct GNUNET_SERVER_Client *client,
2210                      const struct GNUNET_MessageHeader *message)
2211 {
2212   static GNUNET_HashCode all_zeros;
2213   const struct SearchMessage *sm;
2214   struct ClientList *cl;
2215   struct ClientRequestList *crl;
2216   struct PendingRequest *pr;
2217   uint16_t msize;
2218   unsigned int sc;
2219   uint32_t type;
2220   
2221   msize = ntohs (message->size);
2222   if ( (msize < sizeof (struct SearchMessage)) ||
2223        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2224     {
2225       GNUNET_break (0);
2226       GNUNET_SERVER_receive_done (client,
2227                                   GNUNET_SYSERR);
2228       return;
2229     }
2230   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2231   sm = (const struct SearchMessage*) message;
2232
2233   cl = client_list;
2234   while ( (cl != NULL) &&
2235           (cl->client != client) )
2236     cl = cl->next;
2237   if (cl == NULL)
2238     {
2239       cl = GNUNET_malloc (sizeof (struct ClientList));
2240       cl->client = client;
2241       GNUNET_SERVER_client_keep (client);
2242       cl->next = client_list;
2243       client_list = cl;
2244     }
2245   type = ntohl (sm->type);
2246
2247   /* FIXME: detect duplicate request; if duplicate, simply update (merge)
2248      'pr->replies_seen'! */
2249   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2250                       (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0);
2251   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2252   crl->client_list = cl;
2253   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2254                                cl->rl_tail,
2255                                crl);  
2256   crl->req = pr;
2257   pr->type = type;
2258   pr->client_request_list = crl;
2259   GNUNET_array_grow (pr->replies_seen,
2260                      pr->replies_seen_size,
2261                      sc);
2262   memcpy (pr->replies_seen,
2263           &sm[1],
2264           sc * sizeof (GNUNET_HashCode));
2265   pr->replies_seen_off = sc;
2266   pr->anonymity_level = ntohl (sm->anonymity_level);
2267   pr->mingle = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
2268                                         (uint32_t) -1);
2269   pr->query = sm->query;
2270   switch (type)
2271     {
2272     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2273     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2274       if (0 != memcmp (&sm->target,
2275                        &all_zeros,
2276                        sizeof (GNUNET_HashCode)))
2277         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2278       break;
2279     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2280       pr->namespace = (GNUNET_HashCode*) &pr[1];
2281       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2282       break;
2283     default:
2284       break;
2285     }
2286   pr->drq = GNUNET_FS_drq_get (&sm->query,
2287                                pr->type,                               
2288                                &process_local_reply,
2289                                pr,
2290                                GNUNET_TIME_UNIT_FOREVER_REL,
2291                                GNUNET_YES);
2292 }
2293
2294
2295 /* **************************** Startup ************************ */
2296
2297
2298 /**
2299  * List of handlers for P2P messages
2300  * that we care about.
2301  */
2302 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2303   {
2304     { &handle_p2p_get, 
2305       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2306     { &handle_p2p_put, 
2307       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2308     { NULL, 0, 0 }
2309   };
2310
2311
2312 /**
2313  * List of handlers for the messages understood by this
2314  * service.
2315  */
2316 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2317   {&GNUNET_FS_handle_index_start, NULL, 
2318    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2319   {&GNUNET_FS_handle_index_list_get, NULL, 
2320    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2321   {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
2322    sizeof (struct UnindexMessage) },
2323   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
2324    0 },
2325   {NULL, NULL, 0, 0}
2326 };
2327
2328
2329 /**
2330  * Process fs requests.
2331  *
2332  * @param cls closure
2333  * @param s scheduler to use
2334  * @param server the initialized server
2335  * @param c configuration to use
2336  */
2337 static int
2338 main_init (struct GNUNET_SCHEDULER_Handle *s,
2339            struct GNUNET_SERVER_Handle *server,
2340            const struct GNUNET_CONFIGURATION_Handle *c)
2341 {
2342   sched = s;
2343   cfg = c;
2344   core = GNUNET_CORE_connect (sched,
2345                               cfg,
2346                               GNUNET_TIME_UNIT_FOREVER_REL,
2347                               NULL,
2348                               NULL,
2349                               NULL,
2350                               &peer_connect_handler,
2351                               &peer_disconnect_handler,
2352                               NULL, GNUNET_NO,
2353                               NULL, GNUNET_NO,
2354                               p2p_handlers);
2355   if (NULL == core)
2356     {
2357       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2358                   _("Failed to connect to `%s' service.\n"),
2359                   "core");
2360       return GNUNET_SYSERR;
2361     }  
2362   query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2363   peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2364   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
2365   GNUNET_SERVER_disconnect_notify (server, 
2366                                    &handle_client_disconnect,
2367                                    NULL);
2368   GNUNET_SERVER_add_handlers (server, handlers);
2369   GNUNET_SCHEDULER_add_delayed (sched,
2370                                 GNUNET_TIME_UNIT_FOREVER_REL,
2371                                 &shutdown_task,
2372                                 NULL);
2373   return GNUNET_OK;
2374 }
2375
2376
2377 /**
2378  * Process fs requests.
2379  *
2380  * @param cls closure
2381  * @param sched scheduler to use
2382  * @param server the initialized server
2383  * @param cfg configuration to use
2384  */
2385 static void
2386 run (void *cls,
2387      struct GNUNET_SCHEDULER_Handle *sched,
2388      struct GNUNET_SERVER_Handle *server,
2389      const struct GNUNET_CONFIGURATION_Handle *cfg)
2390 {
2391   if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2392        (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2393        (GNUNET_OK != main_init (sched, server, cfg)) )
2394     {    
2395       GNUNET_SCHEDULER_shutdown (sched);
2396       return;   
2397     }
2398 }
2399
2400
2401 /**
2402  * The main function for the fs service.
2403  *
2404  * @param argc number of arguments from the command line
2405  * @param argv command line arguments
2406  * @return 0 ok, 1 on error
2407  */
2408 int
2409 main (int argc, char *const *argv)
2410 {
2411   return (GNUNET_OK ==
2412           GNUNET_SERVICE_run (argc,
2413                               argv,
2414                               "fs",
2415                               GNUNET_SERVICE_OPTION_NONE,
2416                               &run, NULL)) ? 0 : 1;
2417 }
2418
2419 /* end of gnunet-service-fs.c */