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_free (lgc->result);
1318 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1321 msize = ntohs (lgc->result->header.size);
1322 GNUNET_assert (max >= msize);
1323 memcpy (buf, lgc->result, msize);
1324 GNUNET_free (lgc->result);
1326 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1332 * Continuation called from datastore's remove
1336 * @param success did the deletion work?
1337 * @param msg error message
1340 remove_cont (void *cls,
1344 if (GNUNET_OK != success)
1345 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1346 _("Failed to delete bogus block: %s\n"),
1348 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1353 * Mingle hash with the mingle_number to
1354 * produce different bits.
1357 mingle_hash (const GNUNET_HashCode * in,
1358 int32_t mingle_number,
1359 GNUNET_HashCode * hc)
1363 GNUNET_CRYPTO_hash (&mingle_number,
1366 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1371 * We've received an on-demand encoded block
1372 * from the datastore. Attempt to do on-demand
1373 * encoding and (if successful), call the
1374 * continuation with the resulting block. On
1375 * error, clean up and ask the datastore for
1378 * @param key key for the content
1379 * @param size number of bytes in data
1380 * @param data content stored
1381 * @param type type of the content
1382 * @param priority priority of the content
1383 * @param anonymity anonymity-level for the content
1384 * @param expiration expiration time for the content
1385 * @param uid unique identifier for the datum;
1386 * maybe 0 if no unique identifier is available
1387 * @param cont function to call with the actual block
1388 * @param cont_cls closure for cont
1391 handle_on_demand_block (const GNUNET_HashCode * key,
1397 struct GNUNET_TIME_Absolute
1398 expiration, uint64_t uid,
1399 GNUNET_DATASTORE_Iterator cont,
1402 const struct OnDemandBlock *odb;
1403 GNUNET_HashCode nkey;
1404 struct GNUNET_CRYPTO_AesSessionKey skey;
1405 struct GNUNET_CRYPTO_AesInitializationVector iv;
1406 GNUNET_HashCode query;
1408 char ndata[DBLOCK_SIZE];
1409 char edata[DBLOCK_SIZE];
1411 struct GNUNET_DISK_FileHandle *fh;
1414 if (size != sizeof (struct OnDemandBlock))
1417 GNUNET_DATASTORE_remove (dsh,
1423 GNUNET_TIME_UNIT_FOREVER_REL);
1426 odb = (const struct OnDemandBlock*) data;
1427 off = GNUNET_ntohll (odb->offset);
1428 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1431 if ( (NULL == fn) ||
1432 (NULL == (fh = GNUNET_DISK_file_open (fn,
1433 GNUNET_DISK_OPEN_READ))) ||
1435 GNUNET_DISK_file_seek (fh,
1437 GNUNET_DISK_SEEK_SET)) ||
1439 (nsize = GNUNET_DISK_file_read (fh,
1443 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1444 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1445 GNUNET_h2s (&odb->file_id),
1446 (unsigned long long) off,
1449 GNUNET_DISK_file_close (fh);
1450 /* FIXME: if this happens often, we need
1451 to remove the OnDemand block from the DS! */
1452 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1455 GNUNET_DISK_file_close (fh);
1456 GNUNET_CRYPTO_hash (ndata,
1459 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1460 GNUNET_CRYPTO_aes_encrypt (ndata,
1465 GNUNET_CRYPTO_hash (edata,
1468 if (0 != memcmp (&query,
1470 sizeof (GNUNET_HashCode)))
1472 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1473 _("Indexed file `%s' changed at offset %llu\n"),
1475 (unsigned long long) off);
1476 /* FIXME: if this happens often, we need
1477 to remove the OnDemand block from the DS! */
1478 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1485 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1494 * How many bytes should a bloomfilter be if we have already seen
1495 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1496 * of bits set per entry. Furthermore, we should not re-size the
1497 * filter too often (to keep it cheap).
1499 * Since other peers will also add entries but not resize the filter,
1500 * we should generally pick a slightly larger size than what the
1501 * strict math would suggest.
1503 * @return must be a power of two and smaller or equal to 2^15.
1506 compute_bloomfilter_size (unsigned int entry_count)
1509 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1510 uint16_t max = 1 << 15;
1512 if (entry_count > max)
1515 while ((size < max) && (size < ideal))
1524 * Recalculate our bloom filter for filtering replies.
1526 * @param count number of entries we are filtering right now
1527 * @param mingle set to our new mingling value
1528 * @param bf_size set to the size of the bloomfilter
1529 * @param entries the entries to filter
1530 * @return updated bloomfilter, NULL for none
1532 static struct GNUNET_CONTAINER_BloomFilter *
1533 refresh_bloomfilter (unsigned int count,
1536 const GNUNET_HashCode *entries)
1538 struct GNUNET_CONTAINER_BloomFilter *bf;
1541 GNUNET_HashCode mhash;
1545 nsize = compute_bloomfilter_size (count);
1546 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1548 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1551 for (i=0;i<count;i++)
1553 mingle_hash (&entries[i], *mingle, &mhash);
1554 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1561 * Closure used for "target_peer_select_cb".
1563 struct PeerSelectionContext
1566 * The request for which we are selecting
1569 struct PendingRequest *pr;
1572 * Current "prime" target.
1574 struct GNUNET_PeerIdentity target;
1577 * How much do we like this target?
1579 double target_score;
1585 * Function called for each connected peer to determine
1586 * which one(s) would make good targets for forwarding.
1588 * @param cls closure (struct PeerSelectionContext)
1589 * @param key current key code (peer identity)
1590 * @param value value in the hash map (struct ConnectedPeer)
1591 * @return GNUNET_YES if we should continue to
1596 target_peer_select_cb (void *cls,
1597 const GNUNET_HashCode * key,
1600 struct PeerSelectionContext *psc = cls;
1601 struct ConnectedPeer *cp = value;
1602 struct PendingRequest *pr = psc->pr;
1606 /* 1) check if we have already (recently) forwarded to this peer */
1607 for (i=0;i<pr->used_pids_off;i++)
1608 if (pr->used_pids[i] == cp->pid)
1609 return GNUNET_YES; /* skip */
1610 // 2) calculate how much we'd like to forward to this peer
1611 score = 0; // FIXME!
1613 /* store best-fit in closure */
1614 if (score > psc->target_score)
1616 psc->target_score = score;
1617 psc->target.hashPubKey = *key;
1624 * We use a random delay to make the timing of requests
1625 * less predictable. This function returns such a random
1628 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1630 static struct GNUNET_TIME_Relative
1631 get_processing_delay ()
1633 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1634 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1640 * Task that is run for each request with the
1641 * goal of forwarding the associated query to
1642 * other peers. The task should re-schedule
1643 * itself to be re-run once the TTL has expired.
1644 * (or at a later time if more peers should
1645 * be queried earlier).
1647 * @param cls the requests "struct PendingRequest*"
1648 * @param tc task context (unused)
1651 forward_request_task (void *cls,
1652 const struct GNUNET_SCHEDULER_TaskContext *tc);
1656 * We've selected a peer for forwarding of a query.
1657 * Construct the message and then re-schedule the
1658 * task to forward again to (other) peers.
1660 * @param cls closure
1661 * @param size number of bytes available in buf
1662 * @param buf where the callee should write the message
1663 * @return number of bytes written to buf
1666 transmit_request_cb (void *cls,
1670 struct PendingRequest *pr = cls;
1671 struct GetMessage *gm;
1672 GNUNET_HashCode *ext;
1678 /* (1) check for timeout */
1681 /* timeout, try another peer immediately again */
1682 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1684 GNUNET_SCHEDULER_PRIORITY_IDLE,
1685 GNUNET_SCHEDULER_NO_TASK,
1686 GNUNET_TIME_UNIT_ZERO,
1687 &forward_request_task,
1691 /* (2) build query message */
1692 k = 0; // FIXME: count hash codes!
1693 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1694 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1695 gm = (struct GetMessage*) buf;
1696 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1697 gm->header.size = htons (msize);
1698 gm->type = htonl (pr->type);
1699 pr->remaining_priority /= 2;
1700 gm->priority = htonl (pr->remaining_priority);
1701 gm->ttl = htonl (pr->ttl);
1702 gm->filter_mutator = htonl(pr->mingle);
1703 gm->hash_bitmap = htonl (42);
1704 gm->query = pr->query;
1705 ext = (GNUNET_HashCode*) &gm[1];
1706 // FIXME: setup "ext[0]..[k-1]"
1707 bfdata = (char *) &ext[k];
1709 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1713 /* (3) schedule job to do it again (or another peer, etc.) */
1714 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1716 GNUNET_SCHEDULER_PRIORITY_IDLE,
1717 GNUNET_SCHEDULER_NO_TASK,
1718 get_processing_delay (), // FIXME!
1719 &forward_request_task,
1727 * Function called after we've tried to reserve
1728 * a certain amount of bandwidth for a reply.
1729 * Check if we succeeded and if so send our query.
1731 * @param cls the requests "struct PendingRequest*"
1732 * @param peer identifies the peer
1733 * @param latency current latency estimate, "FOREVER" if we have been
1735 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1736 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1737 * @param amount set to the amount that was actually reserved or unreserved
1738 * @param preference current traffic preference for the given peer
1741 target_reservation_cb (void *cls,
1743 GNUNET_PeerIdentity * peer,
1744 unsigned int bpm_in,
1745 unsigned int bpm_out,
1746 struct GNUNET_TIME_Relative
1747 latency, int amount,
1748 unsigned long long preference)
1750 struct PendingRequest *pr = cls;
1753 struct GNUNET_TIME_Relative maxdelay;
1755 GNUNET_assert (peer != NULL);
1756 if ( (amount != DBLOCK_SIZE) ||
1759 /* try again later; FIXME: we may need to un-reserve "amount"? */
1760 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1762 GNUNET_SCHEDULER_PRIORITY_IDLE,
1763 GNUNET_SCHEDULER_NO_TASK,
1764 get_processing_delay (), // FIXME: longer?
1765 &forward_request_task,
1769 // (2) transmit, update ttl/priority
1770 // FIXME: calculate priority, maxdelay, size properly!
1773 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1774 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1779 &transmit_request_cb,
1781 if (pr->cth == NULL)
1783 /* try again later */
1784 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1786 GNUNET_SCHEDULER_PRIORITY_IDLE,
1787 GNUNET_SCHEDULER_NO_TASK,
1788 get_processing_delay (), // FIXME: longer?
1789 &forward_request_task,
1796 * Task that is run for each request with the
1797 * goal of forwarding the associated query to
1798 * other peers. The task should re-schedule
1799 * itself to be re-run once the TTL has expired.
1800 * (or at a later time if more peers should
1801 * be queried earlier).
1803 * @param cls the requests "struct PendingRequest*"
1804 * @param tc task context (unused)
1807 forward_request_task (void *cls,
1808 const struct GNUNET_SCHEDULER_TaskContext *tc)
1810 struct PendingRequest *pr = cls;
1811 struct PeerSelectionContext psc;
1813 pr->task = GNUNET_SCHEDULER_NO_TASK;
1814 if (pr->cth != NULL)
1816 /* we're busy transmitting a result, wait a bit */
1817 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1819 GNUNET_SCHEDULER_PRIORITY_IDLE,
1820 GNUNET_SCHEDULER_NO_TASK,
1821 get_processing_delay (),
1822 &forward_request_task,
1826 /* (1) select target */
1828 psc.target_score = DBL_MIN;
1829 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1830 &target_peer_select_cb,
1832 if (psc.target_score == DBL_MIN)
1834 /* no possible target found, wait some time */
1835 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1837 GNUNET_SCHEDULER_PRIORITY_IDLE,
1838 GNUNET_SCHEDULER_NO_TASK,
1839 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1840 &forward_request_task,
1844 /* (2) reserve reply bandwidth */
1845 // FIXME: need a way to cancel; this
1846 // async operation is problematic (segv-problematic)
1847 // if "pr" is destroyed while it happens!
1848 GNUNET_CORE_peer_configure (core,
1850 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1852 DBLOCK_SIZE, // FIXME: make dependent on type?
1854 &target_reservation_cb,
1860 * We're processing (local) results for a search request
1861 * from a (local) client. Pass applicable results to the
1862 * client and if we are done either clean up (operation
1863 * complete) or switch to P2P search (more results possible).
1865 * @param cls our closure (struct LocalGetContext)
1866 * @param key key for the content
1867 * @param size number of bytes in data
1868 * @param data content stored
1869 * @param type type of the content
1870 * @param priority priority of the content
1871 * @param anonymity anonymity-level for the content
1872 * @param expiration expiration time for the content
1873 * @param uid unique identifier for the datum;
1874 * maybe 0 if no unique identifier is available
1877 process_local_get_result (void *cls,
1878 const GNUNET_HashCode * key,
1884 struct GNUNET_TIME_Absolute
1888 struct LocalGetContext *lgc = cls;
1889 struct PendingRequest *pr;
1890 struct ClientRequestList *crl;
1891 struct ClientList *cl;
1897 /* no further results from datastore; continue
1898 processing further requests from the client and
1899 allow the next task to use the datastore; also,
1900 switch to P2P requests or clean up our state. */
1902 GNUNET_SERVER_receive_done (lgc->client,
1904 if ( (lgc->results_used == 0) ||
1905 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1906 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1907 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1910 while ( (NULL != cl) &&
1911 (cl->client != lgc->client) )
1915 cl = GNUNET_malloc (sizeof (struct ClientList));
1916 cl->client = lgc->client;
1920 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1922 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1923 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1924 pr->client = lgc->client;
1925 GNUNET_SERVER_client_keep (pr->client);
1926 pr->crl_entry = crl;
1928 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1930 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1931 *pr->namespace = lgc->namespace;
1933 pr->replies_seen = lgc->results;
1934 lgc->results = NULL;
1935 pr->start_time = GNUNET_TIME_absolute_get ();
1936 pr->query = lgc->query;
1937 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1938 pr->replies_seen_off = lgc->results_used;
1939 pr->replies_seen_size = lgc->results_size;
1940 lgc->results_size = 0;
1941 pr->type = lgc->type;
1942 pr->anonymity_level = lgc->anonymity_level;
1943 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1947 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1950 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1951 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1953 GNUNET_SCHEDULER_PRIORITY_IDLE,
1954 GNUNET_SCHEDULER_NO_TASK,
1955 get_processing_delay (),
1956 &forward_request_task,
1958 local_get_context_free (lgc);
1961 /* got all possible results, clean up! */
1962 local_get_context_free (lgc);
1965 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
1967 handle_on_demand_block (key, size, data, type, priority,
1968 anonymity, expiration, uid,
1969 &process_local_get_result,
1973 if (type != lgc->type)
1975 /* this should be virtually impossible to reach (DBLOCK
1976 query hash being identical to KBLOCK/SBLOCK query hash);
1977 nevertheless, if it happens, the correct thing is to
1978 simply skip the result. */
1979 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1982 /* check if this is a result we've alredy
1984 for (i=0;i<lgc->results_used;i++)
1985 if (0 == memcmp (key,
1987 sizeof (GNUNET_HashCode)))
1989 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1992 if (lgc->results_used == lgc->results_size)
1993 GNUNET_array_grow (lgc->results,
1995 lgc->results_size * 2 + 2);
1996 GNUNET_CRYPTO_hash (data,
1998 &lgc->results[lgc->results_used++]);
1999 msize = size + sizeof (struct ContentMessage);
2000 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2001 lgc->result = GNUNET_malloc (msize);
2002 lgc->result->header.size = htons (msize);
2003 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2004 lgc->result->type = htonl (type);
2005 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2006 memcpy (&lgc->result[1],
2009 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2011 GNUNET_TIME_UNIT_FOREVER_REL,
2012 &transmit_local_result,
2018 * We're processing a search request from a local
2019 * client. Now it is our turn to query the datastore.
2021 * @param cls our closure (struct LocalGetContext)
2025 transmit_local_get (void *cls,
2026 const struct GNUNET_SCHEDULER_TaskContext *tc)
2028 struct LocalGetContext *lgc = cls;
2032 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2033 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2034 GNUNET_DATASTORE_get (dsh,
2037 &process_local_get_result,
2039 GNUNET_TIME_UNIT_FOREVER_REL);
2044 * We're processing a search request from a local
2045 * client. Now it is our turn to query the datastore.
2047 * @param cls our closure (struct LocalGetContext)
2048 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2051 transmit_local_get_ready (void *cls,
2054 struct LocalGetContext *lgc = cls;
2056 GNUNET_assert (GNUNET_OK == ok);
2057 GNUNET_SCHEDULER_add_continuation (sched,
2059 &transmit_local_get,
2061 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2066 * Handle START_SEARCH-message (search request from client).
2068 * @param cls closure
2069 * @param client identification of the client
2070 * @param message the actual message
2073 handle_start_search (void *cls,
2074 struct GNUNET_SERVER_Client *client,
2075 const struct GNUNET_MessageHeader *message)
2077 const struct SearchMessage *sm;
2078 struct LocalGetContext *lgc;
2082 msize = ntohs (message->size);
2083 if ( (msize < sizeof (struct SearchMessage)) ||
2084 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2087 GNUNET_SERVER_receive_done (client,
2091 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2092 sm = (const struct SearchMessage*) message;
2093 GNUNET_SERVER_client_keep (client);
2094 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2097 lgc->results_used = sc;
2098 GNUNET_array_grow (lgc->results,
2101 memcpy (lgc->results,
2103 sc * sizeof (GNUNET_HashCode));
2105 lgc->client = client;
2106 lgc->type = ntohl (sm->type);
2107 lgc->anonymity_level = ntohl (sm->anonymity_level);
2110 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2111 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2112 lgc->target.hashPubKey = sm->target;
2114 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2115 lgc->namespace = sm->target;
2120 lgc->query = sm->query;
2121 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2122 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2123 &transmit_local_get_ready,
2129 * List of handlers for the messages understood by this
2132 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2133 {&handle_index_start, NULL,
2134 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2135 {&handle_index_list_get, NULL,
2136 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2137 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2138 sizeof (struct UnindexMessage) },
2139 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2146 * Clean up the memory used by the PendingRequest structure (except
2147 * for the client or peer list that the request may be part of).
2149 * @param pr request to clean up
2152 destroy_pending_request (struct PendingRequest *pr)
2154 struct PendingReply *reply;
2155 struct ClientList *cl;
2157 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2160 // FIXME: not sure how this can work (efficiently)
2161 // also, what does the return value mean?
2162 if (pr->client == NULL)
2164 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2169 cl = pr->crl_entry->cl;
2170 GNUNET_CONTAINER_DLL_remove (cl->head,
2174 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2175 GNUNET_SCHEDULER_cancel (sched, pr->task);
2176 if (NULL != pr->cth)
2177 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2179 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2181 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2182 while (NULL != (reply = pr->replies_pending))
2184 pr->replies_pending = reply->next;
2185 GNUNET_free (reply);
2187 GNUNET_PEER_change_rc (pr->source_pid, -1);
2188 GNUNET_PEER_change_rc (pr->target_pid, -1);
2189 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2190 GNUNET_free_non_null (pr->used_pids);
2191 GNUNET_free_non_null (pr->replies_seen);
2192 GNUNET_free_non_null (pr->namespace);
2198 * A client disconnected. Remove all of its pending queries.
2200 * @param cls closure, NULL
2201 * @param client identification of the client
2204 handle_client_disconnect (void *cls,
2205 struct GNUNET_SERVER_Client
2208 struct LocalGetContext *lgc;
2209 struct ClientList *cpos;
2210 struct ClientList *cprev;
2211 struct ClientRequestList *rl;
2214 while ( (NULL != lgc) &&
2215 (lgc->client != client) )
2218 local_get_context_free (lgc);
2221 while ( (NULL != cpos) &&
2222 (clients->client != client) )
2230 clients = cpos->next;
2232 cprev->next = cpos->next;
2233 while (NULL != (rl = cpos->head))
2235 cpos->head = rl->next;
2236 destroy_pending_request (rl->req);
2245 * Iterator over entries in the "requests_by_query" map
2246 * that frees all the entries.
2248 * @param cls closure, NULL
2249 * @param key current key code (the query, unused)
2250 * @param value value in the hash map, of type "struct PendingRequest*"
2251 * @return GNUNET_YES (we should continue to iterate)
2254 destroy_pending_request_cb (void *cls,
2255 const GNUNET_HashCode * key,
2258 struct PendingRequest *pr = value;
2260 destroy_pending_request (pr);
2266 * Task run during shutdown.
2272 shutdown_task (void *cls,
2273 const struct GNUNET_SCHEDULER_TaskContext *tc)
2275 struct IndexInfo *pos;
2278 GNUNET_CORE_disconnect (core);
2279 GNUNET_DATASTORE_disconnect (dsh,
2282 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2283 &destroy_pending_request_cb,
2285 while (clients != NULL)
2286 handle_client_disconnect (NULL,
2288 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2289 requests_by_query = NULL;
2290 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2291 requests_by_peer = NULL;
2292 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2293 requests_by_expiration = NULL;
2294 // FIXME: iterate over entries and free individually?
2295 // (or do we get disconnect notifications?)
2296 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2297 connected_peers = NULL;
2298 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2300 while (NULL != (pos = indexed_files))
2302 indexed_files = pos->next;
2309 * Free (each) request made by the peer.
2311 * @param cls closure, points to peer that the request belongs to
2312 * @param key current key code
2313 * @param value value in the hash map
2314 * @return GNUNET_YES (we should continue to iterate)
2317 destroy_request (void *cls,
2318 const GNUNET_HashCode * key,
2321 const struct GNUNET_PeerIdentity * peer = cls;
2322 struct PendingRequest *pr = value;
2324 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2327 destroy_pending_request (pr);
2334 * Method called whenever a given peer connects.
2336 * @param cls closure, not used
2337 * @param peer peer identity this notification is about
2340 peer_connect_handler (void *cls,
2342 GNUNET_PeerIdentity * peer)
2344 struct ConnectedPeer *cp;
2346 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2347 cp->pid = GNUNET_PEER_intern (peer);
2348 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2351 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2356 * Method called whenever a peer disconnects.
2358 * @param cls closure, not used
2359 * @param peer peer identity this notification is about
2362 peer_disconnect_handler (void *cls,
2364 GNUNET_PeerIdentity * peer)
2366 struct ConnectedPeer *cp;
2368 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2370 GNUNET_PEER_change_rc (cp->pid, -1);
2371 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2373 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2381 * We're processing a GET request from
2382 * another peer and have decided to forward
2383 * it to other peers.
2385 * @param cls our "struct ProcessGetContext *"
2389 forward_get_request (void *cls,
2390 const struct GNUNET_SCHEDULER_TaskContext *tc)
2392 struct ProcessGetContext *pgc = cls;
2393 struct PendingRequest *pr;
2394 struct PendingRequest *eer;
2395 struct GNUNET_PeerIdentity target;
2397 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2398 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2400 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2401 *pr->namespace = pgc->namespace;
2404 pr->bf_size = pgc->bf_size;
2406 pr->start_time = pgc->start_time;
2407 pr->query = pgc->query;
2408 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2409 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2410 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2411 pr->anonymity_level = 1; /* default */
2412 pr->priority = pgc->priority;
2413 pr->remaining_priority = pr->priority;
2414 pr->mingle = pgc->mingle;
2416 pr->type = pgc->type;
2417 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2420 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2421 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2422 &pgc->reply_to.hashPubKey,
2424 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2425 GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2427 pr->start_time.value + pr->ttl);
2428 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2430 /* expire oldest request! */
2431 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2432 GNUNET_PEER_resolve (eer->source_pid,
2434 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2437 destroy_pending_request (eer);
2439 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2441 GNUNET_SCHEDULER_PRIORITY_IDLE,
2442 GNUNET_SCHEDULER_NO_TASK,
2443 get_processing_delay (),
2444 &forward_request_task,
2449 * Transmit the given message by copying it to
2450 * the target buffer "buf". "buf" will be
2451 * NULL and "size" zero if the socket was closed for
2452 * writing in the meantime. In that case, only
2456 * @param cls closure, pointer to the message
2457 * @param size number of bytes available in buf
2458 * @param buf where the callee should write the message
2459 * @return number of bytes written to buf
2462 transmit_message (void *cls,
2463 size_t size, void *buf)
2465 struct GNUNET_MessageHeader *msg = cls;
2471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472 "Dropping reply, core too busy.\n");
2477 msize = ntohs (msg->size);
2478 GNUNET_assert (size >= msize);
2479 memcpy (buf, msg, msize);
2486 * Test if the load on this peer is too high
2487 * to even consider processing the query at
2490 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2493 test_load_too_high ()
2495 return GNUNET_NO; // FIXME
2500 * We're processing (local) results for a search request
2501 * from another peer. Pass applicable results to the
2502 * peer and if we are done either clean up (operation
2503 * complete) or forward to other peers (more results possible).
2505 * @param cls our closure (struct LocalGetContext)
2506 * @param key key for the content
2507 * @param size number of bytes in data
2508 * @param data content stored
2509 * @param type type of the content
2510 * @param priority priority of the content
2511 * @param anonymity anonymity-level for the content
2512 * @param expiration expiration time for the content
2513 * @param uid unique identifier for the datum;
2514 * maybe 0 if no unique identifier is available
2517 process_p2p_get_result (void *cls,
2518 const GNUNET_HashCode * key,
2524 struct GNUNET_TIME_Absolute
2528 struct ProcessGetContext *pgc = cls;
2529 GNUNET_HashCode dhash;
2530 GNUNET_HashCode mhash;
2531 struct PutMessage *reply;
2535 /* no more results */
2536 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2537 ( (0 == pgc->results_found) ||
2538 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2539 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2540 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2542 GNUNET_SCHEDULER_add_continuation (sched,
2544 &forward_get_request,
2546 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2550 if (pgc->bf != NULL)
2551 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2557 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2559 handle_on_demand_block (key, size, data, type, priority,
2560 anonymity, expiration, uid,
2561 &process_p2p_get_result,
2565 /* check for duplicates */
2566 GNUNET_CRYPTO_hash (data, size, &dhash);
2567 mingle_hash (&dhash,
2570 if ( (pgc->bf != NULL) &&
2572 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2576 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2577 "Result from datastore filtered by bloomfilter.\n");
2579 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2582 pgc->results_found++;
2583 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2584 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2585 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2587 if (pgc->bf == NULL)
2590 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2594 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2598 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2599 reply->header.size = htons (sizeof (struct PutMessage) + size);
2600 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2601 reply->type = htonl (type);
2602 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2603 memcpy (&reply[1], data, size);
2604 GNUNET_CORE_notify_transmit_ready (core,
2606 ACCEPTABLE_REPLY_DELAY,
2608 sizeof (struct PutMessage) + size,
2611 if ( (GNUNET_YES == test_load_too_high()) ||
2612 (pgc->results_found > 5 + 2 * pgc->priority) )
2614 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2615 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2618 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2623 * We're processing a GET request from another peer. Give it to our
2626 * @param cls our "struct ProcessGetContext"
2627 * @param ok did we get a datastore slice or not?
2630 ds_get_request (void *cls,
2633 struct ProcessGetContext *pgc = cls;
2635 struct GNUNET_TIME_Relative timeout;
2637 if (GNUNET_OK != ok)
2639 /* no point in doing P2P stuff if we can't even do local */
2644 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2645 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2646 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2647 (pgc->priority + 1));
2648 GNUNET_DATASTORE_get (dsh,
2651 &process_p2p_get_result,
2658 * The priority level imposes a bound on the maximum
2659 * value for the ttl that can be requested.
2661 * @param ttl_in requested ttl
2662 * @param prio given priority
2663 * @return ttl_in if ttl_in is below the limit,
2664 * otherwise the ttl-limit for the given priority
2667 bound_ttl (int32_t ttl_in, uint32_t prio)
2669 unsigned long long allowed;
2673 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2674 if (ttl_in > allowed)
2676 if (allowed >= (1 << 30))
2685 * We've received a request with the specified
2686 * priority. Bound it according to how much
2687 * we trust the given peer.
2689 * @param prio_in requested priority
2690 * @param peer the peer making the request
2691 * @return effective priority
2694 bound_priority (uint32_t prio_in,
2695 const struct GNUNET_PeerIdentity *peer)
2702 * Handle P2P "GET" request.
2704 * @param cls closure, always NULL
2705 * @param other the other peer involved (sender or receiver, NULL
2706 * for loopback messages where we are both sender and receiver)
2707 * @param message the actual message
2708 * @return GNUNET_OK to keep the connection open,
2709 * GNUNET_SYSERR to close it (signal serious error)
2712 handle_p2p_get (void *cls,
2713 const struct GNUNET_PeerIdentity *other,
2714 const struct GNUNET_MessageHeader *message)
2717 const struct GetMessage *gm;
2719 const GNUNET_HashCode *opt;
2720 struct ProcessGetContext *pgc;
2723 uint32_t ttl_decrement;
2728 msize = ntohs(message->size);
2729 if (msize < sizeof (struct GetMessage))
2731 GNUNET_break_op (0);
2732 return GNUNET_SYSERR;
2734 gm = (const struct GetMessage*) message;
2735 bm = ntohl (gm->hash_bitmap);
2743 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2745 GNUNET_break_op (0);
2746 return GNUNET_SYSERR;
2748 opt = (const GNUNET_HashCode*) &gm[1];
2749 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2750 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2753 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2756 pgc->bf_size = bfsize;
2758 pgc->type = ntohl (gm->type);
2759 pgc->bm = ntohl (gm->hash_bitmap);
2760 pgc->mingle = gm->filter_mutator;
2762 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2763 pgc->reply_to.hashPubKey = opt[bits++];
2765 pgc->reply_to = *other;
2766 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2767 pgc->namespace = opt[bits++];
2768 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2770 GNUNET_break_op (0);
2772 return GNUNET_SYSERR;
2774 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2775 pgc->prime_target.hashPubKey = opt[bits++];
2776 /* note that we can really only check load here since otherwise
2777 peers could find out that we are overloaded by being disconnected
2778 after sending us a malformed query... */
2779 if (GNUNET_YES == test_load_too_high ())
2781 if (NULL != pgc->bf)
2782 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2786 "Dropping query from `%s', this peer is too busy.\n",
2787 GNUNET_h2s (other));
2791 net_load_up = 50; // FIXME
2792 net_load_down = 50; // FIXME
2793 pgc->policy = ROUTING_POLICY_NONE;
2794 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2795 (net_load_down < IDLE_LOAD_THRESHOLD) )
2797 pgc->policy |= ROUTING_POLICY_ALL;
2798 pgc->priority = 0; /* no charge */
2802 pgc->priority = bound_priority (ntohl (gm->priority), other);
2804 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2806 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2808 pgc->policy |= ROUTING_POLICY_ALL;
2812 // FIXME: is this sound?
2813 if (net_load_up < 90 + 10 * pgc->priority)
2814 pgc->policy |= ROUTING_POLICY_FORWARD;
2815 if (net_load_down < 90 + 10 * pgc->priority)
2816 pgc->policy |= ROUTING_POLICY_ANSWER;
2819 if (pgc->policy == ROUTING_POLICY_NONE)
2822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2823 "Dropping query from `%s', network saturated.\n",
2824 GNUNET_h2s (other));
2826 if (NULL != pgc->bf)
2827 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2829 return GNUNET_OK; /* drop */
2831 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2832 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2833 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2834 /* decrement ttl (always) */
2835 ttl_decrement = 2 * TTL_DECREMENT +
2836 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2838 if ( (pgc->ttl < 0) &&
2839 (pgc->ttl - ttl_decrement > 0) )
2842 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2843 "Dropping query from `%s' due to TTL underflow.\n",
2844 GNUNET_h2s (other));
2846 /* integer underflow => drop (should be very rare)! */
2847 if (NULL != pgc->bf)
2848 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2852 pgc->ttl -= ttl_decrement;
2853 pgc->start_time = GNUNET_TIME_absolute_get ();
2854 preference = (double) pgc->priority;
2855 if (preference < QUERY_BANDWIDTH_VALUE)
2856 preference = QUERY_BANDWIDTH_VALUE;
2857 // FIXME: also reserve bandwidth for reply?
2858 GNUNET_CORE_peer_configure (core,
2860 GNUNET_TIME_UNIT_FOREVER_REL,
2861 0, 0, preference, NULL, NULL);
2862 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2863 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2867 GNUNET_SCHEDULER_add_continuation (sched,
2869 &forward_get_request,
2871 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2877 * Function called to notify us that we can now transmit a reply to a
2878 * client or peer. "buf" will be NULL and "size" zero if the socket was
2879 * closed for writing in the meantime.
2881 * @param cls closure, points to a "struct PendingRequest*" with
2882 * one or more pending replies
2883 * @param size number of bytes available in buf
2884 * @param buf where the callee should write the message
2885 * @return number of bytes written to buf
2888 transmit_result (void *cls,
2892 struct PendingRequest *pr = cls;
2894 struct PendingReply *reply;
2898 while (NULL != (reply = pr->replies_pending))
2900 if ( (reply->msize + ret < ret) ||
2901 (reply->msize + ret > size) )
2903 pr->replies_pending = reply->next;
2904 memcpy (&cbuf[ret], &reply[1], reply->msize);
2905 ret += reply->msize;
2913 * Iterator over pending requests.
2915 * @param cls response (struct ProcessReplyClosure)
2916 * @param key our query
2917 * @param value value in the hash map (meta-info about the query)
2918 * @return GNUNET_YES (we should continue to iterate)
2921 process_reply (void *cls,
2922 const GNUNET_HashCode * key,
2925 struct ProcessReplyClosure *prq = cls;
2926 struct PendingRequest *pr = value;
2927 struct PendingRequest *eer;
2928 struct PendingReply *reply;
2929 struct PutMessage *pm;
2930 struct ContentMessage *cm;
2931 GNUNET_HashCode chash;
2932 GNUNET_HashCode mhash;
2933 struct GNUNET_PeerIdentity target;
2936 struct GNUNET_TIME_Relative max_delay;
2938 GNUNET_CRYPTO_hash (prq->data,
2943 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2944 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2946 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2947 /* FIXME: does prq->namespace match our expectations? */
2948 /* then: fall-through??? */
2949 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
2952 mingle_hash (&chash, pr->mingle, &mhash);
2953 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
2955 return GNUNET_YES; /* duplicate */
2956 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
2960 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
2961 // FIXME: any checks against duplicates for SKBlocks?
2964 prio = pr->priority;
2965 prq->priority += pr->remaining_priority;
2966 pr->remaining_priority = 0;
2967 if (pr->client != NULL)
2969 if (pr->replies_seen_size == pr->replies_seen_off)
2970 GNUNET_array_grow (pr->replies_seen,
2971 pr->replies_seen_size,
2972 pr->replies_seen_size * 2 + 4);
2973 pr->replies_seen[pr->replies_seen_off++] = chash;
2974 // FIXME: possibly recalculate BF!
2976 if (pr->client == NULL)
2978 msize = sizeof (struct ContentMessage) + prq->size;
2979 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
2980 reply->msize = msize;
2981 cm = (struct ContentMessage*) &reply[1];
2982 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2983 cm->header.size = htons (msize);
2984 cm->type = htonl (prq->type);
2985 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
2986 reply->next = pr->replies_pending;
2987 pr->replies_pending = reply;
2988 memcpy (&reply[1], prq->data, prq->size);
2989 if (pr->cth != NULL)
2991 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
2992 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
2994 /* estimate expiration time from time difference between
2995 first request that will be discarded and this request */
2996 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2997 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3000 GNUNET_PEER_resolve (pr->source_pid,
3002 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3009 if (NULL == pr->cth)
3011 // FIXME: now what? discard?
3016 msize = sizeof (struct PutMessage) + prq->size;
3017 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3018 reply->msize = msize;
3019 reply->next = pr->replies_pending;
3020 pm = (struct PutMessage*) &reply[1];
3021 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3022 pm->header.size = htons (msize);
3023 pm->type = htonl (prq->type);
3024 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3025 pr->replies_pending = reply;
3026 memcpy (&reply[1], prq->data, prq->size);
3029 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3031 GNUNET_TIME_UNIT_FOREVER_REL,
3036 // FIXME: need to try again later (not much
3037 // to do here specifically, but we need to
3038 // check somewhere else to handle this case!)
3041 // FIXME: implement hot-path routing statistics keeping!
3047 * Check if the given KBlock is well-formed.
3049 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3050 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3051 * @param query where to store the query that this block answers
3052 * @return GNUNET_OK if this is actually a well-formed KBlock
3055 check_kblock (const struct KBlock *kb,
3057 GNUNET_HashCode *query)
3059 if (dsize < sizeof (struct KBlock))
3061 GNUNET_break_op (0);
3062 return GNUNET_SYSERR;
3064 if (dsize - sizeof (struct KBlock) !=
3065 ntohs (kb->purpose.size)
3066 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3067 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3069 GNUNET_break_op (0);
3070 return GNUNET_SYSERR;
3073 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3078 GNUNET_break_op (0);
3079 return GNUNET_SYSERR;
3082 GNUNET_CRYPTO_hash (&kb->keyspace,
3083 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3090 * Check if the given SBlock is well-formed.
3092 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3093 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3094 * @param query where to store the query that this block answers
3095 * @param namespace where to store the namespace that this block belongs to
3096 * @return GNUNET_OK if this is actually a well-formed SBlock
3099 check_sblock (const struct SBlock *sb,
3101 GNUNET_HashCode *query,
3102 GNUNET_HashCode *namespace)
3104 if (dsize < sizeof (struct SBlock))
3106 GNUNET_break_op (0);
3107 return GNUNET_SYSERR;
3110 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3112 GNUNET_break_op (0);
3113 return GNUNET_SYSERR;
3116 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3121 GNUNET_break_op (0);
3122 return GNUNET_SYSERR;
3125 *query = sb->identifier;
3126 if (namespace != NULL)
3127 GNUNET_CRYPTO_hash (&sb->subspace,
3128 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3135 * Handle P2P "PUT" request.
3137 * @param cls closure, always NULL
3138 * @param other the other peer involved (sender or receiver, NULL
3139 * for loopback messages where we are both sender and receiver)
3140 * @param message the actual message
3141 * @return GNUNET_OK to keep the connection open,
3142 * GNUNET_SYSERR to close it (signal serious error)
3145 handle_p2p_put (void *cls,
3146 const struct GNUNET_PeerIdentity *other,
3147 const struct GNUNET_MessageHeader *message)
3149 const struct PutMessage *put;
3153 struct GNUNET_TIME_Absolute expiration;
3154 GNUNET_HashCode query;
3155 struct ProcessReplyClosure prq;
3157 msize = ntohs (message->size);
3158 if (msize < sizeof (struct PutMessage))
3161 return GNUNET_SYSERR;
3163 put = (const struct PutMessage*) message;
3164 dsize = msize - sizeof (struct PutMessage);
3165 type = ntohl (put->type);
3166 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3168 /* first, validate! */
3171 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3172 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3173 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3175 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3177 check_kblock ((const struct KBlock*) &put[1],
3180 return GNUNET_SYSERR;
3182 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3184 check_sblock ((const struct SBlock*) &put[1],
3188 return GNUNET_SYSERR;
3190 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3191 // FIXME -- validate SKBLOCK!
3195 /* unknown block type */
3196 GNUNET_break_op (0);
3197 return GNUNET_SYSERR;
3200 /* now, lookup 'query' */
3201 prq.data = (const void*) &put[1];
3204 prq.expiration = expiration;
3206 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3210 // FIXME: if migration is on and load is low,
3211 // queue to store data in datastore;
3212 // use "prq.priority" for that!
3218 * List of handlers for P2P messages
3219 * that we care about.
3221 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3224 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3226 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3232 * Task that will try to initiate a connection with the
3239 core_connect_task (void *cls,
3240 const struct GNUNET_SCHEDULER_TaskContext *tc);
3244 * Function called by the core after we've
3247 * @param cls closure, unused
3248 * @param server handle to the core service
3249 * @param my_identity our peer identity (unused)
3250 * @param publicKey our public key (unused)
3253 core_start_cb (void *cls,
3254 struct GNUNET_CORE_Handle * server,
3255 const struct GNUNET_PeerIdentity *
3258 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *
3263 GNUNET_SCHEDULER_add_delayed (sched,
3265 GNUNET_SCHEDULER_PRIORITY_HIGH,
3266 GNUNET_SCHEDULER_NO_TASK,
3267 GNUNET_TIME_UNIT_SECONDS,
3277 * Task that will try to initiate a connection with the
3284 core_connect_task (void *cls,
3285 const struct GNUNET_SCHEDULER_TaskContext *tc)
3287 GNUNET_CORE_connect (sched,
3289 GNUNET_TIME_UNIT_FOREVER_REL,
3292 &peer_connect_handler,
3293 &peer_disconnect_handler,
3302 * Process fs requests.
3304 * @param cls closure
3305 * @param s scheduler to use
3306 * @param server the initialized server
3307 * @param c configuration to use
3311 struct GNUNET_SCHEDULER_Handle *s,
3312 struct GNUNET_SERVER_Handle *server,
3313 const struct GNUNET_CONFIGURATION_Handle *c)
3318 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3319 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3320 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3321 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3322 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3324 dsh = GNUNET_DATASTORE_connect (cfg,
3328 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3329 _("Failed to connect to datastore service.\n"));
3332 GNUNET_SERVER_disconnect_notify (server,
3333 &handle_client_disconnect,
3335 GNUNET_SERVER_add_handlers (server, handlers);
3336 core_connect_task (NULL, NULL);
3337 GNUNET_SCHEDULER_add_delayed (sched,
3339 GNUNET_SCHEDULER_PRIORITY_IDLE,
3340 GNUNET_SCHEDULER_NO_TASK,
3341 GNUNET_TIME_UNIT_FOREVER_REL,
3348 * The main function for the fs service.
3350 * @param argc number of arguments from the command line
3351 * @param argv command line arguments
3352 * @return 0 ok, 1 on error
3355 main (int argc, char *const *argv)
3357 return (GNUNET_OK ==
3358 GNUNET_SERVICE_run (argc,
3360 "fs", &run, NULL, NULL, NULL)) ? 0 : 1;
3363 /* end of gnunet-service-fs.c */