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