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