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 (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 (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 (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 GNUNET_MessageHeader *msg;
1114 struct IndexInfo *pos;
1116 tc = GNUNET_SERVER_transmit_context_create (client);
1117 iim = (struct IndexInfoMessage*) buf;
1119 pos = indexed_files;
1123 iim->file_id = pos->file_id;
1125 slen = strlen (fn) + 1;
1126 if (slen + sizeof (struct IndexInfoMessage) >
1127 GNUNET_SERVER_MAX_MESSAGE_SIZE)
1132 memcpy (&iim[1], fn, slen);
1133 GNUNET_SERVER_transmit_context_append
1136 sizeof (struct IndexInfoMessage)
1137 - sizeof (struct GNUNET_MessageHeader) + slen,
1138 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_ENTRY);
1141 GNUNET_SERVER_transmit_context_append (tc,
1143 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_END);
1144 GNUNET_SERVER_transmit_context_run (tc,
1145 GNUNET_TIME_UNIT_MINUTES);
1150 * Handle UNINDEX-message.
1152 * @param cls closure
1153 * @param client identification of the client
1154 * @param message the actual message
1157 handle_unindex (void *cls,
1158 struct GNUNET_SERVER_Client *client,
1159 const struct GNUNET_MessageHeader *message)
1161 const struct UnindexMessage *um;
1162 struct IndexInfo *pos;
1163 struct IndexInfo *prev;
1164 struct IndexInfo *next;
1165 struct GNUNET_SERVER_TransmitContext *tc;
1168 um = (const struct UnindexMessage*) message;
1171 pos = indexed_files;
1175 if (0 == memcmp (&pos->file_id,
1177 sizeof (GNUNET_HashCode)))
1180 indexed_files = next;
1193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1194 "Client requested unindexing of file `%s': %s\n",
1195 GNUNET_h2s (&um->file_id),
1196 found ? "found" : "not found");
1198 if (GNUNET_YES == found)
1199 write_index_list ();
1200 tc = GNUNET_SERVER_transmit_context_create (client);
1201 GNUNET_SERVER_transmit_context_append (tc,
1203 GNUNET_MESSAGE_TYPE_FS_UNINDEX_OK);
1204 GNUNET_SERVER_transmit_context_run (tc,
1205 GNUNET_TIME_UNIT_MINUTES);
1210 * Run the next DS request in our
1211 * queue, we're done with the current one.
1216 struct DatastoreRequestQueue *e;
1218 while (NULL != (e = drq_head))
1220 if (0 != GNUNET_TIME_absolute_get_remaining (e->timeout).value)
1222 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1223 GNUNET_SCHEDULER_cancel (sched, e->task);
1224 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1225 e->req (e->req_cls, GNUNET_NO);
1230 if (e->task != GNUNET_SCHEDULER_NO_TASK)
1231 GNUNET_SCHEDULER_cancel (sched, e->task);
1232 e->task = GNUNET_SCHEDULER_NO_TASK;
1233 e->req (e->req_cls, GNUNET_YES);
1234 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1240 * A datastore request had to be timed out.
1242 * @param cls closure (of type "struct DatastoreRequestQueue*")
1243 * @param tc task context, unused
1246 timeout_ds_request (void *cls,
1247 const struct GNUNET_SCHEDULER_TaskContext *tc)
1249 struct DatastoreRequestQueue *e = cls;
1251 e->task = GNUNET_SCHEDULER_NO_TASK;
1252 GNUNET_CONTAINER_DLL_remove (drq_head, drq_tail, e);
1253 e->req (e->req_cls, GNUNET_NO);
1259 * Queue a request for the datastore.
1261 * @param deadline by when the request should run
1262 * @param fun function to call once the request can be run
1263 * @param fun_cls closure for fun
1265 static struct DatastoreRequestQueue *
1266 queue_ds_request (struct GNUNET_TIME_Relative deadline,
1267 RequestFunction fun,
1270 struct DatastoreRequestQueue *e;
1271 struct DatastoreRequestQueue *bef;
1273 if (drq_head == NULL)
1275 /* no other requests pending, run immediately */
1276 fun (fun_cls, GNUNET_OK);
1279 e = GNUNET_malloc (sizeof (struct DatastoreRequestQueue));
1280 e->timeout = GNUNET_TIME_relative_to_absolute (deadline);
1282 e->req_cls = fun_cls;
1283 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1285 /* local request, highest prio, put at head of queue
1286 regardless of deadline */
1292 while ( (NULL != bef) &&
1293 (e->timeout.value < bef->timeout.value) )
1296 GNUNET_CONTAINER_DLL_insert_after (drq_head, drq_tail, bef, e);
1297 if (deadline.value == GNUNET_TIME_UNIT_FOREVER_REL.value)
1299 e->task = GNUNET_SCHEDULER_add_delayed (sched,
1301 &timeout_ds_request,
1308 * Free the state associated with a local get context.
1310 * @param lgc the lgc to free
1313 local_get_context_free (struct LocalGetContext *lgc)
1315 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1316 GNUNET_SERVER_client_drop (lgc->client);
1317 GNUNET_free_non_null (lgc->results);
1318 if (lgc->results_bf != NULL)
1319 GNUNET_CONTAINER_bloomfilter_free (lgc->results_bf);
1320 if (lgc->req != NULL)
1322 if (lgc->req->task != GNUNET_SCHEDULER_NO_TASK)
1323 GNUNET_SCHEDULER_cancel (sched, lgc->req->task);
1324 GNUNET_CONTAINER_DLL_remove (lgc_head, lgc_tail, lgc);
1325 GNUNET_free (lgc->req);
1332 * We're able to transmit the next (local) result to the client.
1333 * Do it and ask the datastore for more. Or, on error, tell
1334 * the datastore to stop giving us more.
1336 * @param cls our closure (struct LocalGetContext)
1337 * @param max maximum number of bytes we can transmit
1338 * @param buf where to copy our message
1339 * @return number of bytes copied to buf
1342 transmit_local_result (void *cls,
1346 struct LocalGetContext *lgc = cls;
1352 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1353 "Failed to transmit result to local client, aborting datastore iteration.\n");
1356 GNUNET_free (lgc->result);
1358 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
1361 msize = ntohs (lgc->result->header.size);
1363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364 "Transmitting %u bytes of result to local client.\n",
1367 GNUNET_assert (max >= msize);
1368 memcpy (buf, lgc->result, msize);
1369 GNUNET_free (lgc->result);
1371 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1377 * Continuation called from datastore's remove
1381 * @param success did the deletion work?
1382 * @param msg error message
1385 remove_cont (void *cls,
1389 if (GNUNET_OK != success)
1390 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1391 _("Failed to delete bogus block: %s\n"),
1393 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1398 * Mingle hash with the mingle_number to
1399 * produce different bits.
1402 mingle_hash (const GNUNET_HashCode * in,
1403 int32_t mingle_number,
1404 GNUNET_HashCode * hc)
1408 GNUNET_CRYPTO_hash (&mingle_number,
1411 GNUNET_CRYPTO_hash_xor (&m, in, hc);
1416 * We've received an on-demand encoded block
1417 * from the datastore. Attempt to do on-demand
1418 * encoding and (if successful), call the
1419 * continuation with the resulting block. On
1420 * error, clean up and ask the datastore for
1423 * @param key key for the content
1424 * @param size number of bytes in data
1425 * @param data content stored
1426 * @param type type of the content
1427 * @param priority priority of the content
1428 * @param anonymity anonymity-level for the content
1429 * @param expiration expiration time for the content
1430 * @param uid unique identifier for the datum;
1431 * maybe 0 if no unique identifier is available
1432 * @param cont function to call with the actual block
1433 * @param cont_cls closure for cont
1436 handle_on_demand_block (const GNUNET_HashCode * key,
1442 struct GNUNET_TIME_Absolute
1443 expiration, uint64_t uid,
1444 GNUNET_DATASTORE_Iterator cont,
1447 const struct OnDemandBlock *odb;
1448 GNUNET_HashCode nkey;
1449 struct GNUNET_CRYPTO_AesSessionKey skey;
1450 struct GNUNET_CRYPTO_AesInitializationVector iv;
1451 GNUNET_HashCode query;
1453 char ndata[DBLOCK_SIZE];
1454 char edata[DBLOCK_SIZE];
1456 struct GNUNET_DISK_FileHandle *fh;
1459 if (size != sizeof (struct OnDemandBlock))
1462 GNUNET_DATASTORE_remove (dsh,
1468 GNUNET_TIME_UNIT_FOREVER_REL);
1471 odb = (const struct OnDemandBlock*) data;
1472 off = GNUNET_ntohll (odb->offset);
1473 fn = (const char*) GNUNET_CONTAINER_multihashmap_get (ifm,
1476 if ( (NULL == fn) ||
1477 (NULL == (fh = GNUNET_DISK_file_open (fn,
1478 GNUNET_DISK_OPEN_READ,
1479 GNUNET_DISK_PERM_NONE))) ||
1481 GNUNET_DISK_file_seek (fh,
1483 GNUNET_DISK_SEEK_SET)) ||
1485 (nsize = GNUNET_DISK_file_read (fh,
1489 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1490 _("Could not access indexed file `%s' at offset %llu: %s\n"),
1491 GNUNET_h2s (&odb->file_id),
1492 (unsigned long long) off,
1495 GNUNET_DISK_file_close (fh);
1496 /* FIXME: if this happens often, we need
1497 to remove the OnDemand block from the DS! */
1498 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1501 GNUNET_DISK_file_close (fh);
1502 GNUNET_CRYPTO_hash (ndata,
1505 GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
1506 GNUNET_CRYPTO_aes_encrypt (ndata,
1511 GNUNET_CRYPTO_hash (edata,
1514 if (0 != memcmp (&query,
1516 sizeof (GNUNET_HashCode)))
1518 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1519 _("Indexed file `%s' changed at offset %llu\n"),
1521 (unsigned long long) off);
1522 /* FIXME: if this happens often, we need
1523 to remove the OnDemand block from the DS! */
1524 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
1531 GNUNET_DATASTORE_BLOCKTYPE_DBLOCK,
1540 * How many bytes should a bloomfilter be if we have already seen
1541 * entry_count responses? Note that BLOOMFILTER_K gives us the number
1542 * of bits set per entry. Furthermore, we should not re-size the
1543 * filter too often (to keep it cheap).
1545 * Since other peers will also add entries but not resize the filter,
1546 * we should generally pick a slightly larger size than what the
1547 * strict math would suggest.
1549 * @return must be a power of two and smaller or equal to 2^15.
1552 compute_bloomfilter_size (unsigned int entry_count)
1555 unsigned int ideal = (entry_count * BLOOMFILTER_K) / 4;
1556 uint16_t max = 1 << 15;
1558 if (entry_count > max)
1561 while ((size < max) && (size < ideal))
1570 * Recalculate our bloom filter for filtering replies.
1572 * @param count number of entries we are filtering right now
1573 * @param mingle set to our new mingling value
1574 * @param bf_size set to the size of the bloomfilter
1575 * @param entries the entries to filter
1576 * @return updated bloomfilter, NULL for none
1578 static struct GNUNET_CONTAINER_BloomFilter *
1579 refresh_bloomfilter (unsigned int count,
1582 const GNUNET_HashCode *entries)
1584 struct GNUNET_CONTAINER_BloomFilter *bf;
1587 GNUNET_HashCode mhash;
1591 nsize = compute_bloomfilter_size (count);
1592 *mingle = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, -1);
1594 bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
1597 for (i=0;i<count;i++)
1599 mingle_hash (&entries[i], *mingle, &mhash);
1600 GNUNET_CONTAINER_bloomfilter_add (bf, &mhash);
1607 * Closure used for "target_peer_select_cb".
1609 struct PeerSelectionContext
1612 * The request for which we are selecting
1615 struct PendingRequest *pr;
1618 * Current "prime" target.
1620 struct GNUNET_PeerIdentity target;
1623 * How much do we like this target?
1625 double target_score;
1631 * Function called for each connected peer to determine
1632 * which one(s) would make good targets for forwarding.
1634 * @param cls closure (struct PeerSelectionContext)
1635 * @param key current key code (peer identity)
1636 * @param value value in the hash map (struct ConnectedPeer)
1637 * @return GNUNET_YES if we should continue to
1642 target_peer_select_cb (void *cls,
1643 const GNUNET_HashCode * key,
1646 struct PeerSelectionContext *psc = cls;
1647 struct ConnectedPeer *cp = value;
1648 struct PendingRequest *pr = psc->pr;
1652 /* 1) check if we have already (recently) forwarded to this peer */
1653 for (i=0;i<pr->used_pids_off;i++)
1654 if (pr->used_pids[i] == cp->pid)
1655 return GNUNET_YES; /* skip */
1656 // 2) calculate how much we'd like to forward to this peer
1657 score = 0; // FIXME!
1659 /* store best-fit in closure */
1660 if (score > psc->target_score)
1662 psc->target_score = score;
1663 psc->target.hashPubKey = *key;
1670 * We use a random delay to make the timing of requests
1671 * less predictable. This function returns such a random
1674 * @return random delay to use for some request, between 0 and TTL_DECREMENT ms
1676 static struct GNUNET_TIME_Relative
1677 get_processing_delay ()
1679 return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1680 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1686 * Task that is run for each request with the
1687 * goal of forwarding the associated query to
1688 * other peers. The task should re-schedule
1689 * itself to be re-run once the TTL has expired.
1690 * (or at a later time if more peers should
1691 * be queried earlier).
1693 * @param cls the requests "struct PendingRequest*"
1694 * @param tc task context (unused)
1697 forward_request_task (void *cls,
1698 const struct GNUNET_SCHEDULER_TaskContext *tc);
1702 * We've selected a peer for forwarding of a query.
1703 * Construct the message and then re-schedule the
1704 * task to forward again to (other) peers.
1706 * @param cls closure
1707 * @param size number of bytes available in buf
1708 * @param buf where the callee should write the message
1709 * @return number of bytes written to buf
1712 transmit_request_cb (void *cls,
1716 struct PendingRequest *pr = cls;
1717 struct GetMessage *gm;
1718 GNUNET_HashCode *ext;
1724 /* (1) check for timeout */
1727 /* timeout, try another peer immediately again */
1728 pr->task = GNUNET_SCHEDULER_add_with_priority (sched,
1729 GNUNET_SCHEDULER_PRIORITY_IDLE,
1730 &forward_request_task,
1734 /* (2) build query message */
1735 k = 0; // FIXME: count hash codes!
1736 msize = sizeof (struct GetMessage) + pr->bf_size + k * sizeof(GNUNET_HashCode);
1737 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1738 gm = (struct GetMessage*) buf;
1739 gm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_GET);
1740 gm->header.size = htons (msize);
1741 gm->type = htonl (pr->type);
1742 pr->remaining_priority /= 2;
1743 gm->priority = htonl (pr->remaining_priority);
1744 gm->ttl = htonl (pr->ttl);
1745 gm->filter_mutator = htonl(pr->mingle);
1746 gm->hash_bitmap = htonl (42);
1747 gm->query = pr->query;
1748 ext = (GNUNET_HashCode*) &gm[1];
1749 // FIXME: setup "ext[0]..[k-1]"
1750 bfdata = (char *) &ext[k];
1752 GNUNET_CONTAINER_bloomfilter_get_raw_data (pr->bf,
1756 /* (3) schedule job to do it again (or another peer, etc.) */
1757 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1758 get_processing_delay (), // FIXME!
1759 &forward_request_task,
1767 * Function called after we've tried to reserve
1768 * a certain amount of bandwidth for a reply.
1769 * Check if we succeeded and if so send our query.
1771 * @param cls the requests "struct PendingRequest*"
1772 * @param peer identifies the peer
1773 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1774 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1775 * @param amount set to the amount that was actually reserved or unreserved
1776 * @param preference current traffic preference for the given peer
1779 target_reservation_cb (void *cls,
1781 GNUNET_PeerIdentity * peer,
1782 unsigned int bpm_in,
1783 unsigned int bpm_out,
1785 uint64_t preference)
1787 struct PendingRequest *pr = cls;
1790 struct GNUNET_TIME_Relative maxdelay;
1793 GNUNET_assert (peer != NULL);
1794 if ( (amount != DBLOCK_SIZE) ||
1797 /* try again later; FIXME: we may need to un-reserve "amount"? */
1798 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1799 get_processing_delay (), // FIXME: longer?
1800 &forward_request_task,
1804 // (2) transmit, update ttl/priority
1805 // FIXME: calculate priority, maxdelay, size properly!
1808 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1809 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1814 &transmit_request_cb,
1816 if (pr->cth == NULL)
1818 /* try again later */
1819 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1820 get_processing_delay (), // FIXME: longer?
1821 &forward_request_task,
1828 * Task that is run for each request with the
1829 * goal of forwarding the associated query to
1830 * other peers. The task should re-schedule
1831 * itself to be re-run once the TTL has expired.
1832 * (or at a later time if more peers should
1833 * be queried earlier).
1835 * @param cls the requests "struct PendingRequest*"
1836 * @param tc task context (unused)
1839 forward_request_task (void *cls,
1840 const struct GNUNET_SCHEDULER_TaskContext *tc)
1842 struct PendingRequest *pr = cls;
1843 struct PeerSelectionContext psc;
1845 pr->task = GNUNET_SCHEDULER_NO_TASK;
1846 if (pr->cth != NULL)
1848 /* we're busy transmitting a result, wait a bit */
1849 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1850 get_processing_delay (),
1851 &forward_request_task,
1855 /* (1) select target */
1857 psc.target_score = DBL_MIN;
1858 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1859 &target_peer_select_cb,
1861 if (psc.target_score == DBL_MIN)
1863 /* no possible target found, wait some time */
1864 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1865 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1866 &forward_request_task,
1870 /* (2) reserve reply bandwidth */
1871 GNUNET_assert (NULL == pr->irc);
1872 pr->irc = GNUNET_CORE_peer_change_preference (sched, cfg,
1874 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1876 DBLOCK_SIZE, // FIXME: make dependent on type?
1878 &target_reservation_cb,
1884 * We're processing (local) results for a search request
1885 * from a (local) client. Pass applicable results to the
1886 * client and if we are done either clean up (operation
1887 * complete) or switch to P2P search (more results possible).
1889 * @param cls our closure (struct LocalGetContext)
1890 * @param key key for the content
1891 * @param size number of bytes in data
1892 * @param data content stored
1893 * @param type type of the content
1894 * @param priority priority of the content
1895 * @param anonymity anonymity-level for the content
1896 * @param expiration expiration time for the content
1897 * @param uid unique identifier for the datum;
1898 * maybe 0 if no unique identifier is available
1901 process_local_get_result (void *cls,
1902 const GNUNET_HashCode * key,
1908 struct GNUNET_TIME_Absolute
1912 struct LocalGetContext *lgc = cls;
1913 struct PendingRequest *pr;
1914 struct ClientRequestList *crl;
1915 struct ClientList *cl;
1922 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1923 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1924 GNUNET_h2s (&lgc->query));
1926 /* no further results from datastore; continue
1927 processing further requests from the client and
1928 allow the next task to use the datastore; also,
1929 switch to P2P requests or clean up our state. */
1931 GNUNET_SERVER_receive_done (lgc->client,
1933 if ( (lgc->results_used == 0) ||
1934 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1935 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1936 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1939 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1940 "Forwarding query for `%s' to network.\n",
1941 GNUNET_h2s (&lgc->query));
1944 while ( (NULL != cl) &&
1945 (cl->client != lgc->client) )
1949 cl = GNUNET_malloc (sizeof (struct ClientList));
1950 cl->client = lgc->client;
1954 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1956 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1957 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1958 pr->client = lgc->client;
1959 GNUNET_SERVER_client_keep (pr->client);
1960 pr->crl_entry = crl;
1962 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1964 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1965 *pr->namespace = lgc->namespace;
1967 pr->replies_seen = lgc->results;
1968 lgc->results = NULL;
1969 pr->start_time = GNUNET_TIME_absolute_get ();
1970 pr->query = lgc->query;
1971 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1972 pr->replies_seen_off = lgc->results_used;
1973 pr->replies_seen_size = lgc->results_size;
1974 lgc->results_size = 0;
1975 pr->type = lgc->type;
1976 pr->anonymity_level = lgc->anonymity_level;
1977 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1981 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1984 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1985 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1986 get_processing_delay (),
1987 &forward_request_task,
1989 local_get_context_free (lgc);
1992 /* got all possible results, clean up! */
1994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1995 "Found all possible results for query for `%s', done!\n",
1996 GNUNET_h2s (&lgc->query));
1998 local_get_context_free (lgc);
2001 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2005 "Received on-demand block for `%s' from local datastore, fetching data.\n",
2006 GNUNET_h2s (&lgc->query));
2008 handle_on_demand_block (key, size, data, type, priority,
2009 anonymity, expiration, uid,
2010 &process_local_get_result,
2014 if ( (type != lgc->type) &&
2015 (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2017 /* this should be virtually impossible to reach (DBLOCK
2018 query hash being identical to KBLOCK/SBLOCK query hash);
2019 nevertheless, if it happens, the correct thing is to
2020 simply skip the result. */
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2026 GNUNET_h2s (&lgc->query));
2028 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2031 /* check if this is a result we've alredy
2033 for (i=0;i<lgc->results_used;i++)
2034 if (0 == memcmp (key,
2036 sizeof (GNUNET_HashCode)))
2039 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2040 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2041 GNUNET_h2s (&lgc->query));
2043 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2046 if (lgc->results_used == lgc->results_size)
2047 GNUNET_array_grow (lgc->results,
2049 lgc->results_size * 2 + 2);
2050 GNUNET_CRYPTO_hash (data,
2052 &lgc->results[lgc->results_used++]);
2053 msize = size + sizeof (struct ContentMessage);
2054 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2055 lgc->result = GNUNET_malloc (msize);
2056 lgc->result->header.size = htons (msize);
2057 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2058 lgc->result->type = htonl (type);
2059 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2060 memcpy (&lgc->result[1],
2064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2065 "Received new result for `%s' from local datastore, passing to client.\n",
2066 GNUNET_h2s (&lgc->query));
2068 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2070 GNUNET_TIME_UNIT_FOREVER_REL,
2071 &transmit_local_result,
2077 * We're processing a search request from a local
2078 * client. Now it is our turn to query the datastore.
2080 * @param cls our closure (struct LocalGetContext)
2084 transmit_local_get (void *cls,
2085 const struct GNUNET_SCHEDULER_TaskContext *tc)
2087 struct LocalGetContext *lgc = cls;
2091 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2092 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2093 GNUNET_DATASTORE_get (dsh,
2096 &process_local_get_result,
2098 GNUNET_TIME_UNIT_FOREVER_REL);
2103 * We're processing a search request from a local
2104 * client. Now it is our turn to query the datastore.
2106 * @param cls our closure (struct LocalGetContext)
2107 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2110 transmit_local_get_ready (void *cls,
2113 struct LocalGetContext *lgc = cls;
2115 GNUNET_assert (GNUNET_OK == ok);
2116 GNUNET_SCHEDULER_add_continuation (sched,
2117 &transmit_local_get,
2119 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2124 * Handle START_SEARCH-message (search request from client).
2126 * @param cls closure
2127 * @param client identification of the client
2128 * @param message the actual message
2131 handle_start_search (void *cls,
2132 struct GNUNET_SERVER_Client *client,
2133 const struct GNUNET_MessageHeader *message)
2135 const struct SearchMessage *sm;
2136 struct LocalGetContext *lgc;
2140 msize = ntohs (message->size);
2141 if ( (msize < sizeof (struct SearchMessage)) ||
2142 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2145 GNUNET_SERVER_receive_done (client,
2149 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2150 sm = (const struct SearchMessage*) message;
2151 GNUNET_SERVER_client_keep (client);
2152 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2155 lgc->results_used = sc;
2156 GNUNET_array_grow (lgc->results,
2159 memcpy (lgc->results,
2161 sc * sizeof (GNUNET_HashCode));
2163 lgc->client = client;
2164 lgc->type = ntohl (sm->type);
2165 lgc->anonymity_level = ntohl (sm->anonymity_level);
2168 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2169 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2170 lgc->target.hashPubKey = sm->target;
2172 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2173 lgc->namespace = sm->target;
2178 lgc->query = sm->query;
2179 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2180 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2181 &transmit_local_get_ready,
2187 * List of handlers for the messages understood by this
2190 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2191 {&handle_index_start, NULL,
2192 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2193 {&handle_index_list_get, NULL,
2194 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2195 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2196 sizeof (struct UnindexMessage) },
2197 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2204 * Clean up the memory used by the PendingRequest structure (except
2205 * for the client or peer list that the request may be part of).
2207 * @param pr request to clean up
2210 destroy_pending_request (struct PendingRequest *pr)
2212 struct PendingReply *reply;
2213 struct ClientList *cl;
2215 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2218 // FIXME: not sure how this can work (efficiently)
2219 // also, what does the return value mean?
2220 if (pr->irc != NULL)
2222 GNUNET_CORE_peer_change_preference_cancel (pr->irc);
2225 if (pr->client == NULL)
2227 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2232 cl = pr->crl_entry->cl;
2233 GNUNET_CONTAINER_DLL_remove (cl->head,
2237 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2238 GNUNET_SCHEDULER_cancel (sched, pr->task);
2239 if (NULL != pr->cth)
2240 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2242 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2244 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2245 while (NULL != (reply = pr->replies_pending))
2247 pr->replies_pending = reply->next;
2248 GNUNET_free (reply);
2250 GNUNET_PEER_change_rc (pr->source_pid, -1);
2251 GNUNET_PEER_change_rc (pr->target_pid, -1);
2252 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2253 GNUNET_free_non_null (pr->used_pids);
2254 GNUNET_free_non_null (pr->replies_seen);
2255 GNUNET_free_non_null (pr->namespace);
2261 * A client disconnected. Remove all of its pending queries.
2263 * @param cls closure, NULL
2264 * @param client identification of the client
2267 handle_client_disconnect (void *cls,
2268 struct GNUNET_SERVER_Client
2271 struct LocalGetContext *lgc;
2272 struct ClientList *cpos;
2273 struct ClientList *cprev;
2274 struct ClientRequestList *rl;
2277 while ( (NULL != lgc) &&
2278 (lgc->client != client) )
2281 local_get_context_free (lgc);
2284 while ( (NULL != cpos) &&
2285 (clients->client != client) )
2293 clients = cpos->next;
2295 cprev->next = cpos->next;
2296 while (NULL != (rl = cpos->head))
2298 cpos->head = rl->next;
2299 destroy_pending_request (rl->req);
2308 * Iterator over entries in the "requests_by_query" map
2309 * that frees all the entries.
2311 * @param cls closure, NULL
2312 * @param key current key code (the query, unused)
2313 * @param value value in the hash map, of type "struct PendingRequest*"
2314 * @return GNUNET_YES (we should continue to iterate)
2317 destroy_pending_request_cb (void *cls,
2318 const GNUNET_HashCode * key,
2321 struct PendingRequest *pr = value;
2323 destroy_pending_request (pr);
2329 * Task run during shutdown.
2335 shutdown_task (void *cls,
2336 const struct GNUNET_SCHEDULER_TaskContext *tc)
2338 struct IndexInfo *pos;
2342 GNUNET_CORE_disconnect (core);
2347 GNUNET_DATASTORE_disconnect (dsh,
2351 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2352 &destroy_pending_request_cb,
2354 while (clients != NULL)
2355 handle_client_disconnect (NULL,
2357 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2358 requests_by_query = NULL;
2359 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2360 requests_by_peer = NULL;
2361 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2362 requests_by_expiration = NULL;
2363 // FIXME: iterate over entries and free individually?
2364 // (or do we get disconnect notifications?)
2365 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2366 connected_peers = NULL;
2367 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2369 while (NULL != (pos = indexed_files))
2371 indexed_files = pos->next;
2378 * Free (each) request made by the peer.
2380 * @param cls closure, points to peer that the request belongs to
2381 * @param key current key code
2382 * @param value value in the hash map
2383 * @return GNUNET_YES (we should continue to iterate)
2386 destroy_request (void *cls,
2387 const GNUNET_HashCode * key,
2390 const struct GNUNET_PeerIdentity * peer = cls;
2391 struct PendingRequest *pr = value;
2393 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2396 destroy_pending_request (pr);
2403 * Method called whenever a given peer connects.
2405 * @param cls closure, not used
2406 * @param peer peer identity this notification is about
2407 * @param latency reported latency of the connection with 'other'
2408 * @param distance reported distance (DV) to 'other'
2411 peer_connect_handler (void *cls,
2413 GNUNET_PeerIdentity * peer,
2414 struct GNUNET_TIME_Relative latency,
2417 struct ConnectedPeer *cp;
2419 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2420 cp->pid = GNUNET_PEER_intern (peer);
2421 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2424 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2429 * Method called whenever a peer disconnects.
2431 * @param cls closure, not used
2432 * @param peer peer identity this notification is about
2435 peer_disconnect_handler (void *cls,
2437 GNUNET_PeerIdentity * peer)
2439 struct ConnectedPeer *cp;
2441 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2443 GNUNET_PEER_change_rc (cp->pid, -1);
2444 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2446 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2454 * We're processing a GET request from
2455 * another peer and have decided to forward
2456 * it to other peers.
2458 * @param cls our "struct ProcessGetContext *"
2462 forward_get_request (void *cls,
2463 const struct GNUNET_SCHEDULER_TaskContext *tc)
2465 struct ProcessGetContext *pgc = cls;
2466 struct PendingRequest *pr;
2467 struct PendingRequest *eer;
2468 struct GNUNET_PeerIdentity target;
2470 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2471 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2473 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2474 *pr->namespace = pgc->namespace;
2477 pr->bf_size = pgc->bf_size;
2479 pr->start_time = pgc->start_time;
2480 pr->query = pgc->query;
2481 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2482 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2483 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2484 pr->anonymity_level = 1; /* default */
2485 pr->priority = pgc->priority;
2486 pr->remaining_priority = pr->priority;
2487 pr->mingle = pgc->mingle;
2489 pr->type = pgc->type;
2490 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2493 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2494 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2495 &pgc->reply_to.hashPubKey,
2497 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2498 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2500 pr->start_time.value + pr->ttl);
2501 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2503 /* expire oldest request! */
2504 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2505 GNUNET_PEER_resolve (eer->source_pid,
2507 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2510 destroy_pending_request (eer);
2512 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2513 get_processing_delay (),
2514 &forward_request_task,
2519 * Transmit the given message by copying it to
2520 * the target buffer "buf". "buf" will be
2521 * NULL and "size" zero if the socket was closed for
2522 * writing in the meantime. In that case, only
2526 * @param cls closure, pointer to the message
2527 * @param size number of bytes available in buf
2528 * @param buf where the callee should write the message
2529 * @return number of bytes written to buf
2532 transmit_message (void *cls,
2533 size_t size, void *buf)
2535 struct GNUNET_MessageHeader *msg = cls;
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "Dropping reply, core too busy.\n");
2547 msize = ntohs (msg->size);
2548 GNUNET_assert (size >= msize);
2549 memcpy (buf, msg, msize);
2556 * Test if the load on this peer is too high
2557 * to even consider processing the query at
2560 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2563 test_load_too_high ()
2565 return GNUNET_NO; // FIXME
2570 * We're processing (local) results for a search request
2571 * from another peer. Pass applicable results to the
2572 * peer and if we are done either clean up (operation
2573 * complete) or forward to other peers (more results possible).
2575 * @param cls our closure (struct LocalGetContext)
2576 * @param key key for the content
2577 * @param size number of bytes in data
2578 * @param data content stored
2579 * @param type type of the content
2580 * @param priority priority of the content
2581 * @param anonymity anonymity-level for the content
2582 * @param expiration expiration time for the content
2583 * @param uid unique identifier for the datum;
2584 * maybe 0 if no unique identifier is available
2587 process_p2p_get_result (void *cls,
2588 const GNUNET_HashCode * key,
2594 struct GNUNET_TIME_Absolute
2598 struct ProcessGetContext *pgc = cls;
2599 GNUNET_HashCode dhash;
2600 GNUNET_HashCode mhash;
2601 struct PutMessage *reply;
2605 /* no more results */
2606 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2607 ( (0 == pgc->results_found) ||
2608 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2609 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2610 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2612 GNUNET_SCHEDULER_add_continuation (sched,
2613 &forward_get_request,
2615 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2619 if (pgc->bf != NULL)
2620 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2626 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2628 handle_on_demand_block (key, size, data, type, priority,
2629 anonymity, expiration, uid,
2630 &process_p2p_get_result,
2634 /* check for duplicates */
2635 GNUNET_CRYPTO_hash (data, size, &dhash);
2636 mingle_hash (&dhash,
2639 if ( (pgc->bf != NULL) &&
2641 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2646 "Result from datastore filtered by bloomfilter.\n");
2648 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2651 pgc->results_found++;
2652 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2653 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2654 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2656 if (pgc->bf == NULL)
2659 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2663 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2667 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2668 reply->header.size = htons (sizeof (struct PutMessage) + size);
2669 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2670 reply->type = htonl (type);
2671 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2672 memcpy (&reply[1], data, size);
2673 GNUNET_CORE_notify_transmit_ready (core,
2675 ACCEPTABLE_REPLY_DELAY,
2677 sizeof (struct PutMessage) + size,
2680 if ( (GNUNET_YES == test_load_too_high()) ||
2681 (pgc->results_found > 5 + 2 * pgc->priority) )
2683 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2684 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2687 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2692 * We're processing a GET request from another peer. Give it to our
2695 * @param cls our "struct ProcessGetContext"
2696 * @param ok did we get a datastore slice or not?
2699 ds_get_request (void *cls,
2702 struct ProcessGetContext *pgc = cls;
2704 struct GNUNET_TIME_Relative timeout;
2706 if (GNUNET_OK != ok)
2708 /* no point in doing P2P stuff if we can't even do local */
2713 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2714 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2715 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2716 (pgc->priority + 1));
2717 GNUNET_DATASTORE_get (dsh,
2720 &process_p2p_get_result,
2727 * The priority level imposes a bound on the maximum
2728 * value for the ttl that can be requested.
2730 * @param ttl_in requested ttl
2731 * @param prio given priority
2732 * @return ttl_in if ttl_in is below the limit,
2733 * otherwise the ttl-limit for the given priority
2736 bound_ttl (int32_t ttl_in, uint32_t prio)
2738 unsigned long long allowed;
2742 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2743 if (ttl_in > allowed)
2745 if (allowed >= (1 << 30))
2754 * We've received a request with the specified
2755 * priority. Bound it according to how much
2756 * we trust the given peer.
2758 * @param prio_in requested priority
2759 * @param peer the peer making the request
2760 * @return effective priority
2763 bound_priority (uint32_t prio_in,
2764 const struct GNUNET_PeerIdentity *peer)
2771 * Handle P2P "GET" request.
2773 * @param cls closure, always NULL
2774 * @param other the other peer involved (sender or receiver, NULL
2775 * for loopback messages where we are both sender and receiver)
2776 * @param message the actual message
2777 * @param latency reported latency of the connection with 'other'
2778 * @param distance reported distance (DV) to 'other'
2779 * @return GNUNET_OK to keep the connection open,
2780 * GNUNET_SYSERR to close it (signal serious error)
2783 handle_p2p_get (void *cls,
2784 const struct GNUNET_PeerIdentity *other,
2785 const struct GNUNET_MessageHeader *message,
2786 struct GNUNET_TIME_Relative latency,
2790 const struct GetMessage *gm;
2792 const GNUNET_HashCode *opt;
2793 struct ProcessGetContext *pgc;
2796 uint32_t ttl_decrement;
2801 msize = ntohs(message->size);
2802 if (msize < sizeof (struct GetMessage))
2804 GNUNET_break_op (0);
2805 return GNUNET_SYSERR;
2807 gm = (const struct GetMessage*) message;
2808 bm = ntohl (gm->hash_bitmap);
2816 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2818 GNUNET_break_op (0);
2819 return GNUNET_SYSERR;
2821 opt = (const GNUNET_HashCode*) &gm[1];
2822 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2823 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2826 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2829 pgc->bf_size = bfsize;
2831 pgc->type = ntohl (gm->type);
2832 pgc->bm = ntohl (gm->hash_bitmap);
2833 pgc->mingle = gm->filter_mutator;
2835 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2836 pgc->reply_to.hashPubKey = opt[bits++];
2838 pgc->reply_to = *other;
2839 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2840 pgc->namespace = opt[bits++];
2841 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2843 GNUNET_break_op (0);
2845 return GNUNET_SYSERR;
2847 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2848 pgc->prime_target.hashPubKey = opt[bits++];
2849 /* note that we can really only check load here since otherwise
2850 peers could find out that we are overloaded by being disconnected
2851 after sending us a malformed query... */
2852 if (GNUNET_YES == test_load_too_high ())
2854 if (NULL != pgc->bf)
2855 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2859 "Dropping query from `%s', this peer is too busy.\n",
2860 GNUNET_i2s (other));
2864 net_load_up = 50; // FIXME
2865 net_load_down = 50; // FIXME
2866 pgc->policy = ROUTING_POLICY_NONE;
2867 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2868 (net_load_down < IDLE_LOAD_THRESHOLD) )
2870 pgc->policy |= ROUTING_POLICY_ALL;
2871 pgc->priority = 0; /* no charge */
2875 pgc->priority = bound_priority (ntohl (gm->priority), other);
2877 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2879 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2881 pgc->policy |= ROUTING_POLICY_ALL;
2885 // FIXME: is this sound?
2886 if (net_load_up < 90 + 10 * pgc->priority)
2887 pgc->policy |= ROUTING_POLICY_FORWARD;
2888 if (net_load_down < 90 + 10 * pgc->priority)
2889 pgc->policy |= ROUTING_POLICY_ANSWER;
2892 if (pgc->policy == ROUTING_POLICY_NONE)
2895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2896 "Dropping query from `%s', network saturated.\n",
2897 GNUNET_i2s (other));
2899 if (NULL != pgc->bf)
2900 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2902 return GNUNET_OK; /* drop */
2904 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2905 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2906 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2907 /* decrement ttl (always) */
2908 ttl_decrement = 2 * TTL_DECREMENT +
2909 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2911 if ( (pgc->ttl < 0) &&
2912 (pgc->ttl - ttl_decrement > 0) )
2915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2916 "Dropping query from `%s' due to TTL underflow.\n",
2917 GNUNET_i2s (other));
2919 /* integer underflow => drop (should be very rare)! */
2920 if (NULL != pgc->bf)
2921 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2925 pgc->ttl -= ttl_decrement;
2926 pgc->start_time = GNUNET_TIME_absolute_get ();
2927 preference = (double) pgc->priority;
2928 if (preference < QUERY_BANDWIDTH_VALUE)
2929 preference = QUERY_BANDWIDTH_VALUE;
2930 // FIXME: also reserve bandwidth for reply?
2931 (void) GNUNET_CORE_peer_change_preference (sched, cfg,
2933 GNUNET_TIME_UNIT_FOREVER_REL,
2934 0, 0, preference, NULL, NULL);
2935 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2936 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2940 GNUNET_SCHEDULER_add_continuation (sched,
2941 &forward_get_request,
2943 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2949 * Function called to notify us that we can now transmit a reply to a
2950 * client or peer. "buf" will be NULL and "size" zero if the socket was
2951 * closed for writing in the meantime.
2953 * @param cls closure, points to a "struct PendingRequest*" with
2954 * one or more pending replies
2955 * @param size number of bytes available in buf
2956 * @param buf where the callee should write the message
2957 * @return number of bytes written to buf
2960 transmit_result (void *cls,
2964 struct PendingRequest *pr = cls;
2966 struct PendingReply *reply;
2970 while (NULL != (reply = pr->replies_pending))
2972 if ( (reply->msize + ret < ret) ||
2973 (reply->msize + ret > size) )
2975 pr->replies_pending = reply->next;
2976 memcpy (&cbuf[ret], &reply[1], reply->msize);
2977 ret += reply->msize;
2978 GNUNET_free (reply);
2985 * Iterator over pending requests.
2987 * @param cls response (struct ProcessReplyClosure)
2988 * @param key our query
2989 * @param value value in the hash map (meta-info about the query)
2990 * @return GNUNET_YES (we should continue to iterate)
2993 process_reply (void *cls,
2994 const GNUNET_HashCode * key,
2997 struct ProcessReplyClosure *prq = cls;
2998 struct PendingRequest *pr = value;
2999 struct PendingRequest *eer;
3000 struct PendingReply *reply;
3001 struct PutMessage *pm;
3002 struct ContentMessage *cm;
3003 GNUNET_HashCode chash;
3004 GNUNET_HashCode mhash;
3005 struct GNUNET_PeerIdentity target;
3008 struct GNUNET_TIME_Relative max_delay;
3010 GNUNET_CRYPTO_hash (prq->data,
3015 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3016 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3018 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3019 /* FIXME: does prq->namespace match our expectations? */
3020 /* then: fall-through??? */
3021 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3024 mingle_hash (&chash, pr->mingle, &mhash);
3025 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3027 return GNUNET_YES; /* duplicate */
3028 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3032 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3033 // FIXME: any checks against duplicates for SKBlocks?
3036 prio = pr->priority;
3037 prq->priority += pr->remaining_priority;
3038 pr->remaining_priority = 0;
3039 if (pr->client != NULL)
3041 if (pr->replies_seen_size == pr->replies_seen_off)
3042 GNUNET_array_grow (pr->replies_seen,
3043 pr->replies_seen_size,
3044 pr->replies_seen_size * 2 + 4);
3045 pr->replies_seen[pr->replies_seen_off++] = chash;
3046 // FIXME: possibly recalculate BF!
3048 if (pr->client == NULL)
3050 msize = sizeof (struct ContentMessage) + prq->size;
3051 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3052 reply->msize = msize;
3053 cm = (struct ContentMessage*) &reply[1];
3054 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3055 cm->header.size = htons (msize);
3056 cm->type = htonl (prq->type);
3057 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3058 reply->next = pr->replies_pending;
3059 pr->replies_pending = reply;
3060 memcpy (&reply[1], prq->data, prq->size);
3061 if (pr->cth != NULL)
3063 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3064 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3066 /* estimate expiration time from time difference between
3067 first request that will be discarded and this request */
3068 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3069 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3072 GNUNET_PEER_resolve (pr->source_pid,
3074 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3081 if (NULL == pr->cth)
3083 // FIXME: now what? discard?
3088 msize = sizeof (struct PutMessage) + prq->size;
3089 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3090 reply->msize = msize;
3091 reply->next = pr->replies_pending;
3092 pm = (struct PutMessage*) &reply[1];
3093 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3094 pm->header.size = htons (msize);
3095 pm->type = htonl (prq->type);
3096 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3097 pr->replies_pending = reply;
3098 memcpy (&reply[1], prq->data, prq->size);
3101 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3103 GNUNET_TIME_UNIT_FOREVER_REL,
3108 // FIXME: need to try again later (not much
3109 // to do here specifically, but we need to
3110 // check somewhere else to handle this case!)
3113 // FIXME: implement hot-path routing statistics keeping!
3119 * Check if the given KBlock is well-formed.
3121 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3122 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3123 * @param query where to store the query that this block answers
3124 * @return GNUNET_OK if this is actually a well-formed KBlock
3127 check_kblock (const struct KBlock *kb,
3129 GNUNET_HashCode *query)
3131 if (dsize < sizeof (struct KBlock))
3133 GNUNET_break_op (0);
3134 return GNUNET_SYSERR;
3136 if (dsize - sizeof (struct KBlock) !=
3137 ntohs (kb->purpose.size)
3138 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3139 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3141 GNUNET_break_op (0);
3142 return GNUNET_SYSERR;
3145 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3150 GNUNET_break_op (0);
3151 return GNUNET_SYSERR;
3154 GNUNET_CRYPTO_hash (&kb->keyspace,
3155 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3162 * Check if the given SBlock is well-formed.
3164 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3165 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3166 * @param query where to store the query that this block answers
3167 * @param namespace where to store the namespace that this block belongs to
3168 * @return GNUNET_OK if this is actually a well-formed SBlock
3171 check_sblock (const struct SBlock *sb,
3173 GNUNET_HashCode *query,
3174 GNUNET_HashCode *namespace)
3176 if (dsize < sizeof (struct SBlock))
3178 GNUNET_break_op (0);
3179 return GNUNET_SYSERR;
3182 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3184 GNUNET_break_op (0);
3185 return GNUNET_SYSERR;
3188 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3193 GNUNET_break_op (0);
3194 return GNUNET_SYSERR;
3197 *query = sb->identifier;
3198 if (namespace != NULL)
3199 GNUNET_CRYPTO_hash (&sb->subspace,
3200 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3207 * Handle P2P "PUT" request.
3209 * @param cls closure, always NULL
3210 * @param other the other peer involved (sender or receiver, NULL
3211 * for loopback messages where we are both sender and receiver)
3212 * @param message the actual message
3213 * @param latency reported latency of the connection with 'other'
3214 * @param distance reported distance (DV) to 'other'
3215 * @return GNUNET_OK to keep the connection open,
3216 * GNUNET_SYSERR to close it (signal serious error)
3219 handle_p2p_put (void *cls,
3220 const struct GNUNET_PeerIdentity *other,
3221 const struct GNUNET_MessageHeader *message,
3222 struct GNUNET_TIME_Relative latency,
3225 const struct PutMessage *put;
3229 struct GNUNET_TIME_Absolute expiration;
3230 GNUNET_HashCode query;
3231 struct ProcessReplyClosure prq;
3233 msize = ntohs (message->size);
3234 if (msize < sizeof (struct PutMessage))
3237 return GNUNET_SYSERR;
3239 put = (const struct PutMessage*) message;
3240 dsize = msize - sizeof (struct PutMessage);
3241 type = ntohl (put->type);
3242 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3244 /* first, validate! */
3247 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3248 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3249 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3251 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3253 check_kblock ((const struct KBlock*) &put[1],
3256 return GNUNET_SYSERR;
3258 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3260 check_sblock ((const struct SBlock*) &put[1],
3264 return GNUNET_SYSERR;
3266 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3267 // FIXME -- validate SKBLOCK!
3271 /* unknown block type */
3272 GNUNET_break_op (0);
3273 return GNUNET_SYSERR;
3276 /* now, lookup 'query' */
3277 prq.data = (const void*) &put[1];
3280 prq.expiration = expiration;
3282 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3286 // FIXME: if migration is on and load is low,
3287 // queue to store data in datastore;
3288 // use "prq.priority" for that!
3294 * List of handlers for P2P messages
3295 * that we care about.
3297 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3300 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3302 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3308 * Process fs requests.
3310 * @param cls closure
3311 * @param s scheduler to use
3312 * @param server the initialized server
3313 * @param c configuration to use
3317 struct GNUNET_SCHEDULER_Handle *s,
3318 struct GNUNET_SERVER_Handle *server,
3319 const struct GNUNET_CONFIGURATION_Handle *c)
3324 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3325 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3326 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3327 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3328 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3330 dsh = GNUNET_DATASTORE_connect (cfg,
3332 core = GNUNET_CORE_connect (sched,
3334 GNUNET_TIME_UNIT_FOREVER_REL,
3338 &peer_connect_handler,
3339 &peer_disconnect_handler,
3344 GNUNET_SERVER_disconnect_notify (server,
3345 &handle_client_disconnect,
3347 GNUNET_SERVER_add_handlers (server, handlers);
3348 GNUNET_SCHEDULER_add_delayed (sched,
3349 GNUNET_TIME_UNIT_FOREVER_REL,
3354 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3355 _("Failed to connect to `%s' service.\n"),
3357 GNUNET_SCHEDULER_shutdown (sched);
3362 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3363 _("Failed to connect to `%s' service.\n"),
3365 GNUNET_SCHEDULER_shutdown (sched);
3372 * The main function for the fs service.
3374 * @param argc number of arguments from the command line
3375 * @param argv command line arguments
3376 * @return 0 ok, 1 on error
3379 main (int argc, char *const *argv)
3381 return (GNUNET_OK ==
3382 GNUNET_SERVICE_run (argc,
3385 GNUNET_SERVICE_OPTION_NONE,
3386 &run, NULL)) ? 0 : 1;
3389 /* end of gnunet-service-fs.c */