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_NO
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 * Node in the heap representing this entry.
451 struct GNUNET_CONTAINER_HeapNode *hnode;
454 * When did we first see this request (form this peer), or, if our
455 * client is initiating, when did we last initiate a search?
457 struct GNUNET_TIME_Absolute start_time;
460 * The query that this request is for.
462 GNUNET_HashCode query;
465 * The task responsible for transmitting queries
468 GNUNET_SCHEDULER_TaskIdentifier task;
471 * (Interned) Peer identifier (only valid if "client" is NULL)
472 * that identifies a peer that gave us this request.
474 GNUNET_PEER_Id source_pid;
477 * (Interned) Peer identifier that identifies a preferred target
480 GNUNET_PEER_Id target_pid;
483 * (Interned) Peer identifiers of peers that have already
484 * received our query for this content.
486 GNUNET_PEER_Id *used_pids;
489 * Size of the 'bf' (in bytes).
494 * Desired anonymity level; only valid for requests from a local client.
496 uint32_t anonymity_level;
499 * How many entries in "used_pids" are actually valid?
501 unsigned int used_pids_off;
504 * How long is the "used_pids" array?
506 unsigned int used_pids_size;
509 * How many entries in "replies_seen" are actually valid?
511 unsigned int replies_seen_off;
514 * How long is the "replies_seen" array?
516 unsigned int replies_seen_size;
519 * Priority with which this request was made. If one of our clients
520 * made the request, then this is the current priority that we are
521 * using when initiating the request. This value is used when
522 * we decide to reward other peers with trust for providing a reply.
527 * Priority points left for us to spend when forwarding this request
530 uint32_t remaining_priority;
533 * Number to mingle hashes for bloom-filter
539 * TTL with which we saw this request (or, if we initiated, TTL that
540 * we used for the request).
545 * Type of the content that this request is for.
553 * All requests from a client are kept in a doubly-linked list.
555 struct ClientRequestList
558 * This is a doubly-linked list.
560 struct ClientRequestList *next;
563 * This is a doubly-linked list.
565 struct ClientRequestList *prev;
568 * A request from this client.
570 struct PendingRequest *req;
573 * Client list with the head and tail of this DLL.
575 struct ClientList *cl;
580 * Linked list of all clients that we are
581 * currently processing requests for.
587 * This is a linked list.
589 struct ClientList *next;
592 * What client is this entry for?
594 struct GNUNET_SERVER_Client* client;
597 * Head of the DLL of requests from this client.
599 struct ClientRequestList *head;
602 * Tail of the DLL of requests from this client.
604 struct ClientRequestList *tail;
610 * Closure for "process_reply" function.
612 struct ProcessReplyClosure
615 * The data for the reply.
620 * When the reply expires.
622 struct GNUNET_TIME_Absolute expiration;
630 * Namespace that this reply belongs to
631 * (if it is of type SBLOCK).
633 GNUNET_HashCode namespace;
641 * How much was this reply worth to us?
648 * Information about a peer that we are connected to.
649 * We track data that is useful for determining which
650 * peers should receive our requests.
656 * List of the last clients for which this peer
657 * successfully answered a query.
659 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
662 * List of the last PIDs for which
663 * this peer successfully answered a query;
664 * We use 0 to indicate no successful reply.
666 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
669 * Average delay between sending the peer a request and
670 * getting a reply (only calculated over the requests for
671 * which we actually got a reply). Calculated
672 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
674 struct GNUNET_TIME_Relative avg_delay;
677 * Average priority of successful replies. Calculated
678 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
683 * The peer's identity.
688 * Number of requests we have currently pending
689 * with this peer (that is, requests that were
690 * transmitted so recently that we would not retransmit
693 unsigned int pending_requests;
696 * Which offset in "last_p2p_replies" will be updated next?
697 * (we go round-robin).
699 unsigned int last_p2p_replies_woff;
702 * Which offset in "last_client_replies" will be updated next?
703 * (we go round-robin).
705 unsigned int last_client_replies_woff;
711 * Our connection to the datastore.
713 static struct GNUNET_DATASTORE_Handle *dsh;
718 static struct GNUNET_SCHEDULER_Handle *sched;
723 const struct GNUNET_CONFIGURATION_Handle *cfg;
726 * Handle to the core service (NULL until we've connected to it).
728 struct GNUNET_CORE_Handle *core;
731 * Head of doubly-linked LGC list.
733 static struct LocalGetContext *lgc_head;
736 * Tail of doubly-linked LGC list.
738 static struct LocalGetContext *lgc_tail;
741 * Head of request queue for the datastore, sorted by timeout.
743 static struct DatastoreRequestQueue *drq_head;
746 * Tail of request queue for the datastore.
748 static struct DatastoreRequestQueue *drq_tail;
751 * Linked list of indexed files.
753 static struct IndexInfo *indexed_files;
756 * Maps hash over content of indexed files to the respective filename.
757 * The filenames are pointers into the indexed_files linked list and
758 * do not need to be freed.
760 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
763 * Map of query hash codes to requests.
765 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_query;
768 * Map of peer IDs to requests (for those requests coming
771 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_peer;
774 * Linked list of all of our clients and their requests.
776 static struct ClientList *clients;
779 * Heap with the request that will expire next at the top. Contains
780 * pointers of type "struct PendingRequest*"; these will *also* be
781 * aliased from the "requests_by_peer" data structures and the
782 * "requests_by_query" table. Note that requests from our clients
783 * don't expire and are thus NOT in the "requests_by_expiration"
784 * (or the "requests_by_peer" tables).
786 static struct GNUNET_CONTAINER_Heap *requests_by_expiration;
789 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
791 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
794 * Maximum number of requests (from other peers) that we're
795 * willing to have pending at any given point in time.
796 * FIXME: set from configuration (and 32 is a tiny value for testing only).
798 static uint64_t max_pending_requests = 32;
802 * Write the current index information list to disk.
807 struct GNUNET_BIO_WriteHandle *wh;
809 struct IndexInfo *pos;
812 GNUNET_CONFIGURATION_get_value_filename (cfg,
817 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
818 _("Configuration option `%s' in section `%s' missing.\n"),
823 wh = GNUNET_BIO_write_open (fn);
826 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
827 _("Could not open `%s'.\n"),
836 GNUNET_BIO_write (wh,
838 sizeof (GNUNET_HashCode))) ||
840 GNUNET_BIO_write_string (wh,
846 GNUNET_BIO_write_close (wh))
848 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
849 _("Error writing `%s'.\n"),
859 * Read index information from disk.
864 struct GNUNET_BIO_ReadHandle *rh;
866 struct IndexInfo *pos;
873 GNUNET_CONFIGURATION_get_value_filename (cfg,
878 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
879 _("Configuration option `%s' in section `%s' missing.\n"),
884 if (GNUNET_NO == GNUNET_DISK_file_test (fn))
886 /* no index info yet */
890 rh = GNUNET_BIO_read_open (fn);
893 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
894 _("Could not open `%s'.\n"),
900 while ( (GNUNET_OK ==
902 "Hash of indexed file",
904 sizeof (GNUNET_HashCode))) &&
906 GNUNET_BIO_read_string (rh,
907 "Name of indexed file",
911 slen = strlen (fname) + 1;
912 pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
914 pos->filename = (const char *) &pos[1];
915 memcpy (&pos[1], fname, slen);
917 GNUNET_CONTAINER_multihashmap_put (ifm,
919 (void*) pos->filename,
920 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
926 pos->next = indexed_files;
932 GNUNET_BIO_read_close (rh, &emsg))
939 * We've validated the hash of the file we're about to
940 * index. Signal success to the client and update
941 * our internal data structures.
943 * @param ii the index info entry for the request
946 signal_index_ok (struct IndexInfo *ii)
949 GNUNET_CONTAINER_multihashmap_put (ifm,
951 (void*) ii->filename,
952 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
954 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
955 _("Index request received for file `%s' is indexed as `%s'. Permitting anyway.\n"),
957 (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
959 GNUNET_SERVER_transmit_context_append (ii->tc,
961 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
962 GNUNET_SERVER_transmit_context_run (ii->tc,
963 GNUNET_TIME_UNIT_MINUTES);
967 ii->next = indexed_files;
970 GNUNET_SERVER_transmit_context_append (ii->tc,
972 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
973 GNUNET_SERVER_transmit_context_run (ii->tc,
974 GNUNET_TIME_UNIT_MINUTES);
980 * Function called once the hash computation over an
981 * indexed file has completed.
983 * @param cls closure, our publishing context
984 * @param res resulting hash, NULL on error
987 hash_for_index_val (void *cls,
988 const GNUNET_HashCode *
991 struct IndexInfo *ii = cls;
993 if ( (res == NULL) ||
996 sizeof(GNUNET_HashCode))) )
998 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
999 _("Hash mismatch trying to index file `%s' which has hash `%s'\n"),
1003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005 GNUNET_h2s (&ii->file_id));
1007 GNUNET_SERVER_transmit_context_append (ii->tc,
1009 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
1010 GNUNET_SERVER_transmit_context_run (ii->tc,
1011 GNUNET_TIME_UNIT_MINUTES);
1015 signal_index_ok (ii);
1020 * Handle INDEX_START-message.
1022 * @param cls closure
1023 * @param client identification of the client
1024 * @param message the actual message
1027 handle_index_start (void *cls,
1028 struct GNUNET_SERVER_Client *client,
1029 const struct GNUNET_MessageHeader *message)
1031 const struct IndexStartMessage *ism;
1034 struct IndexInfo *ii;
1041 msize = ntohs(message->size);
1042 if ( (msize <= sizeof (struct IndexStartMessage)) ||
1043 ( ((const char *)message)[msize-1] != '\0') )
1046 GNUNET_SERVER_receive_done (client,
1050 ism = (const struct IndexStartMessage*) message;
1051 fn = (const char*) &ism[1];
1052 dev = ntohl (ism->device);
1053 ino = GNUNET_ntohll (ism->inode);
1054 ism = (const struct IndexStartMessage*) message;
1055 slen = strlen (fn) + 1;
1056 ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
1057 ii->filename = (const char*) &ii[1];
1058 memcpy (&ii[1], fn, slen);
1059 ii->file_id = ism->file_id;
1060 ii->tc = GNUNET_SERVER_transmit_context_create (client);
1061 if ( ( (dev != 0) ||
1063 (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
1069 /* fast validation OK! */
1070 signal_index_ok (ii);
1074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1075 "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
1076 (unsigned long long) ino,
1077 (unsigned long long) myino,
1079 (unsigned int) mydev);
1081 /* slow validation, need to hash full file (again) */
1082 GNUNET_CRYPTO_hash_file (sched,
1083 GNUNET_SCHEDULER_PRIORITY_IDLE,
1086 &hash_for_index_val,
1092 * Handle INDEX_LIST_GET-message.
1094 * @param cls closure
1095 * @param client identification of the client
1096 * @param message the actual message
1099 handle_index_list_get (void *cls,
1100 struct GNUNET_SERVER_Client *client,
1101 const struct GNUNET_MessageHeader *message)
1103 struct GNUNET_SERVER_TransmitContext *tc;
1104 struct IndexInfoMessage *iim;
1105 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1108 struct GNUNET_MessageHeader *msg;
1109 struct IndexInfo *pos;
1111 tc = GNUNET_SERVER_transmit_context_create (client);
1112 iim = (struct IndexInfoMessage*) buf;
1114 pos = indexed_files;
1118 iim->file_id = pos->file_id;
1120 slen = strlen (fn) + 1;
1121 if (slen + sizeof (struct IndexInfoMessage) >
1122 GNUNET_SERVER_MAX_MESSAGE_SIZE)
1127 memcpy (&iim[1], fn, slen);
1128 GNUNET_SERVER_transmit_context_append
1131 sizeof (struct IndexInfoMessage)
1132 - sizeof (struct GNUNET_MessageHeader) + slen,
1133 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1136 GNUNET_SERVER_transmit_context_append (tc,
1138 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1139 GNUNET_SERVER_transmit_context_run (tc,
1140 GNUNET_TIME_UNIT_MINUTES);
1145 * Handle UNINDEX-message.
1147 * @param cls closure
1148 * @param client identification of the client
1149 * @param message the actual message
1152 handle_unindex (void *cls,
1153 struct GNUNET_SERVER_Client *client,
1154 const struct GNUNET_MessageHeader *message)
1156 const struct UnindexMessage *um;
1157 struct IndexInfo *pos;
1158 struct IndexInfo *prev;
1159 struct IndexInfo *next;
1160 struct GNUNET_SERVER_TransmitContext *tc;
1163 um = (const struct UnindexMessage*) message;
1166 pos = indexed_files;
1170 if (0 == memcmp (&pos->file_id,
1172 sizeof (GNUNET_HashCode)))
1175 indexed_files = pos->next;
1177 prev->next = pos->next;
1188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1189 "Client requested unindexing of file `%s': %s\n",
1190 GNUNET_h2s (&um->file_id),
1191 found ? "found" : "not found");
1193 if (GNUNET_YES == found)
1194 write_index_list ();
1195 tc = GNUNET_SERVER_transmit_context_create (client);
1196 GNUNET_SERVER_transmit_context_append (tc,
1198 GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1199 GNUNET_SERVER_transmit_context_run (tc,
1200 GNUNET_TIME_UNIT_MINUTES);
1205 * Run the next DS request in our
1206 * queue, we're done with the current one.
1211 struct DatastoreRequestQueue *e;
1213 while (NULL != (e = drq_head))
1215 if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1217 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1218 GNUNET_SCHEDULER_cancel (sched, e->task);
1219 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1220 e->req (e->req_cls, GNUNET_NO);
1225 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1226 GNUNET_SCHEDULER_cancel (sched, e->task);
1227 e->task = GNUNET_SCHEDULER_NO_TASK;
1228 e->req (e->req_cls, GNUNET_YES);
1229 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1235 * A datastore request had to be timed out.
1237 * @param cls closure (of type "struct DatastoreRequestQueue*")
1238 * @param tc task context, unused
1241 timeout_ds_request (void *cls,
1242 const struct GNUNET_SCHEDULER_TaskContext *tc)
1244 struct DatastoreRequestQueue *e = cls;
1246 e->task = GNUNET_SCHEDULER_NO_TASK;
1247 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1248 e->req (e->req_cls, GNUNET_NO);
1254 * Queue a request for the datastore.
1256 * @param deadline by when the request should run
1257 * @param fun function to call once the request can be run
1258 * @param fun_cls closure for fun
1260 static struct DatastoreRequestQueue *
1261 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1262 RequestFunction fun,
1265 struct DatastoreRequestQueue *e;
1266 struct DatastoreRequestQueue *bef;
1268 if (drq_head == NULL)
1270 /* no other requests pending, run immediately */
1271 fun (fun_cls, GNUNET_OK);
1274 e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1275 e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1277 e->req_cls = fun_cls;
1278 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1280 /* local request, highest prio, put at head of queue
1281 regardless of deadline */
1287 while ( (NULL != bef) &&
1288 (e->timeout.value < bef->timeout.value) )
1291 GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1292 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1294 e->task = GNUNET_SCHEDULER_add_delayed (sched,
1296 &timeout_ds_request,
1303 * Free the state associated with a local get context.
1305 * @param lgc the lgc to free
1308 local_get_context_free (struct LocalGetContext *lgc)
1310 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1311 GNUNET_SERVER_client_drop (lgc->client);
1312 GNUNET_free_non_null (lgc->results);
1313 if (lgc->results_bf != NULL)
1314 GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1315 if (lgc->req != NULL)
1317 if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1318 GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1319 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1320 GNUNET_free (lgc->req);
1327 * We're able to transmit the next (local) result to the client.
1328 * Do it and ask the datastore for more. Or, on error, tell
1329 * the datastore to stop giving us more.
1331 * @param cls our closure (struct LocalGetContext)
1332 * @param max maximum number of bytes we can transmit
1333 * @param buf where to copy our message
1334 * @return number of bytes copied to buf
1337 transmit_local_result (void *cls,
1341 struct LocalGetContext *lgc = cls;
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348 "Failed to transmit result to local client, aborting datastore iteration.\n");
1351 GNUNET_free (lgc->result);
1353 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1356 msize = ntohs (lgc->result->header.size);
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Transmitting %u bytes of result to local client.\n",
1362 GNUNET_assert (max >= msize);
1363 memcpy (buf, lgc->result, msize);
1364 GNUNET_free (lgc->result);
1366 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1372 * Continuation called from datastore's remove
1376 * @param success did the deletion work?
1377 * @param msg error message
1380 remove_cont (void *cls,
1384 if (GNUNET_OK != success)
1385 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1386 _("Failed to delete bogus block: %s\n"),
1388 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1393 * Mingle hash with the mingle_number to
1394 * produce different bits.
1397 mingle_hash (const GNUNET_HashCode * in,
1398 int32_t mingle_number,
1399 GNUNET_HashCode * hc)
1403 GNUNET_CRYPTO_hash (&mingle_number,
1406 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1411 * We've received an on-demand encoded block
1412 * from the datastore. Attempt to do on-demand
1413 * encoding and (if successful), call the
1414 * continuation with the resulting block. On
1415 * error, clean up and ask the datastore for
1418 * @param key key for the content
1419 * @param size number of bytes in data
1420 * @param data content stored
1421 * @param type type of the content
1422 * @param priority priority of the content
1423 * @param anonymity anonymity-level for the content
1424 * @param expiration expiration time for the content
1425 * @param uid unique identifier for the datum;
1426 * maybe 0 if no unique identifier is available
1427 * @param cont function to call with the actual block
1428 * @param cont_cls closure for cont
1431 handle_on_demand_block (const GNUNET_HashCode * key,
1437 struct GNUNET_TIME_Absolute
1438 expiration, uint64_t uid,
1439 GNUNET_DATASTORE_Iterator cont,
1442 const struct OnDemandBlock *odb;
1443 GNUNET_HashCode nkey;
1444 struct GNUNET_CRYPTO_AesSessionKey skey;
1445 struct GNUNET_CRYPTO_AesInitializationVector iv;
1446 GNUNET_HashCode query;
1448 char ndata[DBLOCK_SIZE];
1449 char edata[DBLOCK_SIZE];
1451 struct GNUNET_DISK_FileHandle *fh;
1454 if (size != sizeof (struct OnDemandBlock))
1457 GNUNET_DATASTORE_remove (dsh,
1463 GNUNET_TIME_UNIT_FOREVER_REL);
1466 odb = (const struct OnDemandBlock*) data;
1467 off = GNUNET_ntohll (odb->offset);
1468 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1471 if ( (NULL == fn) ||
1472 (NULL == (fh = GNUNET_DISK_file_open (fn,
1473 GNUNET_DISK_OPEN_READ,
1474 GNUNET_DISK_PERM_NONE))) ||
1476 GNUNET_DISK_file_seek (fh,
1478 GNUNET_DISK_SEEK_SET)) ||
1480 (nsize = GNUNET_DISK_file_read (fh,
1484 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1485 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1486 GNUNET_h2s (&odb->file_id),
1487 (unsigned long long) off,
1490 GNUNET_DISK_file_close (fh);
1491 /* FIXME: if this happens often, we need
1492 to remove the OnDemand block from the DS! */
1493 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1496 GNUNET_DISK_file_close (fh);
1497 GNUNET_CRYPTO_hash (ndata,
1500 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1501 GNUNET_CRYPTO_aes_encrypt (ndata,
1506 GNUNET_CRYPTO_hash (edata,
1509 if (0 != memcmp (&query,
1511 sizeof (GNUNET_HashCode)))
1513 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1514 _("Indexed file `%s' changed at offset %llu\n"),
1516 (unsigned long long) off);
1517 /* FIXME: if this happens often, we need
1518 to remove the OnDemand block from the DS! */
1519 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1526 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1535 * How many bytes should a bloomfilter be if we have already seen
1536 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1537 * of bits set per entry. Furthermore, we should not re-size the
1538 * filter too often (to keep it cheap).
1540 * Since other peers will also add entries but not resize the filter,
1541 * we should generally pick a slightly larger size than what the
1542 * strict math would suggest.
1544 * @return must be a power of two and smaller or equal to 2^15.
1547 compute_bloomfilter_size (unsigned int entry_count)
1550 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1551 uint16_t max = 1 << 15;
1553 if (entry_count > max)
1556 while ((size < max) && (size < ideal))
1565 * Recalculate our bloom filter for filtering replies.
1567 * @param count number of entries we are filtering right now
1568 * @param mingle set to our new mingling value
1569 * @param bf_size set to the size of the bloomfilter
1570 * @param entries the entries to filter
1571 * @return updated bloomfilter, NULL for none
1573 static struct GNUNET_CONTAINER_BloomFilter *
1574 refresh_bloomfilter (unsigned int count,
1577 const GNUNET_HashCode *entries)
1579 struct GNUNET_CONTAINER_BloomFilter *bf;
1582 GNUNET_HashCode mhash;
1586 nsize = compute_bloomfilter_size (count);
1587 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1589 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1592 for (i=0;i<count;i++)
1594 mingle_hash (&entries[i], *mingle, &mhash);
1595 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1602 * Closure used for "target_peer_select_cb".
1604 struct PeerSelectionContext
1607 * The request for which we are selecting
1610 struct PendingRequest *pr;
1613 * Current "prime" target.
1615 struct GNUNET_PeerIdentity target;
1618 * How much do we like this target?
1620 double target_score;
1626 * Function called for each connected peer to determine
1627 * which one(s) would make good targets for forwarding.
1629 * @param cls closure (struct PeerSelectionContext)
1630 * @param key current key code (peer identity)
1631 * @param value value in the hash map (struct ConnectedPeer)
1632 * @return GNUNET_YES if we should continue to
1637 target_peer_select_cb (void *cls,
1638 const GNUNET_HashCode * key,
1641 struct PeerSelectionContext *psc = cls;
1642 struct ConnectedPeer *cp = value;
1643 struct PendingRequest *pr = psc->pr;
1647 /* 1) check if we have already (recently) forwarded to this peer */
1648 for (i=0;i<pr->used_pids_off;i++)
1649 if (pr->used_pids[i] == cp->pid)
1650 return GNUNET_YES; /* skip */
1651 // 2) calculate how much we'd like to forward to this peer
1652 score = 0; // FIXME!
1654 /* store best-fit in closure */
1655 if (score > psc->target_score)
1657 psc->target_score = score;
1658 psc->target.hashPubKey = *key;
1665 * We use a random delay to make the timing of requests
1666 * less predictable. This function returns such a random
1669 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1671 static struct GNUNET_TIME_Relative
1672 get_processing_delay ()
1674 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1675 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1681 * Task that is run for each request with the
1682 * goal of forwarding the associated query to
1683 * other peers. The task should re-schedule
1684 * itself to be re-run once the TTL has expired.
1685 * (or at a later time if more peers should
1686 * be queried earlier).
1688 * @param cls the requests "struct PendingRequest*"
1689 * @param tc task context (unused)
1692 forward_request_task (void *cls,
1693 const struct GNUNET_SCHEDULER_TaskContext *tc);
1697 * We've selected a peer for forwarding of a query.
1698 * Construct the message and then re-schedule the
1699 * task to forward again to (other) peers.
1701 * @param cls closure
1702 * @param size number of bytes available in buf
1703 * @param buf where the callee should write the message
1704 * @return number of bytes written to buf
1707 transmit_request_cb (void *cls,
1711 struct PendingRequest *pr = cls;
1712 struct GetMessage *gm;
1713 GNUNET_HashCode *ext;
1719 /* (1) check for timeout */
1722 /* timeout, try another peer immediately again */
1723 pr->task = GNUNET_SCHEDULER_add_with_priority (sched,
1724 GNUNET_SCHEDULER_PRIORITY_IDLE,
1725 &forward_request_task,
1729 /* (2) build query message */
1730 k = 0; // FIXME: count hash codes!
1731 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1732 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1733 gm = (struct GetMessage*) buf;
1734 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1735 gm->header.size = htons (msize);
1736 gm->type = htonl (pr->type);
1737 pr->remaining_priority /= 2;
1738 gm->priority = htonl (pr->remaining_priority);
1739 gm->ttl = htonl (pr->ttl);
1740 gm->filter_mutator = htonl(pr->mingle);
1741 gm->hash_bitmap = htonl (42);
1742 gm->query = pr->query;
1743 ext = (GNUNET_HashCode*) &gm[1];
1744 // FIXME: setup "ext[0]..[k-1]"
1745 bfdata = (char *) &ext[k];
1747 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1751 /* (3) schedule job to do it again (or another peer, etc.) */
1752 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1753 get_processing_delay (), // FIXME!
1754 &forward_request_task,
1762 * Function called after we've tried to reserve
1763 * a certain amount of bandwidth for a reply.
1764 * Check if we succeeded and if so send our query.
1766 * @param cls the requests "struct PendingRequest*"
1767 * @param peer identifies the peer
1768 * @param latency current latency estimate, "FOREVER" if we have been
1770 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1771 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1772 * @param amount set to the amount that was actually reserved or unreserved
1773 * @param preference current traffic preference for the given peer
1776 target_reservation_cb (void *cls,
1778 GNUNET_PeerIdentity * peer,
1779 unsigned int bpm_in,
1780 unsigned int bpm_out,
1781 struct GNUNET_TIME_Relative
1782 latency, int amount,
1783 unsigned long long preference)
1785 struct PendingRequest *pr = cls;
1788 struct GNUNET_TIME_Relative maxdelay;
1790 GNUNET_assert (peer != NULL);
1791 if ( (amount != DBLOCK_SIZE) ||
1794 /* try again later; FIXME: we may need to un-reserve "amount"? */
1795 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1796 get_processing_delay (), // FIXME: longer?
1797 &forward_request_task,
1801 // (2) transmit, update ttl/priority
1802 // FIXME: calculate priority, maxdelay, size properly!
1805 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1806 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1811 &transmit_request_cb,
1813 if (pr->cth == NULL)
1815 /* try again later */
1816 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1817 get_processing_delay (), // FIXME: longer?
1818 &forward_request_task,
1825 * Task that is run for each request with the
1826 * goal of forwarding the associated query to
1827 * other peers. The task should re-schedule
1828 * itself to be re-run once the TTL has expired.
1829 * (or at a later time if more peers should
1830 * be queried earlier).
1832 * @param cls the requests "struct PendingRequest*"
1833 * @param tc task context (unused)
1836 forward_request_task (void *cls,
1837 const struct GNUNET_SCHEDULER_TaskContext *tc)
1839 struct PendingRequest *pr = cls;
1840 struct PeerSelectionContext psc;
1842 pr->task = GNUNET_SCHEDULER_NO_TASK;
1843 if (pr->cth != NULL)
1845 /* we're busy transmitting a result, wait a bit */
1846 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1847 get_processing_delay (),
1848 &forward_request_task,
1852 /* (1) select target */
1854 psc.target_score = DBL_MIN;
1855 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1856 &target_peer_select_cb,
1858 if (psc.target_score == DBL_MIN)
1860 /* no possible target found, wait some time */
1861 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1862 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1863 &forward_request_task,
1867 /* (2) reserve reply bandwidth */
1868 // FIXME: need a way to cancel; this
1869 // async operation is problematic (segv-problematic)
1870 // if "pr" is destroyed while it happens!
1871 GNUNET_CORE_peer_configure (core,
1873 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1875 DBLOCK_SIZE, // FIXME: make dependent on type?
1877 &target_reservation_cb,
1883 * We're processing (local) results for a search request
1884 * from a (local) client. Pass applicable results to the
1885 * client and if we are done either clean up (operation
1886 * complete) or switch to P2P search (more results possible).
1888 * @param cls our closure (struct LocalGetContext)
1889 * @param key key for the content
1890 * @param size number of bytes in data
1891 * @param data content stored
1892 * @param type type of the content
1893 * @param priority priority of the content
1894 * @param anonymity anonymity-level for the content
1895 * @param expiration expiration time for the content
1896 * @param uid unique identifier for the datum;
1897 * maybe 0 if no unique identifier is available
1900 process_local_get_result (void *cls,
1901 const GNUNET_HashCode * key,
1907 struct GNUNET_TIME_Absolute
1911 struct LocalGetContext *lgc = cls;
1912 struct PendingRequest *pr;
1913 struct ClientRequestList *crl;
1914 struct ClientList *cl;
1921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1922 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1923 GNUNET_h2s (&lgc->query));
1925 /* no further results from datastore; continue
1926 processing further requests from the client and
1927 allow the next task to use the datastore; also,
1928 switch to P2P requests or clean up our state. */
1930 GNUNET_SERVER_receive_done (lgc->client,
1932 if ( (lgc->results_used == 0) ||
1933 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1934 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1935 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1939 "Forwarding query for `%s' to network.\n",
1940 GNUNET_h2s (&lgc->query));
1943 while ( (NULL != cl) &&
1944 (cl->client != lgc->client) )
1948 cl = GNUNET_malloc (sizeof (struct ClientList));
1949 cl->client = lgc->client;
1953 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1955 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1956 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1957 pr->client = lgc->client;
1958 GNUNET_SERVER_client_keep (pr->client);
1959 pr->crl_entry = crl;
1961 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1963 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1964 *pr->namespace = lgc->namespace;
1966 pr->replies_seen = lgc->results;
1967 lgc->results = NULL;
1968 pr->start_time = GNUNET_TIME_absolute_get ();
1969 pr->query = lgc->query;
1970 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1971 pr->replies_seen_off = lgc->results_used;
1972 pr->replies_seen_size = lgc->results_size;
1973 lgc->results_size = 0;
1974 pr->type = lgc->type;
1975 pr->anonymity_level = lgc->anonymity_level;
1976 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1980 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1983 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1984 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1985 get_processing_delay (),
1986 &forward_request_task,
1988 local_get_context_free (lgc);
1991 /* got all possible results, clean up! */
1993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1994 "Found all possible results for query for `%s', done!\n",
1995 GNUNET_h2s (&lgc->query));
1997 local_get_context_free (lgc);
2000 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2004 "Received on-demand block for `%s' from local datastore, fetching data.\n",
2005 GNUNET_h2s (&lgc->query));
2007 handle_on_demand_block (key, size, data, type, priority,
2008 anonymity, expiration, uid,
2009 &process_local_get_result,
2013 if ( (type != lgc->type) &&
2014 (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2016 /* this should be virtually impossible to reach (DBLOCK
2017 query hash being identical to KBLOCK/SBLOCK query hash);
2018 nevertheless, if it happens, the correct thing is to
2019 simply skip the result. */
2021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2022 "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2025 GNUNET_h2s (&lgc->query));
2027 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2030 /* check if this is a result we've alredy
2032 for (i=0;i<lgc->results_used;i++)
2033 if (0 == memcmp (key,
2035 sizeof (GNUNET_HashCode)))
2038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2040 GNUNET_h2s (&lgc->query));
2042 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2045 if (lgc->results_used == lgc->results_size)
2046 GNUNET_array_grow (lgc->results,
2048 lgc->results_size * 2 + 2);
2049 GNUNET_CRYPTO_hash (data,
2051 &lgc->results[lgc->results_used++]);
2052 msize = size + sizeof (struct ContentMessage);
2053 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2054 lgc->result = GNUNET_malloc (msize);
2055 lgc->result->header.size = htons (msize);
2056 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2057 lgc->result->type = htonl (type);
2058 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2059 memcpy (&lgc->result[1],
2063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2064 "Received new result for `%s' from local datastore, passing to client.\n",
2065 GNUNET_h2s (&lgc->query));
2067 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2069 GNUNET_TIME_UNIT_FOREVER_REL,
2070 &transmit_local_result,
2076 * We're processing a search request from a local
2077 * client. Now it is our turn to query the datastore.
2079 * @param cls our closure (struct LocalGetContext)
2083 transmit_local_get (void *cls,
2084 const struct GNUNET_SCHEDULER_TaskContext *tc)
2086 struct LocalGetContext *lgc = cls;
2090 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2091 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2092 GNUNET_DATASTORE_get (dsh,
2095 &process_local_get_result,
2097 GNUNET_TIME_UNIT_FOREVER_REL);
2102 * We're processing a search request from a local
2103 * client. Now it is our turn to query the datastore.
2105 * @param cls our closure (struct LocalGetContext)
2106 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2109 transmit_local_get_ready (void *cls,
2112 struct LocalGetContext *lgc = cls;
2114 GNUNET_assert (GNUNET_OK == ok);
2115 GNUNET_SCHEDULER_add_continuation (sched,
2116 &transmit_local_get,
2118 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2123 * Handle START_SEARCH-message (search request from client).
2125 * @param cls closure
2126 * @param client identification of the client
2127 * @param message the actual message
2130 handle_start_search (void *cls,
2131 struct GNUNET_SERVER_Client *client,
2132 const struct GNUNET_MessageHeader *message)
2134 const struct SearchMessage *sm;
2135 struct LocalGetContext *lgc;
2139 msize = ntohs (message->size);
2140 if ( (msize < sizeof (struct SearchMessage)) ||
2141 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2144 GNUNET_SERVER_receive_done (client,
2148 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2149 sm = (const struct SearchMessage*) message;
2150 GNUNET_SERVER_client_keep (client);
2151 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2154 lgc->results_used = sc;
2155 GNUNET_array_grow (lgc->results,
2158 memcpy (lgc->results,
2160 sc * sizeof (GNUNET_HashCode));
2162 lgc->client = client;
2163 lgc->type = ntohl (sm->type);
2164 lgc->anonymity_level = ntohl (sm->anonymity_level);
2167 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2168 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2169 lgc->target.hashPubKey = sm->target;
2171 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2172 lgc->namespace = sm->target;
2177 lgc->query = sm->query;
2178 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2179 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2180 &transmit_local_get_ready,
2186 * List of handlers for the messages understood by this
2189 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2190 {&handle_index_start, NULL,
2191 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2192 {&handle_index_list_get, NULL,
2193 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2194 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2195 sizeof (struct UnindexMessage) },
2196 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2203 * Clean up the memory used by the PendingRequest structure (except
2204 * for the client or peer list that the request may be part of).
2206 * @param pr request to clean up
2209 destroy_pending_request (struct PendingRequest *pr)
2211 struct PendingReply *reply;
2212 struct ClientList *cl;
2214 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2217 // FIXME: not sure how this can work (efficiently)
2218 // also, what does the return value mean?
2219 if (pr->client == NULL)
2221 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2226 cl = pr->crl_entry->cl;
2227 GNUNET_CONTAINER_DLL_remove (cl->head,
2231 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2232 GNUNET_SCHEDULER_cancel (sched, pr->task);
2233 if (NULL != pr->cth)
2234 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2236 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2238 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2239 while (NULL != (reply = pr->replies_pending))
2241 pr->replies_pending = reply->next;
2242 GNUNET_free (reply);
2244 GNUNET_PEER_change_rc (pr->source_pid, -1);
2245 GNUNET_PEER_change_rc (pr->target_pid, -1);
2246 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2247 GNUNET_free_non_null (pr->used_pids);
2248 GNUNET_free_non_null (pr->replies_seen);
2249 GNUNET_free_non_null (pr->namespace);
2255 * A client disconnected. Remove all of its pending queries.
2257 * @param cls closure, NULL
2258 * @param client identification of the client
2261 handle_client_disconnect (void *cls,
2262 struct GNUNET_SERVER_Client
2265 struct LocalGetContext *lgc;
2266 struct ClientList *cpos;
2267 struct ClientList *cprev;
2268 struct ClientRequestList *rl;
2271 while ( (NULL != lgc) &&
2272 (lgc->client != client) )
2275 local_get_context_free (lgc);
2278 while ( (NULL != cpos) &&
2279 (clients->client != client) )
2287 clients = cpos->next;
2289 cprev->next = cpos->next;
2290 while (NULL != (rl = cpos->head))
2292 cpos->head = rl->next;
2293 destroy_pending_request (rl->req);
2302 * Iterator over entries in the "requests_by_query" map
2303 * that frees all the entries.
2305 * @param cls closure, NULL
2306 * @param key current key code (the query, unused)
2307 * @param value value in the hash map, of type "struct PendingRequest*"
2308 * @return GNUNET_YES (we should continue to iterate)
2311 destroy_pending_request_cb (void *cls,
2312 const GNUNET_HashCode * key,
2315 struct PendingRequest *pr = value;
2317 destroy_pending_request (pr);
2323 * Task run during shutdown.
2329 shutdown_task (void *cls,
2330 const struct GNUNET_SCHEDULER_TaskContext *tc)
2332 struct IndexInfo *pos;
2336 GNUNET_CORE_disconnect (core);
2341 GNUNET_DATASTORE_disconnect (dsh,
2345 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2346 &destroy_pending_request_cb,
2348 while (clients != NULL)
2349 handle_client_disconnect (NULL,
2351 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2352 requests_by_query = NULL;
2353 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2354 requests_by_peer = NULL;
2355 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2356 requests_by_expiration = NULL;
2357 // FIXME: iterate over entries and free individually?
2358 // (or do we get disconnect notifications?)
2359 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2360 connected_peers = NULL;
2361 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2363 while (NULL != (pos = indexed_files))
2365 indexed_files = pos->next;
2372 * Free (each) request made by the peer.
2374 * @param cls closure, points to peer that the request belongs to
2375 * @param key current key code
2376 * @param value value in the hash map
2377 * @return GNUNET_YES (we should continue to iterate)
2380 destroy_request (void *cls,
2381 const GNUNET_HashCode * key,
2384 const struct GNUNET_PeerIdentity * peer = cls;
2385 struct PendingRequest *pr = value;
2387 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2390 destroy_pending_request (pr);
2397 * Method called whenever a given peer connects.
2399 * @param cls closure, not used
2400 * @param peer peer identity this notification is about
2403 peer_connect_handler (void *cls,
2405 GNUNET_PeerIdentity * peer)
2407 struct ConnectedPeer *cp;
2409 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2410 cp->pid = GNUNET_PEER_intern (peer);
2411 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2414 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2419 * Method called whenever a peer disconnects.
2421 * @param cls closure, not used
2422 * @param peer peer identity this notification is about
2425 peer_disconnect_handler (void *cls,
2427 GNUNET_PeerIdentity * peer)
2429 struct ConnectedPeer *cp;
2431 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2433 GNUNET_PEER_change_rc (cp->pid, -1);
2434 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2436 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2444 * We're processing a GET request from
2445 * another peer and have decided to forward
2446 * it to other peers.
2448 * @param cls our "struct ProcessGetContext *"
2452 forward_get_request (void *cls,
2453 const struct GNUNET_SCHEDULER_TaskContext *tc)
2455 struct ProcessGetContext *pgc = cls;
2456 struct PendingRequest *pr;
2457 struct PendingRequest *eer;
2458 struct GNUNET_PeerIdentity target;
2460 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2461 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2463 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2464 *pr->namespace = pgc->namespace;
2467 pr->bf_size = pgc->bf_size;
2469 pr->start_time = pgc->start_time;
2470 pr->query = pgc->query;
2471 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2472 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2473 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2474 pr->anonymity_level = 1; /* default */
2475 pr->priority = pgc->priority;
2476 pr->remaining_priority = pr->priority;
2477 pr->mingle = pgc->mingle;
2479 pr->type = pgc->type;
2480 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2483 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2484 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2485 &pgc->reply_to.hashPubKey,
2487 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2488 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2490 pr->start_time.value + pr->ttl);
2491 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2493 /* expire oldest request! */
2494 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2495 GNUNET_PEER_resolve (eer->source_pid,
2497 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2500 destroy_pending_request (eer);
2502 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2503 get_processing_delay (),
2504 &forward_request_task,
2509 * Transmit the given message by copying it to
2510 * the target buffer "buf". "buf" will be
2511 * NULL and "size" zero if the socket was closed for
2512 * writing in the meantime. In that case, only
2516 * @param cls closure, pointer to the message
2517 * @param size number of bytes available in buf
2518 * @param buf where the callee should write the message
2519 * @return number of bytes written to buf
2522 transmit_message (void *cls,
2523 size_t size, void *buf)
2525 struct GNUNET_MessageHeader *msg = cls;
2531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532 "Dropping reply, core too busy.\n");
2537 msize = ntohs (msg->size);
2538 GNUNET_assert (size >= msize);
2539 memcpy (buf, msg, msize);
2546 * Test if the load on this peer is too high
2547 * to even consider processing the query at
2550 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2553 test_load_too_high ()
2555 return GNUNET_NO; // FIXME
2560 * We're processing (local) results for a search request
2561 * from another peer. Pass applicable results to the
2562 * peer and if we are done either clean up (operation
2563 * complete) or forward to other peers (more results possible).
2565 * @param cls our closure (struct LocalGetContext)
2566 * @param key key for the content
2567 * @param size number of bytes in data
2568 * @param data content stored
2569 * @param type type of the content
2570 * @param priority priority of the content
2571 * @param anonymity anonymity-level for the content
2572 * @param expiration expiration time for the content
2573 * @param uid unique identifier for the datum;
2574 * maybe 0 if no unique identifier is available
2577 process_p2p_get_result (void *cls,
2578 const GNUNET_HashCode * key,
2584 struct GNUNET_TIME_Absolute
2588 struct ProcessGetContext *pgc = cls;
2589 GNUNET_HashCode dhash;
2590 GNUNET_HashCode mhash;
2591 struct PutMessage *reply;
2595 /* no more results */
2596 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2597 ( (0 == pgc->results_found) ||
2598 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2599 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2600 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2602 GNUNET_SCHEDULER_add_continuation (sched,
2603 &forward_get_request,
2605 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2609 if (pgc->bf != NULL)
2610 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2616 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2618 handle_on_demand_block (key, size, data, type, priority,
2619 anonymity, expiration, uid,
2620 &process_p2p_get_result,
2624 /* check for duplicates */
2625 GNUNET_CRYPTO_hash (data, size, &dhash);
2626 mingle_hash (&dhash,
2629 if ( (pgc->bf != NULL) &&
2631 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2636 "Result from datastore filtered by bloomfilter.\n");
2638 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2641 pgc->results_found++;
2642 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2643 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2644 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2646 if (pgc->bf == NULL)
2649 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2653 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2657 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2658 reply->header.size = htons (sizeof (struct PutMessage) + size);
2659 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2660 reply->type = htonl (type);
2661 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2662 memcpy (&reply[1], data, size);
2663 GNUNET_CORE_notify_transmit_ready (core,
2665 ACCEPTABLE_REPLY_DELAY,
2667 sizeof (struct PutMessage) + size,
2670 if ( (GNUNET_YES == test_load_too_high()) ||
2671 (pgc->results_found > 5 + 2 * pgc->priority) )
2673 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2674 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2677 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2682 * We're processing a GET request from another peer. Give it to our
2685 * @param cls our "struct ProcessGetContext"
2686 * @param ok did we get a datastore slice or not?
2689 ds_get_request (void *cls,
2692 struct ProcessGetContext *pgc = cls;
2694 struct GNUNET_TIME_Relative timeout;
2696 if (GNUNET_OK != ok)
2698 /* no point in doing P2P stuff if we can't even do local */
2703 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2704 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2705 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2706 (pgc->priority + 1));
2707 GNUNET_DATASTORE_get (dsh,
2710 &process_p2p_get_result,
2717 * The priority level imposes a bound on the maximum
2718 * value for the ttl that can be requested.
2720 * @param ttl_in requested ttl
2721 * @param prio given priority
2722 * @return ttl_in if ttl_in is below the limit,
2723 * otherwise the ttl-limit for the given priority
2726 bound_ttl (int32_t ttl_in, uint32_t prio)
2728 unsigned long long allowed;
2732 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2733 if (ttl_in > allowed)
2735 if (allowed >= (1 << 30))
2744 * We've received a request with the specified
2745 * priority. Bound it according to how much
2746 * we trust the given peer.
2748 * @param prio_in requested priority
2749 * @param peer the peer making the request
2750 * @return effective priority
2753 bound_priority (uint32_t prio_in,
2754 const struct GNUNET_PeerIdentity *peer)
2761 * Handle P2P "GET" request.
2763 * @param cls closure, always NULL
2764 * @param other the other peer involved (sender or receiver, NULL
2765 * for loopback messages where we are both sender and receiver)
2766 * @param message the actual message
2767 * @return GNUNET_OK to keep the connection open,
2768 * GNUNET_SYSERR to close it (signal serious error)
2771 handle_p2p_get (void *cls,
2772 const struct GNUNET_PeerIdentity *other,
2773 const struct GNUNET_MessageHeader *message)
2776 const struct GetMessage *gm;
2778 const GNUNET_HashCode *opt;
2779 struct ProcessGetContext *pgc;
2782 uint32_t ttl_decrement;
2787 msize = ntohs(message->size);
2788 if (msize < sizeof (struct GetMessage))
2790 GNUNET_break_op (0);
2791 return GNUNET_SYSERR;
2793 gm = (const struct GetMessage*) message;
2794 bm = ntohl (gm->hash_bitmap);
2802 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2804 GNUNET_break_op (0);
2805 return GNUNET_SYSERR;
2807 opt = (const GNUNET_HashCode*) &gm[1];
2808 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2809 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2812 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2815 pgc->bf_size = bfsize;
2817 pgc->type = ntohl (gm->type);
2818 pgc->bm = ntohl (gm->hash_bitmap);
2819 pgc->mingle = gm->filter_mutator;
2821 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2822 pgc->reply_to.hashPubKey = opt[bits++];
2824 pgc->reply_to = *other;
2825 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2826 pgc->namespace = opt[bits++];
2827 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2829 GNUNET_break_op (0);
2831 return GNUNET_SYSERR;
2833 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2834 pgc->prime_target.hashPubKey = opt[bits++];
2835 /* note that we can really only check load here since otherwise
2836 peers could find out that we are overloaded by being disconnected
2837 after sending us a malformed query... */
2838 if (GNUNET_YES == test_load_too_high ())
2840 if (NULL != pgc->bf)
2841 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2845 "Dropping query from `%s', this peer is too busy.\n",
2846 GNUNET_i2s (other));
2850 net_load_up = 50; // FIXME
2851 net_load_down = 50; // FIXME
2852 pgc->policy = ROUTING_POLICY_NONE;
2853 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2854 (net_load_down < IDLE_LOAD_THRESHOLD) )
2856 pgc->policy |= ROUTING_POLICY_ALL;
2857 pgc->priority = 0; /* no charge */
2861 pgc->priority = bound_priority (ntohl (gm->priority), other);
2863 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2865 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2867 pgc->policy |= ROUTING_POLICY_ALL;
2871 // FIXME: is this sound?
2872 if (net_load_up < 90 + 10 * pgc->priority)
2873 pgc->policy |= ROUTING_POLICY_FORWARD;
2874 if (net_load_down < 90 + 10 * pgc->priority)
2875 pgc->policy |= ROUTING_POLICY_ANSWER;
2878 if (pgc->policy == ROUTING_POLICY_NONE)
2881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2882 "Dropping query from `%s', network saturated.\n",
2883 GNUNET_i2s (other));
2885 if (NULL != pgc->bf)
2886 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2888 return GNUNET_OK; /* drop */
2890 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2891 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2892 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2893 /* decrement ttl (always) */
2894 ttl_decrement = 2 * TTL_DECREMENT +
2895 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2897 if ( (pgc->ttl < 0) &&
2898 (pgc->ttl - ttl_decrement > 0) )
2901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2902 "Dropping query from `%s' due to TTL underflow.\n",
2903 GNUNET_i2s (other));
2905 /* integer underflow => drop (should be very rare)! */
2906 if (NULL != pgc->bf)
2907 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2911 pgc->ttl -= ttl_decrement;
2912 pgc->start_time = GNUNET_TIME_absolute_get ();
2913 preference = (double) pgc->priority;
2914 if (preference < QUERY_BANDWIDTH_VALUE)
2915 preference = QUERY_BANDWIDTH_VALUE;
2916 // FIXME: also reserve bandwidth for reply?
2917 GNUNET_CORE_peer_configure (core,
2919 GNUNET_TIME_UNIT_FOREVER_REL,
2920 0, 0, preference, NULL, NULL);
2921 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2922 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2926 GNUNET_SCHEDULER_add_continuation (sched,
2927 &forward_get_request,
2929 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2935 * Function called to notify us that we can now transmit a reply to a
2936 * client or peer. "buf" will be NULL and "size" zero if the socket was
2937 * closed for writing in the meantime.
2939 * @param cls closure, points to a "struct PendingRequest*" with
2940 * one or more pending replies
2941 * @param size number of bytes available in buf
2942 * @param buf where the callee should write the message
2943 * @return number of bytes written to buf
2946 transmit_result (void *cls,
2950 struct PendingRequest *pr = cls;
2952 struct PendingReply *reply;
2956 while (NULL != (reply = pr->replies_pending))
2958 if ( (reply->msize + ret < ret) ||
2959 (reply->msize + ret > size) )
2961 pr->replies_pending = reply->next;
2962 memcpy (&cbuf[ret], &reply[1], reply->msize);
2963 ret += reply->msize;
2964 GNUNET_free (reply);
2971 * Iterator over pending requests.
2973 * @param cls response (struct ProcessReplyClosure)
2974 * @param key our query
2975 * @param value value in the hash map (meta-info about the query)
2976 * @return GNUNET_YES (we should continue to iterate)
2979 process_reply (void *cls,
2980 const GNUNET_HashCode * key,
2983 struct ProcessReplyClosure *prq = cls;
2984 struct PendingRequest *pr = value;
2985 struct PendingRequest *eer;
2986 struct PendingReply *reply;
2987 struct PutMessage *pm;
2988 struct ContentMessage *cm;
2989 GNUNET_HashCode chash;
2990 GNUNET_HashCode mhash;
2991 struct GNUNET_PeerIdentity target;
2994 struct GNUNET_TIME_Relative max_delay;
2996 GNUNET_CRYPTO_hash (prq->data,
3001 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3002 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3004 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3005 /* FIXME: does prq->namespace match our expectations? */
3006 /* then: fall-through??? */
3007 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3010 mingle_hash (&chash, pr->mingle, &mhash);
3011 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3013 return GNUNET_YES; /* duplicate */
3014 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3018 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3019 // FIXME: any checks against duplicates for SKBlocks?
3022 prio = pr->priority;
3023 prq->priority += pr->remaining_priority;
3024 pr->remaining_priority = 0;
3025 if (pr->client != NULL)
3027 if (pr->replies_seen_size == pr->replies_seen_off)
3028 GNUNET_array_grow (pr->replies_seen,
3029 pr->replies_seen_size,
3030 pr->replies_seen_size * 2 + 4);
3031 pr->replies_seen[pr->replies_seen_off++] = chash;
3032 // FIXME: possibly recalculate BF!
3034 if (pr->client == NULL)
3036 msize = sizeof (struct ContentMessage) + prq->size;
3037 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3038 reply->msize = msize;
3039 cm = (struct ContentMessage*) &reply[1];
3040 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3041 cm->header.size = htons (msize);
3042 cm->type = htonl (prq->type);
3043 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3044 reply->next = pr->replies_pending;
3045 pr->replies_pending = reply;
3046 memcpy (&reply[1], prq->data, prq->size);
3047 if (pr->cth != NULL)
3049 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3050 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3052 /* estimate expiration time from time difference between
3053 first request that will be discarded and this request */
3054 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3055 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3058 GNUNET_PEER_resolve (pr->source_pid,
3060 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3067 if (NULL == pr->cth)
3069 // FIXME: now what? discard?
3074 msize = sizeof (struct PutMessage) + prq->size;
3075 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3076 reply->msize = msize;
3077 reply->next = pr->replies_pending;
3078 pm = (struct PutMessage*) &reply[1];
3079 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3080 pm->header.size = htons (msize);
3081 pm->type = htonl (prq->type);
3082 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3083 pr->replies_pending = reply;
3084 memcpy (&reply[1], prq->data, prq->size);
3087 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3089 GNUNET_TIME_UNIT_FOREVER_REL,
3094 // FIXME: need to try again later (not much
3095 // to do here specifically, but we need to
3096 // check somewhere else to handle this case!)
3099 // FIXME: implement hot-path routing statistics keeping!
3105 * Check if the given KBlock is well-formed.
3107 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3108 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3109 * @param query where to store the query that this block answers
3110 * @return GNUNET_OK if this is actually a well-formed KBlock
3113 check_kblock (const struct KBlock *kb,
3115 GNUNET_HashCode *query)
3117 if (dsize < sizeof (struct KBlock))
3119 GNUNET_break_op (0);
3120 return GNUNET_SYSERR;
3122 if (dsize - sizeof (struct KBlock) !=
3123 ntohs (kb->purpose.size)
3124 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3125 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3127 GNUNET_break_op (0);
3128 return GNUNET_SYSERR;
3131 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3136 GNUNET_break_op (0);
3137 return GNUNET_SYSERR;
3140 GNUNET_CRYPTO_hash (&kb->keyspace,
3141 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3148 * Check if the given SBlock is well-formed.
3150 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3151 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3152 * @param query where to store the query that this block answers
3153 * @param namespace where to store the namespace that this block belongs to
3154 * @return GNUNET_OK if this is actually a well-formed SBlock
3157 check_sblock (const struct SBlock *sb,
3159 GNUNET_HashCode *query,
3160 GNUNET_HashCode *namespace)
3162 if (dsize < sizeof (struct SBlock))
3164 GNUNET_break_op (0);
3165 return GNUNET_SYSERR;
3168 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3170 GNUNET_break_op (0);
3171 return GNUNET_SYSERR;
3174 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3179 GNUNET_break_op (0);
3180 return GNUNET_SYSERR;
3183 *query = sb->identifier;
3184 if (namespace != NULL)
3185 GNUNET_CRYPTO_hash (&sb->subspace,
3186 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3193 * Handle P2P "PUT" request.
3195 * @param cls closure, always NULL
3196 * @param other the other peer involved (sender or receiver, NULL
3197 * for loopback messages where we are both sender and receiver)
3198 * @param message the actual message
3199 * @return GNUNET_OK to keep the connection open,
3200 * GNUNET_SYSERR to close it (signal serious error)
3203 handle_p2p_put (void *cls,
3204 const struct GNUNET_PeerIdentity *other,
3205 const struct GNUNET_MessageHeader *message)
3207 const struct PutMessage *put;
3211 struct GNUNET_TIME_Absolute expiration;
3212 GNUNET_HashCode query;
3213 struct ProcessReplyClosure prq;
3215 msize = ntohs (message->size);
3216 if (msize < sizeof (struct PutMessage))
3219 return GNUNET_SYSERR;
3221 put = (const struct PutMessage*) message;
3222 dsize = msize - sizeof (struct PutMessage);
3223 type = ntohl (put->type);
3224 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3226 /* first, validate! */
3229 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3230 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3231 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3233 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3235 check_kblock ((const struct KBlock*) &put[1],
3238 return GNUNET_SYSERR;
3240 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3242 check_sblock ((const struct SBlock*) &put[1],
3246 return GNUNET_SYSERR;
3248 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3249 // FIXME -- validate SKBLOCK!
3253 /* unknown block type */
3254 GNUNET_break_op (0);
3255 return GNUNET_SYSERR;
3258 /* now, lookup 'query' */
3259 prq.data = (const void*) &put[1];
3262 prq.expiration = expiration;
3264 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3268 // FIXME: if migration is on and load is low,
3269 // queue to store data in datastore;
3270 // use "prq.priority" for that!
3276 * List of handlers for P2P messages
3277 * that we care about.
3279 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3282 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3284 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3290 * Process fs requests.
3292 * @param cls closure
3293 * @param s scheduler to use
3294 * @param server the initialized server
3295 * @param c configuration to use
3299 struct GNUNET_SCHEDULER_Handle *s,
3300 struct GNUNET_SERVER_Handle *server,
3301 const struct GNUNET_CONFIGURATION_Handle *c)
3306 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3307 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3308 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3309 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3310 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3312 dsh = GNUNET_DATASTORE_connect (cfg,
3314 core = GNUNET_CORE_connect (sched,
3316 GNUNET_TIME_UNIT_FOREVER_REL,
3319 &peer_connect_handler,
3320 &peer_disconnect_handler,
3326 GNUNET_SERVER_disconnect_notify (server,
3327 &handle_client_disconnect,
3329 GNUNET_SERVER_add_handlers (server, handlers);
3330 GNUNET_SCHEDULER_add_delayed (sched,
3331 GNUNET_TIME_UNIT_FOREVER_REL,
3336 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3337 _("Failed to connect to `%s' service.\n"),
3339 GNUNET_SCHEDULER_shutdown (sched);
3344 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3345 _("Failed to connect to `%s' service.\n"),
3347 GNUNET_SCHEDULER_shutdown (sched);
3354 * The main function for the fs service.
3356 * @param argc number of arguments from the command line
3357 * @param argv command line arguments
3358 * @return 0 ok, 1 on error
3361 main (int argc, char *const *argv)
3363 return (GNUNET_OK ==
3364 GNUNET_SERVICE_run (argc,
3367 GNUNET_SERVICE_OPTION_NONE,
3368 &run, NULL)) ? 0 : 1;
3371 /* end of gnunet-service-fs.c */