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