b3128cbab715c9cc94fbd850988c22258a1164c5
[oweals/gnunet.git] / src / testbed / gnunet-service-testbed_cache.c
1 /*
2   This file is part of GNUnet.
3   (C) 2012 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 2, 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 testbed/gnunet-service-testbed_cache.h
23  * @brief testbed cache implementation
24  * @author Sree Harsha Totakura
25  */
26 #include "gnunet-service-testbed.h"
27
28 /**
29  * Redefine LOG with a changed log component string
30  */
31 #ifdef LOG
32 #undef LOG
33 #endif
34 #define LOG(kind,...)                                   \
35   GNUNET_log_from (kind, "testbed-cache", __VA_ARGS__)
36
37
38 /**
39  * Time to expire a cache entry
40  */
41 #define CACHE_EXPIRY                            \
42   GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
43
44
45 /**
46  * Type of cache-get requests
47  */
48 enum CacheGetType
49 {
50   /**
51    * Get transport handle
52    */
53   CGT_TRANSPORT_HANDLE = 1,
54
55   /**
56    * Get core handle
57    */
58   CGT_CORE_HANDLE
59 };
60
61
62 /**
63  * The cache-get request handle
64  */
65 struct GSTCacheGetHandle;
66
67
68 /**
69  * This context structure is used to maintain a queue of notifications to check
70  * which of them are to be notified when a peer is connected.
71  */
72 struct ConnectNotifyContext
73 {
74   /**
75    * The next ptr for the DLL
76    */
77   struct ConnectNotifyContext *next;
78
79   /**
80    * The prev ptr for the DLL
81    */
82   struct ConnectNotifyContext *prev;
83
84   /**
85    * The peer identity of the target peer. When this target peer is connected,
86    * call the notify callback
87    */
88   const struct GNUNET_PeerIdentity *target;
89
90   /**
91    * The notify callback to be called when the target peer is connected
92    */
93   GST_cache_peer_connect_notify cb;
94
95   /**
96    * The closure for the notify callback
97    */
98   void *cb_cls;
99
100   /**
101    * The GSTCacheGetHandle reposible for creating this context
102    */
103   struct GSTCacheGetHandle *cgh;
104
105 };
106
107
108 /**
109  * The cache-get request handle
110  */
111 struct GSTCacheGetHandle
112 {
113   /**
114    * The next ptr for the DLL. Used in struct CacheEntry
115    */
116   struct GSTCacheGetHandle *next;
117
118   /**
119    * The prev ptr for the DLL. Used in struct CacheEntry
120    */
121   struct GSTCacheGetHandle *prev;
122
123   /**
124    * The cache entry object this handle corresponds to
125    */
126   struct CacheEntry *entry;
127
128   /**
129    * The cache callback to call when a handle is available
130    */
131   GST_cache_handle_ready_cb cb;
132
133   /**
134    * The closure for the above callback
135    */
136   void *cb_cls;
137
138   /**
139    * The peer connect notify context created for this handle; can be NULL
140    */
141   struct ConnectNotifyContext *nctxt;
142
143   /**
144    * The type of this cache-get request
145    */
146   enum CacheGetType type;
147
148   /**
149    * Did we call the cache callback already?
150    */
151   int notify_called;
152 };
153
154 /**
155  * Cache entry
156  */
157 struct CacheEntry
158 {
159   /**
160    * DLL next ptr for least recently used cache entries
161    */
162   struct CacheEntry *next;
163
164   /**
165    * DLL prev ptr for least recently used cache entries
166    */
167   struct CacheEntry *prev;
168
169   /**
170    * The transport handle to the peer corresponding to this entry; can be NULL
171    */
172   struct GNUNET_TRANSPORT_Handle *transport_handle;
173
174   /**
175    * The operation handle for transport handle
176    */
177   struct GNUNET_TESTBED_Operation *transport_op;
178
179   /**
180    * The core handle to the peer corresponding to this entry; can be NULL
181    */
182   struct GNUNET_CORE_Handle *core_handle;
183
184   /**
185    * The operation handle for core handle
186    */
187   struct GNUNET_TESTBED_Operation *core_op;
188
189   /**
190    * The peer identity of this peer. Will be set upon opening a connection to
191    * the peers CORE service. Will be NULL until then and after the CORE
192    * connection is closed
193    */
194   struct GNUNET_PeerIdentity *peer_identity;
195
196   /**
197    * The configuration of the peer. Should be not NULL as long as the core_handle
198    * or transport_handle are valid
199    */
200   struct GNUNET_CONFIGURATION_Handle *cfg;
201
202   /**
203    * The key for this entry
204    */
205   struct GNUNET_HashCode key;
206
207   /**
208    * The HELLO message
209    */
210   struct GNUNET_MessageHeader *hello;
211
212   /**
213    * the head of the CacheGetHandle queue
214    */
215   struct GSTCacheGetHandle *cgh_qhead;
216
217   /**
218    * the tail of the CacheGetHandle queue
219    */
220   struct GSTCacheGetHandle *cgh_qtail;
221
222   /**
223    * DLL head for the queue of notifications contexts to check which of them are to
224    * be notified when a peer is connected.
225    */
226   struct ConnectNotifyContext *nctxt_qhead;
227
228   /**
229    * DLL tail for the queue of notifications contexts to check which of them are to
230    * be notified when a peer is connected.
231    */
232   struct ConnectNotifyContext *nctxt_qtail;
233
234   /**
235    * The task that calls the cache callback
236    */
237   GNUNET_SCHEDULER_TaskIdentifier notify_task;
238
239   /**
240    * The task to expire this cache entry, free any handlers it has opened and
241    * mark their corresponding operations as done.
242    */
243   GNUNET_SCHEDULER_TaskIdentifier expire_task;
244
245   /**
246    * Number of operations this cache entry is being used
247    */
248   unsigned int demand;
249
250   /**
251    * The id of the peer this entry corresponds to
252    */
253   unsigned int peer_id;
254
255   /**
256    * Is this entry in LRU cache queue?
257    */
258   unsigned int in_lru;
259 };
260
261
262 /**
263  * Hashmap to maintain cache
264  */
265 static struct GNUNET_CONTAINER_MultiHashMap *cache;
266
267 /**
268  * DLL head for least recently used cache entries; least recently used
269  * cache items are at the head. The cache enties are added to this queue when
270  * their demand becomes zero. They are removed from the queue when they are
271  * needed by any operation.
272  */
273 static struct CacheEntry *lru_cache_head;
274
275 /**
276  * DLL tail for least recently used cache entries; recently used cache
277  * items are at the tail.The cache enties are added to this queue when
278  * their demand becomes zero. They are removed from the queue when they are
279  * needed by any operation.
280  */
281 static struct CacheEntry *lru_cache_tail;
282
283 /**
284  * the size of the LRU queue
285  */
286 static unsigned int lru_cache_size;
287
288 /**
289  * the threshold size for the LRU queue
290  */
291 static unsigned int lru_cache_threshold_size;
292
293 /**
294  * The total number of elements in cache
295  */
296 static unsigned int cache_size;
297
298
299 /**
300  * Looks up in the cache and returns the entry
301  *
302  * @param id the peer identity of the peer whose corresponding entry has to be looked up
303  * @return the HELLO message; NULL if not found
304  */
305 static struct CacheEntry *
306 cache_lookup (const struct GNUNET_HashCode *key)
307 {
308   struct CacheEntry *entry;
309
310   if (NULL == cache)
311     return NULL;
312   entry = GNUNET_CONTAINER_multihashmap_get (cache, key);
313   return entry;
314 }
315
316
317 /**
318  * Function to disconnect the core and transport handles; free the existing
319  * configuration; and remove from the LRU cache list. The entry is left to be in
320  * the hash table so that the HELLO can still be found later
321  *
322  * @param entry the cache entry
323  */
324 static void
325 close_handles (struct CacheEntry *entry)
326 {
327   struct ConnectNotifyContext *ctxt;
328
329   GNUNET_assert (0 == entry->demand);
330   if (GNUNET_YES == entry->in_lru)
331   {
332     GNUNET_assert (0 < lru_cache_size);
333     if (GNUNET_SCHEDULER_NO_TASK != entry->expire_task)
334     {
335       GNUNET_SCHEDULER_cancel (entry->expire_task);
336       entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
337     }
338     GNUNET_CONTAINER_DLL_remove (lru_cache_head, lru_cache_tail, entry);
339     lru_cache_size--;
340     entry->in_lru = GNUNET_NO;
341   }
342   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == entry->expire_task);
343   while (NULL != (ctxt = entry->nctxt_qhead))
344   {
345     GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail, ctxt);
346     GNUNET_free (ctxt);
347   }
348   LOG_DEBUG ("Cleaning up handles from an entry in cache\n");
349   if (NULL != entry->transport_handle)
350     GNUNET_assert (NULL != entry->transport_op);
351   if (NULL != entry->transport_op)
352   {
353     GNUNET_TESTBED_operation_done (entry->transport_op);
354     entry->transport_op = NULL;    
355   }
356   if (NULL != entry->core_op)
357   {
358     GNUNET_TESTBED_operation_done (entry->core_op);
359     entry->core_op = NULL;
360   }
361   GNUNET_assert (NULL == entry->core_handle);
362   if (NULL != entry->cfg)
363   {
364     GNUNET_CONFIGURATION_destroy (entry->cfg);
365     entry->cfg = NULL;
366   }
367 }
368
369
370 /**
371  * The task to expire this cache entry, free any handlers it has opened and
372  * mark their corresponding operations as done.
373  *
374  * @param cls the CacheEntry
375  * @param tc the scheduler task context
376  */
377 static void
378 expire_cache_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
379 {
380   struct CacheEntry *entry = cls;
381
382   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != entry->expire_task);
383   entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
384   close_handles (entry);
385 }
386
387
388 /**
389  * Creates a new cache entry and then puts it into the cache's hashtable.
390  *
391  * @param key the hash code to use for inserting the newly created entry
392  * @param peer_id the index of the peer to tag the newly created entry
393  * @return the newly created entry
394  */
395 static struct CacheEntry *
396 add_entry (const struct GNUNET_HashCode *key, unsigned int peer_id)
397 {
398   struct CacheEntry *entry;
399
400   entry = GNUNET_malloc (sizeof (struct CacheEntry));
401   entry->peer_id = peer_id;
402   memcpy (&entry->key, key, sizeof (struct GNUNET_HashCode));
403   GNUNET_assert (GNUNET_OK ==
404                  GNUNET_CONTAINER_multihashmap_put (cache, &entry->key, entry,
405                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
406   cache_size++;
407   return entry;
408 }
409
410
411 /**
412  * Function to find a suitable GSTCacheGetHandle which is waiting for one of the
413  * handles in given entry to be available.
414  *
415  * @param entry the cache entry whose GSTCacheGetHandle list has to be searched
416  * @param head the starting list element in the GSTCacheGetHandle where the
417  *          search has to be begin
418  * @return a suitable GSTCacheGetHandle whose handle ready notify callback
419  *           hasn't been called yet. NULL if no such suitable GSTCacheGetHandle
420  *           is found
421  */
422 static struct GSTCacheGetHandle *
423 search_suitable_cgh (const struct CacheEntry *entry,
424                      const struct GSTCacheGetHandle *head)
425 {
426   const struct GSTCacheGetHandle *cgh;
427
428   for (cgh = head; NULL != cgh; cgh = cgh->next)
429   {
430     if (GNUNET_YES == cgh->notify_called)
431       return NULL;
432     switch (cgh->type)
433     {
434     case CGT_TRANSPORT_HANDLE:
435       if (NULL == entry->transport_handle)
436         continue;
437       break;
438     case CGT_CORE_HANDLE:
439       if (NULL == entry->core_handle)
440         continue;
441       break;
442     }
443     break;
444   }
445   return (struct GSTCacheGetHandle *) cgh;
446 }
447
448
449 /**
450  * Task to call the handle ready notify callback of a queued GSTCacheGetHandle
451  * of an entry when one or all of its handles are available.
452  *
453  * @param cls the cache entry
454  * @param tc the task context from scheduler
455  */
456 static void
457 call_cgh_cb (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
458 {
459   struct CacheEntry *entry = cls;
460   struct GSTCacheGetHandle *cgh;
461   const struct GSTCacheGetHandle *cgh2;
462
463   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != entry->notify_task);
464   entry->notify_task = GNUNET_SCHEDULER_NO_TASK;
465   cgh = search_suitable_cgh (entry, entry->cgh_qhead);
466   GNUNET_assert (NULL != cgh);
467   cgh2 = NULL;
468   if (NULL != cgh->next)
469     cgh2 = search_suitable_cgh (entry, cgh->next);
470   GNUNET_CONTAINER_DLL_remove (entry->cgh_qhead, entry->cgh_qtail, cgh);
471   cgh->notify_called = GNUNET_YES;
472   GNUNET_CONTAINER_DLL_insert_tail (entry->cgh_qhead, entry->cgh_qtail, cgh);
473   if (NULL != cgh2)
474     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
475   if (NULL != cgh->nctxt)
476   {                             /* Register the peer connect notify callback */
477     GNUNET_CONTAINER_DLL_insert_tail (entry->nctxt_qhead, entry->nctxt_qtail,
478                                       cgh->nctxt);
479   }
480   LOG_DEBUG ("Calling notify for handle type %u\n", cgh->type);
481   cgh->cb (cgh->cb_cls, entry->core_handle, entry->transport_handle,
482            entry->peer_identity);
483 }
484
485
486 /**
487  * Function called from peer connect notify callbacks from CORE and TRANSPORT
488  * connections. This function calls the pendning peer connect notify callbacks
489  * which are queued in an entry.
490  *
491  * @param cls the cache entry
492  * @param peer the peer that connected
493  * @param type the type of the handle this notification corresponds to
494  */
495 static void
496 peer_connect_notify_cb (void *cls, const struct GNUNET_PeerIdentity *peer,
497                         const enum CacheGetType type)
498 {
499   struct CacheEntry *entry = cls;
500   struct ConnectNotifyContext *ctxt;
501   struct ConnectNotifyContext *ctxt2;
502   GST_cache_peer_connect_notify cb;
503   void *cb_cls;
504
505
506   for (ctxt = entry->nctxt_qhead; NULL != ctxt;)
507   {
508     GNUNET_assert (NULL != ctxt->cgh);
509     if (type != ctxt->cgh->type)
510     {
511       ctxt = ctxt->next;
512       continue;
513     }
514     if (0 != memcmp (ctxt->target, peer, sizeof (struct GNUNET_PeerIdentity)))
515     {
516       ctxt = ctxt->next;
517       continue;
518     }
519     cb = ctxt->cb;
520     cb_cls = ctxt->cb_cls;
521     ctxt->cgh->nctxt = NULL;
522     ctxt2 = ctxt->next;
523     GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail, ctxt);
524     GNUNET_free (ctxt);
525     ctxt = ctxt2;
526     cb (cb_cls, peer);
527   }
528   if (NULL == ctxt)
529     return;
530
531 }
532
533
534 /**
535  * Function called to notify transport users that another
536  * peer connected to us.
537  *
538  * @param cls closure
539  * @param peer the peer that connected
540  * @param ats performance data
541  * @param ats_count number of entries in ats (excluding 0-termination)
542  */
543 static void
544 transport_peer_connect_notify_cb (void *cls,
545                                   const struct GNUNET_PeerIdentity *peer,
546                                   const struct GNUNET_ATS_Information *ats,
547                                   uint32_t ats_count)
548 {
549   peer_connect_notify_cb (cls, peer, CGT_TRANSPORT_HANDLE);
550 }
551
552
553 /**
554  * Function called when resources for opening a connection to TRANSPORT are
555  * available.
556  *
557  * @param cls the cache entry
558  */
559 static void
560 opstart_get_handle_transport (void *cls)
561 {
562   struct CacheEntry *entry = cls;
563
564   GNUNET_assert (NULL != entry);
565   LOG_DEBUG ("Opening a transport connection to peer %u\n", entry->peer_id);
566   entry->transport_handle =
567       GNUNET_TRANSPORT_connect (entry->cfg, NULL, entry, NULL,
568                                 &transport_peer_connect_notify_cb, NULL);
569   if (NULL == entry->transport_handle)
570   {
571     GNUNET_break (0);
572     return;
573   }
574   if (0 == entry->demand)
575     return;
576   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
577     return;
578   if (NULL != search_suitable_cgh (entry, entry->cgh_qhead))
579     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
580 }
581
582
583 /**
584  * Function called when the operation responsible for opening a TRANSPORT
585  * connection is marked as done.
586  *
587  * @param cls the cache entry
588  */
589 static void
590 oprelease_get_handle_transport (void *cls)
591 {
592   struct CacheEntry *entry = cls;
593
594   if (NULL == entry->transport_handle)
595     return;
596   GNUNET_TRANSPORT_disconnect (entry->transport_handle);
597   entry->transport_handle = NULL;
598 }
599
600
601 /**
602  * Function called after GNUNET_CORE_connect has succeeded (or failed
603  * for good).  Note that the private key of the peer is intentionally
604  * not exposed here; if you need it, your process should try to read
605  * the private key file directly (which should work if you are
606  * authorized...).  Implementations of this function must not call
607  * GNUNET_CORE_disconnect (other than by scheduling a new task to
608  * do this later).
609  *
610  * @param cls closure
611  * @param server handle to the server, NULL if we failed
612  * @param my_identity ID of this peer, NULL if we failed
613  */
614 static void
615 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
616                  const struct GNUNET_PeerIdentity *my_identity)
617 {
618   struct CacheEntry *entry = cls;
619
620   if (NULL == my_identity)
621   {
622     GNUNET_break (0);
623     return;
624   }
625   GNUNET_assert (NULL == entry->peer_identity);
626   entry->core_handle = server;
627   entry->peer_identity = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
628   memcpy (entry->peer_identity, my_identity,
629           sizeof (struct GNUNET_PeerIdentity));
630   if (0 == entry->demand)
631     return;
632   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
633     return;
634   if (NULL != search_suitable_cgh (entry, entry->cgh_qhead))
635     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
636 }
637
638
639 /**
640  * Method called whenever a given peer connects at CORE level
641  *
642  * @param cls closure
643  * @param peer peer identity this notification is about
644  * @param atsi performance data for the connection
645  * @param atsi_count number of records in 'atsi'
646  */
647 static void
648 core_peer_connect_cb (void *cls, const struct GNUNET_PeerIdentity *peer,
649                       const struct GNUNET_ATS_Information *atsi,
650                       unsigned int atsi_count)
651 {
652   peer_connect_notify_cb (cls, peer, CGT_CORE_HANDLE);
653 }
654
655
656 /**
657  * Function called when resources for opening a connection to CORE are
658  * available.
659  *
660  * @param cls the cache entry
661  */
662 static void
663 opstart_get_handle_core (void *cls)
664 {
665   struct CacheEntry *entry = cls;
666
667   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
668     {NULL, 0, 0}
669   };
670
671   GNUNET_assert (NULL != entry);
672   LOG_DEBUG ("Opening a CORE connection to peer %u\n", entry->peer_id);
673   entry->core_handle =
674       GNUNET_CORE_connect (entry->cfg, entry,        /* closure */
675                            &core_startup_cb, /* core startup notify */
676                            &core_peer_connect_cb,    /* peer connect notify */
677                            NULL,     /* peer disconnect notify */
678                            NULL,     /* inbound notify */
679                            GNUNET_NO,        /* inbound header only? */
680                            NULL,     /* outbound notify */
681                            GNUNET_NO,        /* outbound header only? */
682                            no_handlers);
683 }
684
685
686 /**
687  * Function called when the operation responsible for opening a TRANSPORT
688  * connection is marked as done.
689  *
690  * @param cls the cache entry
691  */
692 static void
693 oprelease_get_handle_core (void *cls)
694 {
695   struct CacheEntry *entry = cls;
696
697   if (NULL == entry->core_handle)
698     return;
699   GNUNET_CORE_disconnect (entry->core_handle);
700   entry->core_handle = NULL;
701   GNUNET_free_non_null (entry->peer_identity);
702   entry->peer_identity = NULL;
703 }
704
705
706 /**
707  * Function to get a handle with given configuration. The type of the handle is
708  * implicitly provided in the GSTCacheGetHandle. If the handle is already cached
709  * before, it will be retured in the given callback; the peer_id is used to
710  * lookup in the cache; if not, a new operation is started to open the transport
711  * handle and will be given in the callback when it is available.
712  *
713  * @param cls the cache entry
714  */
715 static struct GSTCacheGetHandle *
716 cache_get_handle (unsigned int peer_id, struct GSTCacheGetHandle *cgh,
717                   const struct GNUNET_CONFIGURATION_Handle *cfg,
718                   const struct GNUNET_PeerIdentity *target,
719                   GST_cache_peer_connect_notify connect_notify_cb,
720                   void *connect_notify_cb_cls)
721 {
722   struct GNUNET_HashCode key;
723   void *handle;
724   struct CacheEntry *entry;
725   struct ConnectNotifyContext *ctxt;
726   struct GNUNET_TESTBED_Operation *op;
727
728   GNUNET_assert (0 != cgh->type);
729   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
730   handle = NULL;
731   entry = cache_lookup (&key);
732   if (NULL != entry)
733   {
734     if (GNUNET_YES == entry->in_lru)
735     {
736       GNUNET_assert (0 == entry->demand);
737       GNUNET_assert (0 < lru_cache_size);
738       if (GNUNET_SCHEDULER_NO_TASK != entry->expire_task)
739       {
740         GNUNET_SCHEDULER_cancel (entry->expire_task);
741         entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
742       }
743       GNUNET_CONTAINER_DLL_remove (lru_cache_head, lru_cache_tail, entry);
744       lru_cache_size--;
745       entry->in_lru = GNUNET_NO;
746     }
747     switch (cgh->type)
748     {
749     case CGT_TRANSPORT_HANDLE:
750       handle = entry->transport_handle;
751       if (NULL != handle)
752         LOG_DEBUG ("Found TRANSPORT handle in cache for peer %u\n",
753                    entry->peer_id);
754       break;
755     case CGT_CORE_HANDLE:
756       handle = entry->core_handle;
757       if (NULL != handle)
758         LOG_DEBUG ("Found CORE handle in cache for peer %u\n", entry->peer_id);
759       break;
760     }
761   }
762   if (NULL == entry)
763     entry = add_entry (&key, peer_id);
764   if (NULL == entry->cfg)
765     entry->cfg = GNUNET_CONFIGURATION_dup (cfg);
766   entry->demand++;
767   cgh->entry = entry;
768   GNUNET_CONTAINER_DLL_insert (entry->cgh_qhead, entry->cgh_qtail, cgh);
769   if ((NULL != target) && (NULL != connect_notify_cb))
770   {
771     ctxt = GNUNET_malloc (sizeof (struct ConnectNotifyContext));
772     ctxt->target = target;
773     ctxt->cb = connect_notify_cb;
774     ctxt->cb_cls = connect_notify_cb_cls;
775     GNUNET_assert (NULL == cgh->nctxt);
776     cgh->nctxt = ctxt;
777     ctxt->cgh = cgh;
778   }
779   if (NULL != handle)
780   {
781     if (GNUNET_SCHEDULER_NO_TASK == entry->notify_task)
782       entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
783     return cgh;
784   }
785   switch (cgh->type)
786   {
787   case CGT_TRANSPORT_HANDLE:
788     if (NULL != entry->transport_op)
789       return cgh;
790     op = GNUNET_TESTBED_operation_create_ (entry, &opstart_get_handle_transport,
791                                            &oprelease_get_handle_transport);
792     entry->transport_op = op;
793     break;
794   case CGT_CORE_HANDLE:
795     if (NULL != entry->core_op)
796       return cgh;
797     op = GNUNET_TESTBED_operation_create_ (entry, &opstart_get_handle_core,
798                                            &oprelease_get_handle_core);
799     entry->core_op = op;
800     break;
801   }
802   GNUNET_TESTBED_operation_queue_insert_ (GST_opq_openfds, op);
803   GNUNET_TESTBED_operation_begin_wait_ (op);
804   return cgh;
805 }
806
807
808 /**
809  * Iterator over hash map entries.
810  *
811  * @param cls closure
812  * @param key current key code
813  * @param value value in the hash map
814  * @return GNUNET_YES if we should continue to
815  *         iterate,
816  *         GNUNET_NO if not.
817  */
818 static int
819 cache_clear_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
820 {
821   struct CacheEntry *entry = value;
822   static unsigned int ncleared;
823
824   GNUNET_assert (NULL != entry);
825   GNUNET_break (0 == entry->demand);
826   LOG_DEBUG ("Clearing entry %u of %u\n", ++ncleared, cache_size);
827   GNUNET_CONTAINER_multihashmap_remove (cache, key, value);
828   close_handles (entry);
829   GNUNET_free_non_null (entry->hello);
830   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == entry->expire_task);
831   GNUNET_assert (NULL == entry->transport_handle);
832   GNUNET_assert (NULL == entry->transport_op);
833   GNUNET_assert (NULL == entry->core_handle);
834   GNUNET_assert (NULL == entry->core_op);
835   GNUNET_assert (NULL == entry->cfg);
836   GNUNET_assert (NULL == entry->cgh_qhead);
837   GNUNET_assert (NULL == entry->cgh_qtail);
838   GNUNET_assert (NULL == entry->nctxt_qhead);
839   GNUNET_assert (NULL == entry->nctxt_qtail);
840   GNUNET_free (entry);
841   return GNUNET_YES;
842 }
843
844
845 /**
846  * Clear cache
847  */
848 void
849 GST_cache_clear ()
850 {
851   GNUNET_CONTAINER_multihashmap_iterate (cache, &cache_clear_iterator, NULL);
852   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (cache));
853   GNUNET_CONTAINER_multihashmap_destroy (cache);
854   cache = NULL;
855   lru_cache_size = 0;
856   lru_cache_threshold_size = 0;
857   cache_size = 0;
858   lru_cache_head = NULL;
859   lru_cache_tail = NULL;
860 }
861
862
863 /**
864  * Initializes the cache
865  *
866  * @param size the size of the cache
867  */
868 void
869 GST_cache_init (unsigned int size)
870 {
871   if (0 == size)
872     return;
873   lru_cache_threshold_size = size;
874   if (size > 1)
875     size = size / 2;
876   cache = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_YES);
877 }
878
879
880 /**
881  * Mark the GetCacheHandle as being done if a handle has been provided already
882  * or as being cancelled if the callback for the handle hasn't been called.
883  *
884  * @param cgh the CacheGetHandle handle
885  */
886 void
887 GST_cache_get_handle_done (struct GSTCacheGetHandle *cgh)
888 {
889   struct CacheEntry *entry;
890
891   entry = cgh->entry;
892   GNUNET_assert (NULL != entry);
893   GNUNET_assert (0 < entry->demand);
894   entry->demand--;
895   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
896   {
897     GNUNET_SCHEDULER_cancel (entry->notify_task);
898     entry->notify_task = GNUNET_SCHEDULER_NO_TASK;
899   }
900   GNUNET_CONTAINER_DLL_remove (entry->cgh_qhead, entry->cgh_qtail, cgh);
901   if (NULL != cgh->nctxt)
902   {
903     GNUNET_assert (cgh == cgh->nctxt->cgh);
904     if (GNUNET_YES == cgh->notify_called)
905       GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail,
906                                    cgh->nctxt);
907     GNUNET_free (cgh->nctxt);
908   }
909   GNUNET_free (cgh);
910   if (0 == entry->demand)
911   {
912     entry->expire_task =
913         GNUNET_SCHEDULER_add_delayed (CACHE_EXPIRY, &expire_cache_entry, entry);
914     GNUNET_CONTAINER_DLL_insert_tail (lru_cache_head, lru_cache_tail, entry);
915     lru_cache_size++;
916     entry->in_lru = GNUNET_YES;
917     if (lru_cache_size > lru_cache_threshold_size)
918       close_handles (lru_cache_head);
919   }
920   else
921   {
922     struct GSTCacheGetHandle *cgh2;
923
924     if (NULL != (cgh2 = search_suitable_cgh (entry, entry->cgh_qhead)))
925       entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
926   }
927 }
928
929
930 /**
931  * Get a transport handle with the given configuration.  If the handle is
932  * already cached before, it will be retured in the given callback; the peer_id
933  * is used to lookup in the cache; if not, a new operation is started to open the
934  * transport handle and will be given in the callback when it is available.
935  *
936  * @param peer_id the index of the peer
937  * @param cfg the configuration with which the transport handle has to be
938  *          created if it was not present in the cache
939  * @param cb the callback to notify when the transport handle is available
940  * @param cb_cls the closure for the above callback
941  * @param target the peer identify of the peer whose connection to our TRANSPORT
942  *          subsystem will be notified through the connect_notify_cb. Can be NULL
943  * @param connect_notify_cb the callback to call when the given target peer is
944  *          connected. This callback will only be called once or never again (in
945  *          case the target peer cannot be connected). Can be NULL
946  * @param connect_notify_cb_cls the closure for the above callback
947  * @return the handle which can be used cancel or mark that the handle is no
948  *           longer being used
949  */
950 struct GSTCacheGetHandle *
951 GST_cache_get_handle_transport (unsigned int peer_id,
952                                 const struct GNUNET_CONFIGURATION_Handle *cfg,
953                                 GST_cache_handle_ready_cb cb, void *cb_cls,
954                                 const struct GNUNET_PeerIdentity *target,
955                                 GST_cache_peer_connect_notify connect_notify_cb,
956                                 void *connect_notify_cb_cls)
957 {
958   struct GSTCacheGetHandle *cgh;
959
960   cgh = GNUNET_malloc (sizeof (struct GSTCacheGetHandle));
961   cgh->cb = cb;
962   cgh->cb_cls = cb_cls;
963   cgh->type = CGT_TRANSPORT_HANDLE;
964   return cache_get_handle (peer_id, cgh, cfg, target, connect_notify_cb,
965                            connect_notify_cb_cls);
966 }
967
968
969 /**
970  * Get a CORE handle with the given configuration. If the handle is already
971  * cached before, it will be retured in the given callback; the peer_id is used
972  * to lookup in the cache. If the handle is not cached before, a new operation
973  * is started to open the CORE handle and will be given in the callback when it
974  * is available along with the peer identity
975  *
976  * @param peer_id the index of the peer
977  * @param cfg the configuration with which the transport handle has to be
978  *          created if it was not present in the cache
979  * @param cb the callback to notify when the transport handle is available
980  * @param cb_cls the closure for the above callback
981  * @param target the peer identify of the peer whose connection to our CORE
982  *          subsystem will be notified through the connect_notify_cb. Can be NULL
983  * @param connect_notify_cb the callback to call when the given target peer is
984  *          connected. This callback will only be called once or never again (in
985  *          case the target peer cannot be connected). Can be NULL
986  * @param connect_notify_cb_cls the closure for the above callback
987  * @return the handle which can be used cancel or mark that the handle is no
988  *           longer being used
989  */
990 struct GSTCacheGetHandle *
991 GST_cache_get_handle_core (unsigned int peer_id,
992                            const struct GNUNET_CONFIGURATION_Handle *cfg,
993                            GST_cache_handle_ready_cb cb, void *cb_cls,
994                            const struct GNUNET_PeerIdentity *target,
995                            GST_cache_peer_connect_notify connect_notify_cb,
996                            void *connect_notify_cb_cls)
997 {
998   struct GSTCacheGetHandle *cgh;
999
1000   cgh = GNUNET_malloc (sizeof (struct GSTCacheGetHandle));
1001   cgh->cb = cb;
1002   cgh->cb_cls = cb_cls;
1003   cgh->type = CGT_CORE_HANDLE;
1004   return cache_get_handle (peer_id, cgh, cfg, target, connect_notify_cb,
1005                            connect_notify_cb_cls);
1006 }
1007
1008
1009 /**
1010  * Looks up in the hello cache and returns the HELLO of the given peer
1011  *
1012  * @param peer_id the index of the peer whose HELLO has to be looked up
1013  * @return the HELLO message; NULL if not found
1014  */
1015 const struct GNUNET_MessageHeader *
1016 GST_cache_lookup_hello (const unsigned int peer_id)
1017 {
1018   struct CacheEntry *entry;
1019   struct GNUNET_HashCode key;
1020
1021   LOG_DEBUG ("Looking up HELLO for peer %u\n", peer_id);
1022   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
1023   entry = cache_lookup (&key);
1024   if (NULL == entry)
1025     return NULL;
1026   if (NULL != entry->hello)
1027     LOG_DEBUG ("HELLO found for peer %u\n", peer_id);
1028   return entry->hello;
1029 }
1030
1031
1032 /**
1033  * Caches the HELLO of the given peer. Updates the HELLO if it was already
1034  * cached before
1035  *
1036  * @param id the peer identity of the peer whose HELLO has to be cached
1037  * @param hello the HELLO message
1038  */
1039 void
1040 GST_cache_add_hello (const unsigned int peer_id,
1041                      const struct GNUNET_MessageHeader *hello)
1042 {
1043   struct CacheEntry *entry;
1044   struct GNUNET_HashCode key;
1045
1046   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
1047   entry = GNUNET_CONTAINER_multihashmap_get (cache, &key);
1048   if (NULL == entry)
1049     entry = add_entry (&key, peer_id);
1050   GNUNET_free_non_null (entry->hello);
1051   entry->hello = GNUNET_copy_message (hello);
1052 }
1053
1054 /* end of gnunet-service-testbed_hc.c */