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