-implementing #2435
[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_SERVER_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   struct 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   struct 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   struct GNUNET_HashCode         *key;
205
206   /**
207    * Flag whether to notify about GET messages.
208    */
209   int16_t get;
210
211   /**
212    * Flag whether to notify about GET_REPONSE messages.
213    */
214   int16_t get_resp;
215
216   /**
217    * Flag whether to notify about PUT messages.
218    */
219   uint16_t put;
220
221   /**
222    * Client to notify of these requests.
223    */
224   struct ClientList             *client;
225 };
226
227
228 /**
229  * List of active clients.
230  */
231 static struct ClientList *client_head;
232
233 /**
234  * List of active clients.
235  */
236 static struct ClientList *client_tail;
237
238 /**
239  * List of active monitoring requests.
240  */
241 static struct ClientMonitorRecord *monitor_head;
242
243 /**
244  * List of active monitoring requests.
245  */
246 static struct ClientMonitorRecord *monitor_tail;
247
248 /**
249  * Hashmap for fast key based lookup, maps keys to 'struct ClientQueryRecord' entries.
250  */
251 static struct GNUNET_CONTAINER_MultiHashMap *forward_map;
252
253 /**
254  * Heap with all of our client's request, sorted by retry time (earliest on top).
255  */
256 static struct GNUNET_CONTAINER_Heap *retry_heap;
257
258 /**
259  * Task that re-transmits requests (using retry_heap).
260  */
261 static GNUNET_SCHEDULER_TaskIdentifier retry_task;
262
263
264 /**
265  * Task run to check for messages that need to be sent to a client.
266  *
267  * @param client a ClientList, containing the client and any messages to be sent to it
268  */
269 static void
270 process_pending_messages (struct ClientList *client);
271
272
273 /**
274  * Add a PendingMessage to the clients list of messages to be sent
275  *
276  * @param client the active client to send the message to
277  * @param pending_message the actual message to send
278  */
279 static void
280 add_pending_message (struct ClientList *client,
281                      struct PendingMessage *pending_message)
282 {
283   GNUNET_CONTAINER_DLL_insert_tail (client->pending_head, client->pending_tail,
284                                     pending_message);
285   process_pending_messages (client);
286 }
287
288
289 /**
290  * Find a client if it exists, add it otherwise.
291  *
292  * @param client the server handle to the client
293  *
294  * @return the client if found, a new client otherwise
295  */
296 static struct ClientList *
297 find_active_client (struct GNUNET_SERVER_Client *client)
298 {
299   struct ClientList *pos = client_head;
300   struct ClientList *ret;
301
302   while (pos != NULL)
303   {
304     if (pos->client_handle == client)
305       return pos;
306     pos = pos->next;
307   }
308   ret = GNUNET_malloc (sizeof (struct ClientList));
309   ret->client_handle = client;
310   GNUNET_CONTAINER_DLL_insert (client_head, client_tail, ret);
311   return ret;
312 }
313
314
315 /**
316  * Iterator over hash map entries that frees all entries
317  * associated with the given client.
318  *
319  * @param cls client to search for in source routes
320  * @param key current key code (ignored)
321  * @param value value in the hash map, a ClientQueryRecord
322  * @return GNUNET_YES (we should continue to iterate)
323  */
324 static int
325 remove_client_records (void *cls, const struct GNUNET_HashCode * key, void *value)
326 {
327   struct ClientList *client = cls;
328   struct ClientQueryRecord *record = value;
329
330   if (record->client != client)
331     return GNUNET_YES;
332   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
333               "Removing client %p's record for key %s\n", client,
334               GNUNET_h2s (key));
335   GNUNET_assert (GNUNET_YES ==
336                  GNUNET_CONTAINER_multihashmap_remove (forward_map, key,
337                                                        record));
338   if (NULL != record->hnode)
339     GNUNET_CONTAINER_heap_remove_node (record->hnode);
340   GNUNET_array_grow (record->seen_replies, record->seen_replies_count, 0);
341   GNUNET_free (record);
342   return GNUNET_YES;
343 }
344
345
346 /**
347  * Functions with this signature are called whenever a client
348  * is disconnected on the network level.
349  *
350  * @param cls closure (NULL for dht)
351  * @param client identification of the client; NULL
352  *        for the last call when the server is destroyed
353  */
354 static void
355 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
356 {
357   struct ClientList *pos;
358   struct PendingMessage *reply;
359   struct ClientMonitorRecord *monitor;
360
361   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Local client %p disconnects\n", client);
362   pos = find_active_client (client);
363   GNUNET_CONTAINER_DLL_remove (client_head, client_tail, pos);
364   if (pos->transmit_handle != NULL)
365     GNUNET_SERVER_notify_transmit_ready_cancel (pos->transmit_handle);
366   while (NULL != (reply = pos->pending_head))
367   {
368     GNUNET_CONTAINER_DLL_remove (pos->pending_head, pos->pending_tail, reply);
369     GNUNET_free (reply);
370   }
371   monitor = monitor_head;
372   while (NULL != monitor)
373   {
374     if (monitor->client == pos)
375     {
376       struct ClientMonitorRecord *next;
377       
378       GNUNET_free_non_null (monitor->key);
379       next = monitor->next;
380       GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, monitor);
381       GNUNET_free (monitor);
382       monitor = next;
383     }
384     else
385       monitor = monitor->next;
386   }
387   GNUNET_CONTAINER_multihashmap_iterate (forward_map, &remove_client_records,
388                                          pos);
389   GNUNET_free (pos);
390 }
391
392
393 /**
394  * Route the given request via the DHT.  This includes updating
395  * the bloom filter and retransmission times, building the P2P
396  * message and initiating the routing operation.
397  */
398 static void
399 transmit_request (struct ClientQueryRecord *cqr)
400 {
401   int32_t reply_bf_mutator;
402   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
403   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
404
405   GNUNET_STATISTICS_update (GDS_stats,
406                             gettext_noop
407                             ("# GET requests from clients injected"), 1,
408                             GNUNET_NO);
409   reply_bf_mutator =
410       (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
411                                           UINT32_MAX);
412   reply_bf =
413       GNUNET_BLOCK_construct_bloomfilter (reply_bf_mutator, cqr->seen_replies,
414                                           cqr->seen_replies_count);
415   peer_bf =
416       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
417                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
418   GDS_NEIGHBOURS_handle_get (cqr->type, cqr->msg_options, cqr->replication,
419                              0 /* hop count */ ,
420                              &cqr->key, cqr->xquery, cqr->xquery_size, reply_bf,
421                              reply_bf_mutator, peer_bf);
422   GNUNET_CONTAINER_bloomfilter_free (reply_bf);
423   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
424
425   /* exponential back-off for retries, max 1h */
426   cqr->retry_frequency =
427       GNUNET_TIME_relative_min (GNUNET_TIME_UNIT_HOURS,
428                                 GNUNET_TIME_relative_multiply
429                                 (cqr->retry_frequency, 2));
430   cqr->retry_time = GNUNET_TIME_relative_to_absolute (cqr->retry_frequency);
431 }
432
433
434 /**
435  * Task that looks at the 'retry_heap' and transmits all of the requests
436  * on the heap that are ready for transmission.  Then re-schedules
437  * itself (unless the heap is empty).
438  *
439  * @param cls unused
440  * @param tc scheduler context
441  */
442 static void
443 transmit_next_request_task (void *cls,
444                             const struct GNUNET_SCHEDULER_TaskContext *tc)
445 {
446   struct ClientQueryRecord *cqr;
447   struct GNUNET_TIME_Relative delay;
448
449   retry_task = GNUNET_SCHEDULER_NO_TASK;
450   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
451     return;
452   while (NULL != (cqr = GNUNET_CONTAINER_heap_remove_root (retry_heap)))
453   {
454     cqr->hnode = NULL;
455     delay = GNUNET_TIME_absolute_get_remaining (cqr->retry_time);
456     if (delay.rel_value > 0)
457     {
458       cqr->hnode =
459           GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
460                                         cqr->retry_time.abs_value);
461       retry_task =
462           GNUNET_SCHEDULER_add_delayed (delay, &transmit_next_request_task,
463                                         NULL);
464       return;
465     }
466     transmit_request (cqr);
467     cqr->hnode =
468         GNUNET_CONTAINER_heap_insert (retry_heap, cqr,
469                                       cqr->retry_time.abs_value);
470   }
471 }
472
473
474 /**
475  * Handler for PUT messages.
476  *
477  * @param cls closure for the service
478  * @param client the client we received this message from
479  * @param message the actual message received
480  */
481 static void
482 handle_dht_local_put (void *cls, struct GNUNET_SERVER_Client *client,
483                       const struct GNUNET_MessageHeader *message)
484 {
485   const struct GNUNET_DHT_ClientPutMessage *dht_msg;
486   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
487   uint16_t size;
488   struct PendingMessage *pm;
489   struct GNUNET_DHT_ClientPutConfirmationMessage *conf;
490
491   size = ntohs (message->size);
492   if (size < sizeof (struct GNUNET_DHT_ClientPutMessage))
493   {
494     GNUNET_break (0);
495     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
496     return;
497   }
498   GNUNET_STATISTICS_update (GDS_stats,
499                             gettext_noop
500                             ("# PUT requests received from clients"), 1,
501                             GNUNET_NO);
502   dht_msg = (const struct GNUNET_DHT_ClientPutMessage *) message;
503   /* give to local clients */
504   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
505               "Handling local PUT of %u-bytes for query %s\n",
506               size - sizeof (struct GNUNET_DHT_ClientPutMessage),
507               GNUNET_h2s (&dht_msg->key));
508   GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
509                             &dht_msg->key, 0, NULL, 0, NULL,
510                             ntohl (dht_msg->type),
511                             size - sizeof (struct GNUNET_DHT_ClientPutMessage),
512                             &dht_msg[1]);
513   /* store locally */
514   GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
515                             &dht_msg->key, 0, NULL, ntohl (dht_msg->type),
516                             size - sizeof (struct GNUNET_DHT_ClientPutMessage),
517                             &dht_msg[1]);
518   /* route to other peers */
519   peer_bf =
520       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
521                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
522   GDS_NEIGHBOURS_handle_put (ntohl (dht_msg->type), ntohl (dht_msg->options),
523                              ntohl (dht_msg->desired_replication_level),
524                              GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
525                              0 /* hop count */ ,
526                              peer_bf, &dht_msg->key, 0, NULL, &dht_msg[1],
527                              size -
528                              sizeof (struct GNUNET_DHT_ClientPutMessage));
529   GDS_CLIENTS_process_put (ntohl (dht_msg->options),
530                            ntohl (dht_msg->type),
531                            0,
532                            ntohl (dht_msg->desired_replication_level),
533                            1,
534                            GDS_NEIGHBOURS_get_id(),
535                            GNUNET_TIME_absolute_ntoh (dht_msg->expiration),
536                            &dht_msg->key,
537                            &dht_msg[1],
538                            size - sizeof (struct GNUNET_DHT_ClientPutMessage));
539   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
540   pm = GNUNET_malloc (sizeof (struct PendingMessage) + 
541                       sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage));
542   conf = (struct GNUNET_DHT_ClientPutConfirmationMessage *) &pm[1];
543   conf->header.size = htons (sizeof (struct GNUNET_DHT_ClientPutConfirmationMessage));
544   conf->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT_OK);
545   conf->reserved = htonl (0);
546   conf->unique_id = dht_msg->unique_id;
547   pm->msg = &conf->header;
548   add_pending_message (find_active_client (client), pm);
549   GNUNET_SERVER_receive_done (client, GNUNET_OK);
550 }
551
552
553 /**
554  * Handler for DHT GET messages from the client.
555  *
556  * @param cls closure for the service
557  * @param client the client we received this message from
558  * @param message the actual message received
559  */
560 static void
561 handle_dht_local_get (void *cls, struct GNUNET_SERVER_Client *client,
562                       const struct GNUNET_MessageHeader *message)
563 {
564   const struct GNUNET_DHT_ClientGetMessage *get;
565   struct ClientQueryRecord *cqr;
566   size_t xquery_size;
567   const char *xquery;
568   uint16_t size;
569
570   size = ntohs (message->size);
571   if (size < sizeof (struct GNUNET_DHT_ClientGetMessage))
572   {
573     GNUNET_break (0);
574     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
575     return;
576   }
577   xquery_size = size - sizeof (struct GNUNET_DHT_ClientGetMessage);
578   get = (const struct GNUNET_DHT_ClientGetMessage *) message;
579   xquery = (const char *) &get[1];
580   GNUNET_STATISTICS_update (GDS_stats,
581                             gettext_noop
582                             ("# GET requests received from clients"), 1,
583                             GNUNET_NO);
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585               "Received request for %s from local client %p\n",
586               GNUNET_h2s (&get->key), client);
587   cqr = GNUNET_malloc (sizeof (struct ClientQueryRecord) + xquery_size);
588   cqr->key = get->key;
589   cqr->client = find_active_client (client);
590   cqr->xquery = (void *) &cqr[1];
591   memcpy (&cqr[1], xquery, xquery_size);
592   cqr->hnode = GNUNET_CONTAINER_heap_insert (retry_heap, cqr, 0);
593   cqr->retry_frequency = GNUNET_TIME_UNIT_MILLISECONDS;
594   cqr->retry_time = GNUNET_TIME_absolute_get ();
595   cqr->unique_id = get->unique_id;
596   cqr->xquery_size = xquery_size;
597   cqr->replication = ntohl (get->desired_replication_level);
598   cqr->msg_options = ntohl (get->options);
599   cqr->type = ntohl (get->type);
600   // FIXME use cqr->key, set multihashmap create to GNUNET_YES
601   GNUNET_CONTAINER_multihashmap_put (forward_map, &get->key, cqr,
602                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
603   GDS_CLIENTS_process_get (ntohl (get->options),
604                            ntohl (get->type),
605                            0,
606                            ntohl (get->desired_replication_level),
607                            1,
608                            GDS_NEIGHBOURS_get_id(),
609                            &get->key);
610   /* start remote requests */
611   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
612     GNUNET_SCHEDULER_cancel (retry_task);
613   retry_task = GNUNET_SCHEDULER_add_now (&transmit_next_request_task, NULL);
614   /* perform local lookup */
615   GDS_DATACACHE_handle_get (&get->key, cqr->type, cqr->xquery, xquery_size,
616                             NULL, 0);
617   GNUNET_SERVER_receive_done (client, GNUNET_OK);
618 }
619
620
621 /**
622  * Closure for 'find_by_unique_id'.
623  */
624 struct FindByUniqueIdContext
625 {
626   /**
627    * Where to store the result, if found.
628    */
629   struct ClientQueryRecord *cqr;
630
631   uint64_t unique_id;
632 };
633
634
635 /**
636  * Function called for each existing DHT record for the given
637  * query.  Checks if it matches the UID given in the closure
638  * and if so returns the entry as a result.
639  *
640  * @param cls the search context
641  * @param key query for the lookup (not used)
642  * @param value the 'struct ClientQueryRecord'
643  * @return GNUNET_YES to continue iteration (result not yet found)
644  */
645 static int
646 find_by_unique_id (void *cls,
647                    const struct GNUNET_HashCode *key,
648                    void *value)
649 {
650   struct FindByUniqueIdContext *fui_ctx = cls;
651   struct ClientQueryRecord *cqr = value;
652
653   if (cqr->unique_id != fui_ctx->unique_id)
654     return GNUNET_YES;
655   fui_ctx->cqr = cqr;
656   return GNUNET_NO;
657 }
658
659
660 /**
661  * Handler for "GET result seen" messages from the client.
662  *
663  * @param cls closure for the service
664  * @param client the client we received this message from
665  * @param message the actual message received
666  */
667 static void
668 handle_dht_local_get_result_seen (void *cls, struct GNUNET_SERVER_Client *client,
669                                   const struct GNUNET_MessageHeader *message)
670 {
671   const struct GNUNET_DHT_ClientGetResultSeenMessage *seen;
672   uint16_t size;
673   unsigned int hash_count;
674   unsigned int old_count;
675   const struct GNUNET_HashCode *hc;
676   struct FindByUniqueIdContext fui_ctx;
677   struct ClientQueryRecord *cqr;
678
679   size = ntohs (message->size);
680   if (size < sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage))
681   {
682     GNUNET_break (0);
683     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
684     return;
685   }
686   seen = (const struct GNUNET_DHT_ClientGetResultSeenMessage *) message;
687   hash_count = (size - sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage)) / sizeof (struct GNUNET_HashCode);
688   if (size != sizeof (struct GNUNET_DHT_ClientGetResultSeenMessage) + hash_count * sizeof (struct GNUNET_HashCode))
689   {
690     GNUNET_break (0);
691     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
692     return;
693   }
694   hc = (const struct GNUNET_HashCode*) &seen[1];
695   fui_ctx.unique_id = seen->unique_id;
696   fui_ctx.cqr = NULL;
697   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map,
698                                               &seen->key,
699                                               &find_by_unique_id,
700                                               &fui_ctx);
701   if (NULL == (cqr = fui_ctx.cqr))
702   {
703     GNUNET_break (0);
704     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
705     return;
706   }
707   /* finally, update 'seen' list */
708   old_count = cqr->seen_replies_count;
709   GNUNET_array_grow (cqr->seen_replies,
710                      cqr->seen_replies_count,
711                      cqr->seen_replies_count + hash_count);
712   memcpy (&cqr->seen_replies[old_count],
713           hc,
714           sizeof (struct GNUNET_HashCode) * hash_count);
715 }
716
717
718 /**
719  * Closure for 'remove_by_unique_id'.
720  */
721 struct RemoveByUniqueIdContext
722 {
723   /**
724    * Client that issued the removal request.
725    */
726   struct ClientList *client;
727
728   /**
729    * Unique ID of the request.
730    */
731   uint64_t unique_id;
732 };
733
734
735 /**
736  * Iterator over hash map entries that frees all entries
737  * that match the given client and unique ID.
738  *
739  * @param cls unique ID and client to search for in source routes
740  * @param key current key code
741  * @param value value in the hash map, a ClientQueryRecord
742  * @return GNUNET_YES (we should continue to iterate)
743  */
744 static int
745 remove_by_unique_id (void *cls, const struct GNUNET_HashCode * key, void *value)
746 {
747   const struct RemoveByUniqueIdContext *ctx = cls;
748   struct ClientQueryRecord *record = value;
749
750   if (record->unique_id != ctx->unique_id)
751     return GNUNET_YES;
752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
753               "Removing client %p's record for key %s (by unique id)\n",
754               ctx->client->client_handle, GNUNET_h2s (key));
755   return remove_client_records (ctx->client, key, record);
756 }
757
758
759 /**
760  * Handler for any generic DHT stop messages, calls the appropriate handler
761  * depending on message type (if processed locally)
762  *
763  * @param cls closure for the service
764  * @param client the client we received this message from
765  * @param message the actual message received
766  *
767  */
768 static void
769 handle_dht_local_get_stop (void *cls, struct GNUNET_SERVER_Client *client,
770                            const struct GNUNET_MessageHeader *message)
771 {
772   const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg =
773       (const struct GNUNET_DHT_ClientGetStopMessage *) message;
774   struct RemoveByUniqueIdContext ctx;
775
776   GNUNET_STATISTICS_update (GDS_stats,
777                             gettext_noop
778                             ("# GET STOP requests received from clients"), 1,
779                             GNUNET_NO);
780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p stopped request for key %s\n",
781               client, GNUNET_h2s (&dht_stop_msg->key));
782   ctx.client = find_active_client (client);
783   ctx.unique_id = dht_stop_msg->unique_id;
784   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, &dht_stop_msg->key,
785                                               &remove_by_unique_id, &ctx);
786   GNUNET_SERVER_receive_done (client, GNUNET_OK);
787 }
788
789
790 /**
791  * Handler for monitor start messages
792  *
793  * @param cls closure for the service
794  * @param client the client we received this message from
795  * @param message the actual message received
796  *
797  */
798 static void
799 handle_dht_local_monitor (void *cls, struct GNUNET_SERVER_Client *client,
800                           const struct GNUNET_MessageHeader *message)
801 {
802   struct ClientMonitorRecord *r;
803   const struct GNUNET_DHT_MonitorStartStopMessage *msg;
804
805   msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
806   r = GNUNET_malloc (sizeof(struct ClientMonitorRecord));
807
808   r->client = find_active_client(client);
809   r->type = ntohl(msg->type);
810   r->get = ntohs(msg->get);
811   r->get_resp = ntohs(msg->get_resp);
812   r->put = ntohs(msg->put);
813   if (0 == ntohs(msg->filter_key))
814       r->key = NULL;
815   else
816   {
817     r->key = GNUNET_malloc (sizeof (struct GNUNET_HashCode));
818     memcpy (r->key, &msg->key, sizeof (struct GNUNET_HashCode));
819   }
820   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, r);
821   GNUNET_SERVER_receive_done (client, GNUNET_OK);
822 }
823
824 /**
825  * Handler for monitor stop messages
826  *
827  * @param cls closure for the service
828  * @param client the client we received this message from
829  * @param message the actual message received
830  *
831  */
832 static void
833 handle_dht_local_monitor_stop (void *cls, struct GNUNET_SERVER_Client *client,
834                                const struct GNUNET_MessageHeader *message)
835 {
836   struct ClientMonitorRecord *r;
837   const struct GNUNET_DHT_MonitorStartStopMessage *msg;
838   int keys_match;
839
840   msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
841   r = monitor_head;
842
843   while (NULL != r)
844   {
845     if (NULL == r->key)
846         keys_match = (0 == ntohs(msg->filter_key));
847     else
848     {
849         keys_match = (0 != ntohs(msg->filter_key)
850                       && !memcmp(r->key, &msg->key, sizeof(struct GNUNET_HashCode)));
851     }
852     if (find_active_client(client) == r->client
853         && ntohl(msg->type) == r->type
854         && r->get == msg->get
855         && r->get_resp == msg->get_resp
856         && r->put == msg->put
857         && keys_match
858         )
859     {
860         GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, r);
861         GNUNET_free_non_null (r->key);
862         GNUNET_free (r);
863         GNUNET_SERVER_receive_done (client, GNUNET_OK);
864         return; /* Delete only ONE entry */
865     }
866     r = r->next;
867   }
868  
869   GNUNET_SERVER_receive_done (client, GNUNET_OK);
870 }
871
872
873 /**
874  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
875  * request.  A ClientList is passed as closure, take the head of the list
876  * and copy it into buf, which has the result of sending the message to the
877  * client.
878  *
879  * @param cls closure to this call
880  * @param size maximum number of bytes available to send
881  * @param buf where to copy the actual message to
882  *
883  * @return the number of bytes actually copied, 0 indicates failure
884  */
885 static size_t
886 send_reply_to_client (void *cls, size_t size, void *buf)
887 {
888   struct ClientList *client = cls;
889   char *cbuf = buf;
890   struct PendingMessage *reply;
891   size_t off;
892   size_t msize;
893
894   client->transmit_handle = NULL;
895   if (buf == NULL)
896   {
897     /* client disconnected */
898     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
899                 "Client %p disconnected, pending messages will be discarded\n",
900                 client->client_handle);
901     return 0;
902   }
903   off = 0;
904   while ((NULL != (reply = client->pending_head)) &&
905          (size >= off + (msize = ntohs (reply->msg->size))))
906   {
907     GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
908                                  reply);
909     memcpy (&cbuf[off], reply->msg, msize);
910     GNUNET_free (reply);
911     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes to client %p\n",
912                 msize, client->client_handle);
913     off += msize;
914   }
915   process_pending_messages (client);
916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitted %u/%u bytes to client %p\n",
917               (unsigned int) off, (unsigned int) size, client->client_handle);
918   return off;
919 }
920
921
922 /**
923  * Task run to check for messages that need to be sent to a client.
924  *
925  * @param client a ClientList, containing the client and any messages to be sent to it
926  */
927 static void
928 process_pending_messages (struct ClientList *client)
929 {
930   if ((client->pending_head == NULL) || (client->transmit_handle != NULL))
931   {
932     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933                 "Not asking for transmission to %p now: %s\n",
934                 client->client_handle,
935                 client->pending_head ==
936                 NULL ? "no more messages" : "request already pending");
937     return;
938   }
939   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
940               "Asking for transmission of %u bytes to client %p\n",
941               ntohs (client->pending_head->msg->size), client->client_handle);
942   client->transmit_handle =
943       GNUNET_SERVER_notify_transmit_ready (client->client_handle,
944                                            ntohs (client->pending_head->
945                                                   msg->size),
946                                            GNUNET_TIME_UNIT_FOREVER_REL,
947                                            &send_reply_to_client, client);
948 }
949
950
951 /**
952  * Closure for 'forward_reply'
953  */
954 struct ForwardReplyContext
955 {
956
957   /**
958    * Actual message to send to matching clients.
959    */
960   struct PendingMessage *pm;
961
962   /**
963    * Embedded payload.
964    */
965   const void *data;
966
967   /**
968    * Type of the data.
969    */
970   enum GNUNET_BLOCK_Type type;
971
972   /**
973    * Number of bytes in data.
974    */
975   size_t data_size;
976
977   /**
978    * Do we need to copy 'pm' because it was already used?
979    */
980   int do_copy;
981
982 };
983
984
985 /**
986  * Iterator over hash map entries that send a given reply to
987  * each of the matching clients.  With some tricky recycling
988  * of the buffer.
989  *
990  * @param cls the 'struct ForwardReplyContext'
991  * @param key current key
992  * @param value value in the hash map, a ClientQueryRecord
993  * @return GNUNET_YES (we should continue to iterate),
994  *         if the result is mal-formed, GNUNET_NO
995  */
996 static int
997 forward_reply (void *cls, const struct GNUNET_HashCode * key, void *value)
998 {
999   struct ForwardReplyContext *frc = cls;
1000   struct ClientQueryRecord *record = value;
1001   struct PendingMessage *pm;
1002   struct GNUNET_DHT_ClientResultMessage *reply;
1003   enum GNUNET_BLOCK_EvaluationResult eval;
1004   int do_free;
1005   struct GNUNET_HashCode ch;
1006   unsigned int i;
1007
1008   if ((record->type != GNUNET_BLOCK_TYPE_ANY) && (record->type != frc->type))
1009   {
1010     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1011                 "Record type missmatch, not passing request for key %s to local client\n",
1012                 GNUNET_h2s (key));
1013     GNUNET_STATISTICS_update (GDS_stats,
1014                               gettext_noop
1015                               ("# Key match, type mismatches in REPLY to CLIENT"),
1016                               1, GNUNET_NO);
1017     return GNUNET_YES;          /* type mismatch */
1018   }
1019   GNUNET_CRYPTO_hash (frc->data, frc->data_size, &ch);
1020   for (i = 0; i < record->seen_replies_count; i++)
1021     if (0 == memcmp (&record->seen_replies[i], &ch, sizeof (struct GNUNET_HashCode)))
1022     {
1023       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1024                   "Duplicate reply, not passing request for key %s to local client\n",
1025                   GNUNET_h2s (key));
1026       GNUNET_STATISTICS_update (GDS_stats,
1027                                 gettext_noop
1028                                 ("# Duplicate REPLIES to CLIENT request dropped"),
1029                                 1, GNUNET_NO);
1030       return GNUNET_YES;        /* duplicate */
1031     }
1032   eval =
1033       GNUNET_BLOCK_evaluate (GDS_block_context, record->type, key, NULL, 0,
1034                              record->xquery, record->xquery_size, frc->data,
1035                              frc->data_size);
1036   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037               "Evaluation result is %d for key %s for local client's query\n",
1038               (int) eval, GNUNET_h2s (key));
1039   switch (eval)
1040   {
1041   case GNUNET_BLOCK_EVALUATION_OK_LAST:
1042     do_free = GNUNET_YES;
1043     break;
1044   case GNUNET_BLOCK_EVALUATION_OK_MORE:
1045     GNUNET_array_append (record->seen_replies, record->seen_replies_count, ch);
1046     do_free = GNUNET_NO;
1047     break;
1048   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1049     /* should be impossible to encounter here */
1050     GNUNET_break (0);
1051     return GNUNET_YES;
1052   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1053     GNUNET_break_op (0);
1054     return GNUNET_NO;
1055   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1056     GNUNET_break (0);
1057     return GNUNET_NO;
1058   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1059     GNUNET_break (0);
1060     return GNUNET_NO;
1061   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1062     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1063                 _("Unsupported block type (%u) in request!\n"), record->type);
1064     return GNUNET_NO;
1065   default:
1066     GNUNET_break (0);
1067     return GNUNET_NO;
1068   }
1069   if (GNUNET_NO == frc->do_copy)
1070   {
1071     /* first time, we can use the original data */
1072     pm = frc->pm;
1073     frc->do_copy = GNUNET_YES;
1074   }
1075   else
1076   {
1077     /* two clients waiting for same reply, must copy for queueing */
1078     pm = GNUNET_malloc (sizeof (struct PendingMessage) +
1079                         ntohs (frc->pm->msg->size));
1080     memcpy (pm, frc->pm,
1081             sizeof (struct PendingMessage) + ntohs (frc->pm->msg->size));
1082     pm->next = pm->prev = NULL;
1083     pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
1084   }
1085   GNUNET_STATISTICS_update (GDS_stats,
1086                             gettext_noop ("# RESULTS queued for clients"), 1,
1087                             GNUNET_NO);
1088   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
1089   reply->unique_id = record->unique_id;
1090   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1091               "Queueing reply to query %s for client %p\n", GNUNET_h2s (key),
1092               record->client->client_handle);
1093   add_pending_message (record->client, pm);
1094   if (GNUNET_YES == do_free)
1095     remove_client_records (record->client, key, record);
1096   return GNUNET_YES;
1097 }
1098
1099
1100 /**
1101  * Handle a reply we've received from another peer.  If the reply
1102  * matches any of our pending queries, forward it to the respective
1103  * client(s).
1104  *
1105  * @param expiration when will the reply expire
1106  * @param key the query this reply is for
1107  * @param get_path_length number of peers in 'get_path'
1108  * @param get_path path the reply took on get
1109  * @param put_path_length number of peers in 'put_path'
1110  * @param put_path path the reply took on put
1111  * @param type type of the reply
1112  * @param data_size number of bytes in 'data'
1113  * @param data application payload data
1114  */
1115 void
1116 GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration,
1117                           const struct GNUNET_HashCode * key,
1118                           unsigned int get_path_length,
1119                           const struct GNUNET_PeerIdentity *get_path,
1120                           unsigned int put_path_length,
1121                           const struct GNUNET_PeerIdentity *put_path,
1122                           enum GNUNET_BLOCK_Type type, size_t data_size,
1123                           const void *data)
1124 {
1125   struct ForwardReplyContext frc;
1126   struct PendingMessage *pm;
1127   struct GNUNET_DHT_ClientResultMessage *reply;
1128   struct GNUNET_PeerIdentity *paths;
1129   size_t msize;
1130
1131   if (NULL == GNUNET_CONTAINER_multihashmap_get (forward_map, key))
1132   {
1133     GNUNET_STATISTICS_update (GDS_stats,
1134                               gettext_noop
1135                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
1136                               GNUNET_NO);
1137     return;                     /* no matching request, fast exit! */
1138   }
1139   msize =
1140       sizeof (struct GNUNET_DHT_ClientResultMessage) + data_size +
1141       (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1142   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1143   {
1144     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1145                 _("Could not pass reply to client, message too big!\n"));
1146     return;
1147   }
1148   pm = (struct PendingMessage *) GNUNET_malloc (msize +
1149                                                 sizeof (struct PendingMessage));
1150   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
1151   pm->msg = &reply->header;
1152   reply->header.size = htons ((uint16_t) msize);
1153   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT);
1154   reply->type = htonl (type);
1155   reply->get_path_length = htonl (get_path_length);
1156   reply->put_path_length = htonl (put_path_length);
1157   reply->unique_id = 0;         /* filled in later */
1158   reply->expiration = GNUNET_TIME_absolute_hton (expiration);
1159   reply->key = *key;
1160   paths = (struct GNUNET_PeerIdentity *) &reply[1];
1161   memcpy (paths, put_path,
1162           sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1163   memcpy (&paths[put_path_length], get_path,
1164           sizeof (struct GNUNET_PeerIdentity) * get_path_length);
1165   memcpy (&paths[get_path_length + put_path_length], data, data_size);
1166   frc.do_copy = GNUNET_NO;
1167   frc.pm = pm;
1168   frc.data = data;
1169   frc.data_size = data_size;
1170   frc.type = type;
1171   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, key, &forward_reply,
1172                                               &frc);
1173   if (GNUNET_NO == frc.do_copy)
1174   {
1175     /* did not match any of the requests, free! */
1176     GNUNET_STATISTICS_update (GDS_stats,
1177                               gettext_noop
1178                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
1179                               GNUNET_NO);
1180     GNUNET_free (pm);
1181   }
1182 }
1183
1184
1185 /**
1186  * Check if some client is monitoring GET messages and notify
1187  * them in that case.
1188  *
1189  * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1190  * @param type The type of data in the request.
1191  * @param hop_count Hop count so far.
1192  * @param path_length number of entries in path (or 0 if not recorded).
1193  * @param path peers on the GET path (or NULL if not recorded).
1194  * @param desired_replication_level Desired replication level.
1195  * @param key Key of the requested data.
1196  */
1197 void
1198 GDS_CLIENTS_process_get (uint32_t options,
1199                          enum GNUNET_BLOCK_Type type,
1200                          uint32_t hop_count,
1201                          uint32_t desired_replication_level, 
1202                          unsigned int path_length,
1203                          const struct GNUNET_PeerIdentity *path,
1204                          const struct GNUNET_HashCode * key)
1205 {
1206   struct ClientMonitorRecord *m;
1207   struct ClientList **cl;
1208   unsigned int cl_size;
1209
1210   cl = NULL;
1211   cl_size = 0;
1212   for (m = monitor_head; NULL != m; m = m->next)
1213   {
1214     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1215         (NULL == m->key ||
1216          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1217     {
1218       struct PendingMessage *pm;
1219       struct GNUNET_DHT_MonitorGetMessage *mmsg;
1220       struct GNUNET_PeerIdentity *msg_path;
1221       size_t msize;
1222       unsigned int i;
1223
1224       /* Don't send duplicates */
1225       for (i = 0; i < cl_size; i++)
1226         if (cl[i] == m->client)
1227           break;
1228       if (i < cl_size)
1229         continue;
1230       GNUNET_array_append (cl, cl_size, m->client);
1231
1232       msize = path_length * sizeof (struct GNUNET_PeerIdentity);
1233       msize += sizeof (struct GNUNET_DHT_MonitorGetMessage);
1234       msize += sizeof (struct PendingMessage);
1235       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1236       mmsg = (struct GNUNET_DHT_MonitorGetMessage *) &pm[1];
1237       pm->msg = &mmsg->header;
1238       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1239       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET);
1240       mmsg->options = htonl(options);
1241       mmsg->type = htonl(type);
1242       mmsg->hop_count = htonl(hop_count);
1243       mmsg->desired_replication_level = htonl(desired_replication_level);
1244       mmsg->get_path_length = htonl(path_length);
1245       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1246       msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1247       if (path_length > 0)
1248         memcpy (msg_path, path,
1249                 path_length * sizeof (struct GNUNET_PeerIdentity));
1250       add_pending_message (m->client, pm);
1251     }
1252   }
1253   GNUNET_free_non_null (cl);
1254 }
1255
1256
1257 /**
1258  * Check if some client is monitoring GET RESP messages and notify
1259  * them in that case.
1260  *
1261  * @param type The type of data in the result.
1262  * @param get_path Peers on GET path (or NULL if not recorded).
1263  * @param get_path_length number of entries in get_path.
1264  * @param put_path peers on the PUT path (or NULL if not recorded).
1265  * @param put_path_length number of entries in get_path.
1266  * @param exp Expiration time of the data.
1267  * @param key Key of the data.
1268  * @param data Pointer to the result data.
1269  * @param size Number of bytes in data.
1270  */
1271 void
1272 GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type,
1273                               const struct GNUNET_PeerIdentity *get_path,
1274                               unsigned int get_path_length,
1275                               const struct GNUNET_PeerIdentity *put_path,
1276                               unsigned int put_path_length,
1277                               struct GNUNET_TIME_Absolute exp,
1278                               const struct GNUNET_HashCode * key,
1279                               const void *data,
1280                               size_t size)
1281 {
1282   struct ClientMonitorRecord *m;
1283   struct ClientList **cl;
1284   unsigned int cl_size;
1285
1286   cl = NULL;
1287   cl_size = 0;
1288   for (m = monitor_head; NULL != m; m = m->next)
1289   {
1290     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1291         (NULL == m->key ||
1292          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1293     {
1294       struct PendingMessage *pm;
1295       struct GNUNET_DHT_MonitorGetRespMessage *mmsg;
1296       struct GNUNET_PeerIdentity *path;
1297       size_t msize;
1298       unsigned int i;
1299
1300       /* Don't send duplicates */
1301       for (i = 0; i < cl_size; i++)
1302         if (cl[i] == m->client)
1303           break;
1304       if (i < cl_size)
1305         continue;
1306       GNUNET_array_append (cl, cl_size, m->client);
1307
1308       msize = size;
1309       msize += (get_path_length + put_path_length)
1310                * sizeof (struct GNUNET_PeerIdentity);
1311       msize += sizeof (struct GNUNET_DHT_MonitorGetRespMessage);
1312       msize += sizeof (struct PendingMessage);
1313       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1314       mmsg = (struct GNUNET_DHT_MonitorGetRespMessage *) &pm[1];
1315       pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1316       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1317       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP);
1318       mmsg->type = htonl(type);
1319       mmsg->put_path_length = htonl(put_path_length);
1320       mmsg->get_path_length = htonl(get_path_length);
1321       path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1322       if (put_path_length > 0)
1323       {
1324         memcpy (path, put_path,
1325                 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1326         path = &path[put_path_length];
1327       }
1328       if (get_path_length > 0)
1329         memcpy (path, get_path,
1330                 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1331       mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1332       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1333       if (size > 0)
1334         memcpy (&path[get_path_length], data, size);
1335       add_pending_message (m->client, pm);
1336     }
1337   }
1338   GNUNET_free_non_null (cl);
1339 }
1340
1341
1342 /**
1343  * Check if some client is monitoring PUT messages and notify
1344  * them in that case.
1345  *
1346  * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1347  * @param type The type of data in the request.
1348  * @param hop_count Hop count so far.
1349  * @param path_length number of entries in path (or 0 if not recorded).
1350  * @param path peers on the PUT path (or NULL if not recorded).
1351  * @param desired_replication_level Desired replication level.
1352  * @param exp Expiration time of the data.
1353  * @param key Key under which data is to be stored.
1354  * @param data Pointer to the data carried.
1355  * @param size Number of bytes in data.
1356  */
1357 void
1358 GDS_CLIENTS_process_put (uint32_t options,
1359                          enum GNUNET_BLOCK_Type type,
1360                          uint32_t hop_count,
1361                          uint32_t desired_replication_level, 
1362                          unsigned int path_length,
1363                          const struct GNUNET_PeerIdentity *path,
1364                          struct GNUNET_TIME_Absolute exp,
1365                          const struct GNUNET_HashCode * key,
1366                          const void *data,
1367                          size_t size)
1368 {
1369   struct ClientMonitorRecord *m;
1370   struct ClientList **cl;
1371   unsigned int cl_size;
1372
1373   cl = NULL;
1374   cl_size = 0;
1375   for (m = monitor_head; NULL != m; m = m->next)
1376   {
1377     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1378         (NULL == m->key ||
1379          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1380     {
1381       struct PendingMessage *pm;
1382       struct GNUNET_DHT_MonitorPutMessage *mmsg;
1383       struct GNUNET_PeerIdentity *msg_path;
1384       size_t msize;
1385       unsigned int i;
1386
1387       /* Don't send duplicates */
1388       for (i = 0; i < cl_size; i++)
1389         if (cl[i] == m->client)
1390           break;
1391       if (i < cl_size)
1392         continue;
1393       GNUNET_array_append (cl, cl_size, m->client);
1394
1395       msize = size;
1396       msize += path_length * sizeof (struct GNUNET_PeerIdentity);
1397       msize += sizeof (struct GNUNET_DHT_MonitorPutMessage);
1398       msize += sizeof (struct PendingMessage);
1399       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1400       mmsg = (struct GNUNET_DHT_MonitorPutMessage *) &pm[1];
1401       pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1402       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1403       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT);
1404       mmsg->options = htonl(options);
1405       mmsg->type = htonl(type);
1406       mmsg->hop_count = htonl(hop_count);
1407       mmsg->desired_replication_level = htonl(desired_replication_level);
1408       mmsg->put_path_length = htonl(path_length);
1409       msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1410       if (path_length > 0)
1411       {
1412         memcpy (msg_path, path,
1413                 path_length * sizeof (struct GNUNET_PeerIdentity));
1414       }
1415       mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1416       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1417       if (size > 0)
1418         memcpy (&msg_path[path_length], data, size);
1419       add_pending_message (m->client, pm);
1420     }
1421   }
1422   GNUNET_free_non_null (cl);
1423 }
1424
1425
1426 /**
1427  * Initialize client subsystem.
1428  *
1429  * @param server the initialized server
1430  */
1431 void
1432 GDS_CLIENTS_init (struct GNUNET_SERVER_Handle *server)
1433 {
1434   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1435     {&handle_dht_local_put, NULL,
1436      GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, 0},
1437     {&handle_dht_local_get, NULL,
1438      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, 0},
1439     {&handle_dht_local_get_stop, NULL,
1440      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP,
1441      sizeof (struct GNUNET_DHT_ClientGetStopMessage)},
1442     {&handle_dht_local_monitor, NULL,
1443      GNUNET_MESSAGE_TYPE_DHT_MONITOR_START,
1444      sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1445     {&handle_dht_local_monitor_stop, NULL,
1446      GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP,
1447      sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1448     {&handle_dht_local_get_result_seen, NULL,
1449      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_RESULTS_KNOWN, 0},
1450     {NULL, NULL, 0, 0}
1451   };
1452   forward_map = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
1453   retry_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1454   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1455   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1456 }
1457
1458
1459 /**
1460  * Shutdown client subsystem.
1461  */
1462 void
1463 GDS_CLIENTS_done ()
1464 {
1465   GNUNET_assert (client_head == NULL);
1466   GNUNET_assert (client_tail == NULL);
1467   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
1468   {
1469     GNUNET_SCHEDULER_cancel (retry_task);
1470     retry_task = GNUNET_SCHEDULER_NO_TASK;
1471   }
1472   if (NULL != retry_heap)
1473   {
1474     GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (retry_heap));
1475     GNUNET_CONTAINER_heap_destroy (retry_heap);
1476     retry_heap = NULL;
1477   }
1478   if (NULL != forward_map)
1479   {
1480     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (forward_map));
1481     GNUNET_CONTAINER_multihashmap_destroy (forward_map);
1482     forward_map = NULL;
1483   }
1484 }
1485
1486 /* end of gnunet-service-dht_clients.c */