die nicely
[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  * - statistics
34  * 
35  */
36 #include "platform.h"
37 #include <float.h>
38 #include "gnunet_constants.h"
39 #include "gnunet_core_service.h"
40 #include "gnunet_datastore_service.h"
41 #include "gnunet_peer_lib.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_util_lib.h"
45 #include "gnunet-service-fs_drq.h"
46 #include "gnunet-service-fs_indexing.h"
47 #include "fs.h"
48
49 #define DEBUG_FS GNUNET_YES
50
51 /**
52  * Maximum number of outgoing messages we queue per peer.
53  * FIXME: set to a tiny value for testing; make configurable.
54  */
55 #define MAX_QUEUE_PER_PEER 2
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   while (client_list != NULL)
932     handle_client_disconnect (NULL,
933                               client_list->client);
934   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
935                                          &clean_peer,
936                                          NULL);
937   GNUNET_break (0 == GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap));
938   GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
939   requests_by_expiration_heap = 0;
940   GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
941   connected_peers = NULL;
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   int no_route;
1247
1248   pr->irc = NULL;
1249   GNUNET_assert (peer != NULL);
1250   // (3) transmit, update ttl/priority
1251   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1252                                           &peer->hashPubKey);
1253   if (cp == NULL)
1254     {
1255       /* Peer must have just left */
1256       return;
1257     }
1258   no_route = GNUNET_NO;
1259   if (amount != DBLOCK_SIZE) 
1260     {
1261       if (pr->pht_entry == NULL)
1262         return;  /* this target round failed */
1263       /* FIXME: if we are "quite" busy, we may still want to skip
1264          this round; need more load detection code! */
1265       no_route = GNUNET_YES;
1266     }
1267   
1268   /* build message and insert message into priority queue */
1269   k = 0;
1270   if (pr->namespace != NULL)
1271     k++;
1272   if (pr->target_pid != 0)
1273     k++;
1274   if (GNUNET_YES == no_route)
1275     k++;      
1276   msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1277   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1278   pm = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1279   pm->msize = msize;
1280   gm = (struct GetMessage*) &pm[1];
1281   gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1282   gm->header.size = htons (msize);
1283   gm->type = htonl (pr->type);
1284   pr->remaining_priority /= 2;
1285   gm->priority = htonl (pr->remaining_priority);
1286   gm->ttl = htonl (pr->ttl);
1287   gm->filter_mutator = htonl(pr->mingle); // FIXME: bad endianess conversion?
1288   gm->hash_bitmap = htonl (42); // FIXME!
1289   gm->query = pr->query;
1290   ext = (GNUNET_HashCode*) &gm[1];
1291   k = 0;
1292   if (pr->namespace != NULL)
1293     memcpy (&ext[k++], pr->namespace, sizeof (GNUNET_HashCode));
1294   if (pr->target_pid != 0)
1295     GNUNET_PEER_resolve (pr->target_pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1296   if (GNUNET_YES == no_route)
1297     GNUNET_PEER_resolve (pr->pht_entry->cp->pid, (struct GNUNET_PeerIdentity*) &ext[k++]);
1298   bfdata = (char *) &ext[k];
1299   if (pr->bf != NULL)
1300     GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1301                                                bfdata,
1302                                                pr->bf_size);
1303   pm->cont = &transmit_query_continuation;
1304   pm->cont_cls = pr;
1305   add_to_pending_messages_for_peer (cp, pm, pr);
1306 }
1307
1308
1309 /**
1310  * Closure used for "target_peer_select_cb".
1311  */
1312 struct PeerSelectionContext 
1313 {
1314   /**
1315    * The request for which we are selecting
1316    * peers.
1317    */
1318   struct PendingRequest *pr;
1319
1320   /**
1321    * Current "prime" target.
1322    */
1323   struct GNUNET_PeerIdentity target;
1324
1325   /**
1326    * How much do we like this target?
1327    */
1328   double target_score;
1329
1330 };
1331
1332
1333 /**
1334  * Function called for each connected peer to determine
1335  * which one(s) would make good targets for forwarding.
1336  *
1337  * @param cls closure (struct PeerSelectionContext)
1338  * @param key current key code (peer identity)
1339  * @param value value in the hash map (struct ConnectedPeer)
1340  * @return GNUNET_YES if we should continue to
1341  *         iterate,
1342  *         GNUNET_NO if not.
1343  */
1344 static int
1345 target_peer_select_cb (void *cls,
1346                        const GNUNET_HashCode * key,
1347                        void *value)
1348 {
1349   struct PeerSelectionContext *psc = cls;
1350   struct ConnectedPeer *cp = value;
1351   struct PendingRequest *pr = psc->pr;
1352   double score;
1353   unsigned int i;
1354   
1355   /* 1) check if we have already (recently) forwarded to this peer */
1356   for (i=0;i<pr->used_pids_off;i++)
1357     if (pr->used_pids[i] == cp->pid)
1358       return GNUNET_YES; /* skip */
1359   // 2) calculate how much we'd like to forward to this peer
1360   score = 42; // FIXME!
1361   // FIXME: also need API to gather data on responsiveness
1362   // of this peer (we have fields for that in 'cp', but
1363   // they are never set!)
1364   
1365   /* store best-fit in closure */
1366   if (score > psc->target_score)
1367     {
1368       psc->target_score = score;
1369       psc->target.hashPubKey = *key; 
1370     }
1371   return GNUNET_YES;
1372 }
1373   
1374
1375 /**
1376  * We're processing a GET request from another peer and have decided
1377  * to forward it to other peers.  This function is called periodically
1378  * and should forward the request to other peers until we have all
1379  * possible replies.  If we have transmitted the *only* reply to
1380  * the initiator we should destroy the pending request.  If we have
1381  * many replies in the queue to the initiator, we should delay sending
1382  * out more queries until the reply queue has shrunk some.
1383  *
1384  * @param cls our "struct ProcessGetContext *"
1385  * @param tc unused
1386  */
1387 static void
1388 forward_request_task (void *cls,
1389                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1390 {
1391   struct PendingRequest *pr = cls;
1392   struct PeerSelectionContext psc;
1393   struct ConnectedPeer *cp; 
1394
1395   pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1396                                            get_processing_delay (),
1397                                            &forward_request_task,
1398                                            pr);
1399   if (pr->irc != NULL)
1400     return; /* previous request still pending */
1401   /* (1) select target */
1402   psc.pr = pr;
1403   psc.target_score = DBL_MIN;
1404   GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1405                                          &target_peer_select_cb,
1406                                          &psc);  
1407   if (psc.target_score == DBL_MIN)
1408     return; /* nobody selected */
1409
1410   /* (2) reserve reply bandwidth */
1411   cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
1412                                           &psc.target.hashPubKey);
1413   pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1414                                                 &psc.target,
1415                                                 GNUNET_CONSTANTS_SERVICE_TIMEOUT, 
1416                                                 (uint32_t) -1 /* no limit */, 
1417                                                 DBLOCK_SIZE, 
1418                                                 (uint64_t) cp->inc_preference,
1419                                                 &target_reservation_cb,
1420                                                 pr);
1421   cp->inc_preference = 0.0;
1422 }
1423
1424
1425 /* **************************** P2P PUT Handling ************************ */
1426
1427
1428 /**
1429  * Function called after we either failed or succeeded
1430  * at transmitting a reply to a peer.  
1431  *
1432  * @param cls the requests "struct PendingRequest*"
1433  * @param pid ID of receiving peer, 0 on transmission error
1434  */
1435 static void
1436 transmit_reply_continuation (void *cls,
1437                              GNUNET_PEER_Id tpid)
1438 {
1439   struct PendingRequest *pr = cls;
1440
1441   switch (pr->type)
1442     {
1443     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1444     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1445       /* only one reply expected, done with the request! */
1446       destroy_pending_request (pr);
1447       break;
1448     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1449     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1450       break;
1451     default:
1452       GNUNET_break (0);
1453       break;
1454     }
1455 }
1456
1457
1458 /**
1459  * Check if the given KBlock is well-formed.
1460  *
1461  * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
1462  * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
1463  * @param query where to store the query that this block answers
1464  * @return GNUNET_OK if this is actually a well-formed KBlock
1465  */
1466 static int
1467 check_kblock (const struct KBlock *kb,
1468               size_t dsize,
1469               GNUNET_HashCode *query)
1470 {
1471   if (dsize < sizeof (struct KBlock))
1472     {
1473       GNUNET_break_op (0);
1474       return GNUNET_SYSERR;
1475     }
1476   if (dsize - sizeof (struct KBlock) !=
1477       ntohs (kb->purpose.size) 
1478       - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) 
1479       - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) ) 
1480     {
1481       GNUNET_break_op (0);
1482       return GNUNET_SYSERR;
1483     }
1484   if (GNUNET_OK !=
1485       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
1486                                 &kb->purpose,
1487                                 &kb->signature,
1488                                 &kb->keyspace)) 
1489     {
1490       GNUNET_break_op (0);
1491       return GNUNET_SYSERR;
1492     }
1493   if (query != NULL)
1494     GNUNET_CRYPTO_hash (&kb->keyspace,
1495                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1496                         query);
1497   return GNUNET_OK;
1498 }
1499
1500
1501 /**
1502  * Check if the given SBlock is well-formed.
1503  *
1504  * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
1505  * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
1506  * @param query where to store the query that this block answers
1507  * @param namespace where to store the namespace that this block belongs to
1508  * @return GNUNET_OK if this is actually a well-formed SBlock
1509  */
1510 static int
1511 check_sblock (const struct SBlock *sb,
1512               size_t dsize,
1513               GNUNET_HashCode *query,   
1514               GNUNET_HashCode *namespace)
1515 {
1516   if (dsize < sizeof (struct SBlock))
1517     {
1518       GNUNET_break_op (0);
1519       return GNUNET_SYSERR;
1520     }
1521   if (dsize !=
1522       ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
1523     {
1524       GNUNET_break_op (0);
1525       return GNUNET_SYSERR;
1526     }
1527   if (GNUNET_OK !=
1528       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
1529                                 &sb->purpose,
1530                                 &sb->signature,
1531                                 &sb->subspace)) 
1532     {
1533       GNUNET_break_op (0);
1534       return GNUNET_SYSERR;
1535     }
1536   if (query != NULL)
1537     *query = sb->identifier;
1538   if (namespace != NULL)
1539     GNUNET_CRYPTO_hash (&sb->subspace,
1540                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1541                         namespace);
1542   return GNUNET_OK;
1543 }
1544
1545
1546 /**
1547  * Transmit the given message by copying it to the target buffer
1548  * "buf".  "buf" will be NULL and "size" zero if the socket was closed
1549  * for writing in the meantime.  In that case, do nothing
1550  * (the disconnect or shutdown handler will take care of the rest).
1551  * If we were able to transmit messages and there are still more
1552  * pending, ask core again for further calls to this function.
1553  *
1554  * @param cls closure, pointer to the 'struct ClientList*'
1555  * @param size number of bytes available in buf
1556  * @param buf where the callee should write the message
1557  * @return number of bytes written to buf
1558  */
1559 static size_t
1560 transmit_to_client (void *cls,
1561                   size_t size, void *buf)
1562 {
1563   struct ClientList *cl = cls;
1564   char *cbuf = buf;
1565   struct ClientResponseMessage *creply;
1566   size_t msize;
1567   
1568   cl->th = NULL;
1569   if (NULL == buf)
1570     {
1571 #if DEBUG_FS
1572       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573                   "Not sending reply, client communication problem.\n");
1574 #endif
1575       return 0;
1576     }
1577   msize = 0;
1578   while ( (NULL != (creply = cl->res_head) ) &&
1579           (creply->msize <= size) )
1580     {
1581       memcpy (&cbuf[msize], &creply[1], creply->msize);
1582       msize += creply->msize;
1583       size -= creply->msize;
1584       GNUNET_CONTAINER_DLL_remove (cl->res_head,
1585                                    cl->res_tail,
1586                                    creply);
1587       GNUNET_free (creply);
1588     }
1589   if (NULL != creply)
1590     cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1591                                                   creply->msize,
1592                                                   GNUNET_TIME_UNIT_FOREVER_REL,
1593                                                   &transmit_to_client,
1594                                                   cl);
1595   return msize;
1596 }
1597
1598
1599 /**
1600  * Closure for "process_reply" function.
1601  */
1602 struct ProcessReplyClosure
1603 {
1604   /**
1605    * The data for the reply.
1606    */
1607   const void *data;
1608
1609   // FIXME: add 'struct ConnectedPeer' to track 'last_xxx_replies' here!
1610
1611   /**
1612    * When the reply expires.
1613    */
1614   struct GNUNET_TIME_Absolute expiration;
1615
1616   /**
1617    * Size of data.
1618    */
1619   size_t size;
1620
1621   /**
1622    * Namespace that this reply belongs to
1623    * (if it is of type SBLOCK).
1624    */
1625   GNUNET_HashCode namespace;
1626
1627   /**
1628    * Type of the block.
1629    */
1630   uint32_t type;
1631
1632   /**
1633    * How much was this reply worth to us?
1634    */
1635   uint32_t priority;
1636 };
1637
1638
1639 /**
1640  * We have received a reply; handle it!
1641  *
1642  * @param cls response (struct ProcessReplyClosure)
1643  * @param key our query
1644  * @param value value in the hash map (info about the query)
1645  * @return GNUNET_YES (we should continue to iterate)
1646  */
1647 static int
1648 process_reply (void *cls,
1649                const GNUNET_HashCode * key,
1650                void *value)
1651 {
1652   struct ProcessReplyClosure *prq = cls;
1653   struct PendingRequest *pr = value;
1654   struct PendingMessage *reply;
1655   struct ClientResponseMessage *creply;
1656   struct ClientList *cl;
1657   struct PutMessage *pm;
1658   struct ContentMessage *cm;
1659   struct ConnectedPeer *cp;
1660   GNUNET_HashCode chash;
1661   GNUNET_HashCode mhash;
1662   size_t msize;
1663   uint32_t prio;
1664
1665 #if DEBUG_FS
1666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1667               "Matched result for query `%s' with pending request\n",
1668               GNUNET_h2s (key));
1669 #endif  
1670   GNUNET_CRYPTO_hash (prq->data,
1671                       prq->size,
1672                       &chash);
1673   switch (prq->type)
1674     {
1675     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1676     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1677       /* only possible reply, stop requesting! */
1678       while (NULL != pr->pending_head)
1679         destroy_pending_message_list_entry (pr->pending_head);
1680       GNUNET_break (GNUNET_YES ==
1681                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1682                                                           key,
1683                                                           pr));
1684       break;
1685     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1686       if (0 != memcmp (pr->namespace,
1687                        &prq->namespace,
1688                        sizeof (GNUNET_HashCode)))
1689         return GNUNET_YES; /* wrong namespace */        
1690       /* then: fall-through! */
1691     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1692       if (pr->bf != NULL) 
1693         {
1694           mingle_hash (&chash, pr->mingle, &mhash);
1695           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1696                                                                &mhash))
1697             return GNUNET_YES; /* duplicate */
1698           GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1699                                             &mhash);
1700         }
1701       if (pr->client_request_list != NULL)
1702         {
1703           if (pr->replies_seen_size == pr->replies_seen_off)
1704             {
1705               GNUNET_array_grow (pr->replies_seen,
1706                                  pr->replies_seen_size,
1707                                  pr->replies_seen_size * 2 + 4);
1708               // FIXME: recalculate BF!
1709             }
1710           pr->replies_seen[pr->replies_seen_off++] = chash;
1711         }
1712       break;
1713     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1714       // FIXME: any checks against duplicates for SKBlocks?
1715       break;
1716     default:
1717       GNUNET_break (0);
1718       return GNUNET_YES;
1719     }
1720   prio = pr->priority;
1721   prq->priority += pr->remaining_priority;
1722   pr->remaining_priority = 0;
1723   if (pr->client_request_list != NULL)
1724     {
1725 #if DEBUG_FS
1726       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1727                   "Transmitting result for query `%s' to local client\n",
1728                   GNUNET_h2s (key));
1729 #endif  
1730       cl = pr->client_request_list->client_list;
1731       msize = sizeof (struct PutMessage) + prq->size;
1732       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1733       creply->msize = msize;
1734       creply->client_list = cl;
1735       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1736                                          cl->res_tail,
1737                                          cl->res_tail,
1738                                          creply);      
1739       pm = (struct PutMessage*) &creply[1];
1740       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1741       pm->header.size = htons (msize);
1742       pm->type = htonl (prq->type);
1743       pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
1744       memcpy (&creply[1], prq->data, prq->size);      
1745       if (NULL == cl->th)
1746         cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1747                                                       msize,
1748                                                       GNUNET_TIME_UNIT_FOREVER_REL,
1749                                                       &transmit_to_client,
1750                                                       cl);
1751       GNUNET_break (cl->th != NULL);
1752     }
1753   else
1754     {
1755       cp = pr->pht_entry->cp;
1756 #if DEBUG_FS
1757       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1758                   "Transmitting result for query `%s' to other peer (PID=%u)\n",
1759                   GNUNET_h2s (key),
1760                   (unsigned int) cp->pid);
1761 #endif  
1762       msize = sizeof (struct ContentMessage) + prq->size;
1763       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1764       reply->cont = &transmit_reply_continuation;
1765       reply->cont_cls = pr;
1766       reply->msize = msize;
1767       reply->priority = (uint32_t) -1; /* send replies first! */
1768       cm = (struct ContentMessage*) &reply[1];
1769       cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
1770       cm->header.size = htons (msize);
1771       cm->type = htonl (prq->type);
1772       cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1773       memcpy (&reply[1], prq->data, prq->size);
1774       add_to_pending_messages_for_peer (cp, reply, pr);
1775     }
1776
1777
1778   // FIXME: implement hot-path routing statistics keeping!
1779   return GNUNET_YES;
1780 }
1781
1782
1783 /**
1784  * Handle P2P "PUT" message.
1785  *
1786  * @param cls closure, always NULL
1787  * @param other the other peer involved (sender or receiver, NULL
1788  *        for loopback messages where we are both sender and receiver)
1789  * @param message the actual message
1790  * @param latency reported latency of the connection with 'other'
1791  * @param distance reported distance (DV) to 'other' 
1792  * @return GNUNET_OK to keep the connection open,
1793  *         GNUNET_SYSERR to close it (signal serious error)
1794  */
1795 static int
1796 handle_p2p_put (void *cls,
1797                 const struct GNUNET_PeerIdentity *other,
1798                 const struct GNUNET_MessageHeader *message,
1799                 struct GNUNET_TIME_Relative latency,
1800                 uint32_t distance)
1801 {
1802   const struct PutMessage *put;
1803   uint16_t msize;
1804   size_t dsize;
1805   uint32_t type;
1806   struct GNUNET_TIME_Absolute expiration;
1807   GNUNET_HashCode query;
1808   struct ProcessReplyClosure prq;
1809
1810   msize = ntohs (message->size);
1811   if (msize < sizeof (struct PutMessage))
1812     {
1813       GNUNET_break_op(0);
1814       return GNUNET_SYSERR;
1815     }
1816   put = (const struct PutMessage*) message;
1817   dsize = msize - sizeof (struct PutMessage);
1818   type = ntohl (put->type);
1819   expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
1820
1821   /* first, validate! */
1822   switch (type)
1823     {
1824     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1825     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1826       GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1827       break;
1828     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1829       if (GNUNET_OK !=
1830           check_kblock ((const struct KBlock*) &put[1],
1831                         dsize,
1832                         &query))
1833         return GNUNET_SYSERR;
1834       break;
1835     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1836       if (GNUNET_OK !=
1837           check_sblock ((const struct SBlock*) &put[1],
1838                         dsize,
1839                         &query,
1840                         &prq.namespace))
1841         return GNUNET_SYSERR;
1842       break;
1843     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1844       // FIXME -- validate SKBLOCK!
1845       GNUNET_break (0);
1846       return GNUNET_OK;
1847     default:
1848       /* unknown block type */
1849       GNUNET_break_op (0);
1850       return GNUNET_SYSERR;
1851     }
1852
1853 #if DEBUG_FS
1854   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1855               "Received result for query `%s' from peer `%4s'\n",
1856               GNUNET_h2s (&query),
1857               GNUNET_i2s (other));
1858 #endif
1859   /* now, lookup 'query' */
1860   prq.data = (const void*) &put[1];
1861   prq.size = dsize;
1862   prq.type = type;
1863   prq.expiration = expiration;
1864   prq.priority = 0;
1865   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1866                                               &query,
1867                                               &process_reply,
1868                                               &prq);
1869   // FIXME: if migration is on and load is low,
1870   // queue to store data in datastore;
1871   // use "prq.priority" for that!
1872   return GNUNET_OK;
1873 }
1874
1875
1876 /* **************************** P2P GET Handling ************************ */
1877
1878
1879 /**
1880  * We're processing (local) results for a search request
1881  * from another peer.  Pass applicable results to the
1882  * peer and if we are done either clean up (operation
1883  * complete) or forward to other peers (more results possible).
1884  *
1885  * @param cls our closure (struct LocalGetContext)
1886  * @param key key for the content
1887  * @param size number of bytes in data
1888  * @param data content stored
1889  * @param type type of the content
1890  * @param priority priority of the content
1891  * @param anonymity anonymity-level for the content
1892  * @param expiration expiration time for the content
1893  * @param uid unique identifier for the datum;
1894  *        maybe 0 if no unique identifier is available
1895  */
1896 static void
1897 process_local_reply (void *cls,
1898                      const GNUNET_HashCode * key,
1899                      uint32_t size,
1900                      const void *data,
1901                      uint32_t type,
1902                      uint32_t priority,
1903                      uint32_t anonymity,
1904                      struct GNUNET_TIME_Absolute
1905                      expiration, 
1906                      uint64_t uid)
1907 {
1908   struct PendingRequest *pr = cls;
1909   struct ProcessReplyClosure prq;
1910   GNUNET_HashCode dhash;
1911   GNUNET_HashCode mhash;
1912   GNUNET_HashCode query;
1913   
1914   pr->drq = NULL;
1915   if (NULL == key)
1916     {
1917       /* no more results */
1918       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1919         pr->task = GNUNET_SCHEDULER_add_now (sched,
1920                                              &forward_request_task,
1921                                              pr);      
1922       return;
1923     }
1924   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1925     {
1926       if (GNUNET_OK != 
1927           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
1928                                             anonymity, expiration, uid, 
1929                                             &process_local_reply,
1930                                             pr))
1931         GNUNET_FS_drq_get_next (GNUNET_YES);
1932       return;
1933     }
1934   /* check for duplicates */
1935   GNUNET_CRYPTO_hash (data, size, &dhash);
1936   mingle_hash (&dhash, 
1937                pr->mingle,
1938                &mhash);
1939   if ( (pr->bf != NULL) &&
1940        (GNUNET_YES ==
1941         GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1942                                            &mhash)) )
1943     {      
1944 #if DEBUG_FS
1945       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1946                   "Result from datastore filtered by bloomfilter (duplicate).\n");
1947 #endif
1948       GNUNET_FS_drq_get_next (GNUNET_YES);
1949       return;
1950     }
1951 #if DEBUG_FS
1952   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953               "Found result for query `%s' in local datastore\n",
1954               GNUNET_h2s (key));
1955 #endif
1956   pr->results_found++;
1957   if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1958        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1959        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1960     {
1961       if (pr->bf == NULL)
1962         {
1963           pr->bf_size = 32;
1964           pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1965                                                       pr->bf_size, 
1966                                                       BLOOMFILTER_K);
1967         }
1968       GNUNET_CONTAINER_bloomfilter_add (pr->bf, 
1969                                         &mhash);
1970     }
1971   memset (&prq, 0, sizeof (prq));
1972   prq.data = data;
1973   prq.expiration = expiration;
1974   prq.size = size;  
1975   if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1976        (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1977                                    size,
1978                                    &query,
1979                                    &prq.namespace)) )
1980     {
1981       GNUNET_break (0);
1982       /* FIXME: consider removing the block? */
1983       GNUNET_FS_drq_get_next (GNUNET_YES);
1984       return;
1985     }
1986   prq.type = type;
1987   prq.priority = priority;  
1988   process_reply (&prq, key, pr);
1989   
1990   if ( (GNUNET_YES == test_load_too_high()) ||
1991        (pr->results_found > 5 + 2 * pr->priority) )
1992     {
1993       GNUNET_FS_drq_get_next (GNUNET_NO);
1994       return;
1995     }
1996   GNUNET_FS_drq_get_next (GNUNET_YES);
1997 }
1998
1999
2000 /**
2001  * The priority level imposes a bound on the maximum
2002  * value for the ttl that can be requested.
2003  *
2004  * @param ttl_in requested ttl
2005  * @param prio given priority
2006  * @return ttl_in if ttl_in is below the limit,
2007  *         otherwise the ttl-limit for the given priority
2008  */
2009 static int32_t
2010 bound_ttl (int32_t ttl_in, uint32_t prio)
2011 {
2012   unsigned long long allowed;
2013
2014   if (ttl_in <= 0)
2015     return ttl_in;
2016   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2017   if (ttl_in > allowed)      
2018     {
2019       if (allowed >= (1 << 30))
2020         return 1 << 30;
2021       return allowed;
2022     }
2023   return ttl_in;
2024 }
2025
2026
2027 /**
2028  * We've received a request with the specified priority.  Bound it
2029  * according to how much we trust the given peer.
2030  * 
2031  * @param prio_in requested priority
2032  * @param cp the peer making the request
2033  * @return effective priority
2034  */
2035 static uint32_t
2036 bound_priority (uint32_t prio_in,
2037                 struct ConnectedPeer *cp)
2038 {
2039   return 0; // FIXME!
2040 }
2041
2042
2043 /**
2044  * Handle P2P "GET" request.
2045  *
2046  * @param cls closure, always NULL
2047  * @param other the other peer involved (sender or receiver, NULL
2048  *        for loopback messages where we are both sender and receiver)
2049  * @param message the actual message
2050  * @param latency reported latency of the connection with 'other'
2051  * @param distance reported distance (DV) to 'other' 
2052  * @return GNUNET_OK to keep the connection open,
2053  *         GNUNET_SYSERR to close it (signal serious error)
2054  */
2055 static int
2056 handle_p2p_get (void *cls,
2057                 const struct GNUNET_PeerIdentity *other,
2058                 const struct GNUNET_MessageHeader *message,
2059                 struct GNUNET_TIME_Relative latency,
2060                 uint32_t distance)
2061 {
2062   struct PendingRequest *pr;
2063   struct PeerRequestEntry *pre;
2064   struct ConnectedPeer *cp;
2065   struct ConnectedPeer *cps;
2066   struct GNUNET_TIME_Relative timeout;
2067   uint16_t msize;
2068   const struct GetMessage *gm;
2069   unsigned int bits;
2070   const GNUNET_HashCode *opt;
2071   uint32_t bm;
2072   size_t bfsize;
2073   uint32_t ttl_decrement;
2074   uint32_t type;
2075   double preference;
2076
2077   msize = ntohs(message->size);
2078   if (msize < sizeof (struct GetMessage))
2079     {
2080       GNUNET_break_op (0);
2081       return GNUNET_SYSERR;
2082     }
2083   gm = (const struct GetMessage*) message;
2084   bm = ntohl (gm->hash_bitmap);
2085   bits = 0;
2086   while (bm > 0)
2087     {
2088       if (1 == (bm & 1))
2089         bits++;
2090       bm >>= 1;
2091     }
2092   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2093     {
2094       GNUNET_break_op (0);
2095       return GNUNET_SYSERR;
2096     }  
2097   opt = (const GNUNET_HashCode*) &gm[1];
2098   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2099
2100   bm = ntohl (gm->hash_bitmap);
2101   if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2102        (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2103     {
2104       GNUNET_break_op (0);
2105       return GNUNET_SYSERR;      
2106     }
2107   bits = 0;
2108   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2109                                            &other->hashPubKey);
2110   GNUNET_assert (NULL != cps);
2111   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2112     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2113                                             &opt[bits++]);
2114   else
2115     cp = cps;
2116   if (cp == NULL)
2117     {
2118       /* FIXME: try connect? */
2119       return GNUNET_OK;
2120     }
2121   /* note that we can really only check load here since otherwise
2122      peers could find out that we are overloaded by not being
2123      disconnected after sending us a malformed query... */
2124   if (GNUNET_YES == test_load_too_high ())
2125     {
2126 #if DEBUG_FS
2127       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2128                   "Dropping query from `%s', this peer is too busy.\n",
2129                   GNUNET_i2s (other));
2130 #endif
2131       return GNUNET_OK;
2132     }
2133
2134 #if DEBUG_FS
2135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2136               "Received request for `%s' of type %u from peer `%4s'\n",
2137               GNUNET_h2s (&gm->query),
2138               (unsigned int) ntohl (gm->type),
2139               GNUNET_i2s (other));
2140 #endif
2141   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2142                       (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2143   if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2144     pr->namespace = (GNUNET_HashCode*) &pr[1];
2145   pr->type = ntohl (gm->type);
2146   pr->mingle = gm->filter_mutator;
2147   if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2148     memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2149   else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2150     {
2151       GNUNET_break_op (0);
2152       GNUNET_free (pr);
2153       return GNUNET_SYSERR;
2154     }
2155   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2156     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2157
2158   pr->anonymity_level = 1;
2159   pr->priority = bound_priority (ntohl (gm->priority), cps);
2160   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2161   pr->query = gm->query;
2162   /* decrement ttl (always) */
2163   ttl_decrement = 2 * TTL_DECREMENT +
2164     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2165                               TTL_DECREMENT);
2166   if ( (pr->ttl < 0) &&
2167        (pr->ttl - ttl_decrement > 0) )
2168     {
2169 #if DEBUG_FS
2170       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171                   "Dropping query from `%s' due to TTL underflow.\n",
2172                   GNUNET_i2s (other));
2173 #endif
2174       /* integer underflow => drop (should be very rare)! */
2175       GNUNET_free (pr);
2176       return GNUNET_OK;
2177     } 
2178   pr->ttl -= ttl_decrement;
2179   pr->start_time = GNUNET_TIME_absolute_get ();
2180
2181   /* get bloom filter */
2182   if (bfsize > 0)
2183     {
2184       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2185                                                   bfsize,
2186                                                   BLOOMFILTER_K);
2187       pr->bf_size = bfsize;
2188     }
2189
2190   /* FIXME: check somewhere if request already exists, and if so,
2191      recycle old state... */
2192   pre = GNUNET_malloc (sizeof (struct PeerRequestEntry));
2193   pre->cp = cp;
2194   pre->req = pr;
2195   GNUNET_CONTAINER_multihashmap_put (query_request_map,
2196                                      &gm->query,
2197                                      pr,
2198                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2199   
2200   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2201                                             pr,
2202                                             GNUNET_TIME_absolute_get().value + pr->ttl);
2203
2204
2205   /* calculate change in traffic preference */
2206   preference = (double) pr->priority;
2207   if (preference < QUERY_BANDWIDTH_VALUE)
2208     preference = QUERY_BANDWIDTH_VALUE;
2209   cps->inc_preference += preference;
2210
2211   /* process locally */
2212   type = pr->type;
2213   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2214     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2215   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2216                                            (pr->priority + 1)); 
2217   pr->drq = GNUNET_FS_drq_get (&gm->query,
2218                                pr->type,                               
2219                                &process_local_reply,
2220                                pr,
2221                                timeout,
2222                                GNUNET_NO);
2223
2224   /* Are multiple results possible?  If so, start processing remotely now! */
2225   switch (pr->type)
2226     {
2227     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2228     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2229       /* only one result, wait for datastore */
2230       break;
2231     default:
2232       pr->task = GNUNET_SCHEDULER_add_now (sched,
2233                                            &forward_request_task,
2234                                            pr);
2235     }
2236
2237   /* make sure we don't track too many requests */
2238   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2239     {
2240       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2241       destroy_pending_request (pr);
2242     }
2243   return GNUNET_OK;
2244 }
2245
2246
2247 /* **************************** CS GET Handling ************************ */
2248
2249
2250 /**
2251  * Handle START_SEARCH-message (search request from client).
2252  *
2253  * @param cls closure
2254  * @param client identification of the client
2255  * @param message the actual message
2256  */
2257 static void
2258 handle_start_search (void *cls,
2259                      struct GNUNET_SERVER_Client *client,
2260                      const struct GNUNET_MessageHeader *message)
2261 {
2262   static GNUNET_HashCode all_zeros;
2263   const struct SearchMessage *sm;
2264   struct ClientList *cl;
2265   struct ClientRequestList *crl;
2266   struct PendingRequest *pr;
2267   uint16_t msize;
2268   unsigned int sc;
2269   uint32_t type;
2270   
2271   msize = ntohs (message->size);
2272   if ( (msize < sizeof (struct SearchMessage)) ||
2273        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2274     {
2275       GNUNET_break (0);
2276       GNUNET_SERVER_receive_done (client,
2277                                   GNUNET_SYSERR);
2278       return;
2279     }
2280   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2281   sm = (const struct SearchMessage*) message;
2282
2283   cl = client_list;
2284   while ( (cl != NULL) &&
2285           (cl->client != client) )
2286     cl = cl->next;
2287   if (cl == NULL)
2288     {
2289       cl = GNUNET_malloc (sizeof (struct ClientList));
2290       cl->client = client;
2291       GNUNET_SERVER_client_keep (client);
2292       cl->next = client_list;
2293       client_list = cl;
2294     }
2295   type = ntohl (sm->type);
2296 #if DEBUG_FS
2297   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2298               "Received request for `%s' of type %u from local client\n",
2299               GNUNET_h2s (&sm->query),
2300               (unsigned int) type);
2301 #endif
2302   /* FIXME: detect duplicate request; if duplicate, simply update (merge)
2303      'pr->replies_seen'! */
2304   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2305                       ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2306   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2307   memset (crl, 0, sizeof (struct ClientRequestList));
2308   crl->client_list = cl;
2309   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2310                                cl->rl_tail,
2311                                crl);  
2312   crl->req = pr;
2313   pr->type = type;
2314   pr->client_request_list = crl;
2315   GNUNET_array_grow (pr->replies_seen,
2316                      pr->replies_seen_size,
2317                      sc);
2318   memcpy (pr->replies_seen,
2319           &sm[1],
2320           sc * sizeof (GNUNET_HashCode));
2321   pr->replies_seen_off = sc;
2322   pr->anonymity_level = ntohl (sm->anonymity_level);
2323   pr->mingle = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
2324                                         (uint32_t) -1);
2325   pr->query = sm->query;
2326   switch (type)
2327     {
2328     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2329     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2330       if (0 != memcmp (&sm->target,
2331                        &all_zeros,
2332                        sizeof (GNUNET_HashCode)))
2333         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2334       break;
2335     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2336       pr->namespace = (GNUNET_HashCode*) &pr[1];
2337       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2338       break;
2339     default:
2340       break;
2341     }
2342   GNUNET_CONTAINER_multihashmap_put (query_request_map,
2343                                      &sm->query,
2344                                      pr,
2345                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2346   pr->drq = GNUNET_FS_drq_get (&sm->query,
2347                                pr->type,                               
2348                                &process_local_reply,
2349                                pr,
2350                                GNUNET_TIME_UNIT_FOREVER_REL,
2351                                GNUNET_YES);
2352 }
2353
2354
2355 /* **************************** Startup ************************ */
2356
2357
2358 /**
2359  * List of handlers for P2P messages
2360  * that we care about.
2361  */
2362 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2363   {
2364     { &handle_p2p_get, 
2365       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2366     { &handle_p2p_put, 
2367       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2368     { NULL, 0, 0 }
2369   };
2370
2371
2372 /**
2373  * List of handlers for the messages understood by this
2374  * service.
2375  */
2376 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2377   {&GNUNET_FS_handle_index_start, NULL, 
2378    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2379   {&GNUNET_FS_handle_index_list_get, NULL, 
2380    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2381   {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
2382    sizeof (struct UnindexMessage) },
2383   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
2384    0 },
2385   {NULL, NULL, 0, 0}
2386 };
2387
2388
2389 /**
2390  * Process fs requests.
2391  *
2392  * @param cls closure
2393  * @param s scheduler to use
2394  * @param server the initialized server
2395  * @param c configuration to use
2396  */
2397 static int
2398 main_init (struct GNUNET_SCHEDULER_Handle *s,
2399            struct GNUNET_SERVER_Handle *server,
2400            const struct GNUNET_CONFIGURATION_Handle *c)
2401 {
2402   sched = s;
2403   cfg = c;
2404   connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2405   query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2406   peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2407   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
2408   core = GNUNET_CORE_connect (sched,
2409                               cfg,
2410                               GNUNET_TIME_UNIT_FOREVER_REL,
2411                               NULL,
2412                               NULL,
2413                               NULL,
2414                               &peer_connect_handler,
2415                               &peer_disconnect_handler,
2416                               NULL, GNUNET_NO,
2417                               NULL, GNUNET_NO,
2418                               p2p_handlers);
2419   if (NULL == core)
2420     {
2421       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2422                   _("Failed to connect to `%s' service.\n"),
2423                   "core");
2424       GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2425       connected_peers = NULL;
2426       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2427       query_request_map = NULL;
2428       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2429       requests_by_expiration_heap = NULL;
2430       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2431       peer_request_map = NULL;
2432
2433       return GNUNET_SYSERR;
2434     }  
2435   GNUNET_SERVER_disconnect_notify (server, 
2436                                    &handle_client_disconnect,
2437                                    NULL);
2438   GNUNET_SERVER_add_handlers (server, handlers);
2439   GNUNET_SCHEDULER_add_delayed (sched,
2440                                 GNUNET_TIME_UNIT_FOREVER_REL,
2441                                 &shutdown_task,
2442                                 NULL);
2443   return GNUNET_OK;
2444 }
2445
2446
2447 /**
2448  * Process fs requests.
2449  *
2450  * @param cls closure
2451  * @param sched scheduler to use
2452  * @param server the initialized server
2453  * @param cfg configuration to use
2454  */
2455 static void
2456 run (void *cls,
2457      struct GNUNET_SCHEDULER_Handle *sched,
2458      struct GNUNET_SERVER_Handle *server,
2459      const struct GNUNET_CONFIGURATION_Handle *cfg)
2460 {
2461   if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2462        (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2463        (GNUNET_OK != main_init (sched, server, cfg)) )
2464     {    
2465       GNUNET_SCHEDULER_shutdown (sched);
2466       return;   
2467     }
2468 }
2469
2470
2471 /**
2472  * The main function for the fs service.
2473  *
2474  * @param argc number of arguments from the command line
2475  * @param argv command line arguments
2476  * @return 0 ok, 1 on error
2477  */
2478 int
2479 main (int argc, char *const *argv)
2480 {
2481   return (GNUNET_OK ==
2482           GNUNET_SERVICE_run (argc,
2483                               argv,
2484                               "fs",
2485                               GNUNET_SERVICE_OPTION_NONE,
2486                               &run, NULL)) ? 0 : 1;
2487 }
2488
2489 /* end of gnunet-service-fs.c */