fix memleak
[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 any generic DHT messages, calls the appropriate handler
555  * depending on message type, sends confirmation if responses aren't otherwise
556  * expected.
557  *
558  * @param cls closure for the service
559  * @param client the client we received this message from
560  * @param message the actual message received
561  */
562 static void
563 handle_dht_local_get (void *cls, struct GNUNET_SERVER_Client *client,
564                       const struct GNUNET_MessageHeader *message)
565 {
566   const struct GNUNET_DHT_ClientGetMessage *get;
567   struct ClientQueryRecord *cqr;
568   size_t xquery_size;
569   const char *xquery;
570   uint16_t size;
571
572   size = ntohs (message->size);
573   if (size < sizeof (struct GNUNET_DHT_ClientGetMessage))
574   {
575     GNUNET_break (0);
576     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
577     return;
578   }
579   xquery_size = size - sizeof (struct GNUNET_DHT_ClientGetMessage);
580   get = (const struct GNUNET_DHT_ClientGetMessage *) message;
581   xquery = (const char *) &get[1];
582   GNUNET_STATISTICS_update (GDS_stats,
583                             gettext_noop
584                             ("# GET requests received from clients"), 1,
585                             GNUNET_NO);
586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
587               "Received request for %s from local client %p\n",
588               GNUNET_h2s (&get->key), client);
589   cqr = GNUNET_malloc (sizeof (struct ClientQueryRecord) + xquery_size);
590   cqr->key = get->key;
591   cqr->client = find_active_client (client);
592   cqr->xquery = (void *) &cqr[1];
593   memcpy (&cqr[1], xquery, xquery_size);
594   cqr->hnode = GNUNET_CONTAINER_heap_insert (retry_heap, cqr, 0);
595   cqr->retry_frequency = GNUNET_TIME_UNIT_MILLISECONDS;
596   cqr->retry_time = GNUNET_TIME_absolute_get ();
597   cqr->unique_id = get->unique_id;
598   cqr->xquery_size = xquery_size;
599   cqr->replication = ntohl (get->desired_replication_level);
600   cqr->msg_options = ntohl (get->options);
601   cqr->type = ntohl (get->type);
602   GNUNET_CONTAINER_multihashmap_put (forward_map, &get->key, cqr,
603                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
604   GDS_CLIENTS_process_get (ntohl (get->options),
605                            ntohl (get->type),
606                            0,
607                            ntohl (get->desired_replication_level),
608                            1,
609                            GDS_NEIGHBOURS_get_id(),
610                            &get->key);
611   /* start remote requests */
612   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
613     GNUNET_SCHEDULER_cancel (retry_task);
614   retry_task = GNUNET_SCHEDULER_add_now (&transmit_next_request_task, NULL);
615   /* perform local lookup */
616   GDS_DATACACHE_handle_get (&get->key, cqr->type, cqr->xquery, xquery_size,
617                             NULL, 0);
618   GNUNET_SERVER_receive_done (client, GNUNET_OK);
619 }
620
621
622 /**
623  * Closure for 'remove_by_unique_id'.
624  */
625 struct RemoveByUniqueIdContext
626 {
627   /**
628    * Client that issued the removal request.
629    */
630   struct ClientList *client;
631
632   /**
633    * Unique ID of the request.
634    */
635   uint64_t unique_id;
636 };
637
638
639 /**
640  * Iterator over hash map entries that frees all entries
641  * that match the given client and unique ID.
642  *
643  * @param cls unique ID and client to search for in source routes
644  * @param key current key code
645  * @param value value in the hash map, a ClientQueryRecord
646  * @return GNUNET_YES (we should continue to iterate)
647  */
648 static int
649 remove_by_unique_id (void *cls, const struct GNUNET_HashCode * key, void *value)
650 {
651   const struct RemoveByUniqueIdContext *ctx = cls;
652   struct ClientQueryRecord *record = value;
653
654   if (record->unique_id != ctx->unique_id)
655     return GNUNET_YES;
656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
657               "Removing client %p's record for key %s (by unique id)\n",
658               ctx->client->client_handle, GNUNET_h2s (key));
659   return remove_client_records (ctx->client, key, record);
660 }
661
662
663 /**
664  * Handler for any generic DHT stop messages, calls the appropriate handler
665  * depending on message type (if processed locally)
666  *
667  * @param cls closure for the service
668  * @param client the client we received this message from
669  * @param message the actual message received
670  *
671  */
672 static void
673 handle_dht_local_get_stop (void *cls, struct GNUNET_SERVER_Client *client,
674                            const struct GNUNET_MessageHeader *message)
675 {
676   const struct GNUNET_DHT_ClientGetStopMessage *dht_stop_msg =
677       (const struct GNUNET_DHT_ClientGetStopMessage *) message;
678   struct RemoveByUniqueIdContext ctx;
679
680   GNUNET_STATISTICS_update (GDS_stats,
681                             gettext_noop
682                             ("# GET STOP requests received from clients"), 1,
683                             GNUNET_NO);
684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Client %p stopped request for key %s\n",
685               client, GNUNET_h2s (&dht_stop_msg->key));
686   ctx.client = find_active_client (client);
687   ctx.unique_id = dht_stop_msg->unique_id;
688   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, &dht_stop_msg->key,
689                                               &remove_by_unique_id, &ctx);
690   GNUNET_SERVER_receive_done (client, GNUNET_OK);
691 }
692
693
694 /**
695  * Handler for monitor start messages
696  *
697  * @param cls closure for the service
698  * @param client the client we received this message from
699  * @param message the actual message received
700  *
701  */
702 static void
703 handle_dht_local_monitor (void *cls, struct GNUNET_SERVER_Client *client,
704                           const struct GNUNET_MessageHeader *message)
705 {
706   struct ClientMonitorRecord *r;
707   const struct GNUNET_DHT_MonitorStartStopMessage *msg;
708
709   msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
710   r = GNUNET_malloc (sizeof(struct ClientMonitorRecord));
711
712   r->client = find_active_client(client);
713   r->type = ntohl(msg->type);
714   r->get = ntohs(msg->get);
715   r->get_resp = ntohs(msg->get_resp);
716   r->put = ntohs(msg->put);
717   if (0 == ntohs(msg->filter_key))
718       r->key = NULL;
719   else
720   {
721     r->key = GNUNET_malloc (sizeof (struct GNUNET_HashCode));
722     memcpy (r->key, &msg->key, sizeof (struct GNUNET_HashCode));
723   }
724   GNUNET_CONTAINER_DLL_insert (monitor_head, monitor_tail, r);
725   GNUNET_SERVER_receive_done (client, GNUNET_OK);
726 }
727
728 /**
729  * Handler for monitor stop messages
730  *
731  * @param cls closure for the service
732  * @param client the client we received this message from
733  * @param message the actual message received
734  *
735  */
736 static void
737 handle_dht_local_monitor_stop (void *cls, struct GNUNET_SERVER_Client *client,
738                                const struct GNUNET_MessageHeader *message)
739 {
740   struct ClientMonitorRecord *r;
741   const struct GNUNET_DHT_MonitorStartStopMessage *msg;
742   int keys_match;
743
744   msg = (struct GNUNET_DHT_MonitorStartStopMessage *) message;
745   r = monitor_head;
746
747   while (NULL != r)
748   {
749     if (NULL == r->key)
750         keys_match = (0 == ntohs(msg->filter_key));
751     else
752     {
753         keys_match = (0 != ntohs(msg->filter_key)
754                       && !memcmp(r->key, &msg->key, sizeof(struct GNUNET_HashCode)));
755     }
756     if (find_active_client(client) == r->client
757         && ntohl(msg->type) == r->type
758         && r->get == msg->get
759         && r->get_resp == msg->get_resp
760         && r->put == msg->put
761         && keys_match
762         )
763     {
764         GNUNET_CONTAINER_DLL_remove (monitor_head, monitor_tail, r);
765         GNUNET_free_non_null (r->key);
766         GNUNET_free (r);
767         GNUNET_SERVER_receive_done (client, GNUNET_OK);
768         return; /* Delete only ONE entry */
769     }
770     r = r->next;
771   }
772  
773   GNUNET_SERVER_receive_done (client, GNUNET_OK);
774 }
775
776
777 /**
778  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
779  * request.  A ClientList is passed as closure, take the head of the list
780  * and copy it into buf, which has the result of sending the message to the
781  * client.
782  *
783  * @param cls closure to this call
784  * @param size maximum number of bytes available to send
785  * @param buf where to copy the actual message to
786  *
787  * @return the number of bytes actually copied, 0 indicates failure
788  */
789 static size_t
790 send_reply_to_client (void *cls, size_t size, void *buf)
791 {
792   struct ClientList *client = cls;
793   char *cbuf = buf;
794   struct PendingMessage *reply;
795   size_t off;
796   size_t msize;
797
798   client->transmit_handle = NULL;
799   if (buf == NULL)
800   {
801     /* client disconnected */
802     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
803                 "Client %p disconnected, pending messages will be discarded\n",
804                 client->client_handle);
805     return 0;
806   }
807   off = 0;
808   while ((NULL != (reply = client->pending_head)) &&
809          (size >= off + (msize = ntohs (reply->msg->size))))
810   {
811     GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
812                                  reply);
813     memcpy (&cbuf[off], reply->msg, msize);
814     GNUNET_free (reply);
815     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting %u bytes to client %p\n",
816                 msize, client->client_handle);
817     off += msize;
818   }
819   process_pending_messages (client);
820   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitted %u/%u bytes to client %p\n",
821               (unsigned int) off, (unsigned int) size, client->client_handle);
822   return off;
823 }
824
825
826 /**
827  * Task run to check for messages that need to be sent to a client.
828  *
829  * @param client a ClientList, containing the client and any messages to be sent to it
830  */
831 static void
832 process_pending_messages (struct ClientList *client)
833 {
834   if ((client->pending_head == NULL) || (client->transmit_handle != NULL))
835   {
836     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
837                 "Not asking for transmission to %p now: %s\n",
838                 client->client_handle,
839                 client->pending_head ==
840                 NULL ? "no more messages" : "request already pending");
841     return;
842   }
843   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
844               "Asking for transmission of %u bytes to client %p\n",
845               ntohs (client->pending_head->msg->size), client->client_handle);
846   client->transmit_handle =
847       GNUNET_SERVER_notify_transmit_ready (client->client_handle,
848                                            ntohs (client->pending_head->
849                                                   msg->size),
850                                            GNUNET_TIME_UNIT_FOREVER_REL,
851                                            &send_reply_to_client, client);
852 }
853
854
855 /**
856  * Closure for 'forward_reply'
857  */
858 struct ForwardReplyContext
859 {
860
861   /**
862    * Actual message to send to matching clients.
863    */
864   struct PendingMessage *pm;
865
866   /**
867    * Embedded payload.
868    */
869   const void *data;
870
871   /**
872    * Type of the data.
873    */
874   enum GNUNET_BLOCK_Type type;
875
876   /**
877    * Number of bytes in data.
878    */
879   size_t data_size;
880
881   /**
882    * Do we need to copy 'pm' because it was already used?
883    */
884   int do_copy;
885
886 };
887
888
889 /**
890  * Iterator over hash map entries that send a given reply to
891  * each of the matching clients.  With some tricky recycling
892  * of the buffer.
893  *
894  * @param cls the 'struct ForwardReplyContext'
895  * @param key current key
896  * @param value value in the hash map, a ClientQueryRecord
897  * @return GNUNET_YES (we should continue to iterate),
898  *         if the result is mal-formed, GNUNET_NO
899  */
900 static int
901 forward_reply (void *cls, const struct GNUNET_HashCode * key, void *value)
902 {
903   struct ForwardReplyContext *frc = cls;
904   struct ClientQueryRecord *record = value;
905   struct PendingMessage *pm;
906   struct GNUNET_DHT_ClientResultMessage *reply;
907   enum GNUNET_BLOCK_EvaluationResult eval;
908   int do_free;
909   struct GNUNET_HashCode ch;
910   unsigned int i;
911
912   if ((record->type != GNUNET_BLOCK_TYPE_ANY) && (record->type != frc->type))
913   {
914     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
915                 "Record type missmatch, not passing request for key %s to local client\n",
916                 GNUNET_h2s (key));
917     GNUNET_STATISTICS_update (GDS_stats,
918                               gettext_noop
919                               ("# Key match, type mismatches in REPLY to CLIENT"),
920                               1, GNUNET_NO);
921     return GNUNET_YES;          /* type mismatch */
922   }
923   GNUNET_CRYPTO_hash (frc->data, frc->data_size, &ch);
924   for (i = 0; i < record->seen_replies_count; i++)
925     if (0 == memcmp (&record->seen_replies[i], &ch, sizeof (struct GNUNET_HashCode)))
926     {
927       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
928                   "Duplicate reply, not passing request for key %s to local client\n",
929                   GNUNET_h2s (key));
930       GNUNET_STATISTICS_update (GDS_stats,
931                                 gettext_noop
932                                 ("# Duplicate REPLIES to CLIENT request dropped"),
933                                 1, GNUNET_NO);
934       return GNUNET_YES;        /* duplicate */
935     }
936   eval =
937       GNUNET_BLOCK_evaluate (GDS_block_context, record->type, key, NULL, 0,
938                              record->xquery, record->xquery_size, frc->data,
939                              frc->data_size);
940   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
941               "Evaluation result is %d for key %s for local client's query\n",
942               (int) eval, GNUNET_h2s (key));
943   switch (eval)
944   {
945   case GNUNET_BLOCK_EVALUATION_OK_LAST:
946     do_free = GNUNET_YES;
947     break;
948   case GNUNET_BLOCK_EVALUATION_OK_MORE:
949     GNUNET_array_append (record->seen_replies, record->seen_replies_count, ch);
950     do_free = GNUNET_NO;
951     break;
952   case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
953     /* should be impossible to encounter here */
954     GNUNET_break (0);
955     return GNUNET_YES;
956   case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
957     GNUNET_break_op (0);
958     return GNUNET_NO;
959   case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
960     GNUNET_break (0);
961     return GNUNET_NO;
962   case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
963     GNUNET_break (0);
964     return GNUNET_NO;
965   case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
966     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
967                 _("Unsupported block type (%u) in request!\n"), record->type);
968     return GNUNET_NO;
969   default:
970     GNUNET_break (0);
971     return GNUNET_NO;
972   }
973   if (GNUNET_NO == frc->do_copy)
974   {
975     /* first time, we can use the original data */
976     pm = frc->pm;
977     frc->do_copy = GNUNET_YES;
978   }
979   else
980   {
981     /* two clients waiting for same reply, must copy for queueing */
982     pm = GNUNET_malloc (sizeof (struct PendingMessage) +
983                         ntohs (frc->pm->msg->size));
984     memcpy (pm, frc->pm,
985             sizeof (struct PendingMessage) + ntohs (frc->pm->msg->size));
986     pm->next = pm->prev = NULL;
987     pm->msg = (struct GNUNET_MessageHeader *) &pm[1];
988   }
989   GNUNET_STATISTICS_update (GDS_stats,
990                             gettext_noop ("# RESULTS queued for clients"), 1,
991                             GNUNET_NO);
992   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
993   reply->unique_id = record->unique_id;
994   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
995               "Queueing reply to query %s for client %p\n", GNUNET_h2s (key),
996               record->client->client_handle);
997   add_pending_message (record->client, pm);
998   if (GNUNET_YES == do_free)
999     remove_client_records (record->client, key, record);
1000   return GNUNET_YES;
1001 }
1002
1003
1004 /**
1005  * Handle a reply we've received from another peer.  If the reply
1006  * matches any of our pending queries, forward it to the respective
1007  * client(s).
1008  *
1009  * @param expiration when will the reply expire
1010  * @param key the query this reply is for
1011  * @param get_path_length number of peers in 'get_path'
1012  * @param get_path path the reply took on get
1013  * @param put_path_length number of peers in 'put_path'
1014  * @param put_path path the reply took on put
1015  * @param type type of the reply
1016  * @param data_size number of bytes in 'data'
1017  * @param data application payload data
1018  */
1019 void
1020 GDS_CLIENTS_handle_reply (struct GNUNET_TIME_Absolute expiration,
1021                           const struct GNUNET_HashCode * key,
1022                           unsigned int get_path_length,
1023                           const struct GNUNET_PeerIdentity *get_path,
1024                           unsigned int put_path_length,
1025                           const struct GNUNET_PeerIdentity *put_path,
1026                           enum GNUNET_BLOCK_Type type, size_t data_size,
1027                           const void *data)
1028 {
1029   struct ForwardReplyContext frc;
1030   struct PendingMessage *pm;
1031   struct GNUNET_DHT_ClientResultMessage *reply;
1032   struct GNUNET_PeerIdentity *paths;
1033   size_t msize;
1034
1035   if (NULL == GNUNET_CONTAINER_multihashmap_get (forward_map, key))
1036   {
1037     GNUNET_STATISTICS_update (GDS_stats,
1038                               gettext_noop
1039                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
1040                               GNUNET_NO);
1041     return;                     /* no matching request, fast exit! */
1042   }
1043   msize =
1044       sizeof (struct GNUNET_DHT_ClientResultMessage) + data_size +
1045       (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1046   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1047   {
1048     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1049                 _("Could not pass reply to client, message too big!\n"));
1050     return;
1051   }
1052   pm = (struct PendingMessage *) GNUNET_malloc (msize +
1053                                                 sizeof (struct PendingMessage));
1054   reply = (struct GNUNET_DHT_ClientResultMessage *) &pm[1];
1055   pm->msg = &reply->header;
1056   reply->header.size = htons ((uint16_t) msize);
1057   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_CLIENT_RESULT);
1058   reply->type = htonl (type);
1059   reply->get_path_length = htonl (get_path_length);
1060   reply->put_path_length = htonl (put_path_length);
1061   reply->unique_id = 0;         /* filled in later */
1062   reply->expiration = GNUNET_TIME_absolute_hton (expiration);
1063   reply->key = *key;
1064   paths = (struct GNUNET_PeerIdentity *) &reply[1];
1065   memcpy (paths, put_path,
1066           sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1067   memcpy (&paths[put_path_length], get_path,
1068           sizeof (struct GNUNET_PeerIdentity) * get_path_length);
1069   memcpy (&paths[get_path_length + put_path_length], data, data_size);
1070   frc.do_copy = GNUNET_NO;
1071   frc.pm = pm;
1072   frc.data = data;
1073   frc.data_size = data_size;
1074   frc.type = type;
1075   GNUNET_CONTAINER_multihashmap_get_multiple (forward_map, key, &forward_reply,
1076                                               &frc);
1077   if (GNUNET_NO == frc.do_copy)
1078   {
1079     /* did not match any of the requests, free! */
1080     GNUNET_STATISTICS_update (GDS_stats,
1081                               gettext_noop
1082                               ("# REPLIES ignored for CLIENTS (no match)"), 1,
1083                               GNUNET_NO);
1084     GNUNET_free (pm);
1085   }
1086 }
1087
1088
1089 /**
1090  * Check if some client is monitoring GET messages and notify
1091  * them in that case.
1092  *
1093  * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1094  * @param type The type of data in the request.
1095  * @param hop_count Hop count so far.
1096  * @param path_length number of entries in path (or 0 if not recorded).
1097  * @param path peers on the GET path (or NULL if not recorded).
1098  * @param desired_replication_level Desired replication level.
1099  * @param key Key of the requested data.
1100  */
1101 void
1102 GDS_CLIENTS_process_get (uint32_t options,
1103                          enum GNUNET_BLOCK_Type type,
1104                          uint32_t hop_count,
1105                          uint32_t desired_replication_level, 
1106                          unsigned int path_length,
1107                          const struct GNUNET_PeerIdentity *path,
1108                          const struct GNUNET_HashCode * key)
1109 {
1110   struct ClientMonitorRecord *m;
1111   struct ClientList **cl;
1112   unsigned int cl_size;
1113
1114   cl = NULL;
1115   cl_size = 0;
1116   for (m = monitor_head; NULL != m; m = m->next)
1117   {
1118     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1119         (NULL == m->key ||
1120          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1121     {
1122       struct PendingMessage *pm;
1123       struct GNUNET_DHT_MonitorGetMessage *mmsg;
1124       struct GNUNET_PeerIdentity *msg_path;
1125       size_t msize;
1126       unsigned int i;
1127
1128       /* Don't send duplicates */
1129       for (i = 0; i < cl_size; i++)
1130         if (cl[i] == m->client)
1131           break;
1132       if (i < cl_size)
1133         continue;
1134       GNUNET_array_append (cl, cl_size, m->client);
1135
1136       msize = path_length * sizeof (struct GNUNET_PeerIdentity);
1137       msize += sizeof (struct GNUNET_DHT_MonitorGetMessage);
1138       msize += sizeof (struct PendingMessage);
1139       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1140       mmsg = (struct GNUNET_DHT_MonitorGetMessage *) &pm[1];
1141       pm->msg = &mmsg->header;
1142       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1143       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET);
1144       mmsg->options = htonl(options);
1145       mmsg->type = htonl(type);
1146       mmsg->hop_count = htonl(hop_count);
1147       mmsg->desired_replication_level = htonl(desired_replication_level);
1148       mmsg->get_path_length = htonl(path_length);
1149       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1150       msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1151       if (path_length > 0)
1152         memcpy (msg_path, path,
1153                 path_length * sizeof (struct GNUNET_PeerIdentity));
1154       add_pending_message (m->client, pm);
1155     }
1156   }
1157   GNUNET_free_non_null (cl);
1158 }
1159
1160
1161 /**
1162  * Check if some client is monitoring GET RESP messages and notify
1163  * them in that case.
1164  *
1165  * @param type The type of data in the result.
1166  * @param get_path Peers on GET path (or NULL if not recorded).
1167  * @param get_path_length number of entries in get_path.
1168  * @param put_path peers on the PUT path (or NULL if not recorded).
1169  * @param put_path_length number of entries in get_path.
1170  * @param exp Expiration time of the data.
1171  * @param key Key of the data.
1172  * @param data Pointer to the result data.
1173  * @param size Number of bytes in data.
1174  */
1175 void
1176 GDS_CLIENTS_process_get_resp (enum GNUNET_BLOCK_Type type,
1177                               const struct GNUNET_PeerIdentity *get_path,
1178                               unsigned int get_path_length,
1179                               const struct GNUNET_PeerIdentity *put_path,
1180                               unsigned int put_path_length,
1181                               struct GNUNET_TIME_Absolute exp,
1182                               const struct GNUNET_HashCode * key,
1183                               const void *data,
1184                               size_t size)
1185 {
1186   struct ClientMonitorRecord *m;
1187   struct ClientList **cl;
1188   unsigned int cl_size;
1189
1190   cl = NULL;
1191   cl_size = 0;
1192   for (m = monitor_head; NULL != m; m = m->next)
1193   {
1194     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1195         (NULL == m->key ||
1196          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1197     {
1198       struct PendingMessage *pm;
1199       struct GNUNET_DHT_MonitorGetRespMessage *mmsg;
1200       struct GNUNET_PeerIdentity *path;
1201       size_t msize;
1202       unsigned int i;
1203
1204       /* Don't send duplicates */
1205       for (i = 0; i < cl_size; i++)
1206         if (cl[i] == m->client)
1207           break;
1208       if (i < cl_size)
1209         continue;
1210       GNUNET_array_append (cl, cl_size, m->client);
1211
1212       msize = size;
1213       msize += (get_path_length + put_path_length)
1214                * sizeof (struct GNUNET_PeerIdentity);
1215       msize += sizeof (struct GNUNET_DHT_MonitorGetRespMessage);
1216       msize += sizeof (struct PendingMessage);
1217       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1218       mmsg = (struct GNUNET_DHT_MonitorGetRespMessage *) &pm[1];
1219       pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1220       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1221       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP);
1222       mmsg->type = htonl(type);
1223       mmsg->put_path_length = htonl(put_path_length);
1224       mmsg->get_path_length = htonl(get_path_length);
1225       path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1226       if (put_path_length > 0)
1227       {
1228         memcpy (path, put_path,
1229                 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1230         path = &path[put_path_length];
1231       }
1232       if (get_path_length > 0)
1233         memcpy (path, get_path,
1234                 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1235       mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1236       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1237       if (size > 0)
1238         memcpy (&path[get_path_length], data, size);
1239       add_pending_message (m->client, pm);
1240     }
1241   }
1242   GNUNET_free_non_null (cl);
1243 }
1244
1245
1246 /**
1247  * Check if some client is monitoring PUT messages and notify
1248  * them in that case.
1249  *
1250  * @param options Options, for instance RecordRoute, DemultiplexEverywhere.
1251  * @param type The type of data in the request.
1252  * @param hop_count Hop count so far.
1253  * @param path_length number of entries in path (or 0 if not recorded).
1254  * @param path peers on the PUT path (or NULL if not recorded).
1255  * @param desired_replication_level Desired replication level.
1256  * @param exp Expiration time of the data.
1257  * @param key Key under which data is to be stored.
1258  * @param data Pointer to the data carried.
1259  * @param size Number of bytes in data.
1260  */
1261 void
1262 GDS_CLIENTS_process_put (uint32_t options,
1263                          enum GNUNET_BLOCK_Type type,
1264                          uint32_t hop_count,
1265                          uint32_t desired_replication_level, 
1266                          unsigned int path_length,
1267                          const struct GNUNET_PeerIdentity *path,
1268                          struct GNUNET_TIME_Absolute exp,
1269                          const struct GNUNET_HashCode * key,
1270                          const void *data,
1271                          size_t size)
1272 {
1273   struct ClientMonitorRecord *m;
1274   struct ClientList **cl;
1275   unsigned int cl_size;
1276
1277   cl = NULL;
1278   cl_size = 0;
1279   for (m = monitor_head; NULL != m; m = m->next)
1280   {
1281     if ((GNUNET_BLOCK_TYPE_ANY == m->type || m->type == type) &&
1282         (NULL == m->key ||
1283          memcmp (key, m->key, sizeof(struct GNUNET_HashCode)) == 0))
1284     {
1285       struct PendingMessage *pm;
1286       struct GNUNET_DHT_MonitorPutMessage *mmsg;
1287       struct GNUNET_PeerIdentity *msg_path;
1288       size_t msize;
1289       unsigned int i;
1290
1291       /* Don't send duplicates */
1292       for (i = 0; i < cl_size; i++)
1293         if (cl[i] == m->client)
1294           break;
1295       if (i < cl_size)
1296         continue;
1297       GNUNET_array_append (cl, cl_size, m->client);
1298
1299       msize = size;
1300       msize += path_length * sizeof (struct GNUNET_PeerIdentity);
1301       msize += sizeof (struct GNUNET_DHT_MonitorPutMessage);
1302       msize += sizeof (struct PendingMessage);
1303       pm = (struct PendingMessage *) GNUNET_malloc (msize);
1304       mmsg = (struct GNUNET_DHT_MonitorPutMessage *) &pm[1];
1305       pm->msg = (struct GNUNET_MessageHeader *) mmsg;
1306       mmsg->header.size = htons (msize - sizeof (struct PendingMessage));
1307       mmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT);
1308       mmsg->options = htonl(options);
1309       mmsg->type = htonl(type);
1310       mmsg->hop_count = htonl(hop_count);
1311       mmsg->desired_replication_level = htonl(desired_replication_level);
1312       mmsg->put_path_length = htonl(path_length);
1313       msg_path = (struct GNUNET_PeerIdentity *) &mmsg[1];
1314       if (path_length > 0)
1315       {
1316         memcpy (msg_path, path,
1317                 path_length * sizeof (struct GNUNET_PeerIdentity));
1318       }
1319       mmsg->expiration_time = GNUNET_TIME_absolute_hton(exp);
1320       memcpy (&mmsg->key, key, sizeof (struct GNUNET_HashCode));
1321       if (size > 0)
1322         memcpy (&msg_path[path_length], data, size);
1323       add_pending_message (m->client, pm);
1324     }
1325   }
1326   GNUNET_free_non_null (cl);
1327 }
1328
1329
1330 /**
1331  * Initialize client subsystem.
1332  *
1333  * @param server the initialized server
1334  */
1335 void
1336 GDS_CLIENTS_init (struct GNUNET_SERVER_Handle *server)
1337 {
1338   static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
1339     {&handle_dht_local_put, NULL,
1340      GNUNET_MESSAGE_TYPE_DHT_CLIENT_PUT, 0},
1341     {&handle_dht_local_get, NULL,
1342      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET, 0},
1343     {&handle_dht_local_get_stop, NULL,
1344      GNUNET_MESSAGE_TYPE_DHT_CLIENT_GET_STOP,
1345      sizeof (struct GNUNET_DHT_ClientGetStopMessage)},
1346     {&handle_dht_local_monitor, NULL,
1347      GNUNET_MESSAGE_TYPE_DHT_MONITOR_START,
1348      sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1349     {&handle_dht_local_monitor_stop, NULL,
1350      GNUNET_MESSAGE_TYPE_DHT_MONITOR_STOP,
1351      sizeof (struct GNUNET_DHT_MonitorStartStopMessage)},
1352     {NULL, NULL, 0, 0}
1353   };
1354   forward_map = GNUNET_CONTAINER_multihashmap_create (1024, GNUNET_NO);
1355   retry_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1356   GNUNET_SERVER_add_handlers (server, plugin_handlers);
1357   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1358 }
1359
1360
1361 /**
1362  * Shutdown client subsystem.
1363  */
1364 void
1365 GDS_CLIENTS_done ()
1366 {
1367   GNUNET_assert (client_head == NULL);
1368   GNUNET_assert (client_tail == NULL);
1369   if (GNUNET_SCHEDULER_NO_TASK != retry_task)
1370   {
1371     GNUNET_SCHEDULER_cancel (retry_task);
1372     retry_task = GNUNET_SCHEDULER_NO_TASK;
1373   }
1374   if (NULL != retry_heap)
1375   {
1376     GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (retry_heap));
1377     GNUNET_CONTAINER_heap_destroy (retry_heap);
1378     retry_heap = NULL;
1379   }
1380   if (NULL != forward_map)
1381   {
1382     GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (forward_map));
1383     GNUNET_CONTAINER_multihashmap_destroy (forward_map);
1384     forward_map = NULL;
1385   }
1386 }
1387
1388 /* end of gnunet-service-dht_clients.c */