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