dde8c6d7a03a30dbe83b3e24d30e6625372114af
[oweals/gnunet.git] / src / dht / gnunet-service-dht_clients.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
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.
9
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.
14
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.
19 */
20
21 /**
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
26  */
27
28 #include "platform.h"
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"
36 #include "dht.h"
37
38
39 /**
40  * Linked list of messages to send to clients.
41  */
42 struct PendingMessage
43 {
44   /**
45    * Pointer to next item in the list
46    */
47   struct PendingMessage *next;
48
49   /**
50    * Pointer to previous item in the list
51    */
52   struct PendingMessage *prev;
53
54   /**
55    * Actual message to be sent, allocated at the end of the struct:
56    * // msg = (cast) &pm[1];
57    * // memcpy (&pm[1], data, len);
58    */
59   const struct GNUNET_MessageHeader *msg;
60
61 };
62
63
64 /**
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.
68  */
69 struct ClientList
70 {
71   /**
72    * Linked list of active clients
73    */
74   struct ClientList *next;
75
76   /**
77    * Linked list of active clients
78    */
79   struct ClientList *prev;
80
81   /**
82    * The handle to this client
83    */
84   struct GNUNET_SERVER_Client *client_handle;
85
86   /**
87    * Handle to the current transmission request, NULL
88    * if none pending.
89    */
90   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
91
92   /**
93    * Linked list of pending messages for this client
94    */
95   struct PendingMessage *pending_head;
96
97   /**
98    * Tail of linked list of pending messages for this client
99    */
100   struct PendingMessage *pending_tail;
101
102 };
103
104
105 /**
106  * Entry in the DHT routing table for a client's GET request.
107  */
108 struct ClientQueryRecord
109 {
110
111   /**
112    * The key this request was about
113    */
114   GNUNET_HashCode key;
115
116   /**
117    * Client responsible for the request.
118    */
119   struct ClientList *client;
120
121   /**
122    * Extended query (see gnunet_block_lib.h), allocated at the end of this struct.
123    */
124   const void *xquery;
125
126   /**
127    * Replies we have already seen for this request.
128    */
129   GNUNET_HashCode *seen_replies;
130
131   /**
132    * Pointer to this nodes heap location in the retry-heap (for fast removal)
133    */
134   struct GNUNET_CONTAINER_HeapNode *hnode;
135
136   /**
137    * What's the delay between re-try operations that we currently use for this
138    * request?
139    */
140   struct GNUNET_TIME_Relative retry_frequency;
141
142   /**
143    * What's the next time we should re-try this request?
144    */
145   struct GNUNET_TIME_Absolute retry_time;
146
147   /**
148    * The unique identifier of this request
149    */
150   uint64_t unique_id;
151
152   /**
153    * Number of bytes in xquery.
154    */
155   size_t xquery_size;
156
157   /**
158    * Number of entries in 'seen_replies'.
159    */
160   unsigned int seen_replies_count;
161
162   /**
163    * Desired replication level
164    */
165   uint32_t replication;
166
167   /**
168    * Any message options for this request
169    */
170   uint32_t msg_options;
171
172   /**
173    * The type for the data for the GET request.
174    */
175   enum GNUNET_BLOCK_Type type;
176
177 };
178
179
180 /**
181  * List of active clients.
182  */
183 static struct ClientList *client_head;
184
185 /**
186  * List of active clients.
187  */
188 static struct ClientList *client_tail;
189
190 /**
191  * Hashmap for fast key based lookup, maps keys to 'struct ClientQueryRecord' entries.
192  */
193 static struct GNUNET_CONTAINER_MultiHashMap *forward_map;
194
195 /**
196  * Heap with all of our client's request, sorted by retry time (earliest on top).
197  */
198 static struct GNUNET_CONTAINER_Heap *retry_heap;
199
200 /**
201  * Task that re-transmits requests (using retry_heap).
202  */
203 static GNUNET_SCHEDULER_TaskIdentifier retry_task;
204
205
206 /**
207  * Find a client if it exists, add it otherwise.
208  *
209  * @param client the server handle to the client
210  *
211  * @return the client if found, a new client otherwise
212  */
213 static struct ClientList *
214 find_active_client (struct GNUNET_SERVER_Client *client)
215 {
216   struct ClientList *pos = client_head;
217   struct ClientList *ret;
218
219   while (pos != NULL)
220   {
221     if (pos->client_handle == client)
222       return pos;
223     pos = pos->next;
224   }
225   ret = GNUNET_malloc (sizeof (struct ClientList));
226   ret->client_handle = client;
227   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, ret);
228   return ret;
229 }
230
231
232 /**
233  * Iterator over hash map entries that frees all entries
234  * associated with the given client.
235  *
236  * @param cls client to search for in source routes
237  * @param key current key code (ignored)
238  * @param value value in the hash map, a ClientQueryRecord
239  * @return GNUNET_YES (we should continue to iterate)
240  */
241 static int
242 remove_client_records (void *cls, const GNUNET_HashCode * key, void *value)
243 {
244   struct ClientList *client = cls;
245   struct ClientQueryRecord *record = value;
246
247   if (record->client != client)
248     return GNUNET_YES;
249 #if DEBUG_DHT
250   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
251               "Removing client %p's record for key %s\n", client,
252               GNUNET_h2s (key));
253 #endif
254   GNUNET_assert (GNUNET_YES ==
255                  GNUNET_CONTAINER_multihashmap_remove (forward_map, key,
256                                                        record));
257   if (NULL != record->hnode)
258     GNUNET_CONTAINER_heap_remove_node (record->hnode);
259   GNUNET_array_grow (record->seen_replies, record->seen_replies_count, 0);
260   GNUNET_free (record);
261   return GNUNET_YES;
262 }
263
264
265 /**
266  * Functions with this signature are called whenever a client
267  * is disconnected on the network level.
268  *
269  * @param cls closure (NULL for dht)
270  * @param client identification of the client; NULL
271  *        for the last call when the server is destroyed
272  */
273 static void
274 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
275 {
276   struct ClientList *pos;
277   struct PendingMessage *reply;
278
279 #if DEBUG_DHT
280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Local client %p disconnects\n", client);
281 #endif
282   pos = find_active_client (client);
283   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, pos);
284   if (pos->transmit_handle != NULL)
285     GNUNET_CONNECTION_notify_transmit_ready_cancel (pos->transmit_handle);
286   while (NULL != (reply = pos->pending_head))
287   {
288     GNUNET_CONTAINER_DLL_remove (pos->pending_head, pos->pending_tail, reply);
289     GNUNET_free (reply);
290   }
291   GNUNET_CONTAINER_multihashmap_iterate (forward_map, &remove_client_records,
292                                          pos);
293   GNUNET_free (pos);
294 }
295
296
297 /**
298  * Route the given request via the DHT.  This includes updating
299  * the bloom filter and retransmission times, building the P2P
300  * message and initiating the routing operation.
301  */
302 static void
303 transmit_request (struct ClientQueryRecord *cqr)
304 {
305   int32_t reply_bf_mutator;
306   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
307   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
308
309   GNUNET_STATISTICS_update (GDS_stats,
310                             gettext_noop
311                             ("# GET requests from clients injected"), 1,
312                             GNUNET_NO);
313   reply_bf_mutator =
314       (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
315                                           UINT32_MAX);
316   reply_bf =
317       GNUNET_BLOCK_construct_bloomfilter (reply_bf_mutator, cqr->seen_replies,
318                                           cqr->seen_replies_count);
319   peer_bf =
320       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
321                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
322   GDS_NEIGHBOURS_handle_get (cqr->type, cqr->msg_options, cqr->replication,
323                              0 /* hop count */ ,
324                              &cqr->key, cqr->xquery, cqr->xquery_size, reply_bf,
325                              reply_bf_mutator, peer_bf);
326   GNUNET_CONTAINER_bloomfilter_free (reply_bf);
327   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
328
329   /* exponential back-off for retries, max 1h */
330   cqr->retry_frequency =
331       GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
332                                 GNUNET_TIME_relative_multiply
333                                 (cqr->retry_frequency, 2));
334   cqr->retry_time = GNUNET_TIME_relative_to_absolute (cqr->retry_frequency);
335 }
336
337
338 /**
339  * Task that looks at the 'retry_heap' and transmits all of the requests
340  * on the heap that are ready for transmission.  Then re-schedules
341  * itself (unless the heap is empty).
342  *
343  * @param cls unused
344  * @param tc scheduler context
345  */
346 static void
347 transmit_next_request_task (void *cls,
348                             const struct GNUNET_SCHEDULER_TaskContext *tc)
349 {
350   struct ClientQueryRecord *cqr;
351   struct GNUNET_TIME_Relative delay;
352
353   retry_task = GNUNET_SCHEDULER_NO_TASK;
354   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
355     return;
356   while (NULL != (cqr = GNUNET_CONTAINER_heap_remove_root (retry_heap)))
357   {
358     cqr->hnode = NULL;
359     delay = GNUNET_TIME_absolute_get_remaining (cqr->retry_time);
360     if (delay.rel_value > 0)
361     {
362       cqr->hnode =
363           GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
364                                         cqr->retry_time.abs_value);
365       retry_task =
366           GNUNET_SCHEDULER_add_delayed (delay, &transmit_next_request_task,
367                                         NULL);
368       return;
369     }
370     transmit_request (cqr);
371     cqr->hnode =
372         GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
373                                       cqr->retry_time.abs_value);
374   }
375 }
376
377
378 /**
379  * Handler for PUT messages.
380  *
381  * @param cls closure for the service
382  * @param client the client we received this message from
383  * @param message the actual message received
384  */
385 static void
386 handle_dht_local_put (void *cls, struct GNUNET_SERVER_Client *client,
387                       const struct GNUNET_MessageHeader *message)
388 {
389   const struct GNUNET_DHT_ClientPutMessage *dht_msg;
390   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
391   uint16_t size;
392
393   size = ntohs (message->size);
394   if (size < sizeof (struct GNUNET_DHT_ClientPutMessage))
395   {
396     GNUNET_break (0);
397     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
398     return;
399   }
400   GNUNET_STATISTICS_update (GDS_stats,
401                             gettext_noop
402                             ("# PUT requests received from clients"), 1,
403                             GNUNET_NO);
404   dht_msg = (const struct GNUNET_DHT_ClientPutMessage *) message;
405   /* give to local clients */
406 #if DEBUG_DHT
407   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
408               "Handling local PUT of %u-bytes for query %s\n",
409               size - sizeof (struct GNUNET_DHT_ClientPutMessage),
410               GNUNET_h2s (&dht_msg->key));
411 #endif
412   GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
413                             &dht_msg->key, 0, NULL, 0, NULL,
414                             ntohl (dht_msg->type),
415                             size - sizeof (struct GNUNET_DHT_ClientPutMessage),
416                             &dht_msg[1]);
417   /* store locally */
418   GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
419                             &dht_msg->key, 0, NULL, ntohl (dht_msg->type),
420                             size - sizeof (struct GNUNET_DHT_ClientPutMessage),
421                             &dht_msg[1]);
422   /* route to other peers */
423   peer_bf =
424       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
425                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
426   GDS_NEIGHBOURS_handle_put (ntohl (dht_msg->type), ntohl (dht_msg->options),
427                              ntohl (dht_msg->desired_replication_level),
428                              GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
429                              0 /* hop count */ ,
430                              peer_bf, &dht_msg->key, 0, NULL, &dht_msg[1],
431                              size -
432                              sizeof (struct GNUNET_DHT_ClientPutMessage));
433   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
434   GNUNET_SERVER_receive_done (client, GNUNET_OK);
435 }
436
437
438 /**
439  * Handler for any generic DHT messages, calls the appropriate handler
440  * depending on message type, sends confirmation if responses aren't otherwise
441  * expected.
442  *
443  * @param cls closure for the service
444  * @param client the client we received this message from
445  * @param message the actual message received
446  */
447 static void
448 handle_dht_local_get (void *cls, struct GNUNET_SERVER_Client *client,
449                       const struct GNUNET_MessageHeader *message)
450 {
451   const struct GNUNET_DHT_ClientGetMessage *get;
452   struct ClientQueryRecord *cqr;
453   size_t xquery_size;
454   const char *xquery;
455   uint16_t size;
456
457   size = ntohs (message->size);
458   if (size < sizeof (struct GNUNET_DHT_ClientGetMessage))
459   {
460     GNUNET_break (0);
461     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
462     return;
463   }
464   xquery_size = size - sizeof (struct GNUNET_DHT_ClientGetMessage);
465   get = (const struct GNUNET_DHT_ClientGetMessage *) message;
466   xquery = (const char *) &get[1];
467   GNUNET_STATISTICS_update (GDS_stats,
468                             gettext_noop
469                             ("# GET requests received from clients"), 1,
470                             GNUNET_NO);
471 #if DEBUG_DHT
472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
473               "Received request for %s from local client %p\n",
474               GNUNET_h2s (&get->key), client);
475 #endif
476   cqr = GNUNET_malloc (sizeof (struct ClientQueryRecord) + xquery_size);
477   cqr->key = get->key;
478   cqr->client = find_active_client (client);
479   cqr->xquery = (void *) &cqr[1];
480   memcpy (&cqr[1], xquery, xquery_size);
481   cqr->hnode = GNUNET_CONTAINER_heap_insert (retry_heap, cqr, 0);
482   cqr->retry_frequency = GNUNET_TIME_UNIT_MILLISECONDS;
483   cqr->retry_time = GNUNET_TIME_absolute_get ();
484   cqr->unique_id = get->unique_id;
485   cqr->xquery_size = xquery_size;
486   cqr->replication = ntohl (get->desired_replication_level);
487   cqr->msg_options = ntohl (get->options);
488   cqr->type = ntohl (get->type);
489   GNUNET_CONTAINER_multihashmap_put (forward_map, &get->key, cqr,
490                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
491   /* start remote requests */
492   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
493     GNUNET_SCHEDULER_cancel (retry_task);
494   retry_task = GNUNET_SCHEDULER_add_now (&transmit_next_request_task, NULL);
495   /* perform local lookup */
496   GDS_DATACACHE_handle_get (&get->key, cqr->type, cqr->xquery, xquery_size,
497                             NULL, 0);
498   GNUNET_SERVER_receive_done (client, GNUNET_OK);
499 }
500
501
502 /**
503  * Closure for 'remove_by_unique_id'.
504  */
505 struct RemoveByUniqueIdContext
506 {
507   /**
508    * Client that issued the removal request.
509    */
510   struct ClientList *client;
511
512   /**
513    * Unique ID of the request.
514    */
515   uint64_t unique_id;
516 };
517
518
519 /**
520  * Iterator over hash map entries that frees all entries
521  * that match the given client and unique ID.
522  *
523  * @param cls unique ID and client to search for in source routes
524  * @param key current key code
525  * @param value value in the hash map, a ClientQueryRecord
526  * @return GNUNET_YES (we should continue to iterate)
527  */
528 static int
529 remove_by_unique_id (void *cls, const GNUNET_HashCode * key, void *value)
530 {
531   const struct RemoveByUniqueIdContext *ctx = cls;
532   struct ClientQueryRecord *record = value;
533
534   if (record->unique_id != ctx->unique_id)
535     return GNUNET_YES;
536 #if DEBUG_DHT
537   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
538               "Removing client %p's record for key %s (by unique id)\n",
539               ctx->client->client_handle, GNUNET_h2s (key));
540 #endif
541   return remove_client_records (ctx->client, key, record);
542 }
543
544
545 /**
546  * Handler for any generic DHT stop messages, calls the appropriate handler
547  * depending on message type (if processed locally)
548  *
549  * @param cls closure for the service
550  * @param client the client we received this message from
551  * @param message the actual message received
552  *
553  */
554 static void
555 handle_dht_local_get_stop (void *cls, struct GNUNET_SERVER_Client *client,
556                            const struct GNUNET_MessageHeader *message)
557 {
558   const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg =
559       (const struct GNUNET_DHT_ClientGetStopMessage *) message;
560   struct RemoveByUniqueIdContext ctx;
561
562   GNUNET_STATISTICS_update (GDS_stats,
563                             gettext_noop
564                             ("# GET STOP requests received from clients"), 1,
565                             GNUNET_NO);
566 #if DEBUG_DHT
567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p stopped request for key %s\n",
568               client, GNUNET_h2s (&dht_stop_msg->key));
569 #endif
570   ctx.client = find_active_client (client);
571   ctx.unique_id = dht_stop_msg->unique_id;
572   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, &dht_stop_msg->key,
573                                               &remove_by_unique_id, &ctx);
574   GNUNET_SERVER_receive_done (client, GNUNET_OK);
575 }
576
577
578 /**
579  * Task run to check for messages that need to be sent to a client.
580  *
581  * @param client a ClientList, containing the client and any messages to be sent to it
582  */
583 static void
584 process_pending_messages (struct ClientList *client);
585
586
587 /**
588  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
589  * request.  A ClientList is passed as closure, take the head of the list
590  * and copy it into buf, which has the result of sending the message to the
591  * client.
592  *
593  * @param cls closure to this call
594  * @param size maximum number of bytes available to send
595  * @param buf where to copy the actual message to
596  *
597  * @return the number of bytes actually copied, 0 indicates failure
598  */
599 static size_t
600 send_reply_to_client (void *cls, size_t size, void *buf)
601 {
602   struct ClientList *client = cls;
603   char *cbuf = buf;
604   struct PendingMessage *reply;
605   size_t off;
606   size_t msize;
607
608   client->transmit_handle = NULL;
609   if (buf == NULL)
610   {
611     /* client disconnected */
612 #if DEBUG_DHT
613     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
614                 "Client %p disconnected, pending messages will be discarded\n",
615                 client->client_handle);
616 #endif
617     return 0;
618   }
619   off = 0;
620   while ((NULL != (reply = client->pending_head)) &&
621          (size >= off + (msize = ntohs (reply->msg->size))))
622   {
623     GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
624                                  reply);
625     memcpy (&cbuf[off], reply->msg, msize);
626     GNUNET_free (reply);
627 #if DEBUG_DHT
628     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes to client %p\n",
629                 msize, client->client_handle);
630 #endif
631     off += msize;
632   }
633   process_pending_messages (client);
634 #if DEBUG_DHT
635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitted %u/%u bytes to client %p\n",
636               (unsigned int) off, (unsigned int) size, client->client_handle);
637 #endif
638   return off;
639 }
640
641
642 /**
643  * Task run to check for messages that need to be sent to a client.
644  *
645  * @param client a ClientList, containing the client and any messages to be sent to it
646  */
647 static void
648 process_pending_messages (struct ClientList *client)
649 {
650   if ((client->pending_head == NULL) || (client->transmit_handle != NULL))
651   {
652 #if DEBUG_DHT
653     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
654                 "Not asking for transmission to %p now: %s\n",
655                 client->client_handle,
656                 client->pending_head ==
657                 NULL ? "no more messages" : "request already pending");
658 #endif
659     return;
660   }
661 #if DEBUG_DHT
662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
663               "Asking for transmission of %u bytes to client %p\n",
664               ntohs (client->pending_head->msg->size), client->client_handle);
665 #endif
666   client->transmit_handle =
667       GNUNET_SERVER_notify_transmit_ready (client->client_handle,
668                                            ntohs (client->pending_head->
669                                                   msg->size),
670                                            GNUNET_TIME_UNIT_FOREVER_REL,
671                                            &send_reply_to_client, client);
672 }
673
674
675 /**
676  * Add a PendingMessage to the clients list of messages to be sent
677  *
678  * @param client the active client to send the message to
679  * @param pending_message the actual message to send
680  */
681 static void
682 add_pending_message (struct ClientList *client,
683                      struct PendingMessage *pending_message)
684 {
685   GNUNET_CONTAINER_DLL_insert_tail (client->pending_head, client->pending_tail,
686                                     pending_message);
687   process_pending_messages (client);
688 }
689
690
691 /**
692  * Closure for 'forward_reply'
693  */
694 struct ForwardReplyContext
695 {
696
697   /**
698    * Actual message to send to matching clients.
699    */
700   struct PendingMessage *pm;
701
702   /**
703    * Embedded payload.
704    */
705   const void *data;
706
707   /**
708    * Type of the data.
709    */
710   enum GNUNET_BLOCK_Type type;
711
712   /**
713    * Number of bytes in data.
714    */
715   size_t data_size;
716
717   /**
718    * Do we need to copy 'pm' because it was already used?
719    */
720   int do_copy;
721
722 };
723
724
725 /**
726  * Iterator over hash map entries that send a given reply to
727  * each of the matching clients.  With some tricky recycling
728  * of the buffer.
729  *
730  * @param cls the 'struct ForwardReplyContext'
731  * @param key current key
732  * @param value value in the hash map, a ClientQueryRecord
733  * @return GNUNET_YES (we should continue to iterate),
734  *         if the result is mal-formed, GNUNET_NO
735  */
736 static int
737 forward_reply (void *cls, const GNUNET_HashCode * key, void *value)
738 {
739   struct ForwardReplyContext *frc = cls;
740   struct ClientQueryRecord *record = value;
741   struct PendingMessage *pm;
742   struct GNUNET_DHT_ClientResultMessage *reply;
743   enum GNUNET_BLOCK_EvaluationResult eval;
744   int do_free;
745   GNUNET_HashCode ch;
746   unsigned int i;
747
748   if ((record->type != GNUNET_BLOCK_TYPE_ANY) && (record->type != frc->type))
749   {
750 #if DEBUG_DHT
751     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
752                 "Record type missmatch, not passing request for key %s to local client\n",
753                 GNUNET_h2s (key));
754 #endif
755     GNUNET_STATISTICS_update (GDS_stats,
756                               gettext_noop
757                               ("# Key match, type mismatches in REPLY to CLIENT"),
758                               1, GNUNET_NO);
759     return GNUNET_YES;          /* type mismatch */
760   }
761   GNUNET_CRYPTO_hash (frc->data, frc->data_size, &ch);
762   for (i = 0; i < record->seen_replies_count; i++)
763     if (0 == memcmp (&record->seen_replies[i], &ch, sizeof (GNUNET_HashCode)))
764     {
765 #if DEBUG_DHT
766       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
767                   "Duplicate reply, not passing request for key %s to local client\n",
768                   GNUNET_h2s (key));
769 #endif
770       GNUNET_STATISTICS_update (GDS_stats,
771                                 gettext_noop
772                                 ("# Duplicate REPLIES to CLIENT request dropped"),
773                                 1, GNUNET_NO);
774       return GNUNET_YES;        /* duplicate */
775     }
776   eval =
777       GNUNET_BLOCK_evaluate (GDS_block_context, record->type, key, NULL, 0,
778                              record->xquery, record->xquery_size, frc->data,
779                              frc->data_size);
780 #if DEBUG_DHT
781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782               "Evaluation result is %d for key %s for local client's query\n",
783               (int) eval, GNUNET_h2s (key));
784 #endif
785   switch (eval)
786   {
787   case GNUNET_BLOCK_EVALUATION_OK_LAST:
788     do_free = GNUNET_YES;
789     break;
790   case GNUNET_BLOCK_EVALUATION_OK_MORE:
791     GNUNET_array_append (record->seen_replies, record->seen_replies_count, ch);
792     do_free = GNUNET_NO;
793     break;
794   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
795     /* should be impossible to encounter here */
796     GNUNET_break (0);
797     return GNUNET_YES;
798   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
799     GNUNET_break_op (0);
800     return GNUNET_NO;
801   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
802     GNUNET_break (0);
803     return GNUNET_NO;
804   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
805     GNUNET_break (0);
806     return GNUNET_NO;
807   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
808     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
809                 _("Unsupported block type (%u) in request!\n"), record->type);
810     return GNUNET_NO;
811   default:
812     GNUNET_break (0);
813     return GNUNET_NO;
814   }
815   if (GNUNET_NO == frc->do_copy)
816   {
817     /* first time, we can use the original data */
818     pm = frc->pm;
819     frc->do_copy = GNUNET_YES;
820   }
821   else
822   {
823     /* two clients waiting for same reply, must copy for queueing */
824     pm = GNUNET_malloc (sizeof (struct PendingMessage) +
825                         ntohs (frc->pm->msg->size));
826     memcpy (pm, frc->pm,
827             sizeof (struct PendingMessage) + ntohs (frc->pm->msg->size));
828     pm->next = pm->prev = NULL;
829   }
830   GNUNET_STATISTICS_update (GDS_stats,
831                             gettext_noop ("# RESULTS queued for clients"), 1,
832                             GNUNET_NO);
833   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
834   reply->unique_id = record->unique_id;
835 #if DEBUG_DHT
836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
837               "Queueing reply to query %s for client %p\n", GNUNET_h2s (key),
838               record->client->client_handle);
839 #endif
840   add_pending_message (record->client, pm);
841   if (GNUNET_YES == do_free)
842     remove_client_records (record->client, key, record);
843   return GNUNET_YES;
844 }
845
846
847 /**
848  * Handle a reply we've received from another peer.  If the reply
849  * matches any of our pending queries, forward it to the respective
850  * client(s).
851  *
852  * @param expiration when will the reply expire
853  * @param key the query this reply is for
854  * @param get_path_length number of peers in 'get_path'
855  * @param get_path path the reply took on get
856  * @param put_path_length number of peers in 'put_path'
857  * @param put_path path the reply took on put
858  * @param type type of the reply
859  * @param data_size number of bytes in 'data'
860  * @param data application payload data
861  */
862 void
863 GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration,
864                           const GNUNET_HashCode * key,
865                           unsigned int get_path_length,
866                           const struct GNUNET_PeerIdentity *get_path,
867                           unsigned int put_path_length,
868                           const struct GNUNET_PeerIdentity *put_path,
869                           enum GNUNET_BLOCK_Type type, size_t data_size,
870                           const void *data)
871 {
872   struct ForwardReplyContext frc;
873   struct PendingMessage *pm;
874   struct GNUNET_DHT_ClientResultMessage *reply;
875   struct GNUNET_PeerIdentity *paths;
876   size_t msize;
877
878   if (NULL == GNUNET_CONTAINER_multihashmap_get (forward_map, key))
879   {
880     GNUNET_STATISTICS_update (GDS_stats,
881                               gettext_noop
882                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
883                               GNUNET_NO);
884     return;                     /* no matching request, fast exit! */
885   }
886   msize =
887       sizeof (struct GNUNET_DHT_ClientResultMessage) + data_size +
888       (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
889   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
890   {
891     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
892                 _("Could not pass reply to client, message too big!\n"));
893     return;
894   }
895   pm = (struct PendingMessage *) GNUNET_malloc (msize +
896                                                 sizeof (struct PendingMessage));
897   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
898   pm->msg = &reply->header;
899   reply->header.size = htons ((uint16_t) msize);
900   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT);
901   reply->type = htonl (type);
902   reply->get_path_length = htonl (get_path_length);
903   reply->put_path_length = htonl (put_path_length);
904   reply->unique_id = 0;         /* filled in later */
905   reply->expiration = GNUNET_TIME_absolute_hton (expiration);
906   reply->key = *key;
907   paths = (struct GNUNET_PeerIdentity *) &reply[1];
908   memcpy (paths, put_path,
909           sizeof (struct GNUNET_PeerIdentity) * put_path_length);
910   memcpy (&paths[put_path_length], get_path,
911           sizeof (struct GNUNET_PeerIdentity) * get_path_length);
912   memcpy (&paths[get_path_length + put_path_length], data, data_size);
913   frc.do_copy = GNUNET_NO;
914   frc.pm = pm;
915   frc.data = data;
916   frc.data_size = data_size;
917   frc.type = type;
918   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, key, &forward_reply,
919                                               &frc);
920   if (GNUNET_NO == frc.do_copy)
921   {
922     /* did not match any of the requests, free! */
923     GNUNET_STATISTICS_update (GDS_stats,
924                               gettext_noop
925                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
926                               GNUNET_NO);
927     GNUNET_free (pm);
928   }
929 }
930
931
932 /**
933  * Initialize client subsystem.
934  *
935  * @param server the initialized server
936  */
937 void
938 GDS_CLIENTS_init (struct GNUNET_SERVER_Handle *server)
939 {
940   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
941     {&handle_dht_local_put, NULL,
942      GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, 0},
943     {&handle_dht_local_get, NULL,
944      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, 0},
945     {&handle_dht_local_get_stop, NULL,
946      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP,
947      sizeof (struct GNUNET_DHT_ClientGetStopMessage)},
948     {NULL, NULL, 0, 0}
949   };
950   forward_map = GNUNET_CONTAINER_multihashmap_create (1024);
951   retry_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
952   GNUNET_SERVER_add_handlers (server, plugin_handlers);
953   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
954 }
955
956
957 /**
958  * Shutdown client subsystem.
959  */
960 void
961 GDS_CLIENTS_done ()
962 {
963   GNUNET_assert (client_head == NULL);
964   GNUNET_assert (client_tail == NULL);
965   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
966   {
967     GNUNET_SCHEDULER_cancel (retry_task);
968     retry_task = GNUNET_SCHEDULER_NO_TASK;
969   }
970   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (retry_heap));
971   GNUNET_CONTAINER_heap_destroy (retry_heap);
972   retry_heap = NULL;
973   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (forward_map));
974   GNUNET_CONTAINER_multihashmap_destroy (forward_map);
975   forward_map = NULL;
976 }
977
978 /* end of gnunet-service-dht_clients.c */