2 This file is part of GNUnet.
3 (C) 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file fs/gnunet-service-fs.c
23 * @brief program that provides the file-sharing service
24 * @author Christian Grothoff
27 * - fix gazillion of minor FIXME's
28 * - possible major issue: we may queue "gazillions" of (K|S)Blocks for the
29 * core to transmit to another peer; need to make sure this is bounded overall...
30 * - randomly delay processing for improved anonymity (can wait)
31 * - content migration (put in local DS) (can wait)
32 * - handle some special cases when forwarding replies based on tracked requests (can wait)
33 * - tracking of success correlations for hot-path routing (can wait)
34 * - various load-based actions (can wait)
35 * - validation of KSBLOCKS (can wait)
36 * - remove on-demand blocks if they keep failing (can wait)
37 * - check that we decrement PIDs always where necessary (can wait)
38 * - find out how to use core-pulling instead of pushing (at least for some cases)
42 #include "gnunet_core_service.h"
43 #include "gnunet_datastore_service.h"
44 #include "gnunet_peer_lib.h"
45 #include "gnunet_protocols.h"
46 #include "gnunet_signatures.h"
47 #include "gnunet_util_lib.h"
52 * In-memory information about indexed files (also available
59 * This is a linked list.
61 struct IndexInfo *next;
64 * Name of the indexed file. Memory allocated
65 * at the end of this struct (do not free).
70 * Context for transmitting confirmation to client,
71 * NULL if we've done this already.
73 struct GNUNET_SERVER_TransmitContext *tc;
76 * Hash of the contents of the file.
78 GNUNET_HashCode file_id;
84 * Signature of a function that is called whenever a datastore
85 * request can be processed (or an entry put on the queue times out).
88 * @param ok GNUNET_OK if DS is ready, GNUNET_SYSERR on timeout
90 typedef void (*RequestFunction)(void *cls,
95 * Doubly-linked list of our requests for the datastore.
97 struct DatastoreRequestQueue
101 * This is a doubly-linked list.
103 struct DatastoreRequestQueue *next;
106 * This is a doubly-linked list.
108 struct DatastoreRequestQueue *prev;
111 * Function to call (will issue the request).
121 * When should this request time-out because we don't care anymore?
123 struct GNUNET_TIME_Absolute timeout;
126 * ID of task used for signaling timeout.
128 GNUNET_SCHEDULER_TaskIdentifier task;
134 * Closure for processing START_SEARCH messages from a client.
136 struct LocalGetContext
140 * This is a doubly-linked list.
142 struct LocalGetContext *next;
145 * This is a doubly-linked list.
147 struct LocalGetContext *prev;
150 * Client that initiated the search.
152 struct GNUNET_SERVER_Client *client;
155 * Array of results that we've already received
158 GNUNET_HashCode *results;
161 * Bloomfilter over all results (for fast query construction);
162 * NULL if we don't have any results.
164 * FIXME: this member is not used, is that OK? If so, it should
167 struct GNUNET_CONTAINER_BloomFilter *results_bf;
170 * DS request associated with this operation.
172 struct DatastoreRequestQueue *req;
175 * Current result message to transmit to client (or NULL).
177 struct ContentMessage *result;
180 * Type of the content that we're looking for.
186 * Desired anonymity level.
188 uint32_t anonymity_level;
191 * Number of results actually stored in the results array.
193 unsigned int results_used;
196 * Size of the results array in memory.
198 unsigned int results_size;
201 * Size (in bytes) of the 'results_bf' bloomfilter.
203 * FIXME: this member is not used, is that OK? If so, it should
206 size_t results_bf_size;
209 * If the request is for a DBLOCK or IBLOCK, this is the identity of
210 * the peer that is known to have a response. Set to all-zeros if
211 * such a target is not known (note that even if OUR anonymity
212 * level is >0 we may happen to know the responder's identity;
213 * nevertheless, we should probably not use it for a DHT-lookup
214 * or similar blunt actions in order to avoid exposing ourselves).
216 struct GNUNET_PeerIdentity target;
219 * If the request is for an SBLOCK, this is the identity of the
220 * pseudonym to which the SBLOCK belongs.
222 GNUNET_HashCode namespace;
225 * Hash of the keyword (aka query) for KBLOCKs; Hash of
226 * the CHK-encoded block for DBLOCKS and IBLOCKS (aka query)
227 * and hash of the identifier XORed with the target for
228 * SBLOCKS (aka query).
230 GNUNET_HashCode query;
236 * Possible routing policies for an FS-GET request.
241 * Simply drop the request.
243 ROUTING_POLICY_NONE = 0,
246 * Answer it if we can from local datastore.
248 ROUTING_POLICY_ANSWER = 1,
251 * Forward the request to other peers (if possible).
253 ROUTING_POLICY_FORWARD = 2,
256 * Forward to other peers, and ask them to route
257 * the response via ourselves.
259 ROUTING_POLICY_INDIRECT = 6,
262 * Do everything we could possibly do (that would
265 ROUTING_POLICY_ALL = 7
270 * Internal context we use for our initial processing
273 struct ProcessGetContext
276 * The search query (used for datastore lookup).
278 GNUNET_HashCode query;
281 * Which peer we should forward the response to.
283 struct GNUNET_PeerIdentity reply_to;
286 * Namespace for the result (only set for SKS requests)
288 GNUNET_HashCode namespace;
291 * Peer that we should forward the query to if possible
292 * (since that peer likely has the content).
294 struct GNUNET_PeerIdentity prime_target;
297 * When did we receive this request?
299 struct GNUNET_TIME_Absolute start_time;
302 * Our entry in the DRQ (non-NULL while we wait for our
303 * turn to interact with the local database).
305 struct DatastoreRequestQueue *drq;
308 * Filter used to eliminate duplicate results. Can be NULL if we
309 * are not yet filtering any results.
311 struct GNUNET_CONTAINER_BloomFilter *bf;
314 * Bitmap describing which of the optional
315 * hash codes / peer identities were given to us.
320 * Desired block type.
325 * Priority of the request.
330 * Size of the 'bf' (in bytes).
335 * In what ways are we going to process
338 enum RoutingPolicy policy;
341 * Time-to-live for the request (value
347 * Number to mingle hashes for bloom-filter
353 * Number of results that were found so far.
355 unsigned int results_found;
360 * Information we keep for each pending reply.
365 * This is a linked list.
367 struct PendingReply *next;
370 * Size of the reply; actual reply message follows
371 * at the end of this struct.
379 * All requests from a client are kept in a doubly-linked list.
381 struct ClientRequestList;
385 * Information we keep for each pending request. We should try to
386 * keep this struct as small as possible since its memory consumption
387 * is key to how many requests we can have pending at once.
389 struct PendingRequest
393 * ID of a client making a request, NULL if this entry is for a
396 struct GNUNET_SERVER_Client *client;
399 * If this request was made by a client,
400 * this is our entry in the client request
401 * list; otherwise NULL.
403 struct ClientRequestList *crl_entry;
406 * If this is a namespace query, pointer to the hash of the public
407 * key of the namespace; otherwise NULL.
409 GNUNET_HashCode *namespace;
412 * Bloomfilter we use to filter out replies that we don't care about
413 * (anymore). NULL as long as we are interested in all replies.
415 struct GNUNET_CONTAINER_BloomFilter *bf;
418 * Replies that we have received but were unable to forward yet
419 * (typically non-null only if we have a pending transmission
420 * request with the client or the respective peer).
422 struct PendingReply *replies_pending;
425 * Pending transmission request with the core service for the target
426 * peer (for processing of 'replies_pending') or Handle for a
427 * pending query-request for P2P-transmission with the core service.
428 * If non-NULL, this request must be cancelled should this struct be
431 struct GNUNET_CORE_TransmitHandle *cth;
434 * Pending transmission request for the target client (for processing of
435 * 'replies_pending').
437 struct GNUNET_CONNECTION_TransmitHandle *th;
440 * Hash code of all replies that we have seen so far (only valid
441 * if client is not NULL since we only track replies like this for
444 GNUNET_HashCode *replies_seen;
447 * When did we first see this request (form this peer), or, if our
448 * client is initiating, when did we last initiate a search?
450 struct GNUNET_TIME_Absolute start_time;
453 * The query that this request is for.
455 GNUNET_HashCode query;
458 * The task responsible for transmitting queries
461 GNUNET_SCHEDULER_TaskIdentifier task;
464 * (Interned) Peer identifier (only valid if "client" is NULL)
465 * that identifies a peer that gave us this request.
467 GNUNET_PEER_Id source_pid;
470 * (Interned) Peer identifier that identifies a preferred target
473 GNUNET_PEER_Id target_pid;
476 * (Interned) Peer identifiers of peers that have already
477 * received our query for this content.
479 GNUNET_PEER_Id *used_pids;
482 * Size of the 'bf' (in bytes).
487 * Desired anonymity level; only valid for requests from a local client.
489 uint32_t anonymity_level;
492 * How many entries in "used_pids" are actually valid?
494 unsigned int used_pids_off;
497 * How long is the "used_pids" array?
499 unsigned int used_pids_size;
502 * How many entries in "replies_seen" are actually valid?
504 unsigned int replies_seen_off;
507 * How long is the "replies_seen" array?
509 unsigned int replies_seen_size;
512 * Priority with which this request was made. If one of our clients
513 * made the request, then this is the current priority that we are
514 * using when initiating the request. This value is used when
515 * we decide to reward other peers with trust for providing a reply.
520 * Priority points left for us to spend when forwarding this request
523 uint32_t remaining_priority;
526 * Number to mingle hashes for bloom-filter
532 * TTL with which we saw this request (or, if we initiated, TTL that
533 * we used for the request).
538 * Type of the content that this request is for.
546 * All requests from a client are kept in a doubly-linked list.
548 struct ClientRequestList
551 * This is a doubly-linked list.
553 struct ClientRequestList *next;
556 * This is a doubly-linked list.
558 struct ClientRequestList *prev;
561 * A request from this client.
563 struct PendingRequest *req;
566 * Client list with the head and tail of this DLL.
568 struct ClientList *cl;
573 * Linked list of all clients that we are
574 * currently processing requests for.
580 * This is a linked list.
582 struct ClientList *next;
585 * What client is this entry for?
587 struct GNUNET_SERVER_Client* client;
590 * Head of the DLL of requests from this client.
592 struct ClientRequestList *head;
595 * Tail of the DLL of requests from this client.
597 struct ClientRequestList *tail;
603 * Closure for "process_reply" function.
605 struct ProcessReplyClosure
608 * The data for the reply.
613 * When the reply expires.
615 struct GNUNET_TIME_Absolute expiration;
623 * Namespace that this reply belongs to
624 * (if it is of type SBLOCK).
626 GNUNET_HashCode namespace;
634 * How much was this reply worth to us?
641 * Information about a peer that we are connected to.
642 * We track data that is useful for determining which
643 * peers should receive our requests.
649 * List of the last clients for which this peer
650 * successfully answered a query.
652 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
655 * List of the last PIDs for which
656 * this peer successfully answered a query;
657 * We use 0 to indicate no successful reply.
659 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
662 * Average delay between sending the peer a request and
663 * getting a reply (only calculated over the requests for
664 * which we actually got a reply). Calculated
665 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
667 struct GNUNET_TIME_Relative avg_delay;
670 * Average priority of successful replies. Calculated
671 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
676 * The peer's identity.
681 * Number of requests we have currently pending
682 * with this peer (that is, requests that were
683 * transmitted so recently that we would not retransmit
686 unsigned int pending_requests;
689 * Which offset in "last_p2p_replies" will be updated next?
690 * (we go round-robin).
692 unsigned int last_p2p_replies_woff;
695 * Which offset in "last_client_replies" will be updated next?
696 * (we go round-robin).
698 unsigned int last_client_replies_woff;
704 * Our connection to the datastore.
706 static struct GNUNET_DATASTORE_Handle *dsh;
711 static struct GNUNET_SCHEDULER_Handle *sched;
716 const struct GNUNET_CONFIGURATION_Handle *cfg;
719 * Handle to the core service (NULL until we've connected to it).
721 struct GNUNET_CORE_Handle *core;
724 * Head of doubly-linked LGC list.
726 static struct LocalGetContext *lgc_head;
729 * Tail of doubly-linked LGC list.
731 static struct LocalGetContext *lgc_tail;
734 * Head of request queue for the datastore, sorted by timeout.
736 static struct DatastoreRequestQueue *drq_head;
739 * Tail of request queue for the datastore.
741 static struct DatastoreRequestQueue *drq_tail;
744 * Linked list of indexed files.
746 static struct IndexInfo *indexed_files;
749 * Maps hash over content of indexed files to the respective filename.
750 * The filenames are pointers into the indexed_files linked list and
751 * do not need to be freed.
753 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
756 * Map of query hash codes to requests.
758 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_query;
761 * Map of peer IDs to requests (for those requests coming
764 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_peer;
767 * Linked list of all of our clients and their requests.
769 static struct ClientList *clients;
772 * Heap with the request that will expire next at the top. Contains
773 * pointers of type "struct PendingRequest*"; these will *also* be
774 * aliased from the "requests_by_peer" data structures and the
775 * "requests_by_query" table. Note that requests from our clients
776 * don't expire and are thus NOT in the "requests_by_expiration"
777 * (or the "requests_by_peer" tables).
779 static struct GNUNET_CONTAINER_Heap *requests_by_expiration;
782 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
784 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
787 * Maximum number of requests (from other peers) that we're
788 * willing to have pending at any given point in time.
789 * FIXME: set from configuration (and 32 is a tiny value for testing only).
791 static uint64_t max_pending_requests = 32;
794 * Write the current index information list to disk.
799 struct GNUNET_BIO_WriteHandle *wh;
801 struct IndexInfo *pos;
804 GNUNET_CONFIGURATION_get_value_filename (cfg,
809 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
810 _("Configuration option `%s' in section `%s' missing.\n"),
815 wh = GNUNET_BIO_write_open (fn);
818 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
819 _("Could not open `%s'.\n"),
828 GNUNET_BIO_write (wh,
830 sizeof (GNUNET_HashCode))) ||
832 GNUNET_BIO_write_string (wh,
838 GNUNET_BIO_write_close (wh))
840 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
841 _("Error writing `%s'.\n"),
851 * Read index information from disk.
856 struct GNUNET_BIO_ReadHandle *rh;
858 struct IndexInfo *pos;
865 GNUNET_CONFIGURATION_get_value_filename (cfg,
870 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
871 _("Configuration option `%s' in section `%s' missing.\n"),
876 rh = GNUNET_BIO_read_open (fn);
879 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
880 _("Could not open `%s'.\n"),
886 while ( (GNUNET_OK ==
888 "Hash of indexed file",
890 sizeof (GNUNET_HashCode))) &&
892 GNUNET_BIO_read_string (rh,
893 "Name of indexed file",
897 slen = strlen (fname) + 1;
898 pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
900 pos->filename = (const char *) &pos[1];
901 memcpy (&pos[1], fname, slen);
903 GNUNET_CONTAINER_multihashmap_put (ifm,
905 (void*) pos->filename,
906 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
912 pos->next = indexed_files;
917 GNUNET_BIO_read_close (rh, &emsg))
924 * We've validated the hash of the file we're about to
925 * index. Signal success to the client and update
926 * our internal data structures.
928 * @param ii the index info entry for the request
931 signal_index_ok (struct IndexInfo *ii)
934 GNUNET_CONTAINER_multihashmap_put (ifm,
936 (void*) ii->filename,
937 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
939 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
940 _("Index request received for file `%s' is indexed as `%s'. Permitting anyway.\n"),
942 (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
944 GNUNET_SERVER_transmit_context_append (ii->tc,
946 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
947 GNUNET_SERVER_transmit_context_run (ii->tc,
948 GNUNET_TIME_UNIT_MINUTES);
952 ii->next = indexed_files;
955 GNUNET_SERVER_transmit_context_append (ii->tc,
957 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
958 GNUNET_SERVER_transmit_context_run (ii->tc,
959 GNUNET_TIME_UNIT_MINUTES);
965 * Function called once the hash computation over an
966 * indexed file has completed.
968 * @param cls closure, our publishing context
969 * @param res resulting hash, NULL on error
972 hash_for_index_val (void *cls,
973 const GNUNET_HashCode *
976 struct IndexInfo *ii = cls;
978 if ( (res == NULL) ||
981 sizeof(GNUNET_HashCode))) )
983 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
984 _("Hash mismatch trying to index file `%s'\n"),
986 GNUNET_SERVER_transmit_context_append (ii->tc,
988 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
989 GNUNET_SERVER_transmit_context_run (ii->tc,
990 GNUNET_TIME_UNIT_MINUTES);
994 signal_index_ok (ii);
999 * Handle INDEX_START-message.
1001 * @param cls closure
1002 * @param client identification of the client
1003 * @param message the actual message
1006 handle_index_start (void *cls,
1007 struct GNUNET_SERVER_Client *client,
1008 const struct GNUNET_MessageHeader *message)
1010 const struct IndexStartMessage *ism;
1013 struct IndexInfo *ii;
1020 msize = ntohs(message->size);
1021 if ( (msize <= sizeof (struct IndexStartMessage)) ||
1022 ( ((const char *)message)[msize-1] != '\0') )
1025 GNUNET_SERVER_receive_done (client,
1029 ism = (const struct IndexStartMessage*) message;
1030 fn = (const char*) &ism[1];
1031 dev = ntohl (ism->device);
1032 ino = GNUNET_ntohll (ism->inode);
1033 ism = (const struct IndexStartMessage*) message;
1034 slen = strlen (fn) + 1;
1035 ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
1036 ii->filename = (const char*) &ii[1];
1037 memcpy (&ii[1], fn, slen);
1038 ii->file_id = ism->file_id;
1039 ii->tc = GNUNET_SERVER_transmit_context_create (client);
1040 if ( ( (dev != 0) ||
1042 (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
1048 /* fast validation OK! */
1049 signal_index_ok (ii);
1052 /* slow validation, need to hash full file (again) */
1053 GNUNET_CRYPTO_hash_file (sched,
1054 GNUNET_SCHEDULER_PRIORITY_IDLE,
1058 &hash_for_index_val,
1064 * Handle INDEX_LIST_GET-message.
1066 * @param cls closure
1067 * @param client identification of the client
1068 * @param message the actual message
1071 handle_index_list_get (void *cls,
1072 struct GNUNET_SERVER_Client *client,
1073 const struct GNUNET_MessageHeader *message)
1075 struct GNUNET_SERVER_TransmitContext *tc;
1076 struct IndexInfoMessage *iim;
1077 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1080 struct GNUNET_MessageHeader *msg;
1081 struct IndexInfo *pos;
1083 tc = GNUNET_SERVER_transmit_context_create (client);
1084 iim = (struct IndexInfoMessage*) buf;
1086 pos = indexed_files;
1090 iim->file_id = pos->file_id;
1092 slen = strlen (fn) + 1;
1093 if (slen + sizeof (struct IndexInfoMessage) >
1094 GNUNET_SERVER_MAX_MESSAGE_SIZE)
1099 memcpy (&iim[1], fn, slen);
1100 GNUNET_SERVER_transmit_context_append
1103 sizeof (struct IndexInfoMessage)
1104 - sizeof (struct GNUNET_MessageHeader) + slen,
1105 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1108 GNUNET_SERVER_transmit_context_append (tc,
1110 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1111 GNUNET_SERVER_transmit_context_run (tc,
1112 GNUNET_TIME_UNIT_MINUTES);
1117 * Handle UNINDEX-message.
1119 * @param cls closure
1120 * @param client identification of the client
1121 * @param message the actual message
1124 handle_unindex (void *cls,
1125 struct GNUNET_SERVER_Client *client,
1126 const struct GNUNET_MessageHeader *message)
1128 const struct UnindexMessage *um;
1129 struct IndexInfo *pos;
1130 struct IndexInfo *prev;
1131 struct IndexInfo *next;
1132 struct GNUNET_SERVER_TransmitContext *tc;
1135 um = (const struct UnindexMessage*) message;
1138 pos = indexed_files;
1142 if (0 == memcmp (&pos->file_id,
1144 sizeof (GNUNET_HashCode)))
1147 indexed_files = pos->next;
1149 prev->next = pos->next;
1159 if (GNUNET_YES == found)
1160 write_index_list ();
1161 tc = GNUNET_SERVER_transmit_context_create (client);
1162 GNUNET_SERVER_transmit_context_append (tc,
1164 GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1165 GNUNET_SERVER_transmit_context_run (tc,
1166 GNUNET_TIME_UNIT_MINUTES);
1171 * Run the next DS request in our
1172 * queue, we're done with the current one.
1177 struct DatastoreRequestQueue *e;
1179 while (NULL != (e = drq_head))
1181 if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1183 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1184 GNUNET_SCHEDULER_cancel (sched, e->task);
1185 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1186 e->req (e->req_cls, GNUNET_NO);
1191 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1192 GNUNET_SCHEDULER_cancel (sched, e->task);
1193 e->task = GNUNET_SCHEDULER_NO_TASK;
1194 e->req (e->req_cls, GNUNET_YES);
1195 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1201 * A datastore request had to be timed out.
1203 * @param cls closure (of type "struct DatastoreRequestQueue*")
1204 * @param tc task context, unused
1207 timeout_ds_request (void *cls,
1208 const struct GNUNET_SCHEDULER_TaskContext *tc)
1210 struct DatastoreRequestQueue *e = cls;
1212 e->task = GNUNET_SCHEDULER_NO_TASK;
1213 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1214 e->req (e->req_cls, GNUNET_NO);
1220 * Queue a request for the datastore.
1222 * @param deadline by when the request should run
1223 * @param fun function to call once the request can be run
1224 * @param fun_cls closure for fun
1226 static struct DatastoreRequestQueue *
1227 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1228 RequestFunction fun,
1231 struct DatastoreRequestQueue *e;
1232 struct DatastoreRequestQueue *bef;
1234 if (drq_head == NULL)
1236 /* no other requests pending, run immediately */
1237 fun (fun_cls, GNUNET_OK);
1240 e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1241 e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1243 e->req_cls = fun_cls;
1244 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1246 /* local request, highest prio, put at head of queue
1247 regardless of deadline */
1253 while ( (NULL != bef) &&
1254 (e->timeout.value < bef->timeout.value) )
1257 GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1258 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1260 e->task = GNUNET_SCHEDULER_add_delayed (sched,
1262 GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1263 GNUNET_SCHEDULER_NO_TASK,
1265 &timeout_ds_request,
1272 * Free the state associated with a local get context.
1274 * @param lgc the lgc to free
1277 local_get_context_free (struct LocalGetContext *lgc)
1279 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1280 GNUNET_SERVER_client_drop (lgc->client);
1281 GNUNET_free_non_null (lgc->results);
1282 if (lgc->results_bf != NULL)
1283 GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1284 if (lgc->req != NULL)
1286 if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1287 GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1288 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1289 GNUNET_free (lgc->req);
1296 * We're able to transmit the next (local) result to the client.
1297 * Do it and ask the datastore for more. Or, on error, tell
1298 * the datastore to stop giving us more.
1300 * @param cls our closure (struct LocalGetContext)
1301 * @param max maximum number of bytes we can transmit
1302 * @param buf where to copy our message
1303 * @return number of bytes copied to buf
1306 transmit_local_result (void *cls,
1310 struct LocalGetContext *lgc = cls;
1316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1317 "Failed to transmit result to local client, aborting datastore iteration.\n");
1320 GNUNET_free (lgc->result);
1322 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1325 msize = ntohs (lgc->result->header.size);
1327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328 "Transmitting %u bytes of result to local client.\n",
1331 GNUNET_assert (max >= msize);
1332 memcpy (buf, lgc->result, msize);
1333 GNUNET_free (lgc->result);
1335 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1341 * Continuation called from datastore's remove
1345 * @param success did the deletion work?
1346 * @param msg error message
1349 remove_cont (void *cls,
1353 if (GNUNET_OK != success)
1354 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1355 _("Failed to delete bogus block: %s\n"),
1357 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1362 * Mingle hash with the mingle_number to
1363 * produce different bits.
1366 mingle_hash (const GNUNET_HashCode * in,
1367 int32_t mingle_number,
1368 GNUNET_HashCode * hc)
1372 GNUNET_CRYPTO_hash (&mingle_number,
1375 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1380 * We've received an on-demand encoded block
1381 * from the datastore. Attempt to do on-demand
1382 * encoding and (if successful), call the
1383 * continuation with the resulting block. On
1384 * error, clean up and ask the datastore for
1387 * @param key key for the content
1388 * @param size number of bytes in data
1389 * @param data content stored
1390 * @param type type of the content
1391 * @param priority priority of the content
1392 * @param anonymity anonymity-level for the content
1393 * @param expiration expiration time for the content
1394 * @param uid unique identifier for the datum;
1395 * maybe 0 if no unique identifier is available
1396 * @param cont function to call with the actual block
1397 * @param cont_cls closure for cont
1400 handle_on_demand_block (const GNUNET_HashCode * key,
1406 struct GNUNET_TIME_Absolute
1407 expiration, uint64_t uid,
1408 GNUNET_DATASTORE_Iterator cont,
1411 const struct OnDemandBlock *odb;
1412 GNUNET_HashCode nkey;
1413 struct GNUNET_CRYPTO_AesSessionKey skey;
1414 struct GNUNET_CRYPTO_AesInitializationVector iv;
1415 GNUNET_HashCode query;
1417 char ndata[DBLOCK_SIZE];
1418 char edata[DBLOCK_SIZE];
1420 struct GNUNET_DISK_FileHandle *fh;
1423 if (size != sizeof (struct OnDemandBlock))
1426 GNUNET_DATASTORE_remove (dsh,
1432 GNUNET_TIME_UNIT_FOREVER_REL);
1435 odb = (const struct OnDemandBlock*) data;
1436 off = GNUNET_ntohll (odb->offset);
1437 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1440 if ( (NULL == fn) ||
1441 (NULL == (fh = GNUNET_DISK_file_open (fn,
1442 GNUNET_DISK_OPEN_READ,
1443 GNUNET_DISK_PERM_NONE))) ||
1445 GNUNET_DISK_file_seek (fh,
1447 GNUNET_DISK_SEEK_SET)) ||
1449 (nsize = GNUNET_DISK_file_read (fh,
1453 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1454 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1455 GNUNET_h2s (&odb->file_id),
1456 (unsigned long long) off,
1459 GNUNET_DISK_file_close (fh);
1460 /* FIXME: if this happens often, we need
1461 to remove the OnDemand block from the DS! */
1462 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1465 GNUNET_DISK_file_close (fh);
1466 GNUNET_CRYPTO_hash (ndata,
1469 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1470 GNUNET_CRYPTO_aes_encrypt (ndata,
1475 GNUNET_CRYPTO_hash (edata,
1478 if (0 != memcmp (&query,
1480 sizeof (GNUNET_HashCode)))
1482 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1483 _("Indexed file `%s' changed at offset %llu\n"),
1485 (unsigned long long) off);
1486 /* FIXME: if this happens often, we need
1487 to remove the OnDemand block from the DS! */
1488 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1495 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1504 * How many bytes should a bloomfilter be if we have already seen
1505 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1506 * of bits set per entry. Furthermore, we should not re-size the
1507 * filter too often (to keep it cheap).
1509 * Since other peers will also add entries but not resize the filter,
1510 * we should generally pick a slightly larger size than what the
1511 * strict math would suggest.
1513 * @return must be a power of two and smaller or equal to 2^15.
1516 compute_bloomfilter_size (unsigned int entry_count)
1519 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1520 uint16_t max = 1 << 15;
1522 if (entry_count > max)
1525 while ((size < max) && (size < ideal))
1534 * Recalculate our bloom filter for filtering replies.
1536 * @param count number of entries we are filtering right now
1537 * @param mingle set to our new mingling value
1538 * @param bf_size set to the size of the bloomfilter
1539 * @param entries the entries to filter
1540 * @return updated bloomfilter, NULL for none
1542 static struct GNUNET_CONTAINER_BloomFilter *
1543 refresh_bloomfilter (unsigned int count,
1546 const GNUNET_HashCode *entries)
1548 struct GNUNET_CONTAINER_BloomFilter *bf;
1551 GNUNET_HashCode mhash;
1555 nsize = compute_bloomfilter_size (count);
1556 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1558 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1561 for (i=0;i<count;i++)
1563 mingle_hash (&entries[i], *mingle, &mhash);
1564 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1571 * Closure used for "target_peer_select_cb".
1573 struct PeerSelectionContext
1576 * The request for which we are selecting
1579 struct PendingRequest *pr;
1582 * Current "prime" target.
1584 struct GNUNET_PeerIdentity target;
1587 * How much do we like this target?
1589 double target_score;
1595 * Function called for each connected peer to determine
1596 * which one(s) would make good targets for forwarding.
1598 * @param cls closure (struct PeerSelectionContext)
1599 * @param key current key code (peer identity)
1600 * @param value value in the hash map (struct ConnectedPeer)
1601 * @return GNUNET_YES if we should continue to
1606 target_peer_select_cb (void *cls,
1607 const GNUNET_HashCode * key,
1610 struct PeerSelectionContext *psc = cls;
1611 struct ConnectedPeer *cp = value;
1612 struct PendingRequest *pr = psc->pr;
1616 /* 1) check if we have already (recently) forwarded to this peer */
1617 for (i=0;i<pr->used_pids_off;i++)
1618 if (pr->used_pids[i] == cp->pid)
1619 return GNUNET_YES; /* skip */
1620 // 2) calculate how much we'd like to forward to this peer
1621 score = 0; // FIXME!
1623 /* store best-fit in closure */
1624 if (score > psc->target_score)
1626 psc->target_score = score;
1627 psc->target.hashPubKey = *key;
1634 * We use a random delay to make the timing of requests
1635 * less predictable. This function returns such a random
1638 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1640 static struct GNUNET_TIME_Relative
1641 get_processing_delay ()
1643 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1644 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1650 * Task that is run for each request with the
1651 * goal of forwarding the associated query to
1652 * other peers. The task should re-schedule
1653 * itself to be re-run once the TTL has expired.
1654 * (or at a later time if more peers should
1655 * be queried earlier).
1657 * @param cls the requests "struct PendingRequest*"
1658 * @param tc task context (unused)
1661 forward_request_task (void *cls,
1662 const struct GNUNET_SCHEDULER_TaskContext *tc);
1666 * We've selected a peer for forwarding of a query.
1667 * Construct the message and then re-schedule the
1668 * task to forward again to (other) peers.
1670 * @param cls closure
1671 * @param size number of bytes available in buf
1672 * @param buf where the callee should write the message
1673 * @return number of bytes written to buf
1676 transmit_request_cb (void *cls,
1680 struct PendingRequest *pr = cls;
1681 struct GetMessage *gm;
1682 GNUNET_HashCode *ext;
1688 /* (1) check for timeout */
1691 /* timeout, try another peer immediately again */
1692 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1694 GNUNET_SCHEDULER_PRIORITY_IDLE,
1695 GNUNET_SCHEDULER_NO_TASK,
1696 GNUNET_TIME_UNIT_ZERO,
1697 &forward_request_task,
1701 /* (2) build query message */
1702 k = 0; // FIXME: count hash codes!
1703 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1704 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1705 gm = (struct GetMessage*) buf;
1706 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1707 gm->header.size = htons (msize);
1708 gm->type = htonl (pr->type);
1709 pr->remaining_priority /= 2;
1710 gm->priority = htonl (pr->remaining_priority);
1711 gm->ttl = htonl (pr->ttl);
1712 gm->filter_mutator = htonl(pr->mingle);
1713 gm->hash_bitmap = htonl (42);
1714 gm->query = pr->query;
1715 ext = (GNUNET_HashCode*) &gm[1];
1716 // FIXME: setup "ext[0]..[k-1]"
1717 bfdata = (char *) &ext[k];
1719 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1723 /* (3) schedule job to do it again (or another peer, etc.) */
1724 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1726 GNUNET_SCHEDULER_PRIORITY_IDLE,
1727 GNUNET_SCHEDULER_NO_TASK,
1728 get_processing_delay (), // FIXME!
1729 &forward_request_task,
1737 * Function called after we've tried to reserve
1738 * a certain amount of bandwidth for a reply.
1739 * Check if we succeeded and if so send our query.
1741 * @param cls the requests "struct PendingRequest*"
1742 * @param peer identifies the peer
1743 * @param latency current latency estimate, "FOREVER" if we have been
1745 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1746 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1747 * @param amount set to the amount that was actually reserved or unreserved
1748 * @param preference current traffic preference for the given peer
1751 target_reservation_cb (void *cls,
1753 GNUNET_PeerIdentity * peer,
1754 unsigned int bpm_in,
1755 unsigned int bpm_out,
1756 struct GNUNET_TIME_Relative
1757 latency, int amount,
1758 unsigned long long preference)
1760 struct PendingRequest *pr = cls;
1763 struct GNUNET_TIME_Relative maxdelay;
1765 GNUNET_assert (peer != NULL);
1766 if ( (amount != DBLOCK_SIZE) ||
1769 /* try again later; FIXME: we may need to un-reserve "amount"? */
1770 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1772 GNUNET_SCHEDULER_PRIORITY_IDLE,
1773 GNUNET_SCHEDULER_NO_TASK,
1774 get_processing_delay (), // FIXME: longer?
1775 &forward_request_task,
1779 // (2) transmit, update ttl/priority
1780 // FIXME: calculate priority, maxdelay, size properly!
1783 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1784 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1789 &transmit_request_cb,
1791 if (pr->cth == NULL)
1793 /* try again later */
1794 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1796 GNUNET_SCHEDULER_PRIORITY_IDLE,
1797 GNUNET_SCHEDULER_NO_TASK,
1798 get_processing_delay (), // FIXME: longer?
1799 &forward_request_task,
1806 * Task that is run for each request with the
1807 * goal of forwarding the associated query to
1808 * other peers. The task should re-schedule
1809 * itself to be re-run once the TTL has expired.
1810 * (or at a later time if more peers should
1811 * be queried earlier).
1813 * @param cls the requests "struct PendingRequest*"
1814 * @param tc task context (unused)
1817 forward_request_task (void *cls,
1818 const struct GNUNET_SCHEDULER_TaskContext *tc)
1820 struct PendingRequest *pr = cls;
1821 struct PeerSelectionContext psc;
1823 pr->task = GNUNET_SCHEDULER_NO_TASK;
1824 if (pr->cth != NULL)
1826 /* we're busy transmitting a result, wait a bit */
1827 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1829 GNUNET_SCHEDULER_PRIORITY_IDLE,
1830 GNUNET_SCHEDULER_NO_TASK,
1831 get_processing_delay (),
1832 &forward_request_task,
1836 /* (1) select target */
1838 psc.target_score = DBL_MIN;
1839 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1840 &target_peer_select_cb,
1842 if (psc.target_score == DBL_MIN)
1844 /* no possible target found, wait some time */
1845 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1847 GNUNET_SCHEDULER_PRIORITY_IDLE,
1848 GNUNET_SCHEDULER_NO_TASK,
1849 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1850 &forward_request_task,
1854 /* (2) reserve reply bandwidth */
1855 // FIXME: need a way to cancel; this
1856 // async operation is problematic (segv-problematic)
1857 // if "pr" is destroyed while it happens!
1858 GNUNET_CORE_peer_configure (core,
1860 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1862 DBLOCK_SIZE, // FIXME: make dependent on type?
1864 &target_reservation_cb,
1870 * We're processing (local) results for a search request
1871 * from a (local) client. Pass applicable results to the
1872 * client and if we are done either clean up (operation
1873 * complete) or switch to P2P search (more results possible).
1875 * @param cls our closure (struct LocalGetContext)
1876 * @param key key for the content
1877 * @param size number of bytes in data
1878 * @param data content stored
1879 * @param type type of the content
1880 * @param priority priority of the content
1881 * @param anonymity anonymity-level for the content
1882 * @param expiration expiration time for the content
1883 * @param uid unique identifier for the datum;
1884 * maybe 0 if no unique identifier is available
1887 process_local_get_result (void *cls,
1888 const GNUNET_HashCode * key,
1894 struct GNUNET_TIME_Absolute
1898 struct LocalGetContext *lgc = cls;
1899 struct PendingRequest *pr;
1900 struct ClientRequestList *crl;
1901 struct ClientList *cl;
1908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1909 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1910 GNUNET_h2s (&lgc->query));
1912 /* no further results from datastore; continue
1913 processing further requests from the client and
1914 allow the next task to use the datastore; also,
1915 switch to P2P requests or clean up our state. */
1917 GNUNET_SERVER_receive_done (lgc->client,
1919 if ( (lgc->results_used == 0) ||
1920 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1921 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1922 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "Forwarding query for `%s' to network.\n",
1927 GNUNET_h2s (&lgc->query));
1930 while ( (NULL != cl) &&
1931 (cl->client != lgc->client) )
1935 cl = GNUNET_malloc (sizeof (struct ClientList));
1936 cl->client = lgc->client;
1940 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1942 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1943 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1944 pr->client = lgc->client;
1945 GNUNET_SERVER_client_keep (pr->client);
1946 pr->crl_entry = crl;
1948 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1950 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1951 *pr->namespace = lgc->namespace;
1953 pr->replies_seen = lgc->results;
1954 lgc->results = NULL;
1955 pr->start_time = GNUNET_TIME_absolute_get ();
1956 pr->query = lgc->query;
1957 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1958 pr->replies_seen_off = lgc->results_used;
1959 pr->replies_seen_size = lgc->results_size;
1960 lgc->results_size = 0;
1961 pr->type = lgc->type;
1962 pr->anonymity_level = lgc->anonymity_level;
1963 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1967 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1970 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1971 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1973 GNUNET_SCHEDULER_PRIORITY_IDLE,
1974 GNUNET_SCHEDULER_NO_TASK,
1975 get_processing_delay (),
1976 &forward_request_task,
1978 local_get_context_free (lgc);
1981 /* got all possible results, clean up! */
1983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1984 "Found all possible results for query for `%s', done!\n",
1985 GNUNET_h2s (&lgc->query));
1987 local_get_context_free (lgc);
1990 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994 "Received on-demand block for `%s' from local datastore, fetching data.\n",
1995 GNUNET_h2s (&lgc->query));
1997 handle_on_demand_block (key, size, data, type, priority,
1998 anonymity, expiration, uid,
1999 &process_local_get_result,
2003 if (type != lgc->type)
2005 /* this should be virtually impossible to reach (DBLOCK
2006 query hash being identical to KBLOCK/SBLOCK query hash);
2007 nevertheless, if it happens, the correct thing is to
2008 simply skip the result. */
2010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2011 "Received block of unexpected type for `%s' from local datastore, ignoring.\n",
2012 GNUNET_h2s (&lgc->query));
2014 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2017 /* check if this is a result we've alredy
2019 for (i=0;i<lgc->results_used;i++)
2020 if (0 == memcmp (key,
2022 sizeof (GNUNET_HashCode)))
2025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2026 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2027 GNUNET_h2s (&lgc->query));
2029 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2032 if (lgc->results_used == lgc->results_size)
2033 GNUNET_array_grow (lgc->results,
2035 lgc->results_size * 2 + 2);
2036 GNUNET_CRYPTO_hash (data,
2038 &lgc->results[lgc->results_used++]);
2039 msize = size + sizeof (struct ContentMessage);
2040 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2041 lgc->result = GNUNET_malloc (msize);
2042 lgc->result->header.size = htons (msize);
2043 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2044 lgc->result->type = htonl (type);
2045 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2046 memcpy (&lgc->result[1],
2050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051 "Received new result for `%s' from local datastore, passing to client.\n",
2052 GNUNET_h2s (&lgc->query));
2054 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2056 GNUNET_TIME_UNIT_FOREVER_REL,
2057 &transmit_local_result,
2063 * We're processing a search request from a local
2064 * client. Now it is our turn to query the datastore.
2066 * @param cls our closure (struct LocalGetContext)
2070 transmit_local_get (void *cls,
2071 const struct GNUNET_SCHEDULER_TaskContext *tc)
2073 struct LocalGetContext *lgc = cls;
2077 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2078 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2079 GNUNET_DATASTORE_get (dsh,
2082 &process_local_get_result,
2084 GNUNET_TIME_UNIT_FOREVER_REL);
2089 * We're processing a search request from a local
2090 * client. Now it is our turn to query the datastore.
2092 * @param cls our closure (struct LocalGetContext)
2093 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2096 transmit_local_get_ready (void *cls,
2099 struct LocalGetContext *lgc = cls;
2101 GNUNET_assert (GNUNET_OK == ok);
2102 GNUNET_SCHEDULER_add_continuation (sched,
2104 &transmit_local_get,
2106 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2111 * Handle START_SEARCH-message (search request from client).
2113 * @param cls closure
2114 * @param client identification of the client
2115 * @param message the actual message
2118 handle_start_search (void *cls,
2119 struct GNUNET_SERVER_Client *client,
2120 const struct GNUNET_MessageHeader *message)
2122 const struct SearchMessage *sm;
2123 struct LocalGetContext *lgc;
2127 msize = ntohs (message->size);
2128 if ( (msize < sizeof (struct SearchMessage)) ||
2129 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2132 GNUNET_SERVER_receive_done (client,
2136 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2137 sm = (const struct SearchMessage*) message;
2138 GNUNET_SERVER_client_keep (client);
2139 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2142 lgc->results_used = sc;
2143 GNUNET_array_grow (lgc->results,
2146 memcpy (lgc->results,
2148 sc * sizeof (GNUNET_HashCode));
2150 lgc->client = client;
2151 lgc->type = ntohl (sm->type);
2152 lgc->anonymity_level = ntohl (sm->anonymity_level);
2155 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2156 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2157 lgc->target.hashPubKey = sm->target;
2159 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2160 lgc->namespace = sm->target;
2165 lgc->query = sm->query;
2166 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2167 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2168 &transmit_local_get_ready,
2174 * List of handlers for the messages understood by this
2177 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2178 {&handle_index_start, NULL,
2179 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2180 {&handle_index_list_get, NULL,
2181 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2182 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2183 sizeof (struct UnindexMessage) },
2184 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2191 * Clean up the memory used by the PendingRequest structure (except
2192 * for the client or peer list that the request may be part of).
2194 * @param pr request to clean up
2197 destroy_pending_request (struct PendingRequest *pr)
2199 struct PendingReply *reply;
2200 struct ClientList *cl;
2202 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2205 // FIXME: not sure how this can work (efficiently)
2206 // also, what does the return value mean?
2207 if (pr->client == NULL)
2209 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2214 cl = pr->crl_entry->cl;
2215 GNUNET_CONTAINER_DLL_remove (cl->head,
2219 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2220 GNUNET_SCHEDULER_cancel (sched, pr->task);
2221 if (NULL != pr->cth)
2222 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2224 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2226 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2227 while (NULL != (reply = pr->replies_pending))
2229 pr->replies_pending = reply->next;
2230 GNUNET_free (reply);
2232 GNUNET_PEER_change_rc (pr->source_pid, -1);
2233 GNUNET_PEER_change_rc (pr->target_pid, -1);
2234 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2235 GNUNET_free_non_null (pr->used_pids);
2236 GNUNET_free_non_null (pr->replies_seen);
2237 GNUNET_free_non_null (pr->namespace);
2243 * A client disconnected. Remove all of its pending queries.
2245 * @param cls closure, NULL
2246 * @param client identification of the client
2249 handle_client_disconnect (void *cls,
2250 struct GNUNET_SERVER_Client
2253 struct LocalGetContext *lgc;
2254 struct ClientList *cpos;
2255 struct ClientList *cprev;
2256 struct ClientRequestList *rl;
2259 while ( (NULL != lgc) &&
2260 (lgc->client != client) )
2263 local_get_context_free (lgc);
2266 while ( (NULL != cpos) &&
2267 (clients->client != client) )
2275 clients = cpos->next;
2277 cprev->next = cpos->next;
2278 while (NULL != (rl = cpos->head))
2280 cpos->head = rl->next;
2281 destroy_pending_request (rl->req);
2290 * Iterator over entries in the "requests_by_query" map
2291 * that frees all the entries.
2293 * @param cls closure, NULL
2294 * @param key current key code (the query, unused)
2295 * @param value value in the hash map, of type "struct PendingRequest*"
2296 * @return GNUNET_YES (we should continue to iterate)
2299 destroy_pending_request_cb (void *cls,
2300 const GNUNET_HashCode * key,
2303 struct PendingRequest *pr = value;
2305 destroy_pending_request (pr);
2311 * Task run during shutdown.
2317 shutdown_task (void *cls,
2318 const struct GNUNET_SCHEDULER_TaskContext *tc)
2320 struct IndexInfo *pos;
2323 GNUNET_CORE_disconnect (core);
2324 GNUNET_DATASTORE_disconnect (dsh,
2327 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2328 &destroy_pending_request_cb,
2330 while (clients != NULL)
2331 handle_client_disconnect (NULL,
2333 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2334 requests_by_query = NULL;
2335 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2336 requests_by_peer = NULL;
2337 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2338 requests_by_expiration = NULL;
2339 // FIXME: iterate over entries and free individually?
2340 // (or do we get disconnect notifications?)
2341 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2342 connected_peers = NULL;
2343 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2345 while (NULL != (pos = indexed_files))
2347 indexed_files = pos->next;
2354 * Free (each) request made by the peer.
2356 * @param cls closure, points to peer that the request belongs to
2357 * @param key current key code
2358 * @param value value in the hash map
2359 * @return GNUNET_YES (we should continue to iterate)
2362 destroy_request (void *cls,
2363 const GNUNET_HashCode * key,
2366 const struct GNUNET_PeerIdentity * peer = cls;
2367 struct PendingRequest *pr = value;
2369 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2372 destroy_pending_request (pr);
2379 * Method called whenever a given peer connects.
2381 * @param cls closure, not used
2382 * @param peer peer identity this notification is about
2385 peer_connect_handler (void *cls,
2387 GNUNET_PeerIdentity * peer)
2389 struct ConnectedPeer *cp;
2391 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2392 cp->pid = GNUNET_PEER_intern (peer);
2393 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2396 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2401 * Method called whenever a peer disconnects.
2403 * @param cls closure, not used
2404 * @param peer peer identity this notification is about
2407 peer_disconnect_handler (void *cls,
2409 GNUNET_PeerIdentity * peer)
2411 struct ConnectedPeer *cp;
2413 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2415 GNUNET_PEER_change_rc (cp->pid, -1);
2416 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2418 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2426 * We're processing a GET request from
2427 * another peer and have decided to forward
2428 * it to other peers.
2430 * @param cls our "struct ProcessGetContext *"
2434 forward_get_request (void *cls,
2435 const struct GNUNET_SCHEDULER_TaskContext *tc)
2437 struct ProcessGetContext *pgc = cls;
2438 struct PendingRequest *pr;
2439 struct PendingRequest *eer;
2440 struct GNUNET_PeerIdentity target;
2442 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2443 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2445 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2446 *pr->namespace = pgc->namespace;
2449 pr->bf_size = pgc->bf_size;
2451 pr->start_time = pgc->start_time;
2452 pr->query = pgc->query;
2453 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2454 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2455 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2456 pr->anonymity_level = 1; /* default */
2457 pr->priority = pgc->priority;
2458 pr->remaining_priority = pr->priority;
2459 pr->mingle = pgc->mingle;
2461 pr->type = pgc->type;
2462 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2465 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2466 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2467 &pgc->reply_to.hashPubKey,
2469 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2470 GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2472 pr->start_time.value + pr->ttl);
2473 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2475 /* expire oldest request! */
2476 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2477 GNUNET_PEER_resolve (eer->source_pid,
2479 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2482 destroy_pending_request (eer);
2484 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2486 GNUNET_SCHEDULER_PRIORITY_IDLE,
2487 GNUNET_SCHEDULER_NO_TASK,
2488 get_processing_delay (),
2489 &forward_request_task,
2494 * Transmit the given message by copying it to
2495 * the target buffer "buf". "buf" will be
2496 * NULL and "size" zero if the socket was closed for
2497 * writing in the meantime. In that case, only
2501 * @param cls closure, pointer to the message
2502 * @param size number of bytes available in buf
2503 * @param buf where the callee should write the message
2504 * @return number of bytes written to buf
2507 transmit_message (void *cls,
2508 size_t size, void *buf)
2510 struct GNUNET_MessageHeader *msg = cls;
2516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2517 "Dropping reply, core too busy.\n");
2522 msize = ntohs (msg->size);
2523 GNUNET_assert (size >= msize);
2524 memcpy (buf, msg, msize);
2531 * Test if the load on this peer is too high
2532 * to even consider processing the query at
2535 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2538 test_load_too_high ()
2540 return GNUNET_NO; // FIXME
2545 * We're processing (local) results for a search request
2546 * from another peer. Pass applicable results to the
2547 * peer and if we are done either clean up (operation
2548 * complete) or forward to other peers (more results possible).
2550 * @param cls our closure (struct LocalGetContext)
2551 * @param key key for the content
2552 * @param size number of bytes in data
2553 * @param data content stored
2554 * @param type type of the content
2555 * @param priority priority of the content
2556 * @param anonymity anonymity-level for the content
2557 * @param expiration expiration time for the content
2558 * @param uid unique identifier for the datum;
2559 * maybe 0 if no unique identifier is available
2562 process_p2p_get_result (void *cls,
2563 const GNUNET_HashCode * key,
2569 struct GNUNET_TIME_Absolute
2573 struct ProcessGetContext *pgc = cls;
2574 GNUNET_HashCode dhash;
2575 GNUNET_HashCode mhash;
2576 struct PutMessage *reply;
2580 /* no more results */
2581 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2582 ( (0 == pgc->results_found) ||
2583 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2584 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2585 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2587 GNUNET_SCHEDULER_add_continuation (sched,
2589 &forward_get_request,
2591 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2595 if (pgc->bf != NULL)
2596 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2602 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2604 handle_on_demand_block (key, size, data, type, priority,
2605 anonymity, expiration, uid,
2606 &process_p2p_get_result,
2610 /* check for duplicates */
2611 GNUNET_CRYPTO_hash (data, size, &dhash);
2612 mingle_hash (&dhash,
2615 if ( (pgc->bf != NULL) &&
2617 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2622 "Result from datastore filtered by bloomfilter.\n");
2624 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2627 pgc->results_found++;
2628 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2629 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2630 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2632 if (pgc->bf == NULL)
2635 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2639 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2643 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2644 reply->header.size = htons (sizeof (struct PutMessage) + size);
2645 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2646 reply->type = htonl (type);
2647 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2648 memcpy (&reply[1], data, size);
2649 GNUNET_CORE_notify_transmit_ready (core,
2651 ACCEPTABLE_REPLY_DELAY,
2653 sizeof (struct PutMessage) + size,
2656 if ( (GNUNET_YES == test_load_too_high()) ||
2657 (pgc->results_found > 5 + 2 * pgc->priority) )
2659 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2660 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2663 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2668 * We're processing a GET request from another peer. Give it to our
2671 * @param cls our "struct ProcessGetContext"
2672 * @param ok did we get a datastore slice or not?
2675 ds_get_request (void *cls,
2678 struct ProcessGetContext *pgc = cls;
2680 struct GNUNET_TIME_Relative timeout;
2682 if (GNUNET_OK != ok)
2684 /* no point in doing P2P stuff if we can't even do local */
2689 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2690 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2691 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2692 (pgc->priority + 1));
2693 GNUNET_DATASTORE_get (dsh,
2696 &process_p2p_get_result,
2703 * The priority level imposes a bound on the maximum
2704 * value for the ttl that can be requested.
2706 * @param ttl_in requested ttl
2707 * @param prio given priority
2708 * @return ttl_in if ttl_in is below the limit,
2709 * otherwise the ttl-limit for the given priority
2712 bound_ttl (int32_t ttl_in, uint32_t prio)
2714 unsigned long long allowed;
2718 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2719 if (ttl_in > allowed)
2721 if (allowed >= (1 << 30))
2730 * We've received a request with the specified
2731 * priority. Bound it according to how much
2732 * we trust the given peer.
2734 * @param prio_in requested priority
2735 * @param peer the peer making the request
2736 * @return effective priority
2739 bound_priority (uint32_t prio_in,
2740 const struct GNUNET_PeerIdentity *peer)
2747 * Handle P2P "GET" request.
2749 * @param cls closure, always NULL
2750 * @param other the other peer involved (sender or receiver, NULL
2751 * for loopback messages where we are both sender and receiver)
2752 * @param message the actual message
2753 * @return GNUNET_OK to keep the connection open,
2754 * GNUNET_SYSERR to close it (signal serious error)
2757 handle_p2p_get (void *cls,
2758 const struct GNUNET_PeerIdentity *other,
2759 const struct GNUNET_MessageHeader *message)
2762 const struct GetMessage *gm;
2764 const GNUNET_HashCode *opt;
2765 struct ProcessGetContext *pgc;
2768 uint32_t ttl_decrement;
2773 msize = ntohs(message->size);
2774 if (msize < sizeof (struct GetMessage))
2776 GNUNET_break_op (0);
2777 return GNUNET_SYSERR;
2779 gm = (const struct GetMessage*) message;
2780 bm = ntohl (gm->hash_bitmap);
2788 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2790 GNUNET_break_op (0);
2791 return GNUNET_SYSERR;
2793 opt = (const GNUNET_HashCode*) &gm[1];
2794 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2795 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2798 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2801 pgc->bf_size = bfsize;
2803 pgc->type = ntohl (gm->type);
2804 pgc->bm = ntohl (gm->hash_bitmap);
2805 pgc->mingle = gm->filter_mutator;
2807 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2808 pgc->reply_to.hashPubKey = opt[bits++];
2810 pgc->reply_to = *other;
2811 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2812 pgc->namespace = opt[bits++];
2813 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2815 GNUNET_break_op (0);
2817 return GNUNET_SYSERR;
2819 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2820 pgc->prime_target.hashPubKey = opt[bits++];
2821 /* note that we can really only check load here since otherwise
2822 peers could find out that we are overloaded by being disconnected
2823 after sending us a malformed query... */
2824 if (GNUNET_YES == test_load_too_high ())
2826 if (NULL != pgc->bf)
2827 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2831 "Dropping query from `%s', this peer is too busy.\n",
2832 GNUNET_h2s (other));
2836 net_load_up = 50; // FIXME
2837 net_load_down = 50; // FIXME
2838 pgc->policy = ROUTING_POLICY_NONE;
2839 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2840 (net_load_down < IDLE_LOAD_THRESHOLD) )
2842 pgc->policy |= ROUTING_POLICY_ALL;
2843 pgc->priority = 0; /* no charge */
2847 pgc->priority = bound_priority (ntohl (gm->priority), other);
2849 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2851 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2853 pgc->policy |= ROUTING_POLICY_ALL;
2857 // FIXME: is this sound?
2858 if (net_load_up < 90 + 10 * pgc->priority)
2859 pgc->policy |= ROUTING_POLICY_FORWARD;
2860 if (net_load_down < 90 + 10 * pgc->priority)
2861 pgc->policy |= ROUTING_POLICY_ANSWER;
2864 if (pgc->policy == ROUTING_POLICY_NONE)
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2868 "Dropping query from `%s', network saturated.\n",
2869 GNUNET_h2s (other));
2871 if (NULL != pgc->bf)
2872 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2874 return GNUNET_OK; /* drop */
2876 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2877 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2878 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2879 /* decrement ttl (always) */
2880 ttl_decrement = 2 * TTL_DECREMENT +
2881 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2883 if ( (pgc->ttl < 0) &&
2884 (pgc->ttl - ttl_decrement > 0) )
2887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2888 "Dropping query from `%s' due to TTL underflow.\n",
2889 GNUNET_h2s (other));
2891 /* integer underflow => drop (should be very rare)! */
2892 if (NULL != pgc->bf)
2893 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2897 pgc->ttl -= ttl_decrement;
2898 pgc->start_time = GNUNET_TIME_absolute_get ();
2899 preference = (double) pgc->priority;
2900 if (preference < QUERY_BANDWIDTH_VALUE)
2901 preference = QUERY_BANDWIDTH_VALUE;
2902 // FIXME: also reserve bandwidth for reply?
2903 GNUNET_CORE_peer_configure (core,
2905 GNUNET_TIME_UNIT_FOREVER_REL,
2906 0, 0, preference, NULL, NULL);
2907 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2908 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2912 GNUNET_SCHEDULER_add_continuation (sched,
2914 &forward_get_request,
2916 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2922 * Function called to notify us that we can now transmit a reply to a
2923 * client or peer. "buf" will be NULL and "size" zero if the socket was
2924 * closed for writing in the meantime.
2926 * @param cls closure, points to a "struct PendingRequest*" with
2927 * one or more pending replies
2928 * @param size number of bytes available in buf
2929 * @param buf where the callee should write the message
2930 * @return number of bytes written to buf
2933 transmit_result (void *cls,
2937 struct PendingRequest *pr = cls;
2939 struct PendingReply *reply;
2943 while (NULL != (reply = pr->replies_pending))
2945 if ( (reply->msize + ret < ret) ||
2946 (reply->msize + ret > size) )
2948 pr->replies_pending = reply->next;
2949 memcpy (&cbuf[ret], &reply[1], reply->msize);
2950 ret += reply->msize;
2958 * Iterator over pending requests.
2960 * @param cls response (struct ProcessReplyClosure)
2961 * @param key our query
2962 * @param value value in the hash map (meta-info about the query)
2963 * @return GNUNET_YES (we should continue to iterate)
2966 process_reply (void *cls,
2967 const GNUNET_HashCode * key,
2970 struct ProcessReplyClosure *prq = cls;
2971 struct PendingRequest *pr = value;
2972 struct PendingRequest *eer;
2973 struct PendingReply *reply;
2974 struct PutMessage *pm;
2975 struct ContentMessage *cm;
2976 GNUNET_HashCode chash;
2977 GNUNET_HashCode mhash;
2978 struct GNUNET_PeerIdentity target;
2981 struct GNUNET_TIME_Relative max_delay;
2983 GNUNET_CRYPTO_hash (prq->data,
2988 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2989 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2991 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2992 /* FIXME: does prq->namespace match our expectations? */
2993 /* then: fall-through??? */
2994 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2997 mingle_hash (&chash, pr->mingle, &mhash);
2998 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3000 return GNUNET_YES; /* duplicate */
3001 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3005 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3006 // FIXME: any checks against duplicates for SKBlocks?
3009 prio = pr->priority;
3010 prq->priority += pr->remaining_priority;
3011 pr->remaining_priority = 0;
3012 if (pr->client != NULL)
3014 if (pr->replies_seen_size == pr->replies_seen_off)
3015 GNUNET_array_grow (pr->replies_seen,
3016 pr->replies_seen_size,
3017 pr->replies_seen_size * 2 + 4);
3018 pr->replies_seen[pr->replies_seen_off++] = chash;
3019 // FIXME: possibly recalculate BF!
3021 if (pr->client == NULL)
3023 msize = sizeof (struct ContentMessage) + prq->size;
3024 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3025 reply->msize = msize;
3026 cm = (struct ContentMessage*) &reply[1];
3027 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3028 cm->header.size = htons (msize);
3029 cm->type = htonl (prq->type);
3030 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3031 reply->next = pr->replies_pending;
3032 pr->replies_pending = reply;
3033 memcpy (&reply[1], prq->data, prq->size);
3034 if (pr->cth != NULL)
3036 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3037 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3039 /* estimate expiration time from time difference between
3040 first request that will be discarded and this request */
3041 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3042 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3045 GNUNET_PEER_resolve (pr->source_pid,
3047 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3054 if (NULL == pr->cth)
3056 // FIXME: now what? discard?
3061 msize = sizeof (struct PutMessage) + prq->size;
3062 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3063 reply->msize = msize;
3064 reply->next = pr->replies_pending;
3065 pm = (struct PutMessage*) &reply[1];
3066 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3067 pm->header.size = htons (msize);
3068 pm->type = htonl (prq->type);
3069 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3070 pr->replies_pending = reply;
3071 memcpy (&reply[1], prq->data, prq->size);
3074 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3076 GNUNET_TIME_UNIT_FOREVER_REL,
3081 // FIXME: need to try again later (not much
3082 // to do here specifically, but we need to
3083 // check somewhere else to handle this case!)
3086 // FIXME: implement hot-path routing statistics keeping!
3092 * Check if the given KBlock is well-formed.
3094 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3095 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3096 * @param query where to store the query that this block answers
3097 * @return GNUNET_OK if this is actually a well-formed KBlock
3100 check_kblock (const struct KBlock *kb,
3102 GNUNET_HashCode *query)
3104 if (dsize < sizeof (struct KBlock))
3106 GNUNET_break_op (0);
3107 return GNUNET_SYSERR;
3109 if (dsize - sizeof (struct KBlock) !=
3110 ntohs (kb->purpose.size)
3111 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3112 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3114 GNUNET_break_op (0);
3115 return GNUNET_SYSERR;
3118 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3123 GNUNET_break_op (0);
3124 return GNUNET_SYSERR;
3127 GNUNET_CRYPTO_hash (&kb->keyspace,
3128 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3135 * Check if the given SBlock is well-formed.
3137 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3138 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3139 * @param query where to store the query that this block answers
3140 * @param namespace where to store the namespace that this block belongs to
3141 * @return GNUNET_OK if this is actually a well-formed SBlock
3144 check_sblock (const struct SBlock *sb,
3146 GNUNET_HashCode *query,
3147 GNUNET_HashCode *namespace)
3149 if (dsize < sizeof (struct SBlock))
3151 GNUNET_break_op (0);
3152 return GNUNET_SYSERR;
3155 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3157 GNUNET_break_op (0);
3158 return GNUNET_SYSERR;
3161 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3166 GNUNET_break_op (0);
3167 return GNUNET_SYSERR;
3170 *query = sb->identifier;
3171 if (namespace != NULL)
3172 GNUNET_CRYPTO_hash (&sb->subspace,
3173 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3180 * Handle P2P "PUT" request.
3182 * @param cls closure, always NULL
3183 * @param other the other peer involved (sender or receiver, NULL
3184 * for loopback messages where we are both sender and receiver)
3185 * @param message the actual message
3186 * @return GNUNET_OK to keep the connection open,
3187 * GNUNET_SYSERR to close it (signal serious error)
3190 handle_p2p_put (void *cls,
3191 const struct GNUNET_PeerIdentity *other,
3192 const struct GNUNET_MessageHeader *message)
3194 const struct PutMessage *put;
3198 struct GNUNET_TIME_Absolute expiration;
3199 GNUNET_HashCode query;
3200 struct ProcessReplyClosure prq;
3202 msize = ntohs (message->size);
3203 if (msize < sizeof (struct PutMessage))
3206 return GNUNET_SYSERR;
3208 put = (const struct PutMessage*) message;
3209 dsize = msize - sizeof (struct PutMessage);
3210 type = ntohl (put->type);
3211 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3213 /* first, validate! */
3216 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3217 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3218 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3220 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3222 check_kblock ((const struct KBlock*) &put[1],
3225 return GNUNET_SYSERR;
3227 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3229 check_sblock ((const struct SBlock*) &put[1],
3233 return GNUNET_SYSERR;
3235 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3236 // FIXME -- validate SKBLOCK!
3240 /* unknown block type */
3241 GNUNET_break_op (0);
3242 return GNUNET_SYSERR;
3245 /* now, lookup 'query' */
3246 prq.data = (const void*) &put[1];
3249 prq.expiration = expiration;
3251 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3255 // FIXME: if migration is on and load is low,
3256 // queue to store data in datastore;
3257 // use "prq.priority" for that!
3263 * List of handlers for P2P messages
3264 * that we care about.
3266 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3269 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3271 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3277 * Task that will try to initiate a connection with the
3284 core_connect_task (void *cls,
3285 const struct GNUNET_SCHEDULER_TaskContext *tc);
3289 * Function called by the core after we've
3292 * @param cls closure, unused
3293 * @param server handle to the core service
3294 * @param my_identity our peer identity (unused)
3295 * @param publicKey our public key (unused)
3298 core_start_cb (void *cls,
3299 struct GNUNET_CORE_Handle * server,
3300 const struct GNUNET_PeerIdentity *
3303 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
3308 GNUNET_SCHEDULER_add_delayed (sched,
3310 GNUNET_SCHEDULER_PRIORITY_HIGH,
3311 GNUNET_SCHEDULER_NO_TASK,
3312 GNUNET_TIME_UNIT_SECONDS,
3322 * Task that will try to initiate a connection with the
3329 core_connect_task (void *cls,
3330 const struct GNUNET_SCHEDULER_TaskContext *tc)
3332 GNUNET_CORE_connect (sched,
3334 GNUNET_TIME_UNIT_FOREVER_REL,
3337 &peer_connect_handler,
3338 &peer_disconnect_handler,
3347 * Process fs requests.
3349 * @param cls closure
3350 * @param s scheduler to use
3351 * @param server the initialized server
3352 * @param c configuration to use
3356 struct GNUNET_SCHEDULER_Handle *s,
3357 struct GNUNET_SERVER_Handle *server,
3358 const struct GNUNET_CONFIGURATION_Handle *c)
3363 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3364 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3365 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3366 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3367 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3369 dsh = GNUNET_DATASTORE_connect (cfg,
3373 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3374 _("Failed to connect to datastore service.\n"));
3377 GNUNET_SERVER_disconnect_notify (server,
3378 &handle_client_disconnect,
3380 GNUNET_SERVER_add_handlers (server, handlers);
3381 core_connect_task (NULL, NULL);
3382 GNUNET_SCHEDULER_add_delayed (sched,
3384 GNUNET_SCHEDULER_PRIORITY_IDLE,
3385 GNUNET_SCHEDULER_NO_TASK,
3386 GNUNET_TIME_UNIT_FOREVER_REL,
3393 * The main function for the fs service.
3395 * @param argc number of arguments from the command line
3396 * @param argv command line arguments
3397 * @return 0 ok, 1 on error
3400 main (int argc, char *const *argv)
3402 return (GNUNET_OK ==
3403 GNUNET_SERVICE_run (argc,
3405 "fs", &run, NULL, NULL, NULL)) ? 0 : 1;
3408 /* end of gnunet-service-fs.c */