fix
[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_YES
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 tpid 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 tpid 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       if (pr->drq != NULL)
1669         {
1670           GNUNET_FS_drq_get_cancel (pr->drq);
1671           pr->drq = NULL;
1672         }
1673       GNUNET_break (GNUNET_YES ==
1674                     GNUNET_CONTAINER_multihashmap_remove (query_request_map,
1675                                                           key,
1676                                                           pr));
1677       break;
1678     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1679       if (0 != memcmp (pr->namespace,
1680                        &prq->namespace,
1681                        sizeof (GNUNET_HashCode)))
1682         return GNUNET_YES; /* wrong namespace */        
1683       /* then: fall-through! */
1684     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1685       if (pr->bf != NULL) 
1686         {
1687           mingle_hash (&chash, pr->mingle, &mhash);
1688           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1689                                                                &mhash))
1690             return GNUNET_YES; /* duplicate */
1691           GNUNET_CONTAINER_bloomfilter_add (pr->bf,
1692                                             &mhash);
1693         }
1694       if (pr->client_request_list != NULL)
1695         {
1696           if (pr->replies_seen_size == pr->replies_seen_off)
1697             {
1698               GNUNET_array_grow (pr->replies_seen,
1699                                  pr->replies_seen_size,
1700                                  pr->replies_seen_size * 2 + 4);
1701               if (pr->bf != NULL)
1702                 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
1703               pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1704                                             &pr->mingle,
1705                                             &pr->bf_size,
1706                                             pr->replies_seen);
1707             }
1708             pr->replies_seen[pr->replies_seen_off++] = chash;
1709               
1710         }
1711       break;
1712     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1713       // FIXME: any checks against duplicates for SKBlocks?
1714       break;
1715     default:
1716       GNUNET_break (0);
1717       return GNUNET_YES;
1718     }
1719   prio = pr->priority;
1720   prq->priority += pr->remaining_priority;
1721   pr->remaining_priority = 0;
1722   if (pr->client_request_list != NULL)
1723     {
1724 #if DEBUG_FS
1725       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1726                   "Transmitting result for query `%s' to local client\n",
1727                   GNUNET_h2s (key));
1728 #endif  
1729       cl = pr->client_request_list->client_list;
1730       msize = sizeof (struct PutMessage) + prq->size;
1731       creply = GNUNET_malloc (msize + sizeof (struct ClientResponseMessage));
1732       creply->msize = msize;
1733       creply->client_list = cl;
1734       GNUNET_CONTAINER_DLL_insert_after (cl->res_head,
1735                                          cl->res_tail,
1736                                          cl->res_tail,
1737                                          creply);      
1738       pm = (struct PutMessage*) &creply[1];
1739       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1740       pm->header.size = htons (msize);
1741       pm->type = htonl (prq->type);
1742       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1743       memcpy (&pm[1], prq->data, prq->size);      
1744       if (NULL == cl->th)
1745         cl->th = GNUNET_SERVER_notify_transmit_ready (cl->client,
1746                                                       msize,
1747                                                       GNUNET_TIME_UNIT_FOREVER_REL,
1748                                                       &transmit_to_client,
1749                                                       cl);
1750       GNUNET_break (cl->th != NULL);
1751     }
1752   else
1753     {
1754       cp = pr->cp;
1755 #if DEBUG_FS
1756       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757                   "Transmitting result for query `%s' to other peer (PID=%u)\n",
1758                   GNUNET_h2s (key),
1759                   (unsigned int) cp->pid);
1760 #endif  
1761       msize = sizeof (struct PutMessage) + prq->size;
1762       reply = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1763       reply->cont = &transmit_reply_continuation;
1764       reply->cont_cls = pr;
1765       reply->msize = msize;
1766       reply->priority = (uint32_t) -1; /* send replies first! */
1767       pm = (struct PutMessage*) &reply[1];
1768       pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
1769       pm->header.size = htons (msize);
1770       pm->type = htonl (prq->type);
1771       pm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
1772       memcpy (&pm[1], prq->data, prq->size);
1773       add_to_pending_messages_for_peer (cp, reply, pr);
1774     }
1775
1776
1777   // FIXME: implement hot-path routing statistics keeping!
1778   return GNUNET_YES;
1779 }
1780
1781
1782 /**
1783  * Handle P2P "PUT" message.
1784  *
1785  * @param cls closure, always NULL
1786  * @param other the other peer involved (sender or receiver, NULL
1787  *        for loopback messages where we are both sender and receiver)
1788  * @param message the actual message
1789  * @param latency reported latency of the connection with 'other'
1790  * @param distance reported distance (DV) to 'other' 
1791  * @return GNUNET_OK to keep the connection open,
1792  *         GNUNET_SYSERR to close it (signal serious error)
1793  */
1794 static int
1795 handle_p2p_put (void *cls,
1796                 const struct GNUNET_PeerIdentity *other,
1797                 const struct GNUNET_MessageHeader *message,
1798                 struct GNUNET_TIME_Relative latency,
1799                 uint32_t distance)
1800 {
1801   const struct PutMessage *put;
1802   uint16_t msize;
1803   size_t dsize;
1804   uint32_t type;
1805   struct GNUNET_TIME_Absolute expiration;
1806   GNUNET_HashCode query;
1807   struct ProcessReplyClosure prq;
1808
1809   msize = ntohs (message->size);
1810   if (msize < sizeof (struct PutMessage))
1811     {
1812       GNUNET_break_op(0);
1813       return GNUNET_SYSERR;
1814     }
1815   put = (const struct PutMessage*) message;
1816   dsize = msize - sizeof (struct PutMessage);
1817   type = ntohl (put->type);
1818   expiration = GNUNET_TIME_absolute_ntoh (put->expiration);
1819
1820   /* first, validate! */
1821   switch (type)
1822     {
1823     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
1824     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
1825       GNUNET_CRYPTO_hash (&put[1], dsize, &query);
1826       break;
1827     case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
1828       if (GNUNET_OK !=
1829           check_kblock ((const struct KBlock*) &put[1],
1830                         dsize,
1831                         &query))
1832         return GNUNET_SYSERR;
1833       break;
1834     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
1835       if (GNUNET_OK !=
1836           check_sblock ((const struct SBlock*) &put[1],
1837                         dsize,
1838                         &query,
1839                         &prq.namespace))
1840         return GNUNET_SYSERR;
1841       break;
1842     case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
1843       // FIXME -- validate SKBLOCK!
1844       GNUNET_break (0);
1845       return GNUNET_OK;
1846     default:
1847       /* unknown block type */
1848       GNUNET_break_op (0);
1849       return GNUNET_SYSERR;
1850     }
1851
1852 #if DEBUG_FS
1853   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1854               "Received result for query `%s' from peer `%4s'\n",
1855               GNUNET_h2s (&query),
1856               GNUNET_i2s (other));
1857 #endif
1858   /* now, lookup 'query' */
1859   prq.data = (const void*) &put[1];
1860   prq.size = dsize;
1861   prq.type = type;
1862   prq.expiration = expiration;
1863   prq.priority = 0;
1864   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
1865                                               &query,
1866                                               &process_reply,
1867                                               &prq);
1868   // FIXME: if migration is on and load is low,
1869   // queue to store data in datastore;
1870   // use "prq.priority" for that!
1871   return GNUNET_OK;
1872 }
1873
1874
1875 /* **************************** P2P GET Handling ************************ */
1876
1877
1878 /**
1879  * We're processing (local) results for a search request
1880  * from another peer.  Pass applicable results to the
1881  * peer and if we are done either clean up (operation
1882  * complete) or forward to other peers (more results possible).
1883  *
1884  * @param cls our closure (struct LocalGetContext)
1885  * @param key key for the content
1886  * @param size number of bytes in data
1887  * @param data content stored
1888  * @param type type of the content
1889  * @param priority priority of the content
1890  * @param anonymity anonymity-level for the content
1891  * @param expiration expiration time for the content
1892  * @param uid unique identifier for the datum;
1893  *        maybe 0 if no unique identifier is available
1894  */
1895 static void
1896 process_local_reply (void *cls,
1897                      const GNUNET_HashCode * key,
1898                      uint32_t size,
1899                      const void *data,
1900                      uint32_t type,
1901                      uint32_t priority,
1902                      uint32_t anonymity,
1903                      struct GNUNET_TIME_Absolute
1904                      expiration, 
1905                      uint64_t uid)
1906 {
1907   struct PendingRequest *pr = cls;
1908   struct ProcessReplyClosure prq;
1909   GNUNET_HashCode dhash;
1910   GNUNET_HashCode mhash;
1911   GNUNET_HashCode query;
1912   
1913   pr->drq = NULL;
1914   if (NULL == key)
1915     {
1916       if (pr->client_request_list != NULL)
1917         GNUNET_SERVER_receive_done (pr->client_request_list->client_list->client, 
1918                                     GNUNET_YES);
1919       /* no more results */
1920       if (pr->task == GNUNET_SCHEDULER_NO_TASK)
1921         pr->task = GNUNET_SCHEDULER_add_now (sched,
1922                                              &forward_request_task,
1923                                              pr);      
1924       return;
1925     }
1926   if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1927     {
1928       if (GNUNET_OK != 
1929           GNUNET_FS_handle_on_demand_block (key, size, data, type, priority, 
1930                                             anonymity, expiration, uid, 
1931                                             &process_local_reply,
1932                                             pr))
1933         GNUNET_FS_drq_get_next (GNUNET_YES);
1934       return;
1935     }
1936   /* check for duplicates */
1937   GNUNET_CRYPTO_hash (data, size, &dhash);
1938   mingle_hash (&dhash, 
1939                pr->mingle,
1940                &mhash);
1941   if ( (pr->bf != NULL) &&
1942        (GNUNET_YES ==
1943         GNUNET_CONTAINER_bloomfilter_test (pr->bf,
1944                                            &mhash)) )
1945     {      
1946 #if DEBUG_FS
1947       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1948                   "Result from datastore filtered by bloomfilter (duplicate).\n");
1949 #endif
1950       GNUNET_FS_drq_get_next (GNUNET_YES);
1951       return;
1952     }
1953 #if DEBUG_FS
1954   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1955               "Found result for query `%s' in local datastore\n",
1956               GNUNET_h2s (key));
1957 #endif
1958   pr->results_found++;
1959   if ( (pr->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1960        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1961        (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1962     {
1963       if (pr->bf == NULL)
1964         {
1965           pr->bf_size = 32;
1966           pr->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1967                                                       pr->bf_size, 
1968                                                       BLOOMFILTER_K);
1969         }
1970       GNUNET_CONTAINER_bloomfilter_add (pr->bf, 
1971                                         &mhash);
1972     }
1973   memset (&prq, 0, sizeof (prq));
1974   prq.data = data;
1975   prq.expiration = expiration;
1976   prq.size = size;  
1977   if ( (type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) &&
1978        (GNUNET_OK != check_sblock ((const struct SBlock*) data,
1979                                    size,
1980                                    &query,
1981                                    &prq.namespace)) )
1982     {
1983       GNUNET_break (0);
1984       /* FIXME: consider removing the block? */
1985       GNUNET_FS_drq_get_next (GNUNET_YES);
1986       return;
1987     }
1988   prq.type = type;
1989   prq.priority = priority;  
1990   process_reply (&prq, key, pr);
1991   
1992   if ( (GNUNET_YES == test_load_too_high()) ||
1993        (pr->results_found > 5 + 2 * pr->priority) ||
1994        (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK) )
1995     {
1996       GNUNET_FS_drq_get_next (GNUNET_NO);
1997       return;
1998     }
1999   GNUNET_FS_drq_get_next (GNUNET_YES);
2000 }
2001
2002
2003 /**
2004  * The priority level imposes a bound on the maximum
2005  * value for the ttl that can be requested.
2006  *
2007  * @param ttl_in requested ttl
2008  * @param prio given priority
2009  * @return ttl_in if ttl_in is below the limit,
2010  *         otherwise the ttl-limit for the given priority
2011  */
2012 static int32_t
2013 bound_ttl (int32_t ttl_in, uint32_t prio)
2014 {
2015   unsigned long long allowed;
2016
2017   if (ttl_in <= 0)
2018     return ttl_in;
2019   allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000; 
2020   if (ttl_in > allowed)      
2021     {
2022       if (allowed >= (1 << 30))
2023         return 1 << 30;
2024       return allowed;
2025     }
2026   return ttl_in;
2027 }
2028
2029
2030 /**
2031  * We've received a request with the specified priority.  Bound it
2032  * according to how much we trust the given peer.
2033  * 
2034  * @param prio_in requested priority
2035  * @param cp the peer making the request
2036  * @return effective priority
2037  */
2038 static uint32_t
2039 bound_priority (uint32_t prio_in,
2040                 struct ConnectedPeer *cp)
2041 {
2042   return 0; // FIXME!
2043 }
2044
2045
2046 /**
2047  * Closure for 'check_duplicate_request'.
2048  */
2049 struct CheckDuplicateRequestClosure
2050 {
2051   /**
2052    * The new request we should check if it already exists.
2053    */
2054   const struct PendingRequest *pr;
2055
2056   /**
2057    * Existing request found by the checker, NULL if none.
2058    */
2059   struct PendingRequest *have;
2060 };
2061
2062
2063 /**
2064  * Iterator over entries in the 'query_request_map' that
2065  * tries to see if we have the same request pending from
2066  * the same peer already.
2067  *
2068  * @param cls closure (our 'struct CheckDuplicateRequestClosure')
2069  * @param key current key code (query, ignored, must match)
2070  * @param value value in the hash map (a 'struct PendingRequest' 
2071  *              that already exists)
2072  * @return GNUNET_YES if we should continue to
2073  *         iterate (no match yet)
2074  *         GNUNET_NO if not (match found).
2075  */
2076 static int
2077 check_duplicate_request (void *cls,
2078                          const GNUNET_HashCode * key,
2079                          void *value)
2080 {
2081   struct CheckDuplicateRequestClosure *cdc = cls;
2082   struct PendingRequest *have = value;
2083
2084   if (cdc->pr->target_pid == have->target_pid)
2085     {
2086       cdc->have = have;
2087       return GNUNET_NO;
2088     }
2089   return GNUNET_YES;
2090 }
2091
2092
2093 /**
2094  * Handle P2P "GET" request.
2095  *
2096  * @param cls closure, always NULL
2097  * @param other the other peer involved (sender or receiver, NULL
2098  *        for loopback messages where we are both sender and receiver)
2099  * @param message the actual message
2100  * @param latency reported latency of the connection with 'other'
2101  * @param distance reported distance (DV) to 'other' 
2102  * @return GNUNET_OK to keep the connection open,
2103  *         GNUNET_SYSERR to close it (signal serious error)
2104  */
2105 static int
2106 handle_p2p_get (void *cls,
2107                 const struct GNUNET_PeerIdentity *other,
2108                 const struct GNUNET_MessageHeader *message,
2109                 struct GNUNET_TIME_Relative latency,
2110                 uint32_t distance)
2111 {
2112   struct PendingRequest *pr;
2113   struct ConnectedPeer *cp;
2114   struct ConnectedPeer *cps;
2115   struct CheckDuplicateRequestClosure cdc;
2116   struct GNUNET_TIME_Relative timeout;
2117   uint16_t msize;
2118   const struct GetMessage *gm;
2119   unsigned int bits;
2120   const GNUNET_HashCode *opt;
2121   uint32_t bm;
2122   size_t bfsize;
2123   uint32_t ttl_decrement;
2124   uint32_t type;
2125   double preference;
2126
2127   msize = ntohs(message->size);
2128   if (msize < sizeof (struct GetMessage))
2129     {
2130       GNUNET_break_op (0);
2131       return GNUNET_SYSERR;
2132     }
2133   gm = (const struct GetMessage*) message;
2134   bm = ntohl (gm->hash_bitmap);
2135   bits = 0;
2136   while (bm > 0)
2137     {
2138       if (1 == (bm & 1))
2139         bits++;
2140       bm >>= 1;
2141     }
2142   if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2143     {
2144       GNUNET_break_op (0);
2145       return GNUNET_SYSERR;
2146     }  
2147   opt = (const GNUNET_HashCode*) &gm[1];
2148   bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2149   bm = ntohl (gm->hash_bitmap);
2150   if ( (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)) &&
2151        (ntohl (gm->type) == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) )
2152     {
2153       GNUNET_break_op (0);
2154       return GNUNET_SYSERR;      
2155     }
2156   bits = 0;
2157   cps = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2158                                            &other->hashPubKey);
2159   GNUNET_assert (NULL != cps);
2160   if (0 != (bm & GET_MESSAGE_BIT_RETURN_TO))
2161     cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2162                                             &opt[bits++]);
2163   else
2164     cp = cps;
2165   if (cp == NULL)
2166     {
2167       /* FIXME: try connect? */
2168       return GNUNET_OK;
2169     }
2170   /* note that we can really only check load here since otherwise
2171      peers could find out that we are overloaded by not being
2172      disconnected after sending us a malformed query... */
2173   if (GNUNET_YES == test_load_too_high ())
2174     {
2175 #if DEBUG_FS
2176       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2177                   "Dropping query from `%s', this peer is too busy.\n",
2178                   GNUNET_i2s (other));
2179 #endif
2180       return GNUNET_OK;
2181     }
2182
2183 #if DEBUG_FS
2184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2185               "Received request for `%s' of type %u from peer `%4s'\n",
2186               GNUNET_h2s (&gm->query),
2187               (unsigned int) ntohl (gm->type),
2188               GNUNET_i2s (other));
2189 #endif
2190   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2191                       (bm & GET_MESSAGE_BIT_SKS_NAMESPACE)?sizeof(GNUNET_HashCode):0);
2192   if ((bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2193     pr->namespace = (GNUNET_HashCode*) &pr[1];
2194   pr->type = ntohl (gm->type);
2195   pr->mingle = ntohl (gm->filter_mutator);
2196   if (0 != (bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2197     memcpy (&pr[1], &opt[bits++], sizeof (GNUNET_HashCode));
2198   else if (pr->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2199     {
2200       GNUNET_break_op (0);
2201       GNUNET_free (pr);
2202       return GNUNET_SYSERR;
2203     }
2204   if (0 != (bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2205     pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &opt[bits++]);
2206
2207   pr->anonymity_level = 1;
2208   pr->priority = bound_priority (ntohl (gm->priority), cps);
2209   pr->ttl = bound_ttl (ntohl (gm->ttl), pr->priority);
2210   pr->query = gm->query;
2211   /* decrement ttl (always) */
2212   ttl_decrement = 2 * TTL_DECREMENT +
2213     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2214                               TTL_DECREMENT);
2215   if ( (pr->ttl < 0) &&
2216        (pr->ttl - ttl_decrement > 0) )
2217     {
2218 #if DEBUG_FS
2219       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2220                   "Dropping query from `%s' due to TTL underflow.\n",
2221                   GNUNET_i2s (other));
2222 #endif
2223       /* integer underflow => drop (should be very rare)! */
2224       GNUNET_free (pr);
2225       return GNUNET_OK;
2226     } 
2227   pr->ttl -= ttl_decrement;
2228   pr->start_time = GNUNET_TIME_absolute_get ();
2229
2230   /* get bloom filter */
2231   if (bfsize > 0)
2232     {
2233       pr->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &opt[bits],
2234                                                   bfsize,
2235                                                   BLOOMFILTER_K);
2236       pr->bf_size = bfsize;
2237     }
2238
2239   cdc.have = NULL;
2240   cdc.pr = pr;
2241   GNUNET_CONTAINER_multihashmap_get_multiple (query_request_map,
2242                                               &gm->query,
2243                                               &check_duplicate_request,
2244                                               &cdc);
2245   if (cdc.have != NULL)
2246     {
2247       if (cdc.have->start_time.value + cdc.have->ttl >=
2248           pr->start_time.value + pr->ttl)
2249         {
2250           /* existing request has higher TTL, drop new one! */
2251           cdc.have->priority += pr->priority;
2252           destroy_pending_request (pr);
2253           return GNUNET_OK;
2254         }
2255       else
2256         {
2257           /* existing request has lower TTL, drop old one! */
2258           pr->priority += cdc.have->priority;
2259           /* Possible optimization: if we have applicable pending
2260              replies in 'cdc.have', we might want to move those over
2261              (this is a really rare special-case, so it is not clear
2262              that this would be worth it) */
2263           destroy_pending_request (cdc.have);
2264           /* keep processing 'pr'! */
2265         }
2266     }
2267
2268   pr->cp = cp;
2269   GNUNET_CONTAINER_multihashmap_put (query_request_map,
2270                                      &gm->query,
2271                                      pr,
2272                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2273   GNUNET_CONTAINER_multihashmap_put (peer_request_map,
2274                                      &other->hashPubKey,
2275                                      pr,
2276                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2277   
2278   pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration_heap,
2279                                             pr,
2280                                             pr->start_time.value + pr->ttl);
2281
2282
2283   /* calculate change in traffic preference */
2284   preference = (double) pr->priority;
2285   if (preference < QUERY_BANDWIDTH_VALUE)
2286     preference = QUERY_BANDWIDTH_VALUE;
2287   cps->inc_preference += preference;
2288
2289   /* process locally */
2290   type = pr->type;
2291   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2292     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2293   timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2294                                            (pr->priority + 1)); 
2295   pr->drq = GNUNET_FS_drq_get (&gm->query,
2296                                pr->type,                               
2297                                &process_local_reply,
2298                                pr,
2299                                timeout,
2300                                GNUNET_NO);
2301
2302   /* Are multiple results possible?  If so, start processing remotely now! */
2303   switch (pr->type)
2304     {
2305     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2306     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2307       /* only one result, wait for datastore */
2308       break;
2309     default:
2310       pr->task = GNUNET_SCHEDULER_add_now (sched,
2311                                            &forward_request_task,
2312                                            pr);
2313     }
2314
2315   /* make sure we don't track too many requests */
2316   if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration_heap) > max_pending_requests)
2317     {
2318       pr = GNUNET_CONTAINER_heap_peek (requests_by_expiration_heap);
2319       destroy_pending_request (pr);
2320     }
2321   return GNUNET_OK;
2322 }
2323
2324
2325 /* **************************** CS GET Handling ************************ */
2326
2327
2328 /**
2329  * Handle START_SEARCH-message (search request from client).
2330  *
2331  * @param cls closure
2332  * @param client identification of the client
2333  * @param message the actual message
2334  */
2335 static void
2336 handle_start_search (void *cls,
2337                      struct GNUNET_SERVER_Client *client,
2338                      const struct GNUNET_MessageHeader *message)
2339 {
2340   static GNUNET_HashCode all_zeros;
2341   const struct SearchMessage *sm;
2342   struct ClientList *cl;
2343   struct ClientRequestList *crl;
2344   struct PendingRequest *pr;
2345   uint16_t msize;
2346   unsigned int sc;
2347   uint32_t type;
2348   
2349   msize = ntohs (message->size);
2350   if ( (msize < sizeof (struct SearchMessage)) ||
2351        (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2352     {
2353       GNUNET_break (0);
2354       GNUNET_SERVER_receive_done (client,
2355                                   GNUNET_SYSERR);
2356       return;
2357     }
2358   sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2359   sm = (const struct SearchMessage*) message;
2360
2361   cl = client_list;
2362   while ( (cl != NULL) &&
2363           (cl->client != client) )
2364     cl = cl->next;
2365   if (cl == NULL)
2366     {
2367       cl = GNUNET_malloc (sizeof (struct ClientList));
2368       cl->client = client;
2369       GNUNET_SERVER_client_keep (client);
2370       cl->next = client_list;
2371       client_list = cl;
2372     }
2373   type = ntohl (sm->type);
2374 #if DEBUG_FS
2375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2376               "Received request for `%s' of type %u from local client\n",
2377               GNUNET_h2s (&sm->query),
2378               (unsigned int) type);
2379 #endif
2380
2381   /* detect duplicate KBLOCK requests */
2382   if (type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK)
2383     {
2384       crl = cl->rl_head;
2385       while ( (crl != NULL) &&
2386               ( (0 != memcmp (&crl->req->query,
2387                               &sm->query,
2388                               sizeof (GNUNET_HashCode))) ||
2389                 (crl->req->type != type) ) )
2390         crl = crl->next;
2391       if (crl != NULL)  
2392         { 
2393           pr = crl->req;
2394           /* Duplicate request (used to send long list of
2395              known/blocked results); merge 'pr->replies_seen'
2396              and update bloom filter */
2397           GNUNET_array_grow (pr->replies_seen,
2398                              pr->replies_seen_size,
2399                              pr->replies_seen_off + sc);
2400           memcpy (&pr->replies_seen[pr->replies_seen_off],
2401                   &sm[1],
2402                   sc * sizeof (GNUNET_HashCode));
2403           pr->replies_seen_off += sc;
2404           if (pr->bf != NULL)
2405             GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2406           pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2407                                         &pr->mingle,
2408                                         &pr->bf_size,
2409                                         pr->replies_seen);
2410           GNUNET_SERVER_receive_done (client,
2411                                       GNUNET_OK);
2412           return;
2413         }
2414     }
2415   pr = GNUNET_malloc (sizeof (struct PendingRequest) + 
2416                       ((type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)?sizeof(GNUNET_HashCode):0));
2417   crl = GNUNET_malloc (sizeof (struct ClientRequestList));
2418   memset (crl, 0, sizeof (struct ClientRequestList));
2419   crl->client_list = cl;
2420   GNUNET_CONTAINER_DLL_insert (cl->rl_head,
2421                                cl->rl_tail,
2422                                crl);  
2423   crl->req = pr;
2424   pr->type = type;
2425   pr->client_request_list = crl;
2426   GNUNET_array_grow (pr->replies_seen,
2427                      pr->replies_seen_size,
2428                      sc);
2429   memcpy (pr->replies_seen,
2430           &sm[1],
2431           sc * sizeof (GNUNET_HashCode));
2432   pr->replies_seen_off = sc;
2433   pr->anonymity_level = ntohl (sm->anonymity_level); 
2434   pr->bf = refresh_bloomfilter (pr->replies_seen_off,
2435                                 &pr->mingle,
2436                                 &pr->bf_size,
2437                                 pr->replies_seen);
2438  pr->query = sm->query;
2439   switch (type)
2440     {
2441     case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2442     case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2443       if (0 != memcmp (&sm->target,
2444                        &all_zeros,
2445                        sizeof (GNUNET_HashCode)))
2446         pr->target_pid = GNUNET_PEER_intern ((const struct GNUNET_PeerIdentity*) &sm->target);
2447       break;
2448     case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2449       pr->namespace = (GNUNET_HashCode*) &pr[1];
2450       memcpy (&pr[1], &sm->target, sizeof (GNUNET_HashCode));
2451       break;
2452     default:
2453       break;
2454     }
2455   GNUNET_CONTAINER_multihashmap_put (query_request_map,
2456                                      &sm->query,
2457                                      pr,
2458                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2459   if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2460     type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* get on-demand blocks too! */
2461   pr->drq = GNUNET_FS_drq_get (&sm->query,
2462                                type,                           
2463                                &process_local_reply,
2464                                pr,
2465                                GNUNET_TIME_UNIT_FOREVER_REL,
2466                                GNUNET_YES);
2467 }
2468
2469
2470 /* **************************** Startup ************************ */
2471
2472
2473 /**
2474  * List of handlers for P2P messages
2475  * that we care about.
2476  */
2477 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
2478   {
2479     { &handle_p2p_get, 
2480       GNUNET_MESSAGE_TYPE_FS_GET, 0 },
2481     { &handle_p2p_put, 
2482       GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
2483     { NULL, 0, 0 }
2484   };
2485
2486
2487 /**
2488  * List of handlers for the messages understood by this
2489  * service.
2490  */
2491 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2492   {&GNUNET_FS_handle_index_start, NULL, 
2493    GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2494   {&GNUNET_FS_handle_index_list_get, NULL, 
2495    GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2496   {&GNUNET_FS_handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX, 
2497    sizeof (struct UnindexMessage) },
2498   {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH, 
2499    0 },
2500   {NULL, NULL, 0, 0}
2501 };
2502
2503
2504 /**
2505  * Process fs requests.
2506  *
2507  * @param s scheduler to use
2508  * @param server the initialized server
2509  * @param c configuration to use
2510  */
2511 static int
2512 main_init (struct GNUNET_SCHEDULER_Handle *s,
2513            struct GNUNET_SERVER_Handle *server,
2514            const struct GNUNET_CONFIGURATION_Handle *c)
2515 {
2516   sched = s;
2517   cfg = c;
2518   connected_peers = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2519   query_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2520   peer_request_map = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
2521   requests_by_expiration_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 
2522   core = GNUNET_CORE_connect (sched,
2523                               cfg,
2524                               GNUNET_TIME_UNIT_FOREVER_REL,
2525                               NULL,
2526                               NULL,
2527                               NULL,
2528                               &peer_connect_handler,
2529                               &peer_disconnect_handler,
2530                               NULL, GNUNET_NO,
2531                               NULL, GNUNET_NO,
2532                               p2p_handlers);
2533   if (NULL == core)
2534     {
2535       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2536                   _("Failed to connect to `%s' service.\n"),
2537                   "core");
2538       GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2539       connected_peers = NULL;
2540       GNUNET_CONTAINER_multihashmap_destroy (query_request_map);
2541       query_request_map = NULL;
2542       GNUNET_CONTAINER_heap_destroy (requests_by_expiration_heap);
2543       requests_by_expiration_heap = NULL;
2544       GNUNET_CONTAINER_multihashmap_destroy (peer_request_map);
2545       peer_request_map = NULL;
2546
2547       return GNUNET_SYSERR;
2548     }  
2549   GNUNET_SERVER_disconnect_notify (server, 
2550                                    &handle_client_disconnect,
2551                                    NULL);
2552   GNUNET_SERVER_add_handlers (server, handlers);
2553   GNUNET_SCHEDULER_add_delayed (sched,
2554                                 GNUNET_TIME_UNIT_FOREVER_REL,
2555                                 &shutdown_task,
2556                                 NULL);
2557   return GNUNET_OK;
2558 }
2559
2560
2561 /**
2562  * Process fs requests.
2563  *
2564  * @param cls closure
2565  * @param sched scheduler to use
2566  * @param server the initialized server
2567  * @param cfg configuration to use
2568  */
2569 static void
2570 run (void *cls,
2571      struct GNUNET_SCHEDULER_Handle *sched,
2572      struct GNUNET_SERVER_Handle *server,
2573      const struct GNUNET_CONFIGURATION_Handle *cfg)
2574 {
2575   if ( (GNUNET_OK != GNUNET_FS_drq_init (sched, cfg)) ||
2576        (GNUNET_OK != GNUNET_FS_indexing_init (sched, cfg)) ||
2577        (GNUNET_OK != main_init (sched, server, cfg)) )
2578     {    
2579       GNUNET_SCHEDULER_shutdown (sched);
2580       return;   
2581     }
2582 }
2583
2584
2585 /**
2586  * The main function for the fs service.
2587  *
2588  * @param argc number of arguments from the command line
2589  * @param argv command line arguments
2590  * @return 0 ok, 1 on error
2591  */
2592 int
2593 main (int argc, char *const *argv)
2594 {
2595   return (GNUNET_OK ==
2596           GNUNET_SERVICE_run (argc,
2597                               argv,
2598                               "fs",
2599                               GNUNET_SERVICE_OPTION_NONE,
2600                               &run, NULL)) ? 0 : 1;
2601 }
2602
2603 /* end of gnunet-service-fs.c */