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"
50 #define DEBUG_FS GNUNET_YES
54 * In-memory information about indexed files (also available
61 * This is a linked list.
63 struct IndexInfo *next;
66 * Name of the indexed file. Memory allocated
67 * at the end of this struct (do not free).
72 * Context for transmitting confirmation to client,
73 * NULL if we've done this already.
75 struct GNUNET_SERVER_TransmitContext *tc;
78 * Hash of the contents of the file.
80 GNUNET_HashCode file_id;
86 * Signature of a function that is called whenever a datastore
87 * request can be processed (or an entry put on the queue times out).
90 * @param ok GNUNET_OK if DS is ready, GNUNET_SYSERR on timeout
92 typedef void (*RequestFunction)(void *cls,
97 * Doubly-linked list of our requests for the datastore.
99 struct DatastoreRequestQueue
103 * This is a doubly-linked list.
105 struct DatastoreRequestQueue *next;
108 * This is a doubly-linked list.
110 struct DatastoreRequestQueue *prev;
113 * Function to call (will issue the request).
123 * When should this request time-out because we don't care anymore?
125 struct GNUNET_TIME_Absolute timeout;
128 * ID of task used for signaling timeout.
130 GNUNET_SCHEDULER_TaskIdentifier task;
136 * Closure for processing START_SEARCH messages from a client.
138 struct LocalGetContext
142 * This is a doubly-linked list.
144 struct LocalGetContext *next;
147 * This is a doubly-linked list.
149 struct LocalGetContext *prev;
152 * Client that initiated the search.
154 struct GNUNET_SERVER_Client *client;
157 * Array of results that we've already received
160 GNUNET_HashCode *results;
163 * Bloomfilter over all results (for fast query construction);
164 * NULL if we don't have any results.
166 * FIXME: this member is not used, is that OK? If so, it should
169 struct GNUNET_CONTAINER_BloomFilter *results_bf;
172 * DS request associated with this operation.
174 struct DatastoreRequestQueue *req;
177 * Current result message to transmit to client (or NULL).
179 struct ContentMessage *result;
182 * Type of the content that we're looking for.
188 * Desired anonymity level.
190 uint32_t anonymity_level;
193 * Number of results actually stored in the results array.
195 unsigned int results_used;
198 * Size of the results array in memory.
200 unsigned int results_size;
203 * Size (in bytes) of the 'results_bf' bloomfilter.
205 * FIXME: this member is not used, is that OK? If so, it should
208 size_t results_bf_size;
211 * If the request is for a DBLOCK or IBLOCK, this is the identity of
212 * the peer that is known to have a response. Set to all-zeros if
213 * such a target is not known (note that even if OUR anonymity
214 * level is >0 we may happen to know the responder's identity;
215 * nevertheless, we should probably not use it for a DHT-lookup
216 * or similar blunt actions in order to avoid exposing ourselves).
218 struct GNUNET_PeerIdentity target;
221 * If the request is for an SBLOCK, this is the identity of the
222 * pseudonym to which the SBLOCK belongs.
224 GNUNET_HashCode namespace;
227 * Hash of the keyword (aka query) for KBLOCKs; Hash of
228 * the CHK-encoded block for DBLOCKS and IBLOCKS (aka query)
229 * and hash of the identifier XORed with the target for
230 * SBLOCKS (aka query).
232 GNUNET_HashCode query;
238 * Possible routing policies for an FS-GET request.
243 * Simply drop the request.
245 ROUTING_POLICY_NONE = 0,
248 * Answer it if we can from local datastore.
250 ROUTING_POLICY_ANSWER = 1,
253 * Forward the request to other peers (if possible).
255 ROUTING_POLICY_FORWARD = 2,
258 * Forward to other peers, and ask them to route
259 * the response via ourselves.
261 ROUTING_POLICY_INDIRECT = 6,
264 * Do everything we could possibly do (that would
267 ROUTING_POLICY_ALL = 7
272 * Internal context we use for our initial processing
275 struct ProcessGetContext
278 * The search query (used for datastore lookup).
280 GNUNET_HashCode query;
283 * Which peer we should forward the response to.
285 struct GNUNET_PeerIdentity reply_to;
288 * Namespace for the result (only set for SKS requests)
290 GNUNET_HashCode namespace;
293 * Peer that we should forward the query to if possible
294 * (since that peer likely has the content).
296 struct GNUNET_PeerIdentity prime_target;
299 * When did we receive this request?
301 struct GNUNET_TIME_Absolute start_time;
304 * Our entry in the DRQ (non-NULL while we wait for our
305 * turn to interact with the local database).
307 struct DatastoreRequestQueue *drq;
310 * Filter used to eliminate duplicate results. Can be NULL if we
311 * are not yet filtering any results.
313 struct GNUNET_CONTAINER_BloomFilter *bf;
316 * Bitmap describing which of the optional
317 * hash codes / peer identities were given to us.
322 * Desired block type.
327 * Priority of the request.
332 * Size of the 'bf' (in bytes).
337 * In what ways are we going to process
340 enum RoutingPolicy policy;
343 * Time-to-live for the request (value
349 * Number to mingle hashes for bloom-filter
355 * Number of results that were found so far.
357 unsigned int results_found;
362 * Information we keep for each pending reply.
367 * This is a linked list.
369 struct PendingReply *next;
372 * Size of the reply; actual reply message follows
373 * at the end of this struct.
381 * All requests from a client are kept in a doubly-linked list.
383 struct ClientRequestList;
387 * Information we keep for each pending request. We should try to
388 * keep this struct as small as possible since its memory consumption
389 * is key to how many requests we can have pending at once.
391 struct PendingRequest
395 * ID of a client making a request, NULL if this entry is for a
398 struct GNUNET_SERVER_Client *client;
401 * If this request was made by a client,
402 * this is our entry in the client request
403 * list; otherwise NULL.
405 struct ClientRequestList *crl_entry;
408 * If this is a namespace query, pointer to the hash of the public
409 * key of the namespace; otherwise NULL.
411 GNUNET_HashCode *namespace;
414 * Bloomfilter we use to filter out replies that we don't care about
415 * (anymore). NULL as long as we are interested in all replies.
417 struct GNUNET_CONTAINER_BloomFilter *bf;
420 * Replies that we have received but were unable to forward yet
421 * (typically non-null only if we have a pending transmission
422 * request with the client or the respective peer).
424 struct PendingReply *replies_pending;
427 * Pending transmission request with the core service for the target
428 * peer (for processing of 'replies_pending') or Handle for a
429 * pending query-request for P2P-transmission with the core service.
430 * If non-NULL, this request must be cancelled should this struct be
433 struct GNUNET_CORE_TransmitHandle *cth;
436 * Pending transmission request for the target client (for processing of
437 * 'replies_pending').
439 struct GNUNET_CONNECTION_TransmitHandle *th;
442 * Hash code of all replies that we have seen so far (only valid
443 * if client is not NULL since we only track replies like this for
446 GNUNET_HashCode *replies_seen;
449 * When did we first see this request (form this peer), or, if our
450 * client is initiating, when did we last initiate a search?
452 struct GNUNET_TIME_Absolute start_time;
455 * The query that this request is for.
457 GNUNET_HashCode query;
460 * The task responsible for transmitting queries
463 GNUNET_SCHEDULER_TaskIdentifier task;
466 * (Interned) Peer identifier (only valid if "client" is NULL)
467 * that identifies a peer that gave us this request.
469 GNUNET_PEER_Id source_pid;
472 * (Interned) Peer identifier that identifies a preferred target
475 GNUNET_PEER_Id target_pid;
478 * (Interned) Peer identifiers of peers that have already
479 * received our query for this content.
481 GNUNET_PEER_Id *used_pids;
484 * Size of the 'bf' (in bytes).
489 * Desired anonymity level; only valid for requests from a local client.
491 uint32_t anonymity_level;
494 * How many entries in "used_pids" are actually valid?
496 unsigned int used_pids_off;
499 * How long is the "used_pids" array?
501 unsigned int used_pids_size;
504 * How many entries in "replies_seen" are actually valid?
506 unsigned int replies_seen_off;
509 * How long is the "replies_seen" array?
511 unsigned int replies_seen_size;
514 * Priority with which this request was made. If one of our clients
515 * made the request, then this is the current priority that we are
516 * using when initiating the request. This value is used when
517 * we decide to reward other peers with trust for providing a reply.
522 * Priority points left for us to spend when forwarding this request
525 uint32_t remaining_priority;
528 * Number to mingle hashes for bloom-filter
534 * TTL with which we saw this request (or, if we initiated, TTL that
535 * we used for the request).
540 * Type of the content that this request is for.
548 * All requests from a client are kept in a doubly-linked list.
550 struct ClientRequestList
553 * This is a doubly-linked list.
555 struct ClientRequestList *next;
558 * This is a doubly-linked list.
560 struct ClientRequestList *prev;
563 * A request from this client.
565 struct PendingRequest *req;
568 * Client list with the head and tail of this DLL.
570 struct ClientList *cl;
575 * Linked list of all clients that we are
576 * currently processing requests for.
582 * This is a linked list.
584 struct ClientList *next;
587 * What client is this entry for?
589 struct GNUNET_SERVER_Client* client;
592 * Head of the DLL of requests from this client.
594 struct ClientRequestList *head;
597 * Tail of the DLL of requests from this client.
599 struct ClientRequestList *tail;
605 * Closure for "process_reply" function.
607 struct ProcessReplyClosure
610 * The data for the reply.
615 * When the reply expires.
617 struct GNUNET_TIME_Absolute expiration;
625 * Namespace that this reply belongs to
626 * (if it is of type SBLOCK).
628 GNUNET_HashCode namespace;
636 * How much was this reply worth to us?
643 * Information about a peer that we are connected to.
644 * We track data that is useful for determining which
645 * peers should receive our requests.
651 * List of the last clients for which this peer
652 * successfully answered a query.
654 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
657 * List of the last PIDs for which
658 * this peer successfully answered a query;
659 * We use 0 to indicate no successful reply.
661 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
664 * Average delay between sending the peer a request and
665 * getting a reply (only calculated over the requests for
666 * which we actually got a reply). Calculated
667 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
669 struct GNUNET_TIME_Relative avg_delay;
672 * Average priority of successful replies. Calculated
673 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
678 * The peer's identity.
683 * Number of requests we have currently pending
684 * with this peer (that is, requests that were
685 * transmitted so recently that we would not retransmit
688 unsigned int pending_requests;
691 * Which offset in "last_p2p_replies" will be updated next?
692 * (we go round-robin).
694 unsigned int last_p2p_replies_woff;
697 * Which offset in "last_client_replies" will be updated next?
698 * (we go round-robin).
700 unsigned int last_client_replies_woff;
706 * Our connection to the datastore.
708 static struct GNUNET_DATASTORE_Handle *dsh;
713 static struct GNUNET_SCHEDULER_Handle *sched;
718 const struct GNUNET_CONFIGURATION_Handle *cfg;
721 * Handle to the core service (NULL until we've connected to it).
723 struct GNUNET_CORE_Handle *core;
726 * Head of doubly-linked LGC list.
728 static struct LocalGetContext *lgc_head;
731 * Tail of doubly-linked LGC list.
733 static struct LocalGetContext *lgc_tail;
736 * Head of request queue for the datastore, sorted by timeout.
738 static struct DatastoreRequestQueue *drq_head;
741 * Tail of request queue for the datastore.
743 static struct DatastoreRequestQueue *drq_tail;
746 * Linked list of indexed files.
748 static struct IndexInfo *indexed_files;
751 * Maps hash over content of indexed files to the respective filename.
752 * The filenames are pointers into the indexed_files linked list and
753 * do not need to be freed.
755 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
758 * Map of query hash codes to requests.
760 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_query;
763 * Map of peer IDs to requests (for those requests coming
766 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_peer;
769 * Linked list of all of our clients and their requests.
771 static struct ClientList *clients;
774 * Heap with the request that will expire next at the top. Contains
775 * pointers of type "struct PendingRequest*"; these will *also* be
776 * aliased from the "requests_by_peer" data structures and the
777 * "requests_by_query" table. Note that requests from our clients
778 * don't expire and are thus NOT in the "requests_by_expiration"
779 * (or the "requests_by_peer" tables).
781 static struct GNUNET_CONTAINER_Heap *requests_by_expiration;
784 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
786 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
789 * Maximum number of requests (from other peers) that we're
790 * willing to have pending at any given point in time.
791 * FIXME: set from configuration (and 32 is a tiny value for testing only).
793 static uint64_t max_pending_requests = 32;
796 * Write the current index information list to disk.
801 struct GNUNET_BIO_WriteHandle *wh;
803 struct IndexInfo *pos;
806 GNUNET_CONFIGURATION_get_value_filename (cfg,
811 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
812 _("Configuration option `%s' in section `%s' missing.\n"),
817 wh = GNUNET_BIO_write_open (fn);
820 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
821 _("Could not open `%s'.\n"),
830 GNUNET_BIO_write (wh,
832 sizeof (GNUNET_HashCode))) ||
834 GNUNET_BIO_write_string (wh,
840 GNUNET_BIO_write_close (wh))
842 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
843 _("Error writing `%s'.\n"),
853 * Read index information from disk.
858 struct GNUNET_BIO_ReadHandle *rh;
860 struct IndexInfo *pos;
867 GNUNET_CONFIGURATION_get_value_filename (cfg,
872 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
873 _("Configuration option `%s' in section `%s' missing.\n"),
878 rh = GNUNET_BIO_read_open (fn);
881 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
882 _("Could not open `%s'.\n"),
888 while ( (GNUNET_OK ==
890 "Hash of indexed file",
892 sizeof (GNUNET_HashCode))) &&
894 GNUNET_BIO_read_string (rh,
895 "Name of indexed file",
899 slen = strlen (fname) + 1;
900 pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
902 pos->filename = (const char *) &pos[1];
903 memcpy (&pos[1], fname, slen);
905 GNUNET_CONTAINER_multihashmap_put (ifm,
907 (void*) pos->filename,
908 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
914 pos->next = indexed_files;
919 GNUNET_BIO_read_close (rh, &emsg))
926 * We've validated the hash of the file we're about to
927 * index. Signal success to the client and update
928 * our internal data structures.
930 * @param ii the index info entry for the request
933 signal_index_ok (struct IndexInfo *ii)
936 GNUNET_CONTAINER_multihashmap_put (ifm,
938 (void*) ii->filename,
939 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
941 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
942 _("Index request received for file `%s' is indexed as `%s'. Permitting anyway.\n"),
944 (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
946 GNUNET_SERVER_transmit_context_append (ii->tc,
948 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
949 GNUNET_SERVER_transmit_context_run (ii->tc,
950 GNUNET_TIME_UNIT_MINUTES);
954 ii->next = indexed_files;
957 GNUNET_SERVER_transmit_context_append (ii->tc,
959 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
960 GNUNET_SERVER_transmit_context_run (ii->tc,
961 GNUNET_TIME_UNIT_MINUTES);
967 * Function called once the hash computation over an
968 * indexed file has completed.
970 * @param cls closure, our publishing context
971 * @param res resulting hash, NULL on error
974 hash_for_index_val (void *cls,
975 const GNUNET_HashCode *
978 struct IndexInfo *ii = cls;
980 if ( (res == NULL) ||
983 sizeof(GNUNET_HashCode))) )
985 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
986 _("Hash mismatch trying to index file `%s'\n"),
988 GNUNET_SERVER_transmit_context_append (ii->tc,
990 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
991 GNUNET_SERVER_transmit_context_run (ii->tc,
992 GNUNET_TIME_UNIT_MINUTES);
996 signal_index_ok (ii);
1001 * Handle INDEX_START-message.
1003 * @param cls closure
1004 * @param client identification of the client
1005 * @param message the actual message
1008 handle_index_start (void *cls,
1009 struct GNUNET_SERVER_Client *client,
1010 const struct GNUNET_MessageHeader *message)
1012 const struct IndexStartMessage *ism;
1015 struct IndexInfo *ii;
1022 msize = ntohs(message->size);
1023 if ( (msize <= sizeof (struct IndexStartMessage)) ||
1024 ( ((const char *)message)[msize-1] != '\0') )
1027 GNUNET_SERVER_receive_done (client,
1031 ism = (const struct IndexStartMessage*) message;
1032 fn = (const char*) &ism[1];
1033 dev = ntohl (ism->device);
1034 ino = GNUNET_ntohll (ism->inode);
1035 ism = (const struct IndexStartMessage*) message;
1036 slen = strlen (fn) + 1;
1037 ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
1038 ii->filename = (const char*) &ii[1];
1039 memcpy (&ii[1], fn, slen);
1040 ii->file_id = ism->file_id;
1041 ii->tc = GNUNET_SERVER_transmit_context_create (client);
1042 if ( ( (dev != 0) ||
1044 (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
1050 /* fast validation OK! */
1051 signal_index_ok (ii);
1054 /* slow validation, need to hash full file (again) */
1055 GNUNET_CRYPTO_hash_file (sched,
1056 GNUNET_SCHEDULER_PRIORITY_IDLE,
1060 &hash_for_index_val,
1066 * Handle INDEX_LIST_GET-message.
1068 * @param cls closure
1069 * @param client identification of the client
1070 * @param message the actual message
1073 handle_index_list_get (void *cls,
1074 struct GNUNET_SERVER_Client *client,
1075 const struct GNUNET_MessageHeader *message)
1077 struct GNUNET_SERVER_TransmitContext *tc;
1078 struct IndexInfoMessage *iim;
1079 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1082 struct GNUNET_MessageHeader *msg;
1083 struct IndexInfo *pos;
1085 tc = GNUNET_SERVER_transmit_context_create (client);
1086 iim = (struct IndexInfoMessage*) buf;
1088 pos = indexed_files;
1092 iim->file_id = pos->file_id;
1094 slen = strlen (fn) + 1;
1095 if (slen + sizeof (struct IndexInfoMessage) >
1096 GNUNET_SERVER_MAX_MESSAGE_SIZE)
1101 memcpy (&iim[1], fn, slen);
1102 GNUNET_SERVER_transmit_context_append
1105 sizeof (struct IndexInfoMessage)
1106 - sizeof (struct GNUNET_MessageHeader) + slen,
1107 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1110 GNUNET_SERVER_transmit_context_append (tc,
1112 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1113 GNUNET_SERVER_transmit_context_run (tc,
1114 GNUNET_TIME_UNIT_MINUTES);
1119 * Handle UNINDEX-message.
1121 * @param cls closure
1122 * @param client identification of the client
1123 * @param message the actual message
1126 handle_unindex (void *cls,
1127 struct GNUNET_SERVER_Client *client,
1128 const struct GNUNET_MessageHeader *message)
1130 const struct UnindexMessage *um;
1131 struct IndexInfo *pos;
1132 struct IndexInfo *prev;
1133 struct IndexInfo *next;
1134 struct GNUNET_SERVER_TransmitContext *tc;
1137 um = (const struct UnindexMessage*) message;
1140 pos = indexed_files;
1144 if (0 == memcmp (&pos->file_id,
1146 sizeof (GNUNET_HashCode)))
1149 indexed_files = pos->next;
1151 prev->next = pos->next;
1161 if (GNUNET_YES == found)
1162 write_index_list ();
1163 tc = GNUNET_SERVER_transmit_context_create (client);
1164 GNUNET_SERVER_transmit_context_append (tc,
1166 GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1167 GNUNET_SERVER_transmit_context_run (tc,
1168 GNUNET_TIME_UNIT_MINUTES);
1173 * Run the next DS request in our
1174 * queue, we're done with the current one.
1179 struct DatastoreRequestQueue *e;
1181 while (NULL != (e = drq_head))
1183 if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1185 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1186 GNUNET_SCHEDULER_cancel (sched, e->task);
1187 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1188 e->req (e->req_cls, GNUNET_NO);
1193 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1194 GNUNET_SCHEDULER_cancel (sched, e->task);
1195 e->task = GNUNET_SCHEDULER_NO_TASK;
1196 e->req (e->req_cls, GNUNET_YES);
1197 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1203 * A datastore request had to be timed out.
1205 * @param cls closure (of type "struct DatastoreRequestQueue*")
1206 * @param tc task context, unused
1209 timeout_ds_request (void *cls,
1210 const struct GNUNET_SCHEDULER_TaskContext *tc)
1212 struct DatastoreRequestQueue *e = cls;
1214 e->task = GNUNET_SCHEDULER_NO_TASK;
1215 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1216 e->req (e->req_cls, GNUNET_NO);
1222 * Queue a request for the datastore.
1224 * @param deadline by when the request should run
1225 * @param fun function to call once the request can be run
1226 * @param fun_cls closure for fun
1228 static struct DatastoreRequestQueue *
1229 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1230 RequestFunction fun,
1233 struct DatastoreRequestQueue *e;
1234 struct DatastoreRequestQueue *bef;
1236 if (drq_head == NULL)
1238 /* no other requests pending, run immediately */
1239 fun (fun_cls, GNUNET_OK);
1242 e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1243 e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1245 e->req_cls = fun_cls;
1246 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1248 /* local request, highest prio, put at head of queue
1249 regardless of deadline */
1255 while ( (NULL != bef) &&
1256 (e->timeout.value < bef->timeout.value) )
1259 GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1260 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1262 e->task = GNUNET_SCHEDULER_add_delayed (sched,
1264 GNUNET_SCHEDULER_PRIORITY_BACKGROUND,
1265 GNUNET_SCHEDULER_NO_TASK,
1267 &timeout_ds_request,
1274 * Free the state associated with a local get context.
1276 * @param lgc the lgc to free
1279 local_get_context_free (struct LocalGetContext *lgc)
1281 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1282 GNUNET_SERVER_client_drop (lgc->client);
1283 GNUNET_free_non_null (lgc->results);
1284 if (lgc->results_bf != NULL)
1285 GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1286 if (lgc->req != NULL)
1288 if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1289 GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1290 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1291 GNUNET_free (lgc->req);
1298 * We're able to transmit the next (local) result to the client.
1299 * Do it and ask the datastore for more. Or, on error, tell
1300 * the datastore to stop giving us more.
1302 * @param cls our closure (struct LocalGetContext)
1303 * @param max maximum number of bytes we can transmit
1304 * @param buf where to copy our message
1305 * @return number of bytes copied to buf
1308 transmit_local_result (void *cls,
1312 struct LocalGetContext *lgc = cls;
1318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1319 "Failed to transmit result to local client, aborting datastore iteration.\n");
1322 GNUNET_free (lgc->result);
1324 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1327 msize = ntohs (lgc->result->header.size);
1329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1330 "Transmitting %u bytes of result to local client.\n",
1333 GNUNET_assert (max >= msize);
1334 memcpy (buf, lgc->result, msize);
1335 GNUNET_free (lgc->result);
1337 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1343 * Continuation called from datastore's remove
1347 * @param success did the deletion work?
1348 * @param msg error message
1351 remove_cont (void *cls,
1355 if (GNUNET_OK != success)
1356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1357 _("Failed to delete bogus block: %s\n"),
1359 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1364 * Mingle hash with the mingle_number to
1365 * produce different bits.
1368 mingle_hash (const GNUNET_HashCode * in,
1369 int32_t mingle_number,
1370 GNUNET_HashCode * hc)
1374 GNUNET_CRYPTO_hash (&mingle_number,
1377 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1382 * We've received an on-demand encoded block
1383 * from the datastore. Attempt to do on-demand
1384 * encoding and (if successful), call the
1385 * continuation with the resulting block. On
1386 * error, clean up and ask the datastore for
1389 * @param key key for the content
1390 * @param size number of bytes in data
1391 * @param data content stored
1392 * @param type type of the content
1393 * @param priority priority of the content
1394 * @param anonymity anonymity-level for the content
1395 * @param expiration expiration time for the content
1396 * @param uid unique identifier for the datum;
1397 * maybe 0 if no unique identifier is available
1398 * @param cont function to call with the actual block
1399 * @param cont_cls closure for cont
1402 handle_on_demand_block (const GNUNET_HashCode * key,
1408 struct GNUNET_TIME_Absolute
1409 expiration, uint64_t uid,
1410 GNUNET_DATASTORE_Iterator cont,
1413 const struct OnDemandBlock *odb;
1414 GNUNET_HashCode nkey;
1415 struct GNUNET_CRYPTO_AesSessionKey skey;
1416 struct GNUNET_CRYPTO_AesInitializationVector iv;
1417 GNUNET_HashCode query;
1419 char ndata[DBLOCK_SIZE];
1420 char edata[DBLOCK_SIZE];
1422 struct GNUNET_DISK_FileHandle *fh;
1425 if (size != sizeof (struct OnDemandBlock))
1428 GNUNET_DATASTORE_remove (dsh,
1434 GNUNET_TIME_UNIT_FOREVER_REL);
1437 odb = (const struct OnDemandBlock*) data;
1438 off = GNUNET_ntohll (odb->offset);
1439 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1442 if ( (NULL == fn) ||
1443 (NULL == (fh = GNUNET_DISK_file_open (fn,
1444 GNUNET_DISK_OPEN_READ,
1445 GNUNET_DISK_PERM_NONE))) ||
1447 GNUNET_DISK_file_seek (fh,
1449 GNUNET_DISK_SEEK_SET)) ||
1451 (nsize = GNUNET_DISK_file_read (fh,
1455 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1456 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1457 GNUNET_h2s (&odb->file_id),
1458 (unsigned long long) off,
1461 GNUNET_DISK_file_close (fh);
1462 /* FIXME: if this happens often, we need
1463 to remove the OnDemand block from the DS! */
1464 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1467 GNUNET_DISK_file_close (fh);
1468 GNUNET_CRYPTO_hash (ndata,
1471 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1472 GNUNET_CRYPTO_aes_encrypt (ndata,
1477 GNUNET_CRYPTO_hash (edata,
1480 if (0 != memcmp (&query,
1482 sizeof (GNUNET_HashCode)))
1484 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1485 _("Indexed file `%s' changed at offset %llu\n"),
1487 (unsigned long long) off);
1488 /* FIXME: if this happens often, we need
1489 to remove the OnDemand block from the DS! */
1490 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1497 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1506 * How many bytes should a bloomfilter be if we have already seen
1507 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1508 * of bits set per entry. Furthermore, we should not re-size the
1509 * filter too often (to keep it cheap).
1511 * Since other peers will also add entries but not resize the filter,
1512 * we should generally pick a slightly larger size than what the
1513 * strict math would suggest.
1515 * @return must be a power of two and smaller or equal to 2^15.
1518 compute_bloomfilter_size (unsigned int entry_count)
1521 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1522 uint16_t max = 1 << 15;
1524 if (entry_count > max)
1527 while ((size < max) && (size < ideal))
1536 * Recalculate our bloom filter for filtering replies.
1538 * @param count number of entries we are filtering right now
1539 * @param mingle set to our new mingling value
1540 * @param bf_size set to the size of the bloomfilter
1541 * @param entries the entries to filter
1542 * @return updated bloomfilter, NULL for none
1544 static struct GNUNET_CONTAINER_BloomFilter *
1545 refresh_bloomfilter (unsigned int count,
1548 const GNUNET_HashCode *entries)
1550 struct GNUNET_CONTAINER_BloomFilter *bf;
1553 GNUNET_HashCode mhash;
1557 nsize = compute_bloomfilter_size (count);
1558 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1560 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1563 for (i=0;i<count;i++)
1565 mingle_hash (&entries[i], *mingle, &mhash);
1566 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1573 * Closure used for "target_peer_select_cb".
1575 struct PeerSelectionContext
1578 * The request for which we are selecting
1581 struct PendingRequest *pr;
1584 * Current "prime" target.
1586 struct GNUNET_PeerIdentity target;
1589 * How much do we like this target?
1591 double target_score;
1597 * Function called for each connected peer to determine
1598 * which one(s) would make good targets for forwarding.
1600 * @param cls closure (struct PeerSelectionContext)
1601 * @param key current key code (peer identity)
1602 * @param value value in the hash map (struct ConnectedPeer)
1603 * @return GNUNET_YES if we should continue to
1608 target_peer_select_cb (void *cls,
1609 const GNUNET_HashCode * key,
1612 struct PeerSelectionContext *psc = cls;
1613 struct ConnectedPeer *cp = value;
1614 struct PendingRequest *pr = psc->pr;
1618 /* 1) check if we have already (recently) forwarded to this peer */
1619 for (i=0;i<pr->used_pids_off;i++)
1620 if (pr->used_pids[i] == cp->pid)
1621 return GNUNET_YES; /* skip */
1622 // 2) calculate how much we'd like to forward to this peer
1623 score = 0; // FIXME!
1625 /* store best-fit in closure */
1626 if (score > psc->target_score)
1628 psc->target_score = score;
1629 psc->target.hashPubKey = *key;
1636 * We use a random delay to make the timing of requests
1637 * less predictable. This function returns such a random
1640 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1642 static struct GNUNET_TIME_Relative
1643 get_processing_delay ()
1645 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1646 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1652 * Task that is run for each request with the
1653 * goal of forwarding the associated query to
1654 * other peers. The task should re-schedule
1655 * itself to be re-run once the TTL has expired.
1656 * (or at a later time if more peers should
1657 * be queried earlier).
1659 * @param cls the requests "struct PendingRequest*"
1660 * @param tc task context (unused)
1663 forward_request_task (void *cls,
1664 const struct GNUNET_SCHEDULER_TaskContext *tc);
1668 * We've selected a peer for forwarding of a query.
1669 * Construct the message and then re-schedule the
1670 * task to forward again to (other) peers.
1672 * @param cls closure
1673 * @param size number of bytes available in buf
1674 * @param buf where the callee should write the message
1675 * @return number of bytes written to buf
1678 transmit_request_cb (void *cls,
1682 struct PendingRequest *pr = cls;
1683 struct GetMessage *gm;
1684 GNUNET_HashCode *ext;
1690 /* (1) check for timeout */
1693 /* timeout, try another peer immediately again */
1694 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1696 GNUNET_SCHEDULER_PRIORITY_IDLE,
1697 GNUNET_SCHEDULER_NO_TASK,
1698 GNUNET_TIME_UNIT_ZERO,
1699 &forward_request_task,
1703 /* (2) build query message */
1704 k = 0; // FIXME: count hash codes!
1705 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1706 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1707 gm = (struct GetMessage*) buf;
1708 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1709 gm->header.size = htons (msize);
1710 gm->type = htonl (pr->type);
1711 pr->remaining_priority /= 2;
1712 gm->priority = htonl (pr->remaining_priority);
1713 gm->ttl = htonl (pr->ttl);
1714 gm->filter_mutator = htonl(pr->mingle);
1715 gm->hash_bitmap = htonl (42);
1716 gm->query = pr->query;
1717 ext = (GNUNET_HashCode*) &gm[1];
1718 // FIXME: setup "ext[0]..[k-1]"
1719 bfdata = (char *) &ext[k];
1721 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1725 /* (3) schedule job to do it again (or another peer, etc.) */
1726 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1728 GNUNET_SCHEDULER_PRIORITY_IDLE,
1729 GNUNET_SCHEDULER_NO_TASK,
1730 get_processing_delay (), // FIXME!
1731 &forward_request_task,
1739 * Function called after we've tried to reserve
1740 * a certain amount of bandwidth for a reply.
1741 * Check if we succeeded and if so send our query.
1743 * @param cls the requests "struct PendingRequest*"
1744 * @param peer identifies the peer
1745 * @param latency current latency estimate, "FOREVER" if we have been
1747 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1748 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1749 * @param amount set to the amount that was actually reserved or unreserved
1750 * @param preference current traffic preference for the given peer
1753 target_reservation_cb (void *cls,
1755 GNUNET_PeerIdentity * peer,
1756 unsigned int bpm_in,
1757 unsigned int bpm_out,
1758 struct GNUNET_TIME_Relative
1759 latency, int amount,
1760 unsigned long long preference)
1762 struct PendingRequest *pr = cls;
1765 struct GNUNET_TIME_Relative maxdelay;
1767 GNUNET_assert (peer != NULL);
1768 if ( (amount != DBLOCK_SIZE) ||
1771 /* try again later; FIXME: we may need to un-reserve "amount"? */
1772 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1774 GNUNET_SCHEDULER_PRIORITY_IDLE,
1775 GNUNET_SCHEDULER_NO_TASK,
1776 get_processing_delay (), // FIXME: longer?
1777 &forward_request_task,
1781 // (2) transmit, update ttl/priority
1782 // FIXME: calculate priority, maxdelay, size properly!
1785 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1786 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1791 &transmit_request_cb,
1793 if (pr->cth == NULL)
1795 /* try again later */
1796 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1798 GNUNET_SCHEDULER_PRIORITY_IDLE,
1799 GNUNET_SCHEDULER_NO_TASK,
1800 get_processing_delay (), // FIXME: longer?
1801 &forward_request_task,
1808 * Task that is run for each request with the
1809 * goal of forwarding the associated query to
1810 * other peers. The task should re-schedule
1811 * itself to be re-run once the TTL has expired.
1812 * (or at a later time if more peers should
1813 * be queried earlier).
1815 * @param cls the requests "struct PendingRequest*"
1816 * @param tc task context (unused)
1819 forward_request_task (void *cls,
1820 const struct GNUNET_SCHEDULER_TaskContext *tc)
1822 struct PendingRequest *pr = cls;
1823 struct PeerSelectionContext psc;
1825 pr->task = GNUNET_SCHEDULER_NO_TASK;
1826 if (pr->cth != NULL)
1828 /* we're busy transmitting a result, wait a bit */
1829 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1831 GNUNET_SCHEDULER_PRIORITY_IDLE,
1832 GNUNET_SCHEDULER_NO_TASK,
1833 get_processing_delay (),
1834 &forward_request_task,
1838 /* (1) select target */
1840 psc.target_score = DBL_MIN;
1841 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1842 &target_peer_select_cb,
1844 if (psc.target_score == DBL_MIN)
1846 /* no possible target found, wait some time */
1847 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1849 GNUNET_SCHEDULER_PRIORITY_IDLE,
1850 GNUNET_SCHEDULER_NO_TASK,
1851 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1852 &forward_request_task,
1856 /* (2) reserve reply bandwidth */
1857 // FIXME: need a way to cancel; this
1858 // async operation is problematic (segv-problematic)
1859 // if "pr" is destroyed while it happens!
1860 GNUNET_CORE_peer_configure (core,
1862 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1864 DBLOCK_SIZE, // FIXME: make dependent on type?
1866 &target_reservation_cb,
1872 * We're processing (local) results for a search request
1873 * from a (local) client. Pass applicable results to the
1874 * client and if we are done either clean up (operation
1875 * complete) or switch to P2P search (more results possible).
1877 * @param cls our closure (struct LocalGetContext)
1878 * @param key key for the content
1879 * @param size number of bytes in data
1880 * @param data content stored
1881 * @param type type of the content
1882 * @param priority priority of the content
1883 * @param anonymity anonymity-level for the content
1884 * @param expiration expiration time for the content
1885 * @param uid unique identifier for the datum;
1886 * maybe 0 if no unique identifier is available
1889 process_local_get_result (void *cls,
1890 const GNUNET_HashCode * key,
1896 struct GNUNET_TIME_Absolute
1900 struct LocalGetContext *lgc = cls;
1901 struct PendingRequest *pr;
1902 struct ClientRequestList *crl;
1903 struct ClientList *cl;
1910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1911 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1912 GNUNET_h2s (&lgc->query));
1914 /* no further results from datastore; continue
1915 processing further requests from the client and
1916 allow the next task to use the datastore; also,
1917 switch to P2P requests or clean up our state. */
1919 GNUNET_SERVER_receive_done (lgc->client,
1921 if ( (lgc->results_used == 0) ||
1922 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1923 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1924 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1928 "Forwarding query for `%s' to network.\n",
1929 GNUNET_h2s (&lgc->query));
1932 while ( (NULL != cl) &&
1933 (cl->client != lgc->client) )
1937 cl = GNUNET_malloc (sizeof (struct ClientList));
1938 cl->client = lgc->client;
1942 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1944 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1945 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1946 pr->client = lgc->client;
1947 GNUNET_SERVER_client_keep (pr->client);
1948 pr->crl_entry = crl;
1950 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1952 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1953 *pr->namespace = lgc->namespace;
1955 pr->replies_seen = lgc->results;
1956 lgc->results = NULL;
1957 pr->start_time = GNUNET_TIME_absolute_get ();
1958 pr->query = lgc->query;
1959 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1960 pr->replies_seen_off = lgc->results_used;
1961 pr->replies_seen_size = lgc->results_size;
1962 lgc->results_size = 0;
1963 pr->type = lgc->type;
1964 pr->anonymity_level = lgc->anonymity_level;
1965 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1969 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1972 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1973 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1975 GNUNET_SCHEDULER_PRIORITY_IDLE,
1976 GNUNET_SCHEDULER_NO_TASK,
1977 get_processing_delay (),
1978 &forward_request_task,
1980 local_get_context_free (lgc);
1983 /* got all possible results, clean up! */
1985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1986 "Found all possible results for query for `%s', done!\n",
1987 GNUNET_h2s (&lgc->query));
1989 local_get_context_free (lgc);
1992 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1995 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1996 "Received on-demand block for `%s' from local datastore, fetching data.\n",
1997 GNUNET_h2s (&lgc->query));
1999 handle_on_demand_block (key, size, data, type, priority,
2000 anonymity, expiration, uid,
2001 &process_local_get_result,
2005 if ( (type != lgc->type) &&
2006 (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2008 /* this should be virtually impossible to reach (DBLOCK
2009 query hash being identical to KBLOCK/SBLOCK query hash);
2010 nevertheless, if it happens, the correct thing is to
2011 simply skip the result. */
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014 "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2017 GNUNET_h2s (&lgc->query));
2019 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2022 /* check if this is a result we've alredy
2024 for (i=0;i<lgc->results_used;i++)
2025 if (0 == memcmp (key,
2027 sizeof (GNUNET_HashCode)))
2030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2031 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2032 GNUNET_h2s (&lgc->query));
2034 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2037 if (lgc->results_used == lgc->results_size)
2038 GNUNET_array_grow (lgc->results,
2040 lgc->results_size * 2 + 2);
2041 GNUNET_CRYPTO_hash (data,
2043 &lgc->results[lgc->results_used++]);
2044 msize = size + sizeof (struct ContentMessage);
2045 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2046 lgc->result = GNUNET_malloc (msize);
2047 lgc->result->header.size = htons (msize);
2048 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2049 lgc->result->type = htonl (type);
2050 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2051 memcpy (&lgc->result[1],
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "Received new result for `%s' from local datastore, passing to client.\n",
2057 GNUNET_h2s (&lgc->query));
2059 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2061 GNUNET_TIME_UNIT_FOREVER_REL,
2062 &transmit_local_result,
2068 * We're processing a search request from a local
2069 * client. Now it is our turn to query the datastore.
2071 * @param cls our closure (struct LocalGetContext)
2075 transmit_local_get (void *cls,
2076 const struct GNUNET_SCHEDULER_TaskContext *tc)
2078 struct LocalGetContext *lgc = cls;
2082 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2083 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2084 GNUNET_DATASTORE_get (dsh,
2087 &process_local_get_result,
2089 GNUNET_TIME_UNIT_FOREVER_REL);
2094 * We're processing a search request from a local
2095 * client. Now it is our turn to query the datastore.
2097 * @param cls our closure (struct LocalGetContext)
2098 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2101 transmit_local_get_ready (void *cls,
2104 struct LocalGetContext *lgc = cls;
2106 GNUNET_assert (GNUNET_OK == ok);
2107 GNUNET_SCHEDULER_add_continuation (sched,
2109 &transmit_local_get,
2111 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2116 * Handle START_SEARCH-message (search request from client).
2118 * @param cls closure
2119 * @param client identification of the client
2120 * @param message the actual message
2123 handle_start_search (void *cls,
2124 struct GNUNET_SERVER_Client *client,
2125 const struct GNUNET_MessageHeader *message)
2127 const struct SearchMessage *sm;
2128 struct LocalGetContext *lgc;
2132 msize = ntohs (message->size);
2133 if ( (msize < sizeof (struct SearchMessage)) ||
2134 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2137 GNUNET_SERVER_receive_done (client,
2141 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2142 sm = (const struct SearchMessage*) message;
2143 GNUNET_SERVER_client_keep (client);
2144 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2147 lgc->results_used = sc;
2148 GNUNET_array_grow (lgc->results,
2151 memcpy (lgc->results,
2153 sc * sizeof (GNUNET_HashCode));
2155 lgc->client = client;
2156 lgc->type = ntohl (sm->type);
2157 lgc->anonymity_level = ntohl (sm->anonymity_level);
2160 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2161 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2162 lgc->target.hashPubKey = sm->target;
2164 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2165 lgc->namespace = sm->target;
2170 lgc->query = sm->query;
2171 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2172 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2173 &transmit_local_get_ready,
2179 * List of handlers for the messages understood by this
2182 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2183 {&handle_index_start, NULL,
2184 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2185 {&handle_index_list_get, NULL,
2186 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2187 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2188 sizeof (struct UnindexMessage) },
2189 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2196 * Clean up the memory used by the PendingRequest structure (except
2197 * for the client or peer list that the request may be part of).
2199 * @param pr request to clean up
2202 destroy_pending_request (struct PendingRequest *pr)
2204 struct PendingReply *reply;
2205 struct ClientList *cl;
2207 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2210 // FIXME: not sure how this can work (efficiently)
2211 // also, what does the return value mean?
2212 if (pr->client == NULL)
2214 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2219 cl = pr->crl_entry->cl;
2220 GNUNET_CONTAINER_DLL_remove (cl->head,
2224 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2225 GNUNET_SCHEDULER_cancel (sched, pr->task);
2226 if (NULL != pr->cth)
2227 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2229 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2231 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2232 while (NULL != (reply = pr->replies_pending))
2234 pr->replies_pending = reply->next;
2235 GNUNET_free (reply);
2237 GNUNET_PEER_change_rc (pr->source_pid, -1);
2238 GNUNET_PEER_change_rc (pr->target_pid, -1);
2239 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2240 GNUNET_free_non_null (pr->used_pids);
2241 GNUNET_free_non_null (pr->replies_seen);
2242 GNUNET_free_non_null (pr->namespace);
2248 * A client disconnected. Remove all of its pending queries.
2250 * @param cls closure, NULL
2251 * @param client identification of the client
2254 handle_client_disconnect (void *cls,
2255 struct GNUNET_SERVER_Client
2258 struct LocalGetContext *lgc;
2259 struct ClientList *cpos;
2260 struct ClientList *cprev;
2261 struct ClientRequestList *rl;
2264 while ( (NULL != lgc) &&
2265 (lgc->client != client) )
2268 local_get_context_free (lgc);
2271 while ( (NULL != cpos) &&
2272 (clients->client != client) )
2280 clients = cpos->next;
2282 cprev->next = cpos->next;
2283 while (NULL != (rl = cpos->head))
2285 cpos->head = rl->next;
2286 destroy_pending_request (rl->req);
2295 * Iterator over entries in the "requests_by_query" map
2296 * that frees all the entries.
2298 * @param cls closure, NULL
2299 * @param key current key code (the query, unused)
2300 * @param value value in the hash map, of type "struct PendingRequest*"
2301 * @return GNUNET_YES (we should continue to iterate)
2304 destroy_pending_request_cb (void *cls,
2305 const GNUNET_HashCode * key,
2308 struct PendingRequest *pr = value;
2310 destroy_pending_request (pr);
2316 * Task run during shutdown.
2322 shutdown_task (void *cls,
2323 const struct GNUNET_SCHEDULER_TaskContext *tc)
2325 struct IndexInfo *pos;
2328 GNUNET_CORE_disconnect (core);
2329 GNUNET_DATASTORE_disconnect (dsh,
2332 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2333 &destroy_pending_request_cb,
2335 while (clients != NULL)
2336 handle_client_disconnect (NULL,
2338 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2339 requests_by_query = NULL;
2340 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2341 requests_by_peer = NULL;
2342 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2343 requests_by_expiration = NULL;
2344 // FIXME: iterate over entries and free individually?
2345 // (or do we get disconnect notifications?)
2346 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2347 connected_peers = NULL;
2348 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2350 while (NULL != (pos = indexed_files))
2352 indexed_files = pos->next;
2359 * Free (each) request made by the peer.
2361 * @param cls closure, points to peer that the request belongs to
2362 * @param key current key code
2363 * @param value value in the hash map
2364 * @return GNUNET_YES (we should continue to iterate)
2367 destroy_request (void *cls,
2368 const GNUNET_HashCode * key,
2371 const struct GNUNET_PeerIdentity * peer = cls;
2372 struct PendingRequest *pr = value;
2374 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2377 destroy_pending_request (pr);
2384 * Method called whenever a given peer connects.
2386 * @param cls closure, not used
2387 * @param peer peer identity this notification is about
2390 peer_connect_handler (void *cls,
2392 GNUNET_PeerIdentity * peer)
2394 struct ConnectedPeer *cp;
2396 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2397 cp->pid = GNUNET_PEER_intern (peer);
2398 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2401 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2406 * Method called whenever a peer disconnects.
2408 * @param cls closure, not used
2409 * @param peer peer identity this notification is about
2412 peer_disconnect_handler (void *cls,
2414 GNUNET_PeerIdentity * peer)
2416 struct ConnectedPeer *cp;
2418 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2420 GNUNET_PEER_change_rc (cp->pid, -1);
2421 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2423 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2431 * We're processing a GET request from
2432 * another peer and have decided to forward
2433 * it to other peers.
2435 * @param cls our "struct ProcessGetContext *"
2439 forward_get_request (void *cls,
2440 const struct GNUNET_SCHEDULER_TaskContext *tc)
2442 struct ProcessGetContext *pgc = cls;
2443 struct PendingRequest *pr;
2444 struct PendingRequest *eer;
2445 struct GNUNET_PeerIdentity target;
2447 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2448 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2450 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2451 *pr->namespace = pgc->namespace;
2454 pr->bf_size = pgc->bf_size;
2456 pr->start_time = pgc->start_time;
2457 pr->query = pgc->query;
2458 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2459 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2460 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2461 pr->anonymity_level = 1; /* default */
2462 pr->priority = pgc->priority;
2463 pr->remaining_priority = pr->priority;
2464 pr->mingle = pgc->mingle;
2466 pr->type = pgc->type;
2467 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2470 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2471 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2472 &pgc->reply_to.hashPubKey,
2474 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2475 GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2477 pr->start_time.value + pr->ttl);
2478 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2480 /* expire oldest request! */
2481 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2482 GNUNET_PEER_resolve (eer->source_pid,
2484 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2487 destroy_pending_request (eer);
2489 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2491 GNUNET_SCHEDULER_PRIORITY_IDLE,
2492 GNUNET_SCHEDULER_NO_TASK,
2493 get_processing_delay (),
2494 &forward_request_task,
2499 * Transmit the given message by copying it to
2500 * the target buffer "buf". "buf" will be
2501 * NULL and "size" zero if the socket was closed for
2502 * writing in the meantime. In that case, only
2506 * @param cls closure, pointer to the message
2507 * @param size number of bytes available in buf
2508 * @param buf where the callee should write the message
2509 * @return number of bytes written to buf
2512 transmit_message (void *cls,
2513 size_t size, void *buf)
2515 struct GNUNET_MessageHeader *msg = cls;
2521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2522 "Dropping reply, core too busy.\n");
2527 msize = ntohs (msg->size);
2528 GNUNET_assert (size >= msize);
2529 memcpy (buf, msg, msize);
2536 * Test if the load on this peer is too high
2537 * to even consider processing the query at
2540 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2543 test_load_too_high ()
2545 return GNUNET_NO; // FIXME
2550 * We're processing (local) results for a search request
2551 * from another peer. Pass applicable results to the
2552 * peer and if we are done either clean up (operation
2553 * complete) or forward to other peers (more results possible).
2555 * @param cls our closure (struct LocalGetContext)
2556 * @param key key for the content
2557 * @param size number of bytes in data
2558 * @param data content stored
2559 * @param type type of the content
2560 * @param priority priority of the content
2561 * @param anonymity anonymity-level for the content
2562 * @param expiration expiration time for the content
2563 * @param uid unique identifier for the datum;
2564 * maybe 0 if no unique identifier is available
2567 process_p2p_get_result (void *cls,
2568 const GNUNET_HashCode * key,
2574 struct GNUNET_TIME_Absolute
2578 struct ProcessGetContext *pgc = cls;
2579 GNUNET_HashCode dhash;
2580 GNUNET_HashCode mhash;
2581 struct PutMessage *reply;
2585 /* no more results */
2586 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2587 ( (0 == pgc->results_found) ||
2588 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2589 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2590 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2592 GNUNET_SCHEDULER_add_continuation (sched,
2594 &forward_get_request,
2596 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2600 if (pgc->bf != NULL)
2601 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2607 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2609 handle_on_demand_block (key, size, data, type, priority,
2610 anonymity, expiration, uid,
2611 &process_p2p_get_result,
2615 /* check for duplicates */
2616 GNUNET_CRYPTO_hash (data, size, &dhash);
2617 mingle_hash (&dhash,
2620 if ( (pgc->bf != NULL) &&
2622 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2627 "Result from datastore filtered by bloomfilter.\n");
2629 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2632 pgc->results_found++;
2633 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2634 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2635 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2637 if (pgc->bf == NULL)
2640 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2644 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2648 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2649 reply->header.size = htons (sizeof (struct PutMessage) + size);
2650 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2651 reply->type = htonl (type);
2652 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2653 memcpy (&reply[1], data, size);
2654 GNUNET_CORE_notify_transmit_ready (core,
2656 ACCEPTABLE_REPLY_DELAY,
2658 sizeof (struct PutMessage) + size,
2661 if ( (GNUNET_YES == test_load_too_high()) ||
2662 (pgc->results_found > 5 + 2 * pgc->priority) )
2664 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2665 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2668 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2673 * We're processing a GET request from another peer. Give it to our
2676 * @param cls our "struct ProcessGetContext"
2677 * @param ok did we get a datastore slice or not?
2680 ds_get_request (void *cls,
2683 struct ProcessGetContext *pgc = cls;
2685 struct GNUNET_TIME_Relative timeout;
2687 if (GNUNET_OK != ok)
2689 /* no point in doing P2P stuff if we can't even do local */
2694 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2695 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2696 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2697 (pgc->priority + 1));
2698 GNUNET_DATASTORE_get (dsh,
2701 &process_p2p_get_result,
2708 * The priority level imposes a bound on the maximum
2709 * value for the ttl that can be requested.
2711 * @param ttl_in requested ttl
2712 * @param prio given priority
2713 * @return ttl_in if ttl_in is below the limit,
2714 * otherwise the ttl-limit for the given priority
2717 bound_ttl (int32_t ttl_in, uint32_t prio)
2719 unsigned long long allowed;
2723 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2724 if (ttl_in > allowed)
2726 if (allowed >= (1 << 30))
2735 * We've received a request with the specified
2736 * priority. Bound it according to how much
2737 * we trust the given peer.
2739 * @param prio_in requested priority
2740 * @param peer the peer making the request
2741 * @return effective priority
2744 bound_priority (uint32_t prio_in,
2745 const struct GNUNET_PeerIdentity *peer)
2752 * Handle P2P "GET" request.
2754 * @param cls closure, always NULL
2755 * @param other the other peer involved (sender or receiver, NULL
2756 * for loopback messages where we are both sender and receiver)
2757 * @param message the actual message
2758 * @return GNUNET_OK to keep the connection open,
2759 * GNUNET_SYSERR to close it (signal serious error)
2762 handle_p2p_get (void *cls,
2763 const struct GNUNET_PeerIdentity *other,
2764 const struct GNUNET_MessageHeader *message)
2767 const struct GetMessage *gm;
2769 const GNUNET_HashCode *opt;
2770 struct ProcessGetContext *pgc;
2773 uint32_t ttl_decrement;
2778 msize = ntohs(message->size);
2779 if (msize < sizeof (struct GetMessage))
2781 GNUNET_break_op (0);
2782 return GNUNET_SYSERR;
2784 gm = (const struct GetMessage*) message;
2785 bm = ntohl (gm->hash_bitmap);
2793 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2795 GNUNET_break_op (0);
2796 return GNUNET_SYSERR;
2798 opt = (const GNUNET_HashCode*) &gm[1];
2799 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2800 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2803 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2806 pgc->bf_size = bfsize;
2808 pgc->type = ntohl (gm->type);
2809 pgc->bm = ntohl (gm->hash_bitmap);
2810 pgc->mingle = gm->filter_mutator;
2812 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2813 pgc->reply_to.hashPubKey = opt[bits++];
2815 pgc->reply_to = *other;
2816 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2817 pgc->namespace = opt[bits++];
2818 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2820 GNUNET_break_op (0);
2822 return GNUNET_SYSERR;
2824 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2825 pgc->prime_target.hashPubKey = opt[bits++];
2826 /* note that we can really only check load here since otherwise
2827 peers could find out that we are overloaded by being disconnected
2828 after sending us a malformed query... */
2829 if (GNUNET_YES == test_load_too_high ())
2831 if (NULL != pgc->bf)
2832 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2836 "Dropping query from `%s', this peer is too busy.\n",
2837 GNUNET_i2s (other));
2841 net_load_up = 50; // FIXME
2842 net_load_down = 50; // FIXME
2843 pgc->policy = ROUTING_POLICY_NONE;
2844 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2845 (net_load_down < IDLE_LOAD_THRESHOLD) )
2847 pgc->policy |= ROUTING_POLICY_ALL;
2848 pgc->priority = 0; /* no charge */
2852 pgc->priority = bound_priority (ntohl (gm->priority), other);
2854 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2856 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2858 pgc->policy |= ROUTING_POLICY_ALL;
2862 // FIXME: is this sound?
2863 if (net_load_up < 90 + 10 * pgc->priority)
2864 pgc->policy |= ROUTING_POLICY_FORWARD;
2865 if (net_load_down < 90 + 10 * pgc->priority)
2866 pgc->policy |= ROUTING_POLICY_ANSWER;
2869 if (pgc->policy == ROUTING_POLICY_NONE)
2872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2873 "Dropping query from `%s', network saturated.\n",
2874 GNUNET_i2s (other));
2876 if (NULL != pgc->bf)
2877 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2879 return GNUNET_OK; /* drop */
2881 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2882 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2883 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2884 /* decrement ttl (always) */
2885 ttl_decrement = 2 * TTL_DECREMENT +
2886 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2888 if ( (pgc->ttl < 0) &&
2889 (pgc->ttl - ttl_decrement > 0) )
2892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2893 "Dropping query from `%s' due to TTL underflow.\n",
2894 GNUNET_i2s (other));
2896 /* integer underflow => drop (should be very rare)! */
2897 if (NULL != pgc->bf)
2898 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2902 pgc->ttl -= ttl_decrement;
2903 pgc->start_time = GNUNET_TIME_absolute_get ();
2904 preference = (double) pgc->priority;
2905 if (preference < QUERY_BANDWIDTH_VALUE)
2906 preference = QUERY_BANDWIDTH_VALUE;
2907 // FIXME: also reserve bandwidth for reply?
2908 GNUNET_CORE_peer_configure (core,
2910 GNUNET_TIME_UNIT_FOREVER_REL,
2911 0, 0, preference, NULL, NULL);
2912 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2913 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2917 GNUNET_SCHEDULER_add_continuation (sched,
2919 &forward_get_request,
2921 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2927 * Function called to notify us that we can now transmit a reply to a
2928 * client or peer. "buf" will be NULL and "size" zero if the socket was
2929 * closed for writing in the meantime.
2931 * @param cls closure, points to a "struct PendingRequest*" with
2932 * one or more pending replies
2933 * @param size number of bytes available in buf
2934 * @param buf where the callee should write the message
2935 * @return number of bytes written to buf
2938 transmit_result (void *cls,
2942 struct PendingRequest *pr = cls;
2944 struct PendingReply *reply;
2948 while (NULL != (reply = pr->replies_pending))
2950 if ( (reply->msize + ret < ret) ||
2951 (reply->msize + ret > size) )
2953 pr->replies_pending = reply->next;
2954 memcpy (&cbuf[ret], &reply[1], reply->msize);
2955 ret += reply->msize;
2963 * Iterator over pending requests.
2965 * @param cls response (struct ProcessReplyClosure)
2966 * @param key our query
2967 * @param value value in the hash map (meta-info about the query)
2968 * @return GNUNET_YES (we should continue to iterate)
2971 process_reply (void *cls,
2972 const GNUNET_HashCode * key,
2975 struct ProcessReplyClosure *prq = cls;
2976 struct PendingRequest *pr = value;
2977 struct PendingRequest *eer;
2978 struct PendingReply *reply;
2979 struct PutMessage *pm;
2980 struct ContentMessage *cm;
2981 GNUNET_HashCode chash;
2982 GNUNET_HashCode mhash;
2983 struct GNUNET_PeerIdentity target;
2986 struct GNUNET_TIME_Relative max_delay;
2988 GNUNET_CRYPTO_hash (prq->data,
2993 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2994 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2996 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2997 /* FIXME: does prq->namespace match our expectations? */
2998 /* then: fall-through??? */
2999 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3002 mingle_hash (&chash, pr->mingle, &mhash);
3003 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3005 return GNUNET_YES; /* duplicate */
3006 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3010 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3011 // FIXME: any checks against duplicates for SKBlocks?
3014 prio = pr->priority;
3015 prq->priority += pr->remaining_priority;
3016 pr->remaining_priority = 0;
3017 if (pr->client != NULL)
3019 if (pr->replies_seen_size == pr->replies_seen_off)
3020 GNUNET_array_grow (pr->replies_seen,
3021 pr->replies_seen_size,
3022 pr->replies_seen_size * 2 + 4);
3023 pr->replies_seen[pr->replies_seen_off++] = chash;
3024 // FIXME: possibly recalculate BF!
3026 if (pr->client == NULL)
3028 msize = sizeof (struct ContentMessage) + prq->size;
3029 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3030 reply->msize = msize;
3031 cm = (struct ContentMessage*) &reply[1];
3032 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3033 cm->header.size = htons (msize);
3034 cm->type = htonl (prq->type);
3035 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3036 reply->next = pr->replies_pending;
3037 pr->replies_pending = reply;
3038 memcpy (&reply[1], prq->data, prq->size);
3039 if (pr->cth != NULL)
3041 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3042 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3044 /* estimate expiration time from time difference between
3045 first request that will be discarded and this request */
3046 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3047 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3050 GNUNET_PEER_resolve (pr->source_pid,
3052 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3059 if (NULL == pr->cth)
3061 // FIXME: now what? discard?
3066 msize = sizeof (struct PutMessage) + prq->size;
3067 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3068 reply->msize = msize;
3069 reply->next = pr->replies_pending;
3070 pm = (struct PutMessage*) &reply[1];
3071 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3072 pm->header.size = htons (msize);
3073 pm->type = htonl (prq->type);
3074 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3075 pr->replies_pending = reply;
3076 memcpy (&reply[1], prq->data, prq->size);
3079 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3081 GNUNET_TIME_UNIT_FOREVER_REL,
3086 // FIXME: need to try again later (not much
3087 // to do here specifically, but we need to
3088 // check somewhere else to handle this case!)
3091 // FIXME: implement hot-path routing statistics keeping!
3097 * Check if the given KBlock is well-formed.
3099 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3100 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3101 * @param query where to store the query that this block answers
3102 * @return GNUNET_OK if this is actually a well-formed KBlock
3105 check_kblock (const struct KBlock *kb,
3107 GNUNET_HashCode *query)
3109 if (dsize < sizeof (struct KBlock))
3111 GNUNET_break_op (0);
3112 return GNUNET_SYSERR;
3114 if (dsize - sizeof (struct KBlock) !=
3115 ntohs (kb->purpose.size)
3116 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3117 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3119 GNUNET_break_op (0);
3120 return GNUNET_SYSERR;
3123 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3128 GNUNET_break_op (0);
3129 return GNUNET_SYSERR;
3132 GNUNET_CRYPTO_hash (&kb->keyspace,
3133 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3140 * Check if the given SBlock is well-formed.
3142 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3143 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3144 * @param query where to store the query that this block answers
3145 * @param namespace where to store the namespace that this block belongs to
3146 * @return GNUNET_OK if this is actually a well-formed SBlock
3149 check_sblock (const struct SBlock *sb,
3151 GNUNET_HashCode *query,
3152 GNUNET_HashCode *namespace)
3154 if (dsize < sizeof (struct SBlock))
3156 GNUNET_break_op (0);
3157 return GNUNET_SYSERR;
3160 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3162 GNUNET_break_op (0);
3163 return GNUNET_SYSERR;
3166 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3171 GNUNET_break_op (0);
3172 return GNUNET_SYSERR;
3175 *query = sb->identifier;
3176 if (namespace != NULL)
3177 GNUNET_CRYPTO_hash (&sb->subspace,
3178 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3185 * Handle P2P "PUT" request.
3187 * @param cls closure, always NULL
3188 * @param other the other peer involved (sender or receiver, NULL
3189 * for loopback messages where we are both sender and receiver)
3190 * @param message the actual message
3191 * @return GNUNET_OK to keep the connection open,
3192 * GNUNET_SYSERR to close it (signal serious error)
3195 handle_p2p_put (void *cls,
3196 const struct GNUNET_PeerIdentity *other,
3197 const struct GNUNET_MessageHeader *message)
3199 const struct PutMessage *put;
3203 struct GNUNET_TIME_Absolute expiration;
3204 GNUNET_HashCode query;
3205 struct ProcessReplyClosure prq;
3207 msize = ntohs (message->size);
3208 if (msize < sizeof (struct PutMessage))
3211 return GNUNET_SYSERR;
3213 put = (const struct PutMessage*) message;
3214 dsize = msize - sizeof (struct PutMessage);
3215 type = ntohl (put->type);
3216 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3218 /* first, validate! */
3221 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3222 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3223 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3225 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3227 check_kblock ((const struct KBlock*) &put[1],
3230 return GNUNET_SYSERR;
3232 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3234 check_sblock ((const struct SBlock*) &put[1],
3238 return GNUNET_SYSERR;
3240 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3241 // FIXME -- validate SKBLOCK!
3245 /* unknown block type */
3246 GNUNET_break_op (0);
3247 return GNUNET_SYSERR;
3250 /* now, lookup 'query' */
3251 prq.data = (const void*) &put[1];
3254 prq.expiration = expiration;
3256 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3260 // FIXME: if migration is on and load is low,
3261 // queue to store data in datastore;
3262 // use "prq.priority" for that!
3268 * List of handlers for P2P messages
3269 * that we care about.
3271 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3274 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3276 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3282 * Task that will try to initiate a connection with the
3289 core_connect_task (void *cls,
3290 const struct GNUNET_SCHEDULER_TaskContext *tc);
3294 * Function called by the core after we've
3297 * @param cls closure, unused
3298 * @param server handle to the core service
3299 * @param my_identity our peer identity (unused)
3300 * @param publicKey our public key (unused)
3303 core_start_cb (void *cls,
3304 struct GNUNET_CORE_Handle * server,
3305 const struct GNUNET_PeerIdentity *
3308 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
3313 GNUNET_SCHEDULER_add_delayed (sched,
3315 GNUNET_SCHEDULER_PRIORITY_HIGH,
3316 GNUNET_SCHEDULER_NO_TASK,
3317 GNUNET_TIME_UNIT_SECONDS,
3327 * Task that will try to initiate a connection with the
3334 core_connect_task (void *cls,
3335 const struct GNUNET_SCHEDULER_TaskContext *tc)
3337 GNUNET_CORE_connect (sched,
3339 GNUNET_TIME_UNIT_FOREVER_REL,
3342 &peer_connect_handler,
3343 &peer_disconnect_handler,
3352 * Process fs requests.
3354 * @param cls closure
3355 * @param s scheduler to use
3356 * @param server the initialized server
3357 * @param c configuration to use
3361 struct GNUNET_SCHEDULER_Handle *s,
3362 struct GNUNET_SERVER_Handle *server,
3363 const struct GNUNET_CONFIGURATION_Handle *c)
3368 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3369 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3370 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3371 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3372 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3374 dsh = GNUNET_DATASTORE_connect (cfg,
3378 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3379 _("Failed to connect to datastore service.\n"));
3382 GNUNET_SERVER_disconnect_notify (server,
3383 &handle_client_disconnect,
3385 GNUNET_SERVER_add_handlers (server, handlers);
3386 core_connect_task (NULL, NULL);
3387 GNUNET_SCHEDULER_add_delayed (sched,
3389 GNUNET_SCHEDULER_PRIORITY_IDLE,
3390 GNUNET_SCHEDULER_NO_TASK,
3391 GNUNET_TIME_UNIT_FOREVER_REL,
3398 * The main function for the fs service.
3400 * @param argc number of arguments from the command line
3401 * @param argv command line arguments
3402 * @return 0 ok, 1 on error
3405 main (int argc, char *const *argv)
3407 return (GNUNET_OK ==
3408 GNUNET_SERVICE_run (argc,
3410 "fs", &run, NULL, NULL, NULL)) ? 0 : 1;
3413 /* end of gnunet-service-fs.c */