2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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 3, 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 dht/gnunet-service-dht_clients.c
23 * @brief GNUnet DHT service's client management code
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_constants.h"
30 #include "gnunet_protocols.h"
31 #include "gnunet_statistics_service.h"
32 #include "gnunet-service-dht.h"
33 #include "gnunet-service-dht_clients.h"
34 #include "gnunet-service-dht_datacache.h"
35 #include "gnunet-service-dht_neighbours.h"
40 * Linked list of messages to send to clients.
45 * Pointer to next item in the list
47 struct PendingMessage *next;
50 * Pointer to previous item in the list
52 struct PendingMessage *prev;
55 * Actual message to be sent, allocated at the end of the struct:
56 * // msg = (cast) &pm[1];
57 * // memcpy (&pm[1], data, len);
59 const struct GNUNET_MessageHeader *msg;
65 * Struct containing information about a client,
66 * handle to connect to it, and any pending messages
67 * that need to be sent to it.
72 * Linked list of active clients
74 struct ClientList *next;
77 * Linked list of active clients
79 struct ClientList *prev;
82 * The handle to this client
84 struct GNUNET_SERVER_Client *client_handle;
87 * Handle to the current transmission request, NULL
90 struct GNUNET_SERVER_TransmitHandle *transmit_handle;
93 * Linked list of pending messages for this client
95 struct PendingMessage *pending_head;
98 * Tail of linked list of pending messages for this client
100 struct PendingMessage *pending_tail;
106 * Entry in the DHT routing table for a client's GET request.
108 struct ClientQueryRecord
112 * The key this request was about
114 struct GNUNET_HashCode key;
117 * Client responsible for the request.
119 struct ClientList *client;
122 * Extended query (see gnunet_block_lib.h), allocated at the end of this struct.
127 * Replies we have already seen for this request.
129 struct GNUNET_HashCode *seen_replies;
132 * Pointer to this nodes heap location in the retry-heap (for fast removal)
134 struct GNUNET_CONTAINER_HeapNode *hnode;
137 * What's the delay between re-try operations that we currently use for this
140 struct GNUNET_TIME_Relative retry_frequency;
143 * What's the next time we should re-try this request?
145 struct GNUNET_TIME_Absolute retry_time;
148 * The unique identifier of this request
153 * Number of bytes in xquery.
158 * Number of entries in 'seen_replies'.
160 unsigned int seen_replies_count;
163 * Desired replication level
165 uint32_t replication;
168 * Any message options for this request
170 uint32_t msg_options;
173 * The type for the data for the GET request.
175 enum GNUNET_BLOCK_Type type;
181 * Struct containing paremeters of monitoring requests.
183 struct ClientMonitorRecord
187 * Next element in DLL.
189 struct ClientMonitorRecord *next;
192 * Previous element in DLL.
194 struct ClientMonitorRecord *prev;
197 * Type of blocks that are of interest
199 enum GNUNET_BLOCK_Type type;
202 * Key of data of interest, NULL for all.
204 struct GNUNET_HashCode *key;
207 * Flag whether to notify about GET messages.
212 * Flag whether to notify about GET_REPONSE messages.
217 * Flag whether to notify about PUT messages.
222 * Client to notify of these requests.
224 struct ClientList *client;
229 * List of active clients.
231 static struct ClientList *client_head;
234 * List of active clients.
236 static struct ClientList *client_tail;
239 * List of active monitoring requests.
241 static struct ClientMonitorRecord *monitor_head;
244 * List of active monitoring requests.
246 static struct ClientMonitorRecord *monitor_tail;
249 * Hashmap for fast key based lookup, maps keys to 'struct ClientQueryRecord' entries.
251 static struct GNUNET_CONTAINER_MultiHashMap *forward_map;
254 * Heap with all of our client's request, sorted by retry time (earliest on top).
256 static struct GNUNET_CONTAINER_Heap *retry_heap;
259 * Task that re-transmits requests (using retry_heap).
261 static GNUNET_SCHEDULER_TaskIdentifier retry_task;
265 * Task run to check for messages that need to be sent to a client.
267 * @param client a ClientList, containing the client and any messages to be sent to it
270 process_pending_messages (struct ClientList *client);
274 * Add a PendingMessage to the clients list of messages to be sent
276 * @param client the active client to send the message to
277 * @param pending_message the actual message to send
280 add_pending_message (struct ClientList *client,
281 struct PendingMessage *pending_message)
283 GNUNET_CONTAINER_DLL_insert_tail (client->pending_head, client->pending_tail,
285 process_pending_messages (client);
290 * Find a client if it exists, add it otherwise.
292 * @param client the server handle to the client
294 * @return the client if found, a new client otherwise
296 static struct ClientList *
297 find_active_client (struct GNUNET_SERVER_Client *client)
299 struct ClientList *pos = client_head;
300 struct ClientList *ret;
304 if (pos->client_handle == client)
308 ret = GNUNET_malloc (sizeof (struct ClientList));
309 ret->client_handle = client;
310 GNUNET_CONTAINER_DLL_insert (client_head, client_tail, ret);
316 * Iterator over hash map entries that frees all entries
317 * associated with the given client.
319 * @param cls client to search for in source routes
320 * @param key current key code (ignored)
321 * @param value value in the hash map, a ClientQueryRecord
322 * @return GNUNET_YES (we should continue to iterate)
325 remove_client_records (void *cls, const struct GNUNET_HashCode * key, void *value)
327 struct ClientList *client = cls;
328 struct ClientQueryRecord *record = value;
330 if (record->client != client)
332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
333 "Removing client %p's record for key %s\n", client,
335 GNUNET_assert (GNUNET_YES ==
336 GNUNET_CONTAINER_multihashmap_remove (forward_map, key,
338 if (NULL != record->hnode)
339 GNUNET_CONTAINER_heap_remove_node (record->hnode);
340 GNUNET_array_grow (record->seen_replies, record->seen_replies_count, 0);
341 GNUNET_free (record);
347 * Functions with this signature are called whenever a client
348 * is disconnected on the network level.
350 * @param cls closure (NULL for dht)
351 * @param client identification of the client; NULL
352 * for the last call when the server is destroyed
355 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
357 struct ClientList *pos;
358 struct PendingMessage *reply;
359 struct ClientMonitorRecord *monitor;
361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Local client %p disconnects\n", client);
362 pos = find_active_client (client);
363 GNUNET_CONTAINER_DLL_remove (client_head, client_tail, pos);
364 if (pos->transmit_handle != NULL)
365 GNUNET_SERVER_notify_transmit_ready_cancel (pos->transmit_handle);
366 while (NULL != (reply = pos->pending_head))
368 GNUNET_CONTAINER_DLL_remove (pos->pending_head, pos->pending_tail, reply);
371 monitor = monitor_head;
372 while (NULL != monitor)
374 if (monitor->client == pos)
376 struct ClientMonitorRecord *next;
378 GNUNET_free_non_null (monitor->key);
379 next = monitor->next;
380 GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, monitor);
381 GNUNET_free (monitor);
385 monitor = monitor->next;
387 GNUNET_CONTAINER_multihashmap_iterate (forward_map, &remove_client_records,
394 * Route the given request via the DHT. This includes updating
395 * the bloom filter and retransmission times, building the P2P
396 * message and initiating the routing operation.
399 transmit_request (struct ClientQueryRecord *cqr)
401 int32_t reply_bf_mutator;
402 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
403 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
405 GNUNET_STATISTICS_update (GDS_stats,
407 ("# GET requests from clients injected"), 1,
410 (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
413 GNUNET_BLOCK_construct_bloomfilter (reply_bf_mutator, cqr->seen_replies,
414 cqr->seen_replies_count);
416 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
417 GNUNET_CONSTANTS_BLOOMFILTER_K);
418 GDS_NEIGHBOURS_handle_get (cqr->type, cqr->msg_options, cqr->replication,
420 &cqr->key, cqr->xquery, cqr->xquery_size, reply_bf,
421 reply_bf_mutator, peer_bf);
422 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
423 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
425 /* exponential back-off for retries, max 1h */
426 cqr->retry_frequency = GNUNET_TIME_STD_BACKOFF (cqr->retry_frequency);
427 cqr->retry_time = GNUNET_TIME_relative_to_absolute (cqr->retry_frequency);
432 * Task that looks at the 'retry_heap' and transmits all of the requests
433 * on the heap that are ready for transmission. Then re-schedules
434 * itself (unless the heap is empty).
437 * @param tc scheduler context
440 transmit_next_request_task (void *cls,
441 const struct GNUNET_SCHEDULER_TaskContext *tc)
443 struct ClientQueryRecord *cqr;
444 struct GNUNET_TIME_Relative delay;
446 retry_task = GNUNET_SCHEDULER_NO_TASK;
447 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
449 while (NULL != (cqr = GNUNET_CONTAINER_heap_remove_root (retry_heap)))
452 delay = GNUNET_TIME_absolute_get_remaining (cqr->retry_time);
453 if (delay.rel_value > 0)
456 GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
457 cqr->retry_time.abs_value);
459 GNUNET_SCHEDULER_add_delayed (delay, &transmit_next_request_task,
463 transmit_request (cqr);
465 GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
466 cqr->retry_time.abs_value);
472 * Handler for PUT messages.
474 * @param cls closure for the service
475 * @param client the client we received this message from
476 * @param message the actual message received
479 handle_dht_local_put (void *cls, struct GNUNET_SERVER_Client *client,
480 const struct GNUNET_MessageHeader *message)
482 const struct GNUNET_DHT_ClientPutMessage *dht_msg;
483 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
485 struct PendingMessage *pm;
486 struct GNUNET_DHT_ClientPutConfirmationMessage *conf;
488 size = ntohs (message->size);
489 if (size < sizeof (struct GNUNET_DHT_ClientPutMessage))
492 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
495 GNUNET_STATISTICS_update (GDS_stats,
497 ("# PUT requests received from clients"), 1,
499 dht_msg = (const struct GNUNET_DHT_ClientPutMessage *) message;
500 /* give to local clients */
501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502 "Handling local PUT of %u-bytes for query %s\n",
503 size - sizeof (struct GNUNET_DHT_ClientPutMessage),
504 GNUNET_h2s (&dht_msg->key));
505 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
506 &dht_msg->key, 0, NULL, 0, NULL,
507 ntohl (dht_msg->type),
508 size - sizeof (struct GNUNET_DHT_ClientPutMessage),
511 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
512 &dht_msg->key, 0, NULL, ntohl (dht_msg->type),
513 size - sizeof (struct GNUNET_DHT_ClientPutMessage),
515 /* route to other peers */
517 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
518 GNUNET_CONSTANTS_BLOOMFILTER_K);
519 GDS_NEIGHBOURS_handle_put (ntohl (dht_msg->type), ntohl (dht_msg->options),
520 ntohl (dht_msg->desired_replication_level),
521 GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
523 peer_bf, &dht_msg->key, 0, NULL, &dht_msg[1],
525 sizeof (struct GNUNET_DHT_ClientPutMessage));
526 GDS_CLIENTS_process_put (ntohl (dht_msg->options),
527 ntohl (dht_msg->type),
529 ntohl (dht_msg->desired_replication_level),
531 GDS_NEIGHBOURS_get_id(),
532 GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
535 size - sizeof (struct GNUNET_DHT_ClientPutMessage));
536 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
537 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
538 sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage));
539 conf = (struct GNUNET_DHT_ClientPutConfirmationMessage *) &pm[1];
540 conf->header.size = htons (sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage));
541 conf->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT_OK);
542 conf->reserved = htonl (0);
543 conf->unique_id = dht_msg->unique_id;
544 pm->msg = &conf->header;
545 add_pending_message (find_active_client (client), pm);
546 GNUNET_SERVER_receive_done (client, GNUNET_OK);
551 * Handler for DHT GET messages from the client.
553 * @param cls closure for the service
554 * @param client the client we received this message from
555 * @param message the actual message received
558 handle_dht_local_get (void *cls, struct GNUNET_SERVER_Client *client,
559 const struct GNUNET_MessageHeader *message)
561 const struct GNUNET_DHT_ClientGetMessage *get;
562 struct ClientQueryRecord *cqr;
567 size = ntohs (message->size);
568 if (size < sizeof (struct GNUNET_DHT_ClientGetMessage))
571 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
574 xquery_size = size - sizeof (struct GNUNET_DHT_ClientGetMessage);
575 get = (const struct GNUNET_DHT_ClientGetMessage *) message;
576 xquery = (const char *) &get[1];
577 GNUNET_STATISTICS_update (GDS_stats,
579 ("# GET requests received from clients"), 1,
581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582 "Received request for %s from local client %p\n",
583 GNUNET_h2s (&get->key), client);
584 cqr = GNUNET_malloc (sizeof (struct ClientQueryRecord) + xquery_size);
586 cqr->client = find_active_client (client);
587 cqr->xquery = (void *) &cqr[1];
588 memcpy (&cqr[1], xquery, xquery_size);
589 cqr->hnode = GNUNET_CONTAINER_heap_insert (retry_heap, cqr, 0);
590 cqr->retry_frequency = GNUNET_TIME_UNIT_SECONDS;
591 cqr->retry_time = GNUNET_TIME_absolute_get ();
592 cqr->unique_id = get->unique_id;
593 cqr->xquery_size = xquery_size;
594 cqr->replication = ntohl (get->desired_replication_level);
595 cqr->msg_options = ntohl (get->options);
596 cqr->type = ntohl (get->type);
597 // FIXME use cqr->key, set multihashmap create to GNUNET_YES
598 GNUNET_CONTAINER_multihashmap_put (forward_map, &get->key, cqr,
599 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
600 GDS_CLIENTS_process_get (ntohl (get->options),
603 ntohl (get->desired_replication_level),
605 GDS_NEIGHBOURS_get_id(),
607 /* start remote requests */
608 if (GNUNET_SCHEDULER_NO_TASK != retry_task)
609 GNUNET_SCHEDULER_cancel (retry_task);
610 retry_task = GNUNET_SCHEDULER_add_now (&transmit_next_request_task, NULL);
611 /* perform local lookup */
612 GDS_DATACACHE_handle_get (&get->key, cqr->type, cqr->xquery, xquery_size,
614 GNUNET_SERVER_receive_done (client, GNUNET_OK);
619 * Closure for 'find_by_unique_id'.
621 struct FindByUniqueIdContext
624 * Where to store the result, if found.
626 struct ClientQueryRecord *cqr;
633 * Function called for each existing DHT record for the given
634 * query. Checks if it matches the UID given in the closure
635 * and if so returns the entry as a result.
637 * @param cls the search context
638 * @param key query for the lookup (not used)
639 * @param value the 'struct ClientQueryRecord'
640 * @return GNUNET_YES to continue iteration (result not yet found)
643 find_by_unique_id (void *cls,
644 const struct GNUNET_HashCode *key,
647 struct FindByUniqueIdContext *fui_ctx = cls;
648 struct ClientQueryRecord *cqr = value;
650 if (cqr->unique_id != fui_ctx->unique_id)
658 * Handler for "GET result seen" messages from the client.
660 * @param cls closure for the service
661 * @param client the client we received this message from
662 * @param message the actual message received
665 handle_dht_local_get_result_seen (void *cls, struct GNUNET_SERVER_Client *client,
666 const struct GNUNET_MessageHeader *message)
668 const struct GNUNET_DHT_ClientGetResultSeenMessage *seen;
670 unsigned int hash_count;
671 unsigned int old_count;
672 const struct GNUNET_HashCode *hc;
673 struct FindByUniqueIdContext fui_ctx;
674 struct ClientQueryRecord *cqr;
676 size = ntohs (message->size);
677 if (size < sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage))
680 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
683 seen = (const struct GNUNET_DHT_ClientGetResultSeenMessage *) message;
684 hash_count = (size - sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof (struct GNUNET_HashCode);
685 if (size != sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage) + hash_count * sizeof (struct GNUNET_HashCode))
688 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
691 hc = (const struct GNUNET_HashCode*) &seen[1];
692 fui_ctx.unique_id = seen->unique_id;
694 GNUNET_CONTAINER_multihashmap_get_multiple (forward_map,
698 if (NULL == (cqr = fui_ctx.cqr))
701 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
704 /* finally, update 'seen' list */
705 old_count = cqr->seen_replies_count;
706 GNUNET_array_grow (cqr->seen_replies,
707 cqr->seen_replies_count,
708 cqr->seen_replies_count + hash_count);
709 memcpy (&cqr->seen_replies[old_count],
711 sizeof (struct GNUNET_HashCode) * hash_count);
716 * Closure for 'remove_by_unique_id'.
718 struct RemoveByUniqueIdContext
721 * Client that issued the removal request.
723 struct ClientList *client;
726 * Unique ID of the request.
733 * Iterator over hash map entries that frees all entries
734 * that match the given client and unique ID.
736 * @param cls unique ID and client to search for in source routes
737 * @param key current key code
738 * @param value value in the hash map, a ClientQueryRecord
739 * @return GNUNET_YES (we should continue to iterate)
742 remove_by_unique_id (void *cls, const struct GNUNET_HashCode * key, void *value)
744 const struct RemoveByUniqueIdContext *ctx = cls;
745 struct ClientQueryRecord *record = value;
747 if (record->unique_id != ctx->unique_id)
749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
750 "Removing client %p's record for key %s (by unique id)\n",
751 ctx->client->client_handle, GNUNET_h2s (key));
752 return remove_client_records (ctx->client, key, record);
757 * Handler for any generic DHT stop messages, calls the appropriate handler
758 * depending on message type (if processed locally)
760 * @param cls closure for the service
761 * @param client the client we received this message from
762 * @param message the actual message received
766 handle_dht_local_get_stop (void *cls, struct GNUNET_SERVER_Client *client,
767 const struct GNUNET_MessageHeader *message)
769 const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg =
770 (const struct GNUNET_DHT_ClientGetStopMessage *) message;
771 struct RemoveByUniqueIdContext ctx;
773 GNUNET_STATISTICS_update (GDS_stats,
775 ("# GET STOP requests received from clients"), 1,
777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p stopped request for key %s\n",
778 client, GNUNET_h2s (&dht_stop_msg->key));
779 ctx.client = find_active_client (client);
780 ctx.unique_id = dht_stop_msg->unique_id;
781 GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, &dht_stop_msg->key,
782 &remove_by_unique_id, &ctx);
783 GNUNET_SERVER_receive_done (client, GNUNET_OK);
788 * Handler for monitor start messages
790 * @param cls closure for the service
791 * @param client the client we received this message from
792 * @param message the actual message received
796 handle_dht_local_monitor (void *cls, struct GNUNET_SERVER_Client *client,
797 const struct GNUNET_MessageHeader *message)
799 struct ClientMonitorRecord *r;
800 const struct GNUNET_DHT_MonitorStartStopMessage *msg;
802 msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
803 r = GNUNET_malloc (sizeof(struct ClientMonitorRecord));
805 r->client = find_active_client(client);
806 r->type = ntohl(msg->type);
807 r->get = ntohs(msg->get);
808 r->get_resp = ntohs(msg->get_resp);
809 r->put = ntohs(msg->put);
810 if (0 == ntohs(msg->filter_key))
814 r->key = GNUNET_malloc (sizeof (struct GNUNET_HashCode));
815 memcpy (r->key, &msg->key, sizeof (struct GNUNET_HashCode));
817 GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, r);
818 GNUNET_SERVER_receive_done (client, GNUNET_OK);
822 * Handler for monitor stop messages
824 * @param cls closure for the service
825 * @param client the client we received this message from
826 * @param message the actual message received
830 handle_dht_local_monitor_stop (void *cls, struct GNUNET_SERVER_Client *client,
831 const struct GNUNET_MessageHeader *message)
833 struct ClientMonitorRecord *r;
834 const struct GNUNET_DHT_MonitorStartStopMessage *msg;
837 msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
843 keys_match = (0 == ntohs(msg->filter_key));
846 keys_match = (0 != ntohs(msg->filter_key)
847 && !memcmp(r->key, &msg->key, sizeof(struct GNUNET_HashCode)));
849 if (find_active_client(client) == r->client
850 && ntohl(msg->type) == r->type
851 && r->get == msg->get
852 && r->get_resp == msg->get_resp
853 && r->put == msg->put
857 GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, r);
858 GNUNET_free_non_null (r->key);
860 GNUNET_SERVER_receive_done (client, GNUNET_OK);
861 return; /* Delete only ONE entry */
866 GNUNET_SERVER_receive_done (client, GNUNET_OK);
871 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
872 * request. A ClientList is passed as closure, take the head of the list
873 * and copy it into buf, which has the result of sending the message to the
876 * @param cls closure to this call
877 * @param size maximum number of bytes available to send
878 * @param buf where to copy the actual message to
880 * @return the number of bytes actually copied, 0 indicates failure
883 send_reply_to_client (void *cls, size_t size, void *buf)
885 struct ClientList *client = cls;
887 struct PendingMessage *reply;
891 client->transmit_handle = NULL;
894 /* client disconnected */
895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
896 "Client %p disconnected, pending messages will be discarded\n",
897 client->client_handle);
901 while ((NULL != (reply = client->pending_head)) &&
902 (size >= off + (msize = ntohs (reply->msg->size))))
904 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
906 memcpy (&cbuf[off], reply->msg, msize);
908 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes to client %p\n",
909 msize, client->client_handle);
912 process_pending_messages (client);
913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitted %u/%u bytes to client %p\n",
914 (unsigned int) off, (unsigned int) size, client->client_handle);
920 * Task run to check for messages that need to be sent to a client.
922 * @param client a ClientList, containing the client and any messages to be sent to it
925 process_pending_messages (struct ClientList *client)
927 if ((client->pending_head == NULL) || (client->transmit_handle != NULL))
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "Not asking for transmission to %p now: %s\n",
931 client->client_handle,
932 client->pending_head ==
933 NULL ? "no more messages" : "request already pending");
936 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
937 "Asking for transmission of %u bytes to client %p\n",
938 ntohs (client->pending_head->msg->size), client->client_handle);
939 client->transmit_handle =
940 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
941 ntohs (client->pending_head->
943 GNUNET_TIME_UNIT_FOREVER_REL,
944 &send_reply_to_client, client);
949 * Closure for 'forward_reply'
951 struct ForwardReplyContext
955 * Actual message to send to matching clients.
957 struct PendingMessage *pm;
967 enum GNUNET_BLOCK_Type type;
970 * Number of bytes in data.
975 * Do we need to copy 'pm' because it was already used?
983 * Iterator over hash map entries that send a given reply to
984 * each of the matching clients. With some tricky recycling
987 * @param cls the 'struct ForwardReplyContext'
988 * @param key current key
989 * @param value value in the hash map, a ClientQueryRecord
990 * @return GNUNET_YES (we should continue to iterate),
991 * if the result is mal-formed, GNUNET_NO
994 forward_reply (void *cls, const struct GNUNET_HashCode * key, void *value)
996 struct ForwardReplyContext *frc = cls;
997 struct ClientQueryRecord *record = value;
998 struct PendingMessage *pm;
999 struct GNUNET_DHT_ClientResultMessage *reply;
1000 enum GNUNET_BLOCK_EvaluationResult eval;
1002 struct GNUNET_HashCode ch;
1005 if ((record->type != GNUNET_BLOCK_TYPE_ANY) && (record->type != frc->type))
1007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1008 "Record type missmatch, not passing request for key %s to local client\n",
1010 GNUNET_STATISTICS_update (GDS_stats,
1012 ("# Key match, type mismatches in REPLY to CLIENT"),
1014 return GNUNET_YES; /* type mismatch */
1016 GNUNET_CRYPTO_hash (frc->data, frc->data_size, &ch);
1017 for (i = 0; i < record->seen_replies_count; i++)
1018 if (0 == memcmp (&record->seen_replies[i], &ch, sizeof (struct GNUNET_HashCode)))
1020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1021 "Duplicate reply, not passing request for key %s to local client\n",
1023 GNUNET_STATISTICS_update (GDS_stats,
1025 ("# Duplicate REPLIES to CLIENT request dropped"),
1027 return GNUNET_YES; /* duplicate */
1030 GNUNET_BLOCK_evaluate (GDS_block_context, record->type, key, NULL, 0,
1031 record->xquery, record->xquery_size, frc->data,
1033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1034 "Evaluation result is %d for key %s for local client's query\n",
1035 (int) eval, GNUNET_h2s (key));
1038 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1039 do_free = GNUNET_YES;
1041 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1042 GNUNET_array_append (record->seen_replies, record->seen_replies_count, ch);
1043 do_free = GNUNET_NO;
1045 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1046 /* should be impossible to encounter here */
1049 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1050 GNUNET_break_op (0);
1052 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1055 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1058 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1060 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1061 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1062 _("Unsupported block type (%u) in request!\n"), record->type);
1068 if (GNUNET_NO == frc->do_copy)
1070 /* first time, we can use the original data */
1072 frc->do_copy = GNUNET_YES;
1076 /* two clients waiting for same reply, must copy for queueing */
1077 pm = GNUNET_malloc (sizeof (struct PendingMessage) +
1078 ntohs (frc->pm->msg->size));
1079 memcpy (pm, frc->pm,
1080 sizeof (struct PendingMessage) + ntohs (frc->pm->msg->size));
1081 pm->next = pm->prev = NULL;
1082 pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1084 GNUNET_STATISTICS_update (GDS_stats,
1085 gettext_noop ("# RESULTS queued for clients"), 1,
1087 reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
1088 reply->unique_id = record->unique_id;
1089 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1090 "Queueing reply to query %s for client %p\n", GNUNET_h2s (key),
1091 record->client->client_handle);
1092 add_pending_message (record->client, pm);
1093 if (GNUNET_YES == do_free)
1094 remove_client_records (record->client, key, record);
1100 * Handle a reply we've received from another peer. If the reply
1101 * matches any of our pending queries, forward it to the respective
1104 * @param expiration when will the reply expire
1105 * @param key the query this reply is for
1106 * @param get_path_length number of peers in 'get_path'
1107 * @param get_path path the reply took on get
1108 * @param put_path_length number of peers in 'put_path'
1109 * @param put_path path the reply took on put
1110 * @param type type of the reply
1111 * @param data_size number of bytes in 'data'
1112 * @param data application payload data
1115 GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration,
1116 const struct GNUNET_HashCode *key,
1117 unsigned int get_path_length,
1118 const struct GNUNET_PeerIdentity *get_path,
1119 unsigned int put_path_length,
1120 const struct GNUNET_PeerIdentity *put_path,
1121 enum GNUNET_BLOCK_Type type, size_t data_size,
1124 struct ForwardReplyContext frc;
1125 struct PendingMessage *pm;
1126 struct GNUNET_DHT_ClientResultMessage *reply;
1127 struct GNUNET_PeerIdentity *paths;
1130 if (NULL == GNUNET_CONTAINER_multihashmap_get (forward_map, key))
1132 GNUNET_STATISTICS_update (GDS_stats,
1134 ("# REPLIES ignored for CLIENTS (no match)"), 1,
1136 return; /* no matching request, fast exit! */
1139 sizeof (struct GNUNET_DHT_ClientResultMessage) + data_size +
1140 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1141 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1143 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1144 _("Could not pass reply to client, message too big!\n"));
1147 pm = GNUNET_malloc (msize + sizeof (struct PendingMessage));
1148 reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
1149 pm->msg = &reply->header;
1150 reply->header.size = htons ((uint16_t) msize);
1151 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT);
1152 reply->type = htonl (type);
1153 reply->get_path_length = htonl (get_path_length);
1154 reply->put_path_length = htonl (put_path_length);
1155 reply->unique_id = 0; /* filled in later */
1156 reply->expiration = GNUNET_TIME_absolute_hton (expiration);
1158 paths = (struct GNUNET_PeerIdentity *) &reply[1];
1159 memcpy (paths, put_path,
1160 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1161 memcpy (&paths[put_path_length], get_path,
1162 sizeof (struct GNUNET_PeerIdentity) * get_path_length);
1163 memcpy (&paths[get_path_length + put_path_length], data, data_size);
1164 frc.do_copy = GNUNET_NO;
1167 frc.data_size = data_size;
1169 GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, key, &forward_reply,
1171 if (GNUNET_NO == frc.do_copy)
1173 /* did not match any of the requests, free! */
1174 GNUNET_STATISTICS_update (GDS_stats,
1176 ("# REPLIES ignored for CLIENTS (no match)"), 1,
1184 * Check if some client is monitoring GET messages and notify
1185 * them in that case.
1187 * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1188 * @param type The type of data in the request.
1189 * @param hop_count Hop count so far.
1190 * @param path_length number of entries in path (or 0 if not recorded).
1191 * @param path peers on the GET path (or NULL if not recorded).
1192 * @param desired_replication_level Desired replication level.
1193 * @param key Key of the requested data.
1196 GDS_CLIENTS_process_get (uint32_t options,
1197 enum GNUNET_BLOCK_Type type,
1199 uint32_t desired_replication_level,
1200 unsigned int path_length,
1201 const struct GNUNET_PeerIdentity *path,
1202 const struct GNUNET_HashCode * key)
1204 struct ClientMonitorRecord *m;
1205 struct ClientList **cl;
1206 unsigned int cl_size;
1210 for (m = monitor_head; NULL != m; m = m->next)
1212 if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1214 memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1216 struct PendingMessage *pm;
1217 struct GNUNET_DHT_MonitorGetMessage *mmsg;
1218 struct GNUNET_PeerIdentity *msg_path;
1222 /* Don't send duplicates */
1223 for (i = 0; i < cl_size; i++)
1224 if (cl[i] == m->client)
1228 GNUNET_array_append (cl, cl_size, m->client);
1230 msize = path_length * sizeof (struct GNUNET_PeerIdentity);
1231 msize += sizeof (struct GNUNET_DHT_MonitorGetMessage);
1232 msize += sizeof (struct PendingMessage);
1233 pm = GNUNET_malloc (msize);
1234 mmsg = (struct GNUNET_DHT_MonitorGetMessage *) &pm[1];
1235 pm->msg = &mmsg->header;
1236 mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1237 mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET);
1238 mmsg->options = htonl(options);
1239 mmsg->type = htonl(type);
1240 mmsg->hop_count = htonl(hop_count);
1241 mmsg->desired_replication_level = htonl(desired_replication_level);
1242 mmsg->get_path_length = htonl(path_length);
1243 memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1244 msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1245 if (path_length > 0)
1246 memcpy (msg_path, path,
1247 path_length * sizeof (struct GNUNET_PeerIdentity));
1248 add_pending_message (m->client, pm);
1251 GNUNET_free_non_null (cl);
1256 * Check if some client is monitoring GET RESP messages and notify
1257 * them in that case.
1259 * @param type The type of data in the result.
1260 * @param get_path Peers on GET path (or NULL if not recorded).
1261 * @param get_path_length number of entries in get_path.
1262 * @param put_path peers on the PUT path (or NULL if not recorded).
1263 * @param put_path_length number of entries in get_path.
1264 * @param exp Expiration time of the data.
1265 * @param key Key of the data.
1266 * @param data Pointer to the result data.
1267 * @param size Number of bytes in data.
1270 GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type,
1271 const struct GNUNET_PeerIdentity *get_path,
1272 unsigned int get_path_length,
1273 const struct GNUNET_PeerIdentity *put_path,
1274 unsigned int put_path_length,
1275 struct GNUNET_TIME_Absolute exp,
1276 const struct GNUNET_HashCode * key,
1280 struct ClientMonitorRecord *m;
1281 struct ClientList **cl;
1282 unsigned int cl_size;
1286 for (m = monitor_head; NULL != m; m = m->next)
1288 if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1290 memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1292 struct PendingMessage *pm;
1293 struct GNUNET_DHT_MonitorGetRespMessage *mmsg;
1294 struct GNUNET_PeerIdentity *path;
1298 /* Don't send duplicates */
1299 for (i = 0; i < cl_size; i++)
1300 if (cl[i] == m->client)
1304 GNUNET_array_append (cl, cl_size, m->client);
1307 msize += (get_path_length + put_path_length)
1308 * sizeof (struct GNUNET_PeerIdentity);
1309 msize += sizeof (struct GNUNET_DHT_MonitorGetRespMessage);
1310 msize += sizeof (struct PendingMessage);
1311 pm = GNUNET_malloc (msize);
1312 mmsg = (struct GNUNET_DHT_MonitorGetRespMessage *) &pm[1];
1313 pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1314 mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1315 mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP);
1316 mmsg->type = htonl(type);
1317 mmsg->put_path_length = htonl(put_path_length);
1318 mmsg->get_path_length = htonl(get_path_length);
1319 path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1320 if (put_path_length > 0)
1322 memcpy (path, put_path,
1323 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1324 path = &path[put_path_length];
1326 if (get_path_length > 0)
1327 memcpy (path, get_path,
1328 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1329 mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1330 memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1332 memcpy (&path[get_path_length], data, size);
1333 add_pending_message (m->client, pm);
1336 GNUNET_free_non_null (cl);
1341 * Check if some client is monitoring PUT messages and notify
1342 * them in that case.
1344 * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1345 * @param type The type of data in the request.
1346 * @param hop_count Hop count so far.
1347 * @param path_length number of entries in path (or 0 if not recorded).
1348 * @param path peers on the PUT path (or NULL if not recorded).
1349 * @param desired_replication_level Desired replication level.
1350 * @param exp Expiration time of the data.
1351 * @param key Key under which data is to be stored.
1352 * @param data Pointer to the data carried.
1353 * @param size Number of bytes in data.
1356 GDS_CLIENTS_process_put (uint32_t options,
1357 enum GNUNET_BLOCK_Type type,
1359 uint32_t desired_replication_level,
1360 unsigned int path_length,
1361 const struct GNUNET_PeerIdentity *path,
1362 struct GNUNET_TIME_Absolute exp,
1363 const struct GNUNET_HashCode * key,
1367 struct ClientMonitorRecord *m;
1368 struct ClientList **cl;
1369 unsigned int cl_size;
1373 for (m = monitor_head; NULL != m; m = m->next)
1375 if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1377 memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1379 struct PendingMessage *pm;
1380 struct GNUNET_DHT_MonitorPutMessage *mmsg;
1381 struct GNUNET_PeerIdentity *msg_path;
1385 /* Don't send duplicates */
1386 for (i = 0; i < cl_size; i++)
1387 if (cl[i] == m->client)
1391 GNUNET_array_append (cl, cl_size, m->client);
1394 msize += path_length * sizeof (struct GNUNET_PeerIdentity);
1395 msize += sizeof (struct GNUNET_DHT_MonitorPutMessage);
1396 msize += sizeof (struct PendingMessage);
1397 pm = GNUNET_malloc (msize);
1398 mmsg = (struct GNUNET_DHT_MonitorPutMessage *) &pm[1];
1399 pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1400 mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1401 mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT);
1402 mmsg->options = htonl(options);
1403 mmsg->type = htonl(type);
1404 mmsg->hop_count = htonl(hop_count);
1405 mmsg->desired_replication_level = htonl(desired_replication_level);
1406 mmsg->put_path_length = htonl(path_length);
1407 msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1408 if (path_length > 0)
1410 memcpy (msg_path, path,
1411 path_length * sizeof (struct GNUNET_PeerIdentity));
1413 mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1414 memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1416 memcpy (&msg_path[path_length], data, size);
1417 add_pending_message (m->client, pm);
1420 GNUNET_free_non_null (cl);
1425 * Initialize client subsystem.
1427 * @param server the initialized server
1430 GDS_CLIENTS_init (struct GNUNET_SERVER_Handle *server)
1432 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1433 {&handle_dht_local_put, NULL,
1434 GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, 0},
1435 {&handle_dht_local_get, NULL,
1436 GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, 0},
1437 {&handle_dht_local_get_stop, NULL,
1438 GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP,
1439 sizeof (struct GNUNET_DHT_ClientGetStopMessage)},
1440 {&handle_dht_local_monitor, NULL,
1441 GNUNET_MESSAGE_TYPE_DHT_MONITOR_START,
1442 sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1443 {&handle_dht_local_monitor_stop, NULL,
1444 GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP,
1445 sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1446 {&handle_dht_local_get_result_seen, NULL,
1447 GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN, 0},
1450 forward_map = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
1451 retry_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1452 GNUNET_SERVER_add_handlers (server, plugin_handlers);
1453 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1458 * Shutdown client subsystem.
1463 GNUNET_assert (client_head == NULL);
1464 GNUNET_assert (client_tail == NULL);
1465 if (GNUNET_SCHEDULER_NO_TASK != retry_task)
1467 GNUNET_SCHEDULER_cancel (retry_task);
1468 retry_task = GNUNET_SCHEDULER_NO_TASK;
1470 if (NULL != retry_heap)
1472 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (retry_heap));
1473 GNUNET_CONTAINER_heap_destroy (retry_heap);
1476 if (NULL != forward_map)
1478 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (forward_map));
1479 GNUNET_CONTAINER_multihashmap_destroy (forward_map);
1484 /* end of gnunet-service-dht_clients.c */