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_get_info 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 = pos->next;
1182 prev->next = pos->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 latency current latency estimate, "FOREVER" if we have been
1775 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1776 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1777 * @param amount set to the amount that was actually reserved or unreserved
1778 * @param preference current traffic preference for the given peer
1781 target_reservation_cb (void *cls,
1783 GNUNET_PeerIdentity * peer,
1784 unsigned int bpm_in,
1785 unsigned int bpm_out,
1786 struct GNUNET_TIME_Relative
1787 latency, int amount,
1788 unsigned long long preference)
1790 struct PendingRequest *pr = cls;
1793 struct GNUNET_TIME_Relative maxdelay;
1796 GNUNET_assert (peer != NULL);
1797 if ( (amount != DBLOCK_SIZE) ||
1800 /* try again later; FIXME: we may need to un-reserve "amount"? */
1801 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1802 get_processing_delay (), // FIXME: longer?
1803 &forward_request_task,
1807 // (2) transmit, update ttl/priority
1808 // FIXME: calculate priority, maxdelay, size properly!
1811 maxdelay = GNUNET_CONSTANTS_SERVICE_TIMEOUT;
1812 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
1817 &transmit_request_cb,
1819 if (pr->cth == NULL)
1821 /* try again later */
1822 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1823 get_processing_delay (), // FIXME: longer?
1824 &forward_request_task,
1831 * Task that is run for each request with the
1832 * goal of forwarding the associated query to
1833 * other peers. The task should re-schedule
1834 * itself to be re-run once the TTL has expired.
1835 * (or at a later time if more peers should
1836 * be queried earlier).
1838 * @param cls the requests "struct PendingRequest*"
1839 * @param tc task context (unused)
1842 forward_request_task (void *cls,
1843 const struct GNUNET_SCHEDULER_TaskContext *tc)
1845 struct PendingRequest *pr = cls;
1846 struct PeerSelectionContext psc;
1848 pr->task = GNUNET_SCHEDULER_NO_TASK;
1849 if (pr->cth != NULL)
1851 /* we're busy transmitting a result, wait a bit */
1852 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1853 get_processing_delay (),
1854 &forward_request_task,
1858 /* (1) select target */
1860 psc.target_score = DBL_MIN;
1861 GNUNET_CONTAINER_multihashmap_iterate (connected_peers,
1862 &target_peer_select_cb,
1864 if (psc.target_score == DBL_MIN)
1866 /* no possible target found, wait some time */
1867 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1868 get_processing_delay (), // FIXME: exponential back-off? or at least wait longer...
1869 &forward_request_task,
1873 /* (2) reserve reply bandwidth */
1874 GNUNET_assert (NULL == pr->irc);
1875 pr->irc = GNUNET_CORE_peer_get_info (sched, cfg,
1877 GNUNET_CONSTANTS_SERVICE_TIMEOUT,
1879 DBLOCK_SIZE, // FIXME: make dependent on type?
1881 &target_reservation_cb,
1887 * We're processing (local) results for a search request
1888 * from a (local) client. Pass applicable results to the
1889 * client and if we are done either clean up (operation
1890 * complete) or switch to P2P search (more results possible).
1892 * @param cls our closure (struct LocalGetContext)
1893 * @param key key for the content
1894 * @param size number of bytes in data
1895 * @param data content stored
1896 * @param type type of the content
1897 * @param priority priority of the content
1898 * @param anonymity anonymity-level for the content
1899 * @param expiration expiration time for the content
1900 * @param uid unique identifier for the datum;
1901 * maybe 0 if no unique identifier is available
1904 process_local_get_result (void *cls,
1905 const GNUNET_HashCode * key,
1911 struct GNUNET_TIME_Absolute
1915 struct LocalGetContext *lgc = cls;
1916 struct PendingRequest *pr;
1917 struct ClientRequestList *crl;
1918 struct ClientList *cl;
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "Received last result for `%s' from local datastore, deciding what to do next.\n",
1927 GNUNET_h2s (&lgc->query));
1929 /* no further results from datastore; continue
1930 processing further requests from the client and
1931 allow the next task to use the datastore; also,
1932 switch to P2P requests or clean up our state. */
1934 GNUNET_SERVER_receive_done (lgc->client,
1936 if ( (lgc->results_used == 0) ||
1937 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
1938 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
1939 (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
1942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943 "Forwarding query for `%s' to network.\n",
1944 GNUNET_h2s (&lgc->query));
1947 while ( (NULL != cl) &&
1948 (cl->client != lgc->client) )
1952 cl = GNUNET_malloc (sizeof (struct ClientList));
1953 cl->client = lgc->client;
1957 crl = GNUNET_malloc (sizeof (struct ClientRequestList));
1959 GNUNET_CONTAINER_DLL_insert (cl->head, cl->tail, crl);
1960 pr = GNUNET_malloc (sizeof (struct PendingRequest));
1961 pr->client = lgc->client;
1962 GNUNET_SERVER_client_keep (pr->client);
1963 pr->crl_entry = crl;
1965 if (lgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
1967 pr->namespace = GNUNET_malloc (sizeof (GNUNET_HashCode));
1968 *pr->namespace = lgc->namespace;
1970 pr->replies_seen = lgc->results;
1971 lgc->results = NULL;
1972 pr->start_time = GNUNET_TIME_absolute_get ();
1973 pr->query = lgc->query;
1974 pr->target_pid = GNUNET_PEER_intern (&lgc->target);
1975 pr->replies_seen_off = lgc->results_used;
1976 pr->replies_seen_size = lgc->results_size;
1977 lgc->results_size = 0;
1978 pr->type = lgc->type;
1979 pr->anonymity_level = lgc->anonymity_level;
1980 pr->bf = refresh_bloomfilter (pr->replies_seen_off,
1984 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
1987 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
1988 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
1989 get_processing_delay (),
1990 &forward_request_task,
1992 local_get_context_free (lgc);
1995 /* got all possible results, clean up! */
1997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998 "Found all possible results for query for `%s', done!\n",
1999 GNUNET_h2s (&lgc->query));
2001 local_get_context_free (lgc);
2004 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "Received on-demand block for `%s' from local datastore, fetching data.\n",
2009 GNUNET_h2s (&lgc->query));
2011 handle_on_demand_block (key, size, data, type, priority,
2012 anonymity, expiration, uid,
2013 &process_local_get_result,
2017 if ( (type != lgc->type) &&
2018 (lgc->type != GNUNET_DATASTORE_BLOCKTYPE_ANY) )
2020 /* this should be virtually impossible to reach (DBLOCK
2021 query hash being identical to KBLOCK/SBLOCK query hash);
2022 nevertheless, if it happens, the correct thing is to
2023 simply skip the result. */
2025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2026 "Received block of unexpected type (%u, want %u) for `%s' from local datastore, ignoring.\n",
2029 GNUNET_h2s (&lgc->query));
2031 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2034 /* check if this is a result we've alredy
2036 for (i=0;i<lgc->results_used;i++)
2037 if (0 == memcmp (key,
2039 sizeof (GNUNET_HashCode)))
2042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2043 "Received duplicate result for `%s' from local datastore, ignoring.\n",
2044 GNUNET_h2s (&lgc->query));
2046 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2049 if (lgc->results_used == lgc->results_size)
2050 GNUNET_array_grow (lgc->results,
2052 lgc->results_size * 2 + 2);
2053 GNUNET_CRYPTO_hash (data,
2055 &lgc->results[lgc->results_used++]);
2056 msize = size + sizeof (struct ContentMessage);
2057 GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
2058 lgc->result = GNUNET_malloc (msize);
2059 lgc->result->header.size = htons (msize);
2060 lgc->result->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
2061 lgc->result->type = htonl (type);
2062 lgc->result->expiration = GNUNET_TIME_absolute_hton (expiration);
2063 memcpy (&lgc->result[1],
2067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2068 "Received new result for `%s' from local datastore, passing to client.\n",
2069 GNUNET_h2s (&lgc->query));
2071 GNUNET_SERVER_notify_transmit_ready (lgc->client,
2073 GNUNET_TIME_UNIT_FOREVER_REL,
2074 &transmit_local_result,
2080 * We're processing a search request from a local
2081 * client. Now it is our turn to query the datastore.
2083 * @param cls our closure (struct LocalGetContext)
2087 transmit_local_get (void *cls,
2088 const struct GNUNET_SCHEDULER_TaskContext *tc)
2090 struct LocalGetContext *lgc = cls;
2094 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2095 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2096 GNUNET_DATASTORE_get (dsh,
2099 &process_local_get_result,
2101 GNUNET_TIME_UNIT_FOREVER_REL);
2106 * We're processing a search request from a local
2107 * client. Now it is our turn to query the datastore.
2109 * @param cls our closure (struct LocalGetContext)
2110 * @param ok did we succeed to queue for datastore access, should always be GNUNET_OK
2113 transmit_local_get_ready (void *cls,
2116 struct LocalGetContext *lgc = cls;
2118 GNUNET_assert (GNUNET_OK == ok);
2119 GNUNET_SCHEDULER_add_continuation (sched,
2120 &transmit_local_get,
2122 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2127 * Handle START_SEARCH-message (search request from client).
2129 * @param cls closure
2130 * @param client identification of the client
2131 * @param message the actual message
2134 handle_start_search (void *cls,
2135 struct GNUNET_SERVER_Client *client,
2136 const struct GNUNET_MessageHeader *message)
2138 const struct SearchMessage *sm;
2139 struct LocalGetContext *lgc;
2143 msize = ntohs (message->size);
2144 if ( (msize < sizeof (struct SearchMessage)) ||
2145 (0 != (msize - sizeof (struct SearchMessage)) % sizeof (GNUNET_HashCode)) )
2148 GNUNET_SERVER_receive_done (client,
2152 sc = (msize - sizeof (struct SearchMessage)) / sizeof (GNUNET_HashCode);
2153 sm = (const struct SearchMessage*) message;
2154 GNUNET_SERVER_client_keep (client);
2155 lgc = GNUNET_malloc (sizeof (struct LocalGetContext));
2158 lgc->results_used = sc;
2159 GNUNET_array_grow (lgc->results,
2162 memcpy (lgc->results,
2164 sc * sizeof (GNUNET_HashCode));
2166 lgc->client = client;
2167 lgc->type = ntohl (sm->type);
2168 lgc->anonymity_level = ntohl (sm->anonymity_level);
2171 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
2172 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
2173 lgc->target.hashPubKey = sm->target;
2175 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
2176 lgc->namespace = sm->target;
2181 lgc->query = sm->query;
2182 GNUNET_CONTAINER_DLL_insert (lgc_head, lgc_tail, lgc);
2183 lgc->req = queue_ds_request (GNUNET_TIME_UNIT_FOREVER_REL,
2184 &transmit_local_get_ready,
2190 * List of handlers for the messages understood by this
2193 static struct GNUNET_SERVER_MessageHandler handlers[] = {
2194 {&handle_index_start, NULL,
2195 GNUNET_MESSAGE_TYPE_FS_INDEX_START, 0},
2196 {&handle_index_list_get, NULL,
2197 GNUNET_MESSAGE_TYPE_FS_INDEX_LIST_GET, sizeof(struct GNUNET_MessageHeader) },
2198 {&handle_unindex, NULL, GNUNET_MESSAGE_TYPE_FS_UNINDEX,
2199 sizeof (struct UnindexMessage) },
2200 {&handle_start_search, NULL, GNUNET_MESSAGE_TYPE_FS_START_SEARCH,
2207 * Clean up the memory used by the PendingRequest structure (except
2208 * for the client or peer list that the request may be part of).
2210 * @param pr request to clean up
2213 destroy_pending_request (struct PendingRequest *pr)
2215 struct PendingReply *reply;
2216 struct ClientList *cl;
2218 GNUNET_CONTAINER_multihashmap_remove (requests_by_query,
2221 // FIXME: not sure how this can work (efficiently)
2222 // also, what does the return value mean?
2223 if (pr->irc != NULL)
2225 GNUNET_CORE_peer_get_info_cancel (pr->irc);
2228 if (pr->client == NULL)
2230 GNUNET_CONTAINER_heap_remove_node (requests_by_expiration,
2235 cl = pr->crl_entry->cl;
2236 GNUNET_CONTAINER_DLL_remove (cl->head,
2240 if (GNUNET_SCHEDULER_NO_TASK != pr->task)
2241 GNUNET_SCHEDULER_cancel (sched, pr->task);
2242 if (NULL != pr->cth)
2243 GNUNET_CORE_notify_transmit_ready_cancel (pr->cth);
2245 GNUNET_CONTAINER_bloomfilter_free (pr->bf);
2247 GNUNET_CONNECTION_notify_transmit_ready_cancel (pr->th);
2248 while (NULL != (reply = pr->replies_pending))
2250 pr->replies_pending = reply->next;
2251 GNUNET_free (reply);
2253 GNUNET_PEER_change_rc (pr->source_pid, -1);
2254 GNUNET_PEER_change_rc (pr->target_pid, -1);
2255 GNUNET_PEER_decrement_rcs (pr->used_pids, pr->used_pids_off);
2256 GNUNET_free_non_null (pr->used_pids);
2257 GNUNET_free_non_null (pr->replies_seen);
2258 GNUNET_free_non_null (pr->namespace);
2264 * A client disconnected. Remove all of its pending queries.
2266 * @param cls closure, NULL
2267 * @param client identification of the client
2270 handle_client_disconnect (void *cls,
2271 struct GNUNET_SERVER_Client
2274 struct LocalGetContext *lgc;
2275 struct ClientList *cpos;
2276 struct ClientList *cprev;
2277 struct ClientRequestList *rl;
2280 while ( (NULL != lgc) &&
2281 (lgc->client != client) )
2284 local_get_context_free (lgc);
2287 while ( (NULL != cpos) &&
2288 (clients->client != client) )
2296 clients = cpos->next;
2298 cprev->next = cpos->next;
2299 while (NULL != (rl = cpos->head))
2301 cpos->head = rl->next;
2302 destroy_pending_request (rl->req);
2311 * Iterator over entries in the "requests_by_query" map
2312 * that frees all the entries.
2314 * @param cls closure, NULL
2315 * @param key current key code (the query, unused)
2316 * @param value value in the hash map, of type "struct PendingRequest*"
2317 * @return GNUNET_YES (we should continue to iterate)
2320 destroy_pending_request_cb (void *cls,
2321 const GNUNET_HashCode * key,
2324 struct PendingRequest *pr = value;
2326 destroy_pending_request (pr);
2332 * Task run during shutdown.
2338 shutdown_task (void *cls,
2339 const struct GNUNET_SCHEDULER_TaskContext *tc)
2341 struct IndexInfo *pos;
2345 GNUNET_CORE_disconnect (core);
2350 GNUNET_DATASTORE_disconnect (dsh,
2354 GNUNET_CONTAINER_multihashmap_iterate (requests_by_query,
2355 &destroy_pending_request_cb,
2357 while (clients != NULL)
2358 handle_client_disconnect (NULL,
2360 GNUNET_CONTAINER_multihashmap_destroy (requests_by_query);
2361 requests_by_query = NULL;
2362 GNUNET_CONTAINER_multihashmap_destroy (requests_by_peer);
2363 requests_by_peer = NULL;
2364 GNUNET_CONTAINER_heap_destroy (requests_by_expiration);
2365 requests_by_expiration = NULL;
2366 // FIXME: iterate over entries and free individually?
2367 // (or do we get disconnect notifications?)
2368 GNUNET_CONTAINER_multihashmap_destroy (connected_peers);
2369 connected_peers = NULL;
2370 GNUNET_CONTAINER_multihashmap_destroy (ifm);
2372 while (NULL != (pos = indexed_files))
2374 indexed_files = pos->next;
2381 * Free (each) request made by the peer.
2383 * @param cls closure, points to peer that the request belongs to
2384 * @param key current key code
2385 * @param value value in the hash map
2386 * @return GNUNET_YES (we should continue to iterate)
2389 destroy_request (void *cls,
2390 const GNUNET_HashCode * key,
2393 const struct GNUNET_PeerIdentity * peer = cls;
2394 struct PendingRequest *pr = value;
2396 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2399 destroy_pending_request (pr);
2406 * Method called whenever a given peer connects.
2408 * @param cls closure, not used
2409 * @param peer peer identity this notification is about
2412 peer_connect_handler (void *cls,
2414 GNUNET_PeerIdentity * peer)
2416 struct ConnectedPeer *cp;
2418 cp = GNUNET_malloc (sizeof (struct ConnectedPeer));
2419 cp->pid = GNUNET_PEER_intern (peer);
2420 GNUNET_CONTAINER_multihashmap_put (connected_peers,
2423 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2428 * Method called whenever a peer disconnects.
2430 * @param cls closure, not used
2431 * @param peer peer identity this notification is about
2434 peer_disconnect_handler (void *cls,
2436 GNUNET_PeerIdentity * peer)
2438 struct ConnectedPeer *cp;
2440 cp = GNUNET_CONTAINER_multihashmap_get (connected_peers,
2442 GNUNET_PEER_change_rc (cp->pid, -1);
2443 GNUNET_PEER_decrement_rcs (cp->last_p2p_replies, P2P_SUCCESS_LIST_SIZE);
2445 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_peer,
2453 * We're processing a GET request from
2454 * another peer and have decided to forward
2455 * it to other peers.
2457 * @param cls our "struct ProcessGetContext *"
2461 forward_get_request (void *cls,
2462 const struct GNUNET_SCHEDULER_TaskContext *tc)
2464 struct ProcessGetContext *pgc = cls;
2465 struct PendingRequest *pr;
2466 struct PendingRequest *eer;
2467 struct GNUNET_PeerIdentity target;
2469 pr = GNUNET_malloc (sizeof (struct PendingRequest));
2470 if (GET_MESSAGE_BIT_SKS_NAMESPACE == (GET_MESSAGE_BIT_SKS_NAMESPACE & pgc->bm))
2472 pr->namespace = GNUNET_malloc (sizeof(GNUNET_HashCode));
2473 *pr->namespace = pgc->namespace;
2476 pr->bf_size = pgc->bf_size;
2478 pr->start_time = pgc->start_time;
2479 pr->query = pgc->query;
2480 pr->source_pid = GNUNET_PEER_intern (&pgc->reply_to);
2481 if (GET_MESSAGE_BIT_TRANSMIT_TO == (GET_MESSAGE_BIT_TRANSMIT_TO & pgc->bm))
2482 pr->target_pid = GNUNET_PEER_intern (&pgc->prime_target);
2483 pr->anonymity_level = 1; /* default */
2484 pr->priority = pgc->priority;
2485 pr->remaining_priority = pr->priority;
2486 pr->mingle = pgc->mingle;
2488 pr->type = pgc->type;
2489 GNUNET_CONTAINER_multihashmap_put (requests_by_query,
2492 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2493 GNUNET_CONTAINER_multihashmap_put (requests_by_peer,
2494 &pgc->reply_to.hashPubKey,
2496 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
2497 pr->hnode = GNUNET_CONTAINER_heap_insert (requests_by_expiration,
2499 pr->start_time.value + pr->ttl);
2500 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) > max_pending_requests)
2502 /* expire oldest request! */
2503 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
2504 GNUNET_PEER_resolve (eer->source_pid,
2506 GNUNET_CONTAINER_multihashmap_remove (requests_by_peer,
2509 destroy_pending_request (eer);
2511 pr->task = GNUNET_SCHEDULER_add_delayed (sched,
2512 get_processing_delay (),
2513 &forward_request_task,
2518 * Transmit the given message by copying it to
2519 * the target buffer "buf". "buf" will be
2520 * NULL and "size" zero if the socket was closed for
2521 * writing in the meantime. In that case, only
2525 * @param cls closure, pointer to the message
2526 * @param size number of bytes available in buf
2527 * @param buf where the callee should write the message
2528 * @return number of bytes written to buf
2531 transmit_message (void *cls,
2532 size_t size, void *buf)
2534 struct GNUNET_MessageHeader *msg = cls;
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "Dropping reply, core too busy.\n");
2546 msize = ntohs (msg->size);
2547 GNUNET_assert (size >= msize);
2548 memcpy (buf, msg, msize);
2555 * Test if the load on this peer is too high
2556 * to even consider processing the query at
2559 * @return GNUNET_YES if the load is too high, GNUNET_NO otherwise
2562 test_load_too_high ()
2564 return GNUNET_NO; // FIXME
2569 * We're processing (local) results for a search request
2570 * from another peer. Pass applicable results to the
2571 * peer and if we are done either clean up (operation
2572 * complete) or forward to other peers (more results possible).
2574 * @param cls our closure (struct LocalGetContext)
2575 * @param key key for the content
2576 * @param size number of bytes in data
2577 * @param data content stored
2578 * @param type type of the content
2579 * @param priority priority of the content
2580 * @param anonymity anonymity-level for the content
2581 * @param expiration expiration time for the content
2582 * @param uid unique identifier for the datum;
2583 * maybe 0 if no unique identifier is available
2586 process_p2p_get_result (void *cls,
2587 const GNUNET_HashCode * key,
2593 struct GNUNET_TIME_Absolute
2597 struct ProcessGetContext *pgc = cls;
2598 GNUNET_HashCode dhash;
2599 GNUNET_HashCode mhash;
2600 struct PutMessage *reply;
2604 /* no more results */
2605 if ( ( (pgc->policy & ROUTING_POLICY_FORWARD) == ROUTING_POLICY_FORWARD) &&
2606 ( (0 == pgc->results_found) ||
2607 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2608 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2609 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) ) )
2611 GNUNET_SCHEDULER_add_continuation (sched,
2612 &forward_get_request,
2614 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2618 if (pgc->bf != NULL)
2619 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2625 if (type == GNUNET_DATASTORE_BLOCKTYPE_ONDEMAND)
2627 handle_on_demand_block (key, size, data, type, priority,
2628 anonymity, expiration, uid,
2629 &process_p2p_get_result,
2633 /* check for duplicates */
2634 GNUNET_CRYPTO_hash (data, size, &dhash);
2635 mingle_hash (&dhash,
2638 if ( (pgc->bf != NULL) &&
2640 GNUNET_CONTAINER_bloomfilter_test (pgc->bf,
2644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645 "Result from datastore filtered by bloomfilter.\n");
2647 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2650 pgc->results_found++;
2651 if ( (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_KBLOCK) ||
2652 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK) ||
2653 (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK) )
2655 if (pgc->bf == NULL)
2658 pgc->bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
2662 GNUNET_CONTAINER_bloomfilter_add (pgc->bf,
2666 reply = GNUNET_malloc (sizeof (struct PutMessage) + size);
2667 reply->header.size = htons (sizeof (struct PutMessage) + size);
2668 reply->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
2669 reply->type = htonl (type);
2670 reply->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (expiration));
2671 memcpy (&reply[1], data, size);
2672 GNUNET_CORE_notify_transmit_ready (core,
2674 ACCEPTABLE_REPLY_DELAY,
2676 sizeof (struct PutMessage) + size,
2679 if ( (GNUNET_YES == test_load_too_high()) ||
2680 (pgc->results_found > 5 + 2 * pgc->priority) )
2682 GNUNET_DATASTORE_get_next (dsh, GNUNET_NO);
2683 pgc->policy &= ~ ROUTING_POLICY_FORWARD;
2686 GNUNET_DATASTORE_get_next (dsh, GNUNET_YES);
2691 * We're processing a GET request from another peer. Give it to our
2694 * @param cls our "struct ProcessGetContext"
2695 * @param ok did we get a datastore slice or not?
2698 ds_get_request (void *cls,
2701 struct ProcessGetContext *pgc = cls;
2703 struct GNUNET_TIME_Relative timeout;
2705 if (GNUNET_OK != ok)
2707 /* no point in doing P2P stuff if we can't even do local */
2712 if (type == GNUNET_DATASTORE_BLOCKTYPE_DBLOCK)
2713 type = GNUNET_DATASTORE_BLOCKTYPE_ANY; /* to get on-demand as well */
2714 timeout = GNUNET_TIME_relative_multiply (BASIC_DATASTORE_REQUEST_DELAY,
2715 (pgc->priority + 1));
2716 GNUNET_DATASTORE_get (dsh,
2719 &process_p2p_get_result,
2726 * The priority level imposes a bound on the maximum
2727 * value for the ttl that can be requested.
2729 * @param ttl_in requested ttl
2730 * @param prio given priority
2731 * @return ttl_in if ttl_in is below the limit,
2732 * otherwise the ttl-limit for the given priority
2735 bound_ttl (int32_t ttl_in, uint32_t prio)
2737 unsigned long long allowed;
2741 allowed = ((unsigned long long) prio) * TTL_DECREMENT / 1000;
2742 if (ttl_in > allowed)
2744 if (allowed >= (1 << 30))
2753 * We've received a request with the specified
2754 * priority. Bound it according to how much
2755 * we trust the given peer.
2757 * @param prio_in requested priority
2758 * @param peer the peer making the request
2759 * @return effective priority
2762 bound_priority (uint32_t prio_in,
2763 const struct GNUNET_PeerIdentity *peer)
2770 * Handle P2P "GET" request.
2772 * @param cls closure, always NULL
2773 * @param other the other peer involved (sender or receiver, NULL
2774 * for loopback messages where we are both sender and receiver)
2775 * @param message the actual message
2776 * @return GNUNET_OK to keep the connection open,
2777 * GNUNET_SYSERR to close it (signal serious error)
2780 handle_p2p_get (void *cls,
2781 const struct GNUNET_PeerIdentity *other,
2782 const struct GNUNET_MessageHeader *message)
2785 const struct GetMessage *gm;
2787 const GNUNET_HashCode *opt;
2788 struct ProcessGetContext *pgc;
2791 uint32_t ttl_decrement;
2796 msize = ntohs(message->size);
2797 if (msize < sizeof (struct GetMessage))
2799 GNUNET_break_op (0);
2800 return GNUNET_SYSERR;
2802 gm = (const struct GetMessage*) message;
2803 bm = ntohl (gm->hash_bitmap);
2811 if (msize < sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode))
2813 GNUNET_break_op (0);
2814 return GNUNET_SYSERR;
2816 opt = (const GNUNET_HashCode*) &gm[1];
2817 bfsize = msize - sizeof (struct GetMessage) + bits * sizeof (GNUNET_HashCode);
2818 pgc = GNUNET_malloc (sizeof (struct ProcessGetContext));
2821 pgc->bf = GNUNET_CONTAINER_bloomfilter_init ((const char*) &pgc[1],
2824 pgc->bf_size = bfsize;
2826 pgc->type = ntohl (gm->type);
2827 pgc->bm = ntohl (gm->hash_bitmap);
2828 pgc->mingle = gm->filter_mutator;
2830 if (0 != (pgc->bm & GET_MESSAGE_BIT_RETURN_TO))
2831 pgc->reply_to.hashPubKey = opt[bits++];
2833 pgc->reply_to = *other;
2834 if (0 != (pgc->bm & GET_MESSAGE_BIT_SKS_NAMESPACE))
2835 pgc->namespace = opt[bits++];
2836 else if (pgc->type == GNUNET_DATASTORE_BLOCKTYPE_SBLOCK)
2838 GNUNET_break_op (0);
2840 return GNUNET_SYSERR;
2842 if (0 != (pgc->bm & GET_MESSAGE_BIT_TRANSMIT_TO))
2843 pgc->prime_target.hashPubKey = opt[bits++];
2844 /* note that we can really only check load here since otherwise
2845 peers could find out that we are overloaded by being disconnected
2846 after sending us a malformed query... */
2847 if (GNUNET_YES == test_load_too_high ())
2849 if (NULL != pgc->bf)
2850 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2853 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2854 "Dropping query from `%s', this peer is too busy.\n",
2855 GNUNET_i2s (other));
2859 net_load_up = 50; // FIXME
2860 net_load_down = 50; // FIXME
2861 pgc->policy = ROUTING_POLICY_NONE;
2862 if ( (net_load_up < IDLE_LOAD_THRESHOLD) &&
2863 (net_load_down < IDLE_LOAD_THRESHOLD) )
2865 pgc->policy |= ROUTING_POLICY_ALL;
2866 pgc->priority = 0; /* no charge */
2870 pgc->priority = bound_priority (ntohl (gm->priority), other);
2872 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) &&
2874 IDLE_LOAD_THRESHOLD + pgc->priority * pgc->priority) )
2876 pgc->policy |= ROUTING_POLICY_ALL;
2880 // FIXME: is this sound?
2881 if (net_load_up < 90 + 10 * pgc->priority)
2882 pgc->policy |= ROUTING_POLICY_FORWARD;
2883 if (net_load_down < 90 + 10 * pgc->priority)
2884 pgc->policy |= ROUTING_POLICY_ANSWER;
2887 if (pgc->policy == ROUTING_POLICY_NONE)
2890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2891 "Dropping query from `%s', network saturated.\n",
2892 GNUNET_i2s (other));
2894 if (NULL != pgc->bf)
2895 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2897 return GNUNET_OK; /* drop */
2899 if ((pgc->policy & ROUTING_POLICY_INDIRECT) != ROUTING_POLICY_INDIRECT)
2900 pgc->priority = 0; /* kill the priority (we cannot benefit) */
2901 pgc->ttl = bound_ttl (ntohl (gm->ttl), pgc->priority);
2902 /* decrement ttl (always) */
2903 ttl_decrement = 2 * TTL_DECREMENT +
2904 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2906 if ( (pgc->ttl < 0) &&
2907 (pgc->ttl - ttl_decrement > 0) )
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911 "Dropping query from `%s' due to TTL underflow.\n",
2912 GNUNET_i2s (other));
2914 /* integer underflow => drop (should be very rare)! */
2915 if (NULL != pgc->bf)
2916 GNUNET_CONTAINER_bloomfilter_free (pgc->bf);
2920 pgc->ttl -= ttl_decrement;
2921 pgc->start_time = GNUNET_TIME_absolute_get ();
2922 preference = (double) pgc->priority;
2923 if (preference < QUERY_BANDWIDTH_VALUE)
2924 preference = QUERY_BANDWIDTH_VALUE;
2925 // FIXME: also reserve bandwidth for reply?
2926 (void) GNUNET_CORE_peer_get_info (sched, cfg,
2928 GNUNET_TIME_UNIT_FOREVER_REL,
2929 0, 0, preference, NULL, NULL);
2930 if (0 != (pgc->policy & ROUTING_POLICY_ANSWER))
2931 pgc->drq = queue_ds_request (BASIC_DATASTORE_REQUEST_DELAY,
2935 GNUNET_SCHEDULER_add_continuation (sched,
2936 &forward_get_request,
2938 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
2944 * Function called to notify us that we can now transmit a reply to a
2945 * client or peer. "buf" will be NULL and "size" zero if the socket was
2946 * closed for writing in the meantime.
2948 * @param cls closure, points to a "struct PendingRequest*" with
2949 * one or more pending replies
2950 * @param size number of bytes available in buf
2951 * @param buf where the callee should write the message
2952 * @return number of bytes written to buf
2955 transmit_result (void *cls,
2959 struct PendingRequest *pr = cls;
2961 struct PendingReply *reply;
2965 while (NULL != (reply = pr->replies_pending))
2967 if ( (reply->msize + ret < ret) ||
2968 (reply->msize + ret > size) )
2970 pr->replies_pending = reply->next;
2971 memcpy (&cbuf[ret], &reply[1], reply->msize);
2972 ret += reply->msize;
2973 GNUNET_free (reply);
2980 * Iterator over pending requests.
2982 * @param cls response (struct ProcessReplyClosure)
2983 * @param key our query
2984 * @param value value in the hash map (meta-info about the query)
2985 * @return GNUNET_YES (we should continue to iterate)
2988 process_reply (void *cls,
2989 const GNUNET_HashCode * key,
2992 struct ProcessReplyClosure *prq = cls;
2993 struct PendingRequest *pr = value;
2994 struct PendingRequest *eer;
2995 struct PendingReply *reply;
2996 struct PutMessage *pm;
2997 struct ContentMessage *cm;
2998 GNUNET_HashCode chash;
2999 GNUNET_HashCode mhash;
3000 struct GNUNET_PeerIdentity target;
3003 struct GNUNET_TIME_Relative max_delay;
3005 GNUNET_CRYPTO_hash (prq->data,
3010 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3011 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3013 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3014 /* FIXME: does prq->namespace match our expectations? */
3015 /* then: fall-through??? */
3016 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3019 mingle_hash (&chash, pr->mingle, &mhash);
3020 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pr->bf,
3022 return GNUNET_YES; /* duplicate */
3023 GNUNET_CONTAINER_bloomfilter_add (pr->bf,
3027 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3028 // FIXME: any checks against duplicates for SKBlocks?
3031 prio = pr->priority;
3032 prq->priority += pr->remaining_priority;
3033 pr->remaining_priority = 0;
3034 if (pr->client != NULL)
3036 if (pr->replies_seen_size == pr->replies_seen_off)
3037 GNUNET_array_grow (pr->replies_seen,
3038 pr->replies_seen_size,
3039 pr->replies_seen_size * 2 + 4);
3040 pr->replies_seen[pr->replies_seen_off++] = chash;
3041 // FIXME: possibly recalculate BF!
3043 if (pr->client == NULL)
3045 msize = sizeof (struct ContentMessage) + prq->size;
3046 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3047 reply->msize = msize;
3048 cm = (struct ContentMessage*) &reply[1];
3049 cm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_CONTENT);
3050 cm->header.size = htons (msize);
3051 cm->type = htonl (prq->type);
3052 cm->expiration = GNUNET_TIME_absolute_hton (prq->expiration);
3053 reply->next = pr->replies_pending;
3054 pr->replies_pending = reply;
3055 memcpy (&reply[1], prq->data, prq->size);
3056 if (pr->cth != NULL)
3058 max_delay = GNUNET_TIME_UNIT_FOREVER_REL;
3059 if (GNUNET_CONTAINER_heap_get_size (requests_by_expiration) >= max_pending_requests)
3061 /* estimate expiration time from time difference between
3062 first request that will be discarded and this request */
3063 eer = GNUNET_CONTAINER_heap_peek (requests_by_expiration);
3064 max_delay = GNUNET_TIME_absolute_get_difference (pr->start_time,
3067 GNUNET_PEER_resolve (pr->source_pid,
3069 pr->cth = GNUNET_CORE_notify_transmit_ready (core,
3076 if (NULL == pr->cth)
3078 // FIXME: now what? discard?
3083 msize = sizeof (struct PutMessage) + prq->size;
3084 reply = GNUNET_malloc (msize + sizeof (struct PendingReply));
3085 reply->msize = msize;
3086 reply->next = pr->replies_pending;
3087 pm = (struct PutMessage*) &reply[1];
3088 pm->header.type = htons (GNUNET_MESSAGE_TYPE_FS_PUT);
3089 pm->header.size = htons (msize);
3090 pm->type = htonl (prq->type);
3091 pm->expiration = GNUNET_TIME_relative_hton (GNUNET_TIME_absolute_get_remaining (prq->expiration));
3092 pr->replies_pending = reply;
3093 memcpy (&reply[1], prq->data, prq->size);
3096 pr->th = GNUNET_SERVER_notify_transmit_ready (pr->client,
3098 GNUNET_TIME_UNIT_FOREVER_REL,
3103 // FIXME: need to try again later (not much
3104 // to do here specifically, but we need to
3105 // check somewhere else to handle this case!)
3108 // FIXME: implement hot-path routing statistics keeping!
3114 * Check if the given KBlock is well-formed.
3116 * @param kb the kblock data (or at least "dsize" bytes claiming to be one)
3117 * @param dsize size of "kb" in bytes; check for < sizeof(struct KBlock)!
3118 * @param query where to store the query that this block answers
3119 * @return GNUNET_OK if this is actually a well-formed KBlock
3122 check_kblock (const struct KBlock *kb,
3124 GNUNET_HashCode *query)
3126 if (dsize < sizeof (struct KBlock))
3128 GNUNET_break_op (0);
3129 return GNUNET_SYSERR;
3131 if (dsize - sizeof (struct KBlock) !=
3132 ntohs (kb->purpose.size)
3133 - sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose)
3134 - sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) )
3136 GNUNET_break_op (0);
3137 return GNUNET_SYSERR;
3140 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_KBLOCK,
3145 GNUNET_break_op (0);
3146 return GNUNET_SYSERR;
3149 GNUNET_CRYPTO_hash (&kb->keyspace,
3150 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3157 * Check if the given SBlock is well-formed.
3159 * @param sb the sblock data (or at least "dsize" bytes claiming to be one)
3160 * @param dsize size of "kb" in bytes; check for < sizeof(struct SBlock)!
3161 * @param query where to store the query that this block answers
3162 * @param namespace where to store the namespace that this block belongs to
3163 * @return GNUNET_OK if this is actually a well-formed SBlock
3166 check_sblock (const struct SBlock *sb,
3168 GNUNET_HashCode *query,
3169 GNUNET_HashCode *namespace)
3171 if (dsize < sizeof (struct SBlock))
3173 GNUNET_break_op (0);
3174 return GNUNET_SYSERR;
3177 ntohs (sb->purpose.size) + sizeof (struct GNUNET_CRYPTO_RsaSignature))
3179 GNUNET_break_op (0);
3180 return GNUNET_SYSERR;
3183 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_FS_SBLOCK,
3188 GNUNET_break_op (0);
3189 return GNUNET_SYSERR;
3192 *query = sb->identifier;
3193 if (namespace != NULL)
3194 GNUNET_CRYPTO_hash (&sb->subspace,
3195 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
3202 * Handle P2P "PUT" request.
3204 * @param cls closure, always NULL
3205 * @param other the other peer involved (sender or receiver, NULL
3206 * for loopback messages where we are both sender and receiver)
3207 * @param message the actual message
3208 * @return GNUNET_OK to keep the connection open,
3209 * GNUNET_SYSERR to close it (signal serious error)
3212 handle_p2p_put (void *cls,
3213 const struct GNUNET_PeerIdentity *other,
3214 const struct GNUNET_MessageHeader *message)
3216 const struct PutMessage *put;
3220 struct GNUNET_TIME_Absolute expiration;
3221 GNUNET_HashCode query;
3222 struct ProcessReplyClosure prq;
3224 msize = ntohs (message->size);
3225 if (msize < sizeof (struct PutMessage))
3228 return GNUNET_SYSERR;
3230 put = (const struct PutMessage*) message;
3231 dsize = msize - sizeof (struct PutMessage);
3232 type = ntohl (put->type);
3233 expiration = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_ntoh (put->expiration));
3235 /* first, validate! */
3238 case GNUNET_DATASTORE_BLOCKTYPE_DBLOCK:
3239 case GNUNET_DATASTORE_BLOCKTYPE_IBLOCK:
3240 GNUNET_CRYPTO_hash (&put[1], dsize, &query);
3242 case GNUNET_DATASTORE_BLOCKTYPE_KBLOCK:
3244 check_kblock ((const struct KBlock*) &put[1],
3247 return GNUNET_SYSERR;
3249 case GNUNET_DATASTORE_BLOCKTYPE_SBLOCK:
3251 check_sblock ((const struct SBlock*) &put[1],
3255 return GNUNET_SYSERR;
3257 case GNUNET_DATASTORE_BLOCKTYPE_SKBLOCK:
3258 // FIXME -- validate SKBLOCK!
3262 /* unknown block type */
3263 GNUNET_break_op (0);
3264 return GNUNET_SYSERR;
3267 /* now, lookup 'query' */
3268 prq.data = (const void*) &put[1];
3271 prq.expiration = expiration;
3273 GNUNET_CONTAINER_multihashmap_get_multiple (requests_by_query,
3277 // FIXME: if migration is on and load is low,
3278 // queue to store data in datastore;
3279 // use "prq.priority" for that!
3285 * List of handlers for P2P messages
3286 * that we care about.
3288 static struct GNUNET_CORE_MessageHandler p2p_handlers[] =
3291 GNUNET_MESSAGE_TYPE_FS_GET, 0 },
3293 GNUNET_MESSAGE_TYPE_FS_PUT, 0 },
3299 * Process fs requests.
3301 * @param cls closure
3302 * @param s scheduler to use
3303 * @param server the initialized server
3304 * @param c configuration to use
3308 struct GNUNET_SCHEDULER_Handle *s,
3309 struct GNUNET_SERVER_Handle *server,
3310 const struct GNUNET_CONFIGURATION_Handle *c)
3315 ifm = GNUNET_CONTAINER_multihashmap_create (128);
3316 requests_by_query = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3317 requests_by_peer = GNUNET_CONTAINER_multihashmap_create (128); // FIXME: get size from config
3318 connected_peers = GNUNET_CONTAINER_multihashmap_create (64);
3319 requests_by_expiration = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
3321 dsh = GNUNET_DATASTORE_connect (cfg,
3323 core = GNUNET_CORE_connect (sched,
3325 GNUNET_TIME_UNIT_FOREVER_REL,
3328 &peer_connect_handler,
3329 &peer_disconnect_handler,
3334 GNUNET_SERVER_disconnect_notify (server,
3335 &handle_client_disconnect,
3337 GNUNET_SERVER_add_handlers (server, handlers);
3338 GNUNET_SCHEDULER_add_delayed (sched,
3339 GNUNET_TIME_UNIT_FOREVER_REL,
3344 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3345 _("Failed to connect to `%s' service.\n"),
3347 GNUNET_SCHEDULER_shutdown (sched);
3352 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
3353 _("Failed to connect to `%s' service.\n"),
3355 GNUNET_SCHEDULER_shutdown (sched);
3362 * The main function for the fs service.
3364 * @param argc number of arguments from the command line
3365 * @param argv command line arguments
3366 * @return 0 ok, 1 on error
3369 main (int argc, char *const *argv)
3371 return (GNUNET_OK ==
3372 GNUNET_SERVICE_run (argc,
3375 GNUNET_SERVICE_OPTION_NONE,
3376 &run, NULL)) ? 0 : 1;
3379 /* end of gnunet-service-fs.c */