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