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 * Context of our GNUNET_CORE_peer_change_preference call.
422 struct GNUNET_CORE_InformationRequestContext *irc;
425 * Replies that we have received but were unable to forward yet
426 * (typically non-null only if we have a pending transmission
427 * request with the client or the respective peer).
429 struct PendingReply *replies_pending;
432 * Pending transmission request with the core service for the target
433 * peer (for processing of 'replies_pending') or Handle for a
434 * pending query-request for P2P-transmission with the core service.
435 * If non-NULL, this request must be cancelled should this struct be
438 struct GNUNET_CORE_TransmitHandle *cth;
441 * Pending transmission request for the target client (for processing of
442 * 'replies_pending').
444 struct GNUNET_CONNECTION_TransmitHandle *th;
447 * Hash code of all replies that we have seen so far (only valid
448 * if client is not NULL since we only track replies like this for
451 GNUNET_HashCode *replies_seen;
454 * Node in the heap representing this entry.
456 struct GNUNET_CONTAINER_HeapNode *hnode;
459 * When did we first see this request (form this peer), or, if our
460 * client is initiating, when did we last initiate a search?
462 struct GNUNET_TIME_Absolute start_time;
465 * The query that this request is for.
467 GNUNET_HashCode query;
470 * The task responsible for transmitting queries
473 GNUNET_SCHEDULER_TaskIdentifier task;
476 * (Interned) Peer identifier (only valid if "client" is NULL)
477 * that identifies a peer that gave us this request.
479 GNUNET_PEER_Id source_pid;
482 * (Interned) Peer identifier that identifies a preferred target
485 GNUNET_PEER_Id target_pid;
488 * (Interned) Peer identifiers of peers that have already
489 * received our query for this content.
491 GNUNET_PEER_Id *used_pids;
494 * Size of the 'bf' (in bytes).
499 * Desired anonymity level; only valid for requests from a local client.
501 uint32_t anonymity_level;
504 * How many entries in "used_pids" are actually valid?
506 unsigned int used_pids_off;
509 * How long is the "used_pids" array?
511 unsigned int used_pids_size;
514 * How many entries in "replies_seen" are actually valid?
516 unsigned int replies_seen_off;
519 * How long is the "replies_seen" array?
521 unsigned int replies_seen_size;
524 * Priority with which this request was made. If one of our clients
525 * made the request, then this is the current priority that we are
526 * using when initiating the request. This value is used when
527 * we decide to reward other peers with trust for providing a reply.
532 * Priority points left for us to spend when forwarding this request
535 uint32_t remaining_priority;
538 * Number to mingle hashes for bloom-filter
544 * TTL with which we saw this request (or, if we initiated, TTL that
545 * we used for the request).
550 * Type of the content that this request is for.
558 * All requests from a client are kept in a doubly-linked list.
560 struct ClientRequestList
563 * This is a doubly-linked list.
565 struct ClientRequestList *next;
568 * This is a doubly-linked list.
570 struct ClientRequestList *prev;
573 * A request from this client.
575 struct PendingRequest *req;
578 * Client list with the head and tail of this DLL.
580 struct ClientList *cl;
585 * Linked list of all clients that we are
586 * currently processing requests for.
592 * This is a linked list.
594 struct ClientList *next;
597 * What client is this entry for?
599 struct GNUNET_SERVER_Client* client;
602 * Head of the DLL of requests from this client.
604 struct ClientRequestList *head;
607 * Tail of the DLL of requests from this client.
609 struct ClientRequestList *tail;
615 * Closure for "process_reply" function.
617 struct ProcessReplyClosure
620 * The data for the reply.
625 * When the reply expires.
627 struct GNUNET_TIME_Absolute expiration;
635 * Namespace that this reply belongs to
636 * (if it is of type SBLOCK).
638 GNUNET_HashCode namespace;
646 * How much was this reply worth to us?
653 * Information about a peer that we are connected to.
654 * We track data that is useful for determining which
655 * peers should receive our requests.
661 * List of the last clients for which this peer
662 * successfully answered a query.
664 struct GNUNET_SERVER_Client *last_client_replies[CS2P_SUCCESS_LIST_SIZE];
667 * List of the last PIDs for which
668 * this peer successfully answered a query;
669 * We use 0 to indicate no successful reply.
671 GNUNET_PEER_Id last_p2p_replies[P2P_SUCCESS_LIST_SIZE];
674 * Average delay between sending the peer a request and
675 * getting a reply (only calculated over the requests for
676 * which we actually got a reply). Calculated
677 * as a moving average: new_delay = ((n-1)*last_delay+curr_delay) / n
679 struct GNUNET_TIME_Relative avg_delay;
682 * Average priority of successful replies. Calculated
683 * as a moving average: new_avg = ((n-1)*last_avg+curr_prio) / n
688 * The peer's identity.
693 * Number of requests we have currently pending
694 * with this peer (that is, requests that were
695 * transmitted so recently that we would not retransmit
698 unsigned int pending_requests;
701 * Which offset in "last_p2p_replies" will be updated next?
702 * (we go round-robin).
704 unsigned int last_p2p_replies_woff;
707 * Which offset in "last_client_replies" will be updated next?
708 * (we go round-robin).
710 unsigned int last_client_replies_woff;
716 * Our connection to the datastore.
718 static struct GNUNET_DATASTORE_Handle *dsh;
723 static struct GNUNET_SCHEDULER_Handle *sched;
728 const struct GNUNET_CONFIGURATION_Handle *cfg;
731 * Handle to the core service (NULL until we've connected to it).
733 struct GNUNET_CORE_Handle *core;
736 * Head of doubly-linked LGC list.
738 static struct LocalGetContext *lgc_head;
741 * Tail of doubly-linked LGC list.
743 static struct LocalGetContext *lgc_tail;
746 * Head of request queue for the datastore, sorted by timeout.
748 static struct DatastoreRequestQueue *drq_head;
751 * Tail of request queue for the datastore.
753 static struct DatastoreRequestQueue *drq_tail;
756 * Linked list of indexed files.
758 static struct IndexInfo *indexed_files;
761 * Maps hash over content of indexed files to the respective filename.
762 * The filenames are pointers into the indexed_files linked list and
763 * do not need to be freed.
765 static struct GNUNET_CONTAINER_MultiHashMap *ifm;
768 * Map of query hash codes to requests.
770 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_query;
773 * Map of peer IDs to requests (for those requests coming
776 static struct GNUNET_CONTAINER_MultiHashMap *requests_by_peer;
779 * Linked list of all of our clients and their requests.
781 static struct ClientList *clients;
784 * Heap with the request that will expire next at the top. Contains
785 * pointers of type "struct PendingRequest*"; these will *also* be
786 * aliased from the "requests_by_peer" data structures and the
787 * "requests_by_query" table. Note that requests from our clients
788 * don't expire and are thus NOT in the "requests_by_expiration"
789 * (or the "requests_by_peer" tables).
791 static struct GNUNET_CONTAINER_Heap *requests_by_expiration;
794 * Map of peer identifiers to "struct ConnectedPeer" (for that peer).
796 static struct GNUNET_CONTAINER_MultiHashMap *connected_peers;
799 * Maximum number of requests (from other peers) that we're
800 * willing to have pending at any given point in time.
801 * FIXME: set from configuration (and 32 is a tiny value for testing only).
803 static uint64_t max_pending_requests = 32;
807 * Write the current index information list to disk.
812 struct GNUNET_BIO_WriteHandle *wh;
814 struct IndexInfo *pos;
817 GNUNET_CONFIGURATION_get_value_filename (cfg,
822 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
823 _("Configuration option `%s' in section `%s' missing.\n"),
828 wh = GNUNET_BIO_write_open (fn);
831 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
832 _("Could not open `%s'.\n"),
841 GNUNET_BIO_write (wh,
843 sizeof (GNUNET_HashCode))) ||
845 GNUNET_BIO_write_string (wh,
851 GNUNET_BIO_write_close (wh))
853 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
854 _("Error writing `%s'.\n"),
864 * Read index information from disk.
869 struct GNUNET_BIO_ReadHandle *rh;
871 struct IndexInfo *pos;
878 GNUNET_CONFIGURATION_get_value_filename (cfg,
883 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
884 _("Configuration option `%s' in section `%s' missing.\n"),
889 if (GNUNET_NO == GNUNET_DISK_file_test (fn))
891 /* no index info yet */
895 rh = GNUNET_BIO_read_open (fn);
898 GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
899 _("Could not open `%s'.\n"),
905 while ( (GNUNET_OK ==
907 "Hash of indexed file",
909 sizeof (GNUNET_HashCode))) &&
911 GNUNET_BIO_read_string (rh,
912 "Name of indexed file",
916 slen = strlen (fname) + 1;
917 pos = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
919 pos->filename = (const char *) &pos[1];
920 memcpy (&pos[1], fname, slen);
922 GNUNET_CONTAINER_multihashmap_put (ifm,
924 (void*) pos->filename,
925 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
931 pos->next = indexed_files;
937 GNUNET_BIO_read_close (rh, &emsg))
944 * We've validated the hash of the file we're about to
945 * index. Signal success to the client and update
946 * our internal data structures.
948 * @param ii the index info entry for the request
951 signal_index_ok (struct IndexInfo *ii)
954 GNUNET_CONTAINER_multihashmap_put (ifm,
956 (void*) ii->filename,
957 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
959 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
960 _("Index request received for file `%s' is indexed as `%s'. Permitting anyway.\n"),
962 (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
964 GNUNET_SERVER_transmit_context_append_data (ii->tc,
966 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
967 GNUNET_SERVER_transmit_context_run (ii->tc,
968 GNUNET_TIME_UNIT_MINUTES);
972 ii->next = indexed_files;
975 GNUNET_SERVER_transmit_context_append_data (ii->tc,
977 GNUNET_MESSAGE_TYPE_FS_INDEX_START_OK);
978 GNUNET_SERVER_transmit_context_run (ii->tc,
979 GNUNET_TIME_UNIT_MINUTES);
985 * Function called once the hash computation over an
986 * indexed file has completed.
988 * @param cls closure, our publishing context
989 * @param res resulting hash, NULL on error
992 hash_for_index_val (void *cls,
993 const GNUNET_HashCode *
996 struct IndexInfo *ii = cls;
998 if ( (res == NULL) ||
1001 sizeof(GNUNET_HashCode))) )
1003 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1004 _("Hash mismatch trying to index file `%s' which has hash `%s'\n"),
1008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1010 GNUNET_h2s (&ii->file_id));
1012 GNUNET_SERVER_transmit_context_append_data (ii->tc,
1014 GNUNET_MESSAGE_TYPE_FS_INDEX_START_FAILED);
1015 GNUNET_SERVER_transmit_context_run (ii->tc,
1016 GNUNET_TIME_UNIT_MINUTES);
1020 signal_index_ok (ii);
1025 * Handle INDEX_START-message.
1027 * @param cls closure
1028 * @param client identification of the client
1029 * @param message the actual message
1032 handle_index_start (void *cls,
1033 struct GNUNET_SERVER_Client *client,
1034 const struct GNUNET_MessageHeader *message)
1036 const struct IndexStartMessage *ism;
1039 struct IndexInfo *ii;
1046 msize = ntohs(message->size);
1047 if ( (msize <= sizeof (struct IndexStartMessage)) ||
1048 ( ((const char *)message)[msize-1] != '\0') )
1051 GNUNET_SERVER_receive_done (client,
1055 ism = (const struct IndexStartMessage*) message;
1056 fn = (const char*) &ism[1];
1057 dev = ntohl (ism->device);
1058 ino = GNUNET_ntohll (ism->inode);
1059 ism = (const struct IndexStartMessage*) message;
1060 slen = strlen (fn) + 1;
1061 ii = GNUNET_malloc (sizeof (struct IndexInfo) + slen);
1062 ii->filename = (const char*) &ii[1];
1063 memcpy (&ii[1], fn, slen);
1064 ii->file_id = ism->file_id;
1065 ii->tc = GNUNET_SERVER_transmit_context_create (client);
1066 if ( ( (dev != 0) ||
1068 (GNUNET_OK == GNUNET_DISK_file_get_identifiers (fn,
1074 /* fast validation OK! */
1075 signal_index_ok (ii);
1079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080 "Mismatch in file identifiers (%llu != %llu or %u != %u), need to hash.\n",
1081 (unsigned long long) ino,
1082 (unsigned long long) myino,
1084 (unsigned int) mydev);
1086 /* slow validation, need to hash full file (again) */
1087 GNUNET_CRYPTO_hash_file (sched,
1088 GNUNET_SCHEDULER_PRIORITY_IDLE,
1091 &hash_for_index_val,
1097 * Handle INDEX_LIST_GET-message.
1099 * @param cls closure
1100 * @param client identification of the client
1101 * @param message the actual message
1104 handle_index_list_get (void *cls,
1105 struct GNUNET_SERVER_Client *client,
1106 const struct GNUNET_MessageHeader *message)
1108 struct GNUNET_SERVER_TransmitContext *tc;
1109 struct IndexInfoMessage *iim;
1110 char buf[GNUNET_SERVER_MAX_MESSAGE_SIZE];
1113 struct IndexInfo *pos;
1115 tc = GNUNET_SERVER_transmit_context_create (client);
1116 iim = (struct IndexInfoMessage*) buf;
1117 pos = indexed_files;
1121 slen = strlen (fn) + 1;
1122 if (slen + sizeof (struct IndexInfoMessage) >
1123 GNUNET_SERVER_MAX_MESSAGE_SIZE)
1128 iim->header.type = htons (GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1129 iim->header.size = htons (slen + sizeof (struct IndexInfoMessage));
1131 iim->file_id = pos->file_id;
1132 memcpy (&iim[1], fn, slen);
1133 GNUNET_SERVER_transmit_context_append_message (tc,
1137 GNUNET_SERVER_transmit_context_append_data (tc,
1139 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1140 GNUNET_SERVER_transmit_context_run (tc,
1141 GNUNET_TIME_UNIT_MINUTES);
1146 * Handle UNINDEX-message.
1148 * @param cls closure
1149 * @param client identification of the client
1150 * @param message the actual message
1153 handle_unindex (void *cls,
1154 struct GNUNET_SERVER_Client *client,
1155 const struct GNUNET_MessageHeader *message)
1157 const struct UnindexMessage *um;
1158 struct IndexInfo *pos;
1159 struct IndexInfo *prev;
1160 struct IndexInfo *next;
1161 struct GNUNET_SERVER_TransmitContext *tc;
1164 um = (const struct UnindexMessage*) message;
1167 pos = indexed_files;
1171 if (0 == memcmp (&pos->file_id,
1173 sizeof (GNUNET_HashCode)))
1176 indexed_files = next;
1189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1190 "Client requested unindexing of file `%s': %s\n",
1191 GNUNET_h2s (&um->file_id),
1192 found ? "found" : "not found");
1194 if (GNUNET_YES == found)
1195 write_index_list ();
1196 tc = GNUNET_SERVER_transmit_context_create (client);
1197 GNUNET_SERVER_transmit_context_append_data (tc,
1199 GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1200 GNUNET_SERVER_transmit_context_run (tc,
1201 GNUNET_TIME_UNIT_MINUTES);
1206 * Run the next DS request in our
1207 * queue, we're done with the current one.
1212 struct DatastoreRequestQueue *e;
1214 while (NULL != (e = drq_head))
1216 if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1218 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1219 GNUNET_SCHEDULER_cancel (sched, e->task);
1220 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1221 e->req (e->req_cls, GNUNET_NO);
1226 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1227 GNUNET_SCHEDULER_cancel (sched, e->task);
1228 e->task = GNUNET_SCHEDULER_NO_TASK;
1229 e->req (e->req_cls, GNUNET_YES);
1230 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1236 * A datastore request had to be timed out.
1238 * @param cls closure (of type "struct DatastoreRequestQueue*")
1239 * @param tc task context, unused
1242 timeout_ds_request (void *cls,
1243 const struct GNUNET_SCHEDULER_TaskContext *tc)
1245 struct DatastoreRequestQueue *e = cls;
1247 e->task = GNUNET_SCHEDULER_NO_TASK;
1248 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1249 e->req (e->req_cls, GNUNET_NO);
1255 * Queue a request for the datastore.
1257 * @param deadline by when the request should run
1258 * @param fun function to call once the request can be run
1259 * @param fun_cls closure for fun
1261 static struct DatastoreRequestQueue *
1262 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1263 RequestFunction fun,
1266 struct DatastoreRequestQueue *e;
1267 struct DatastoreRequestQueue *bef;
1269 if (drq_head == NULL)
1271 /* no other requests pending, run immediately */
1272 fun (fun_cls, GNUNET_OK);
1275 e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1276 e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1278 e->req_cls = fun_cls;
1279 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1281 /* local request, highest prio, put at head of queue
1282 regardless of deadline */
1288 while ( (NULL != bef) &&
1289 (e->timeout.value < bef->timeout.value) )
1292 GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1293 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1295 e->task = GNUNET_SCHEDULER_add_delayed (sched,
1297 &timeout_ds_request,
1304 * Free the state associated with a local get context.
1306 * @param lgc the lgc to free
1309 local_get_context_free (struct LocalGetContext *lgc)
1311 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1312 GNUNET_SERVER_client_drop (lgc->client);
1313 GNUNET_free_non_null (lgc->results);
1314 if (lgc->results_bf != NULL)
1315 GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1316 if (lgc->req != NULL)
1318 if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1319 GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1320 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1321 GNUNET_free (lgc->req);
1328 * We're able to transmit the next (local) result to the client.
1329 * Do it and ask the datastore for more. Or, on error, tell
1330 * the datastore to stop giving us more.
1332 * @param cls our closure (struct LocalGetContext)
1333 * @param max maximum number of bytes we can transmit
1334 * @param buf where to copy our message
1335 * @return number of bytes copied to buf
1338 transmit_local_result (void *cls,
1342 struct LocalGetContext *lgc = cls;
1348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349 "Failed to transmit result to local client, aborting datastore iteration.\n");
1352 GNUNET_free (lgc->result);
1354 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1357 msize = ntohs (lgc->result->header.size);
1359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1360 "Transmitting %u bytes of result to local client.\n",
1363 GNUNET_assert (max >= msize);
1364 memcpy (buf, lgc->result, msize);
1365 GNUNET_free (lgc->result);
1367 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1373 * Continuation called from datastore's remove
1377 * @param success did the deletion work?
1378 * @param msg error message
1381 remove_cont (void *cls,
1385 if (GNUNET_OK != success)
1386 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1387 _("Failed to delete bogus block: %s\n"),
1389 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1394 * Mingle hash with the mingle_number to
1395 * produce different bits.
1398 mingle_hash (const GNUNET_HashCode * in,
1399 int32_t mingle_number,
1400 GNUNET_HashCode * hc)
1404 GNUNET_CRYPTO_hash (&mingle_number,
1407 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1412 * We've received an on-demand encoded block
1413 * from the datastore. Attempt to do on-demand
1414 * encoding and (if successful), call the
1415 * continuation with the resulting block. On
1416 * error, clean up and ask the datastore for
1419 * @param key key for the content
1420 * @param size number of bytes in data
1421 * @param data content stored
1422 * @param type type of the content
1423 * @param priority priority of the content
1424 * @param anonymity anonymity-level for the content
1425 * @param expiration expiration time for the content
1426 * @param uid unique identifier for the datum;
1427 * maybe 0 if no unique identifier is available
1428 * @param cont function to call with the actual block
1429 * @param cont_cls closure for cont
1432 handle_on_demand_block (const GNUNET_HashCode * key,
1438 struct GNUNET_TIME_Absolute
1439 expiration, uint64_t uid,
1440 GNUNET_DATASTORE_Iterator cont,
1443 const struct OnDemandBlock *odb;
1444 GNUNET_HashCode nkey;
1445 struct GNUNET_CRYPTO_AesSessionKey skey;
1446 struct GNUNET_CRYPTO_AesInitializationVector iv;
1447 GNUNET_HashCode query;
1449 char ndata[DBLOCK_SIZE];
1450 char edata[DBLOCK_SIZE];
1452 struct GNUNET_DISK_FileHandle *fh;
1455 if (size != sizeof (struct OnDemandBlock))
1458 GNUNET_DATASTORE_remove (dsh,
1464 GNUNET_TIME_UNIT_FOREVER_REL);
1467 odb = (const struct OnDemandBlock*) data;
1468 off = GNUNET_ntohll (odb->offset);
1469 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1472 if ( (NULL == fn) ||
1473 (NULL == (fh = GNUNET_DISK_file_open (fn,
1474 GNUNET_DISK_OPEN_READ,
1475 GNUNET_DISK_PERM_NONE))) ||
1477 GNUNET_DISK_file_seek (fh,
1479 GNUNET_DISK_SEEK_SET)) ||
1481 (nsize = GNUNET_DISK_file_read (fh,
1485 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1486 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1487 GNUNET_h2s (&odb->file_id),
1488 (unsigned long long) off,
1491 GNUNET_DISK_file_close (fh);
1492 /* FIXME: if this happens often, we need
1493 to remove the OnDemand block from the DS! */
1494 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1497 GNUNET_DISK_file_close (fh);
1498 GNUNET_CRYPTO_hash (ndata,
1501 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1502 GNUNET_CRYPTO_aes_encrypt (ndata,
1507 GNUNET_CRYPTO_hash (edata,
1510 if (0 != memcmp (&query,
1512 sizeof (GNUNET_HashCode)))
1514 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1515 _("Indexed file `%s' changed at offset %llu\n"),
1517 (unsigned long long) off);
1518 /* FIXME: if this happens often, we need
1519 to remove the OnDemand block from the DS! */
1520 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1527 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1536 * How many bytes should a bloomfilter be if we have already seen
1537 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1538 * of bits set per entry. Furthermore, we should not re-size the
1539 * filter too often (to keep it cheap).
1541 * Since other peers will also add entries but not resize the filter,
1542 * we should generally pick a slightly larger size than what the
1543 * strict math would suggest.
1545 * @return must be a power of two and smaller or equal to 2^15.
1548 compute_bloomfilter_size (unsigned int entry_count)
1551 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1552 uint16_t max = 1 << 15;
1554 if (entry_count > max)
1557 while ((size < max) && (size < ideal))
1566 * Recalculate our bloom filter for filtering replies.
1568 * @param count number of entries we are filtering right now
1569 * @param mingle set to our new mingling value
1570 * @param bf_size set to the size of the bloomfilter
1571 * @param entries the entries to filter
1572 * @return updated bloomfilter, NULL for none
1574 static struct GNUNET_CONTAINER_BloomFilter *
1575 refresh_bloomfilter (unsigned int count,
1578 const GNUNET_HashCode *entries)
1580 struct GNUNET_CONTAINER_BloomFilter *bf;
1583 GNUNET_HashCode mhash;
1587 nsize = compute_bloomfilter_size (count);
1588 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1590 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1593 for (i=0;i<count;i++)
1595 mingle_hash (&entries[i], *mingle, &mhash);
1596 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1603 * Closure used for "target_peer_select_cb".
1605 struct PeerSelectionContext
1608 * The request for which we are selecting
1611 struct PendingRequest *pr;
1614 * Current "prime" target.
1616 struct GNUNET_PeerIdentity target;
1619 * How much do we like this target?
1621 double target_score;
1627 * Function called for each connected peer to determine
1628 * which one(s) would make good targets for forwarding.
1630 * @param cls closure (struct PeerSelectionContext)
1631 * @param key current key code (peer identity)
1632 * @param value value in the hash map (struct ConnectedPeer)
1633 * @return GNUNET_YES if we should continue to
1638 target_peer_select_cb (void *cls,
1639 const GNUNET_HashCode * key,
1642 struct PeerSelectionContext *psc = cls;
1643 struct ConnectedPeer *cp = value;
1644 struct PendingRequest *pr = psc->pr;
1648 /* 1) check if we have already (recently) forwarded to this peer */
1649 for (i=0;i<pr->used_pids_off;i++)
1650 if (pr->used_pids[i] == cp->pid)
1651 return GNUNET_YES; /* skip */
1652 // 2) calculate how much we'd like to forward to this peer
1653 score = 0; // FIXME!
1655 /* store best-fit in closure */
1656 if (score > psc->target_score)
1658 psc->target_score = score;
1659 psc->target.hashPubKey = *key;
1666 * We use a random delay to make the timing of requests
1667 * less predictable. This function returns such a random
1670 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1672 static struct GNUNET_TIME_Relative
1673 get_processing_delay ()
1675 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1676 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1682 * Task that is run for each request with the
1683 * goal of forwarding the associated query to
1684 * other peers. The task should re-schedule
1685 * itself to be re-run once the TTL has expired.
1686 * (or at a later time if more peers should
1687 * be queried earlier).
1689 * @param cls the requests "struct PendingRequest*"
1690 * @param tc task context (unused)
1693 forward_request_task (void *cls,
1694 const struct GNUNET_SCHEDULER_TaskContext *tc);
1698 * We've selected a peer for forwarding of a query.
1699 * Construct the message and then re-schedule the
1700 * task to forward again to (other) peers.
1702 * @param cls closure
1703 * @param size number of bytes available in buf
1704 * @param buf where the callee should write the message
1705 * @return number of bytes written to buf
1708 transmit_request_cb (void *cls,
1712 struct PendingRequest *pr = cls;
1713 struct GetMessage *gm;
1714 GNUNET_HashCode *ext;
1720 /* (1) check for timeout */
1723 /* timeout, try another peer immediately again */
1724 pr->task = GNUNET_SCHEDULER_add_with_priority (sched,
1725 GNUNET_SCHEDULER_PRIORITY_IDLE,
1726 &forward_request_task,
1730 /* (2) build query message */
1731 k = 0; // FIXME: count hash codes!
1732 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1733 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1734 gm = (struct GetMessage*) buf;
1735 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1736 gm->header.size = htons (msize);
1737 gm->type = htonl (pr->type);
1738 pr->remaining_priority /= 2;
1739 gm->priority = htonl (pr->remaining_priority);
1740 gm->ttl = htonl (pr->ttl);
1741 gm->filter_mutator = htonl(pr->mingle);
1742 gm->hash_bitmap = htonl (42);
1743 gm->query = pr->query;
1744 ext = (GNUNET_HashCode*) &gm[1];
1745 // FIXME: setup "ext[0]..[k-1]"
1746 bfdata = (char *) &ext[k];
1748 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1752 /* (3) schedule job to do it again (or another peer, etc.) */
1753 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1754 get_processing_delay (), // FIXME!
1755 &forward_request_task,
1763 * Function called after we've tried to reserve
1764 * a certain amount of bandwidth for a reply.
1765 * Check if we succeeded and if so send our query.
1767 * @param cls the requests "struct PendingRequest*"
1768 * @param peer identifies the peer
1769 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1770 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1771 * @param amount set to the amount that was actually reserved or unreserved
1772 * @param preference current traffic preference for the given peer
1775 target_reservation_cb (void *cls,
1777 GNUNET_PeerIdentity * peer,
1778 unsigned int bpm_in,
1779 unsigned int bpm_out,
1781 uint64_t preference)
1783 struct PendingRequest *pr = cls;
1786 struct GNUNET_TIME_Relative maxdelay;
1789 GNUNET_assert (peer != NULL);
1790 if ( (amount != DBLOCK_SIZE) ||
1793 /* try again later; FIXME: we may need to un-reserve "amount"? */
1794 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1795 get_processing_delay (), // FIXME: longer?
1796 &forward_request_task,
1800 // (2) transmit, update ttl/priority
1801 // FIXME: calculate priority, maxdelay, size properly!
1804 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1805 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1810 &transmit_request_cb,
1812 if (pr->cth == NULL)
1814 /* try again later */
1815 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1816 get_processing_delay (), // FIXME: longer?
1817 &forward_request_task,
1824 * Task that is run for each request with the
1825 * goal of forwarding the associated query to
1826 * other peers. The task should re-schedule
1827 * itself to be re-run once the TTL has expired.
1828 * (or at a later time if more peers should
1829 * be queried earlier).
1831 * @param cls the requests "struct PendingRequest*"
1832 * @param tc task context (unused)
1835 forward_request_task (void *cls,
1836 const struct GNUNET_SCHEDULER_TaskContext *tc)
1838 struct PendingRequest *pr = cls;
1839 struct PeerSelectionContext psc;
1841 pr->task = GNUNET_SCHEDULER_NO_TASK;
1842 if (pr->cth != NULL)
1844 /* we're busy transmitting a result, wait a bit */
1845 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1846 get_processing_delay (),
1847 &forward_request_task,
1851 /* (1) select target */
1853 psc.target_score = DBL_MIN;
1854 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1855 &target_peer_select_cb,
1857 if (psc.target_score == DBL_MIN)
1859 /* no possible target found, wait some time */
1860 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1861 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1862 &forward_request_task,
1866 /* (2) reserve reply bandwidth */
1867 GNUNET_assert (NULL == pr->irc);
1868 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1870 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1872 DBLOCK_SIZE, // FIXME: make dependent on type?
1874 &target_reservation_cb,
1880 * We're processing (local) results for a search request
1881 * from a (local) client. Pass applicable results to the
1882 * client and if we are done either clean up (operation
1883 * complete) or switch to P2P search (more results possible).
1885 * @param cls our closure (struct LocalGetContext)
1886 * @param key key for the content
1887 * @param size number of bytes in data
1888 * @param data content stored
1889 * @param type type of the content
1890 * @param priority priority of the content
1891 * @param anonymity anonymity-level for the content
1892 * @param expiration expiration time for the content
1893 * @param uid unique identifier for the datum;
1894 * maybe 0 if no unique identifier is available
1897 process_local_get_result (void *cls,
1898 const GNUNET_HashCode * key,
1904 struct GNUNET_TIME_Absolute
1908 struct LocalGetContext *lgc = cls;
1909 struct PendingRequest *pr;
1910 struct ClientRequestList *crl;
1911 struct ClientList *cl;
1918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1920 GNUNET_h2s (&lgc->query));
1922 /* no further results from datastore; continue
1923 processing further requests from the client and
1924 allow the next task to use the datastore; also,
1925 switch to P2P requests or clean up our state. */
1927 GNUNET_SERVER_receive_done (lgc->client,
1929 if ( (lgc->results_used == 0) ||
1930 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1931 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1932 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1935 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1936 "Forwarding query for `%s' to network.\n",
1937 GNUNET_h2s (&lgc->query));
1940 while ( (NULL != cl) &&
1941 (cl->client != lgc->client) )
1945 cl = GNUNET_malloc (sizeof (struct ClientList));
1946 cl->client = lgc->client;
1950 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1952 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1953 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1954 pr->client = lgc->client;
1955 GNUNET_SERVER_client_keep (pr->client);
1956 pr->crl_entry = crl;
1958 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1960 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1961 *pr->namespace = lgc->namespace;
1963 pr->replies_seen = lgc->results;
1964 lgc->results = NULL;
1965 pr->start_time = GNUNET_TIME_absolute_get ();
1966 pr->query = lgc->query;
1967 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1968 pr->replies_seen_off = lgc->results_used;
1969 pr->replies_seen_size = lgc->results_size;
1970 lgc->results_size = 0;
1971 pr->type = lgc->type;
1972 pr->anonymity_level = lgc->anonymity_level;
1973 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1977 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1980 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1981 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1982 get_processing_delay (),
1983 &forward_request_task,
1985 local_get_context_free (lgc);
1988 /* got all possible results, clean up! */
1990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1991 "Found all possible results for query for `%s', done!\n",
1992 GNUNET_h2s (&lgc->query));
1994 local_get_context_free (lgc);
1997 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "Received on-demand block for `%s' from local datastore, fetching data.\n",
2002 GNUNET_h2s (&lgc->query));
2004 handle_on_demand_block (key, size, data, type, priority,
2005 anonymity, expiration, uid,
2006 &process_local_get_result,
2010 if ( (type != lgc->type) &&
2011 (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2013 /* this should be virtually impossible to reach (DBLOCK
2014 query hash being identical to KBLOCK/SBLOCK query hash);
2015 nevertheless, if it happens, the correct thing is to
2016 simply skip the result. */
2018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2019 "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2022 GNUNET_h2s (&lgc->query));
2024 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2027 /* check if this is a result we've alredy
2029 for (i=0;i<lgc->results_used;i++)
2030 if (0 == memcmp (key,
2032 sizeof (GNUNET_HashCode)))
2035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2036 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2037 GNUNET_h2s (&lgc->query));
2039 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2042 if (lgc->results_used == lgc->results_size)
2043 GNUNET_array_grow (lgc->results,
2045 lgc->results_size * 2 + 2);
2046 GNUNET_CRYPTO_hash (data,
2048 &lgc->results[lgc->results_used++]);
2049 msize = size + sizeof (struct ContentMessage);
2050 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2051 lgc->result = GNUNET_malloc (msize);
2052 lgc->result->header.size = htons (msize);
2053 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2054 lgc->result->type = htonl (type);
2055 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2056 memcpy (&lgc->result[1],
2060 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061 "Received new result for `%s' from local datastore, passing to client.\n",
2062 GNUNET_h2s (&lgc->query));
2064 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2066 GNUNET_TIME_UNIT_FOREVER_REL,
2067 &transmit_local_result,
2073 * We're processing a search request from a local
2074 * client. Now it is our turn to query the datastore.
2076 * @param cls our closure (struct LocalGetContext)
2080 transmit_local_get (void *cls,
2081 const struct GNUNET_SCHEDULER_TaskContext *tc)
2083 struct LocalGetContext *lgc = cls;
2087 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2088 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2089 GNUNET_DATASTORE_get (dsh,
2092 &process_local_get_result,
2094 GNUNET_TIME_UNIT_FOREVER_REL);
2099 * We're processing a search request from a local
2100 * client. Now it is our turn to query the datastore.
2102 * @param cls our closure (struct LocalGetContext)
2103 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2106 transmit_local_get_ready (void *cls,
2109 struct LocalGetContext *lgc = cls;
2111 GNUNET_assert (GNUNET_OK == ok);
2112 GNUNET_SCHEDULER_add_continuation (sched,
2113 &transmit_local_get,
2115 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2120 * Handle START_SEARCH-message (search request from client).
2122 * @param cls closure
2123 * @param client identification of the client
2124 * @param message the actual message
2127 handle_start_search (void *cls,
2128 struct GNUNET_SERVER_Client *client,
2129 const struct GNUNET_MessageHeader *message)
2131 const struct SearchMessage *sm;
2132 struct LocalGetContext *lgc;
2136 msize = ntohs (message->size);
2137 if ( (msize < sizeof (struct SearchMessage)) ||
2138 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2141 GNUNET_SERVER_receive_done (client,
2145 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2146 sm = (const struct SearchMessage*) message;
2147 GNUNET_SERVER_client_keep (client);
2148 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2151 lgc->results_used = sc;
2152 GNUNET_array_grow (lgc->results,
2155 memcpy (lgc->results,
2157 sc * sizeof (GNUNET_HashCode));
2159 lgc->client = client;
2160 lgc->type = ntohl (sm->type);
2161 lgc->anonymity_level = ntohl (sm->anonymity_level);
2164 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2165 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2166 lgc->target.hashPubKey = sm->target;
2168 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2169 lgc->namespace = sm->target;
2174 lgc->query = sm->query;
2175 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2176 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2177 &transmit_local_get_ready,
2183 * List of handlers for the messages understood by this
2186 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2187 {&handle_index_start, NULL,
2188 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2189 {&handle_index_list_get, NULL,
2190 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2191 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2192 sizeof (struct UnindexMessage) },
2193 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2200 * Clean up the memory used by the PendingRequest structure (except
2201 * for the client or peer list that the request may be part of).
2203 * @param pr request to clean up
2206 destroy_pending_request (struct PendingRequest *pr)
2208 struct PendingReply *reply;
2209 struct ClientList *cl;
2211 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2214 // FIXME: not sure how this can work (efficiently)
2215 // also, what does the return value mean?
2216 if (pr->irc != NULL)
2218 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
2221 if (pr->client == NULL)
2223 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2228 cl = pr->crl_entry->cl;
2229 GNUNET_CONTAINER_DLL_remove (cl->head,
2233 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2234 GNUNET_SCHEDULER_cancel (sched, pr->task);
2235 if (NULL != pr->cth)
2236 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2238 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2240 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2241 while (NULL != (reply = pr->replies_pending))
2243 pr->replies_pending = reply->next;
2244 GNUNET_free (reply);
2246 GNUNET_PEER_change_rc (pr->source_pid, -1);
2247 GNUNET_PEER_change_rc (pr->target_pid, -1);
2248 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2249 GNUNET_free_non_null (pr->used_pids);
2250 GNUNET_free_non_null (pr->replies_seen);
2251 GNUNET_free_non_null (pr->namespace);
2257 * A client disconnected. Remove all of its pending queries.
2259 * @param cls closure, NULL
2260 * @param client identification of the client
2263 handle_client_disconnect (void *cls,
2264 struct GNUNET_SERVER_Client
2267 struct LocalGetContext *lgc;
2268 struct ClientList *cpos;
2269 struct ClientList *cprev;
2270 struct ClientRequestList *rl;
2275 while ( (NULL != lgc) &&
2276 (lgc->client != client) )
2279 local_get_context_free (lgc);
2282 while ( (NULL != cpos) &&
2283 (clients->client != client) )
2291 clients = cpos->next;
2293 cprev->next = cpos->next;
2294 while (NULL != (rl = cpos->head))
2296 cpos->head = rl->next;
2297 destroy_pending_request (rl->req);
2306 * Iterator over entries in the "requests_by_query" map
2307 * that frees all the entries.
2309 * @param cls closure, NULL
2310 * @param key current key code (the query, unused)
2311 * @param value value in the hash map, of type "struct PendingRequest*"
2312 * @return GNUNET_YES (we should continue to iterate)
2315 destroy_pending_request_cb (void *cls,
2316 const GNUNET_HashCode * key,
2319 struct PendingRequest *pr = value;
2321 destroy_pending_request (pr);
2327 * Task run during shutdown.
2333 shutdown_task (void *cls,
2334 const struct GNUNET_SCHEDULER_TaskContext *tc)
2336 struct IndexInfo *pos;
2340 GNUNET_CORE_disconnect (core);
2345 GNUNET_DATASTORE_disconnect (dsh,
2349 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2350 &destroy_pending_request_cb,
2352 while (clients != NULL)
2353 handle_client_disconnect (NULL,
2355 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2356 requests_by_query = NULL;
2357 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2358 requests_by_peer = NULL;
2359 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2360 requests_by_expiration = NULL;
2361 // FIXME: iterate over entries and free individually?
2362 // (or do we get disconnect notifications?)
2363 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2364 connected_peers = NULL;
2365 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2367 while (NULL != (pos = indexed_files))
2369 indexed_files = pos->next;
2376 * Free (each) request made by the peer.
2378 * @param cls closure, points to peer that the request belongs to
2379 * @param key current key code
2380 * @param value value in the hash map
2381 * @return GNUNET_YES (we should continue to iterate)
2384 destroy_request (void *cls,
2385 const GNUNET_HashCode * key,
2388 const struct GNUNET_PeerIdentity * peer = cls;
2389 struct PendingRequest *pr = value;
2391 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2394 destroy_pending_request (pr);
2401 * Method called whenever a given peer connects.
2403 * @param cls closure, not used
2404 * @param peer peer identity this notification is about
2405 * @param latency reported latency of the connection with 'other'
2406 * @param distance reported distance (DV) to 'other'
2409 peer_connect_handler (void *cls,
2411 GNUNET_PeerIdentity * peer,
2412 struct GNUNET_TIME_Relative latency,
2415 struct ConnectedPeer *cp;
2417 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2418 cp->pid = GNUNET_PEER_intern (peer);
2419 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2422 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2427 * Method called whenever a peer disconnects.
2429 * @param cls closure, not used
2430 * @param peer peer identity this notification is about
2433 peer_disconnect_handler (void *cls,
2435 GNUNET_PeerIdentity * peer)
2437 struct ConnectedPeer *cp;
2439 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2441 GNUNET_PEER_change_rc (cp->pid, -1);
2442 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2444 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2452 * We're processing a GET request from
2453 * another peer and have decided to forward
2454 * it to other peers.
2456 * @param cls our "struct ProcessGetContext *"
2460 forward_get_request (void *cls,
2461 const struct GNUNET_SCHEDULER_TaskContext *tc)
2463 struct ProcessGetContext *pgc = cls;
2464 struct PendingRequest *pr;
2465 struct PendingRequest *eer;
2466 struct GNUNET_PeerIdentity target;
2468 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2469 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2471 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2472 *pr->namespace = pgc->namespace;
2475 pr->bf_size = pgc->bf_size;
2477 pr->start_time = pgc->start_time;
2478 pr->query = pgc->query;
2479 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2480 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2481 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2482 pr->anonymity_level = 1; /* default */
2483 pr->priority = pgc->priority;
2484 pr->remaining_priority = pr->priority;
2485 pr->mingle = pgc->mingle;
2487 pr->type = pgc->type;
2488 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2491 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2492 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2493 &pgc->reply_to.hashPubKey,
2495 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2496 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2498 pr->start_time.value + pr->ttl);
2499 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2501 /* expire oldest request! */
2502 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2503 GNUNET_PEER_resolve (eer->source_pid,
2505 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2508 destroy_pending_request (eer);
2510 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2511 get_processing_delay (),
2512 &forward_request_task,
2517 * Transmit the given message by copying it to
2518 * the target buffer "buf". "buf" will be
2519 * NULL and "size" zero if the socket was closed for
2520 * writing in the meantime. In that case, only
2524 * @param cls closure, pointer to the message
2525 * @param size number of bytes available in buf
2526 * @param buf where the callee should write the message
2527 * @return number of bytes written to buf
2530 transmit_message (void *cls,
2531 size_t size, void *buf)
2533 struct GNUNET_MessageHeader *msg = cls;
2539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540 "Dropping reply, core too busy.\n");
2545 msize = ntohs (msg->size);
2546 GNUNET_assert (size >= msize);
2547 memcpy (buf, msg, msize);
2554 * Test if the load on this peer is too high
2555 * to even consider processing the query at
2558 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2561 test_load_too_high ()
2563 return GNUNET_NO; // FIXME
2568 * We're processing (local) results for a search request
2569 * from another peer. Pass applicable results to the
2570 * peer and if we are done either clean up (operation
2571 * complete) or forward to other peers (more results possible).
2573 * @param cls our closure (struct LocalGetContext)
2574 * @param key key for the content
2575 * @param size number of bytes in data
2576 * @param data content stored
2577 * @param type type of the content
2578 * @param priority priority of the content
2579 * @param anonymity anonymity-level for the content
2580 * @param expiration expiration time for the content
2581 * @param uid unique identifier for the datum;
2582 * maybe 0 if no unique identifier is available
2585 process_p2p_get_result (void *cls,
2586 const GNUNET_HashCode * key,
2592 struct GNUNET_TIME_Absolute
2596 struct ProcessGetContext *pgc = cls;
2597 GNUNET_HashCode dhash;
2598 GNUNET_HashCode mhash;
2599 struct PutMessage *reply;
2603 /* no more results */
2604 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2605 ( (0 == pgc->results_found) ||
2606 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2607 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2608 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2610 GNUNET_SCHEDULER_add_continuation (sched,
2611 &forward_get_request,
2613 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2617 if (pgc->bf != NULL)
2618 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2624 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2626 handle_on_demand_block (key, size, data, type, priority,
2627 anonymity, expiration, uid,
2628 &process_p2p_get_result,
2632 /* check for duplicates */
2633 GNUNET_CRYPTO_hash (data, size, &dhash);
2634 mingle_hash (&dhash,
2637 if ( (pgc->bf != NULL) &&
2639 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2644 "Result from datastore filtered by bloomfilter.\n");
2646 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2649 pgc->results_found++;
2650 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2651 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2652 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2654 if (pgc->bf == NULL)
2657 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2661 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2665 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2666 reply->header.size = htons (sizeof (struct PutMessage) + size);
2667 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2668 reply->type = htonl (type);
2669 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2670 memcpy (&reply[1], data, size);
2671 GNUNET_CORE_notify_transmit_ready (core,
2673 ACCEPTABLE_REPLY_DELAY,
2675 sizeof (struct PutMessage) + size,
2678 if ( (GNUNET_YES == test_load_too_high()) ||
2679 (pgc->results_found > 5 + 2 * pgc->priority) )
2681 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2682 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2685 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2690 * We're processing a GET request from another peer. Give it to our
2693 * @param cls our "struct ProcessGetContext"
2694 * @param ok did we get a datastore slice or not?
2697 ds_get_request (void *cls,
2700 struct ProcessGetContext *pgc = cls;
2702 struct GNUNET_TIME_Relative timeout;
2704 if (GNUNET_OK != ok)
2706 /* no point in doing P2P stuff if we can't even do local */
2711 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2712 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2713 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2714 (pgc->priority + 1));
2715 GNUNET_DATASTORE_get (dsh,
2718 &process_p2p_get_result,
2725 * The priority level imposes a bound on the maximum
2726 * value for the ttl that can be requested.
2728 * @param ttl_in requested ttl
2729 * @param prio given priority
2730 * @return ttl_in if ttl_in is below the limit,
2731 * otherwise the ttl-limit for the given priority
2734 bound_ttl (int32_t ttl_in, uint32_t prio)
2736 unsigned long long allowed;
2740 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2741 if (ttl_in > allowed)
2743 if (allowed >= (1 << 30))
2752 * We've received a request with the specified
2753 * priority. Bound it according to how much
2754 * we trust the given peer.
2756 * @param prio_in requested priority
2757 * @param peer the peer making the request
2758 * @return effective priority
2761 bound_priority (uint32_t prio_in,
2762 const struct GNUNET_PeerIdentity *peer)
2769 * Handle P2P "GET" request.
2771 * @param cls closure, always NULL
2772 * @param other the other peer involved (sender or receiver, NULL
2773 * for loopback messages where we are both sender and receiver)
2774 * @param message the actual message
2775 * @param latency reported latency of the connection with 'other'
2776 * @param distance reported distance (DV) to 'other'
2777 * @return GNUNET_OK to keep the connection open,
2778 * GNUNET_SYSERR to close it (signal serious error)
2781 handle_p2p_get (void *cls,
2782 const struct GNUNET_PeerIdentity *other,
2783 const struct GNUNET_MessageHeader *message,
2784 struct GNUNET_TIME_Relative latency,
2788 const struct GetMessage *gm;
2790 const GNUNET_HashCode *opt;
2791 struct ProcessGetContext *pgc;
2794 uint32_t ttl_decrement;
2799 msize = ntohs(message->size);
2800 if (msize < sizeof (struct GetMessage))
2802 GNUNET_break_op (0);
2803 return GNUNET_SYSERR;
2805 gm = (const struct GetMessage*) message;
2806 bm = ntohl (gm->hash_bitmap);
2814 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2816 GNUNET_break_op (0);
2817 return GNUNET_SYSERR;
2819 opt = (const GNUNET_HashCode*) &gm[1];
2820 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2821 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2824 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2827 pgc->bf_size = bfsize;
2829 pgc->type = ntohl (gm->type);
2830 pgc->bm = ntohl (gm->hash_bitmap);
2831 pgc->mingle = gm->filter_mutator;
2833 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2834 pgc->reply_to.hashPubKey = opt[bits++];
2836 pgc->reply_to = *other;
2837 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2838 pgc->namespace = opt[bits++];
2839 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2841 GNUNET_break_op (0);
2843 return GNUNET_SYSERR;
2845 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2846 pgc->prime_target.hashPubKey = opt[bits++];
2847 /* note that we can really only check load here since otherwise
2848 peers could find out that we are overloaded by being disconnected
2849 after sending us a malformed query... */
2850 if (GNUNET_YES == test_load_too_high ())
2852 if (NULL != pgc->bf)
2853 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2857 "Dropping query from `%s', this peer is too busy.\n",
2858 GNUNET_i2s (other));
2862 net_load_up = 50; // FIXME
2863 net_load_down = 50; // FIXME
2864 pgc->policy = ROUTING_POLICY_NONE;
2865 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2866 (net_load_down < IDLE_LOAD_THRESHOLD) )
2868 pgc->policy |= ROUTING_POLICY_ALL;
2869 pgc->priority = 0; /* no charge */
2873 pgc->priority = bound_priority (ntohl (gm->priority), other);
2875 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2877 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2879 pgc->policy |= ROUTING_POLICY_ALL;
2883 // FIXME: is this sound?
2884 if (net_load_up < 90 + 10 * pgc->priority)
2885 pgc->policy |= ROUTING_POLICY_FORWARD;
2886 if (net_load_down < 90 + 10 * pgc->priority)
2887 pgc->policy |= ROUTING_POLICY_ANSWER;
2890 if (pgc->policy == ROUTING_POLICY_NONE)
2893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894 "Dropping query from `%s', network saturated.\n",
2895 GNUNET_i2s (other));
2897 if (NULL != pgc->bf)
2898 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2900 return GNUNET_OK; /* drop */
2902 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2903 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2904 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2905 /* decrement ttl (always) */
2906 ttl_decrement = 2 * TTL_DECREMENT +
2907 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2909 if ( (pgc->ttl < 0) &&
2910 (pgc->ttl - ttl_decrement > 0) )
2913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914 "Dropping query from `%s' due to TTL underflow.\n",
2915 GNUNET_i2s (other));
2917 /* integer underflow => drop (should be very rare)! */
2918 if (NULL != pgc->bf)
2919 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2923 pgc->ttl -= ttl_decrement;
2924 pgc->start_time = GNUNET_TIME_absolute_get ();
2925 preference = (double) pgc->priority;
2926 if (preference < QUERY_BANDWIDTH_VALUE)
2927 preference = QUERY_BANDWIDTH_VALUE;
2928 // FIXME: also reserve bandwidth for reply?
2929 (void) GNUNET_CORE_peer_change_preference (sched, cfg,
2931 GNUNET_TIME_UNIT_FOREVER_REL,
2932 0, 0, preference, NULL, NULL);
2933 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2934 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2938 GNUNET_SCHEDULER_add_continuation (sched,
2939 &forward_get_request,
2941 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2947 * Function called to notify us that we can now transmit a reply to a
2948 * client or peer. "buf" will be NULL and "size" zero if the socket was
2949 * closed for writing in the meantime.
2951 * @param cls closure, points to a "struct PendingRequest*" with
2952 * one or more pending replies
2953 * @param size number of bytes available in buf
2954 * @param buf where the callee should write the message
2955 * @return number of bytes written to buf
2958 transmit_result (void *cls,
2962 struct PendingRequest *pr = cls;
2964 struct PendingReply *reply;
2968 while (NULL != (reply = pr->replies_pending))
2970 if ( (reply->msize + ret < ret) ||
2971 (reply->msize + ret > size) )
2973 pr->replies_pending = reply->next;
2974 memcpy (&cbuf[ret], &reply[1], reply->msize);
2975 ret += reply->msize;
2976 GNUNET_free (reply);
2983 * Iterator over pending requests.
2985 * @param cls response (struct ProcessReplyClosure)
2986 * @param key our query
2987 * @param value value in the hash map (meta-info about the query)
2988 * @return GNUNET_YES (we should continue to iterate)
2991 process_reply (void *cls,
2992 const GNUNET_HashCode * key,
2995 struct ProcessReplyClosure *prq = cls;
2996 struct PendingRequest *pr = value;
2997 struct PendingRequest *eer;
2998 struct PendingReply *reply;
2999 struct PutMessage *pm;
3000 struct ContentMessage *cm;
3001 GNUNET_HashCode chash;
3002 GNUNET_HashCode mhash;
3003 struct GNUNET_PeerIdentity target;
3006 struct GNUNET_TIME_Relative max_delay;
3008 GNUNET_CRYPTO_hash (prq->data,
3013 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3014 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3016 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3017 /* FIXME: does prq->namespace match our expectations? */
3018 /* then: fall-through??? */
3019 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3022 mingle_hash (&chash, pr->mingle, &mhash);
3023 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3025 return GNUNET_YES; /* duplicate */
3026 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3030 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3031 // FIXME: any checks against duplicates for SKBlocks?
3034 prio = pr->priority;
3035 prq->priority += pr->remaining_priority;
3036 pr->remaining_priority = 0;
3037 if (pr->client != NULL)
3039 if (pr->replies_seen_size == pr->replies_seen_off)
3040 GNUNET_array_grow (pr->replies_seen,
3041 pr->replies_seen_size,
3042 pr->replies_seen_size * 2 + 4);
3043 pr->replies_seen[pr->replies_seen_off++] = chash;
3044 // FIXME: possibly recalculate BF!
3046 if (pr->client == NULL)
3048 msize = sizeof (struct ContentMessage) + prq->size;
3049 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3050 reply->msize = msize;
3051 cm = (struct ContentMessage*) &reply[1];
3052 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3053 cm->header.size = htons (msize);
3054 cm->type = htonl (prq->type);
3055 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3056 reply->next = pr->replies_pending;
3057 pr->replies_pending = reply;
3058 memcpy (&reply[1], prq->data, prq->size);
3059 if (pr->cth != NULL)
3061 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3062 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3064 /* estimate expiration time from time difference between
3065 first request that will be discarded and this request */
3066 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3067 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3070 GNUNET_PEER_resolve (pr->source_pid,
3072 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3079 if (NULL == pr->cth)
3081 // FIXME: now what? discard?
3086 msize = sizeof (struct PutMessage) + prq->size;
3087 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3088 reply->msize = msize;
3089 reply->next = pr->replies_pending;
3090 pm = (struct PutMessage*) &reply[1];
3091 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3092 pm->header.size = htons (msize);
3093 pm->type = htonl (prq->type);
3094 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3095 pr->replies_pending = reply;
3096 memcpy (&reply[1], prq->data, prq->size);
3099 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3101 GNUNET_TIME_UNIT_FOREVER_REL,
3106 // FIXME: need to try again later (not much
3107 // to do here specifically, but we need to
3108 // check somewhere else to handle this case!)
3111 // FIXME: implement hot-path routing statistics keeping!
3117 * Check if the given KBlock is well-formed.
3119 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3120 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3121 * @param query where to store the query that this block answers
3122 * @return GNUNET_OK if this is actually a well-formed KBlock
3125 check_kblock (const struct KBlock *kb,
3127 GNUNET_HashCode *query)
3129 if (dsize < sizeof (struct KBlock))
3131 GNUNET_break_op (0);
3132 return GNUNET_SYSERR;
3134 if (dsize - sizeof (struct KBlock) !=
3135 ntohs (kb->purpose.size)
3136 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3137 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3139 GNUNET_break_op (0);
3140 return GNUNET_SYSERR;
3143 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3148 GNUNET_break_op (0);
3149 return GNUNET_SYSERR;
3152 GNUNET_CRYPTO_hash (&kb->keyspace,
3153 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3160 * Check if the given SBlock is well-formed.
3162 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3163 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3164 * @param query where to store the query that this block answers
3165 * @param namespace where to store the namespace that this block belongs to
3166 * @return GNUNET_OK if this is actually a well-formed SBlock
3169 check_sblock (const struct SBlock *sb,
3171 GNUNET_HashCode *query,
3172 GNUNET_HashCode *namespace)
3174 if (dsize < sizeof (struct SBlock))
3176 GNUNET_break_op (0);
3177 return GNUNET_SYSERR;
3180 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3182 GNUNET_break_op (0);
3183 return GNUNET_SYSERR;
3186 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3191 GNUNET_break_op (0);
3192 return GNUNET_SYSERR;
3195 *query = sb->identifier;
3196 if (namespace != NULL)
3197 GNUNET_CRYPTO_hash (&sb->subspace,
3198 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3205 * Handle P2P "PUT" request.
3207 * @param cls closure, always NULL
3208 * @param other the other peer involved (sender or receiver, NULL
3209 * for loopback messages where we are both sender and receiver)
3210 * @param message the actual message
3211 * @param latency reported latency of the connection with 'other'
3212 * @param distance reported distance (DV) to 'other'
3213 * @return GNUNET_OK to keep the connection open,
3214 * GNUNET_SYSERR to close it (signal serious error)
3217 handle_p2p_put (void *cls,
3218 const struct GNUNET_PeerIdentity *other,
3219 const struct GNUNET_MessageHeader *message,
3220 struct GNUNET_TIME_Relative latency,
3223 const struct PutMessage *put;
3227 struct GNUNET_TIME_Absolute expiration;
3228 GNUNET_HashCode query;
3229 struct ProcessReplyClosure prq;
3231 msize = ntohs (message->size);
3232 if (msize < sizeof (struct PutMessage))
3235 return GNUNET_SYSERR;
3237 put = (const struct PutMessage*) message;
3238 dsize = msize - sizeof (struct PutMessage);
3239 type = ntohl (put->type);
3240 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3242 /* first, validate! */
3245 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3246 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3247 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3249 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3251 check_kblock ((const struct KBlock*) &put[1],
3254 return GNUNET_SYSERR;
3256 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3258 check_sblock ((const struct SBlock*) &put[1],
3262 return GNUNET_SYSERR;
3264 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3265 // FIXME -- validate SKBLOCK!
3269 /* unknown block type */
3270 GNUNET_break_op (0);
3271 return GNUNET_SYSERR;
3274 /* now, lookup 'query' */
3275 prq.data = (const void*) &put[1];
3278 prq.expiration = expiration;
3280 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3284 // FIXME: if migration is on and load is low,
3285 // queue to store data in datastore;
3286 // use "prq.priority" for that!
3292 * List of handlers for P2P messages
3293 * that we care about.
3295 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3298 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3300 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3306 * Process fs requests.
3308 * @param cls closure
3309 * @param s scheduler to use
3310 * @param server the initialized server
3311 * @param c configuration to use
3315 struct GNUNET_SCHEDULER_Handle *s,
3316 struct GNUNET_SERVER_Handle *server,
3317 const struct GNUNET_CONFIGURATION_Handle *c)
3322 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3323 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3324 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3325 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3326 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3328 dsh = GNUNET_DATASTORE_connect (cfg,
3330 core = GNUNET_CORE_connect (sched,
3332 GNUNET_TIME_UNIT_FOREVER_REL,
3336 &peer_connect_handler,
3337 &peer_disconnect_handler,
3342 GNUNET_SERVER_disconnect_notify (server,
3343 &handle_client_disconnect,
3345 GNUNET_SERVER_add_handlers (server, handlers);
3346 GNUNET_SCHEDULER_add_delayed (sched,
3347 GNUNET_TIME_UNIT_FOREVER_REL,
3352 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3353 _("Failed to connect to `%s' service.\n"),
3355 GNUNET_SCHEDULER_shutdown (sched);
3360 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3361 _("Failed to connect to `%s' service.\n"),
3363 GNUNET_SCHEDULER_shutdown (sched);
3370 * The main function for the fs service.
3372 * @param argc number of arguments from the command line
3373 * @param argv command line arguments
3374 * @return 0 ok, 1 on error
3377 main (int argc, char *const *argv)
3379 return (GNUNET_OK ==
3380 GNUNET_SERVICE_run (argc,
3383 GNUNET_SERVICE_OPTION_NONE,
3384 &run, NULL)) ? 0 : 1;
3387 /* end of gnunet-service-fs.c */