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