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