ac4bcecec434c91e24bcf44c55c5553a8019b294
[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.c
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 key the peer identity of the peer whose corresponding entry has to be
303  *          looked up
304  * @return the HELLO message; NULL if not found
305  */
306 static struct CacheEntry *
307 cache_lookup (const struct GNUNET_HashCode *key)
308 {
309   struct CacheEntry *entry;
310
311   if (NULL == cache)
312     return NULL;
313   entry = GNUNET_CONTAINER_multihashmap_get (cache, key);
314   return entry;
315 }
316
317
318 /**
319  * Function to disconnect the core and transport handles; free the existing
320  * configuration; and remove from the LRU cache list. The entry is left to be in
321  * the hash table so that the HELLO can still be found later
322  *
323  * @param entry the cache entry
324  */
325 static void
326 close_handles (struct CacheEntry *entry)
327 {
328   struct ConnectNotifyContext *ctxt;
329
330   GNUNET_assert (0 == entry->demand);
331   if (GNUNET_YES == entry->in_lru)
332   {
333     GNUNET_assert (0 < lru_cache_size);
334     if (GNUNET_SCHEDULER_NO_TASK != entry->expire_task)
335     {
336       GNUNET_SCHEDULER_cancel (entry->expire_task);
337       entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
338     }
339     GNUNET_CONTAINER_DLL_remove (lru_cache_head, lru_cache_tail, entry);
340     lru_cache_size--;
341     entry->in_lru = GNUNET_NO;
342   }
343   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == entry->expire_task);
344   while (NULL != (ctxt = entry->nctxt_qhead))
345   {
346     GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail, ctxt);
347     GNUNET_free (ctxt);
348   }
349   LOG_DEBUG ("Cleaning up handles from an entry in cache\n");
350   if (NULL != entry->transport_handle)
351     GNUNET_assert (NULL != entry->transport_op);
352   if (NULL != entry->transport_op)
353   {
354     GNUNET_TESTBED_operation_done (entry->transport_op);
355     entry->transport_op = NULL;    
356   }
357   if (NULL != entry->core_op)
358   {
359     GNUNET_TESTBED_operation_done (entry->core_op);
360     entry->core_op = NULL;
361   }
362   GNUNET_assert (NULL == entry->core_handle);
363   if (NULL != entry->cfg)
364   {
365     GNUNET_CONFIGURATION_destroy (entry->cfg);
366     entry->cfg = NULL;
367   }
368 }
369
370
371 /**
372  * The task to expire this cache entry, free any handlers it has opened and
373  * mark their corresponding operations as done.
374  *
375  * @param cls the CacheEntry
376  * @param tc the scheduler task context
377  */
378 static void
379 expire_cache_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
380 {
381   struct CacheEntry *entry = cls;
382
383   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != entry->expire_task);
384   entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
385   close_handles (entry);
386 }
387
388
389 /**
390  * Creates a new cache entry and then puts it into the cache's hashtable.
391  *
392  * @param key the hash code to use for inserting the newly created entry
393  * @param peer_id the index of the peer to tag the newly created entry
394  * @return the newly created entry
395  */
396 static struct CacheEntry *
397 add_entry (const struct GNUNET_HashCode *key, unsigned int peer_id)
398 {
399   struct CacheEntry *entry;
400
401   entry = GNUNET_malloc (sizeof (struct CacheEntry));
402   entry->peer_id = peer_id;
403   memcpy (&entry->key, key, sizeof (struct GNUNET_HashCode));
404   GNUNET_assert (GNUNET_OK ==
405                  GNUNET_CONTAINER_multihashmap_put (cache, &entry->key, entry,
406                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
407   cache_size++;
408   return entry;
409 }
410
411
412 /**
413  * Function to find a suitable GSTCacheGetHandle which is waiting for one of the
414  * handles in given entry to be available.
415  *
416  * @param entry the cache entry whose GSTCacheGetHandle list has to be searched
417  * @param head the starting list element in the GSTCacheGetHandle where the
418  *          search has to be begin
419  * @return a suitable GSTCacheGetHandle whose handle ready notify callback
420  *           hasn't been called yet. NULL if no such suitable GSTCacheGetHandle
421  *           is found
422  */
423 static struct GSTCacheGetHandle *
424 search_suitable_cgh (const struct CacheEntry *entry,
425                      const struct GSTCacheGetHandle *head)
426 {
427   const struct GSTCacheGetHandle *cgh;
428
429   for (cgh = head; NULL != cgh; cgh = cgh->next)
430   {
431     if (GNUNET_YES == cgh->notify_called)
432       return NULL;
433     switch (cgh->type)
434     {
435     case CGT_TRANSPORT_HANDLE:
436       if (NULL == entry->transport_handle)
437         continue;
438       break;
439     case CGT_CORE_HANDLE:
440       if (NULL == entry->core_handle)
441         continue;
442       if (NULL == entry->peer_identity) /* Our CORE connection isn't ready yet */
443         continue;
444       break;
445     }
446     break;
447   }
448   return (struct GSTCacheGetHandle *) cgh;
449 }
450
451
452 /**
453  * Task to call the handle ready notify callback of a queued GSTCacheGetHandle
454  * of an entry when one or all of its handles are available.
455  *
456  * @param cls the cache entry
457  * @param tc the task context from scheduler
458  */
459 static void
460 call_cgh_cb (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
461 {
462   struct CacheEntry *entry = cls;
463   struct GSTCacheGetHandle *cgh;
464   const struct GSTCacheGetHandle *cgh2;
465
466   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != entry->notify_task);
467   entry->notify_task = GNUNET_SCHEDULER_NO_TASK;
468   cgh = search_suitable_cgh (entry, entry->cgh_qhead);
469   GNUNET_assert (NULL != cgh);
470   cgh2 = NULL;
471   if (NULL != cgh->next)
472     cgh2 = search_suitable_cgh (entry, cgh->next);
473   GNUNET_CONTAINER_DLL_remove (entry->cgh_qhead, entry->cgh_qtail, cgh);
474   cgh->notify_called = GNUNET_YES;
475   GNUNET_CONTAINER_DLL_insert_tail (entry->cgh_qhead, entry->cgh_qtail, cgh);
476   if (NULL != cgh2)
477     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
478   if (NULL != cgh->nctxt)
479   {                             /* Register the peer connect notify callback */
480     GNUNET_CONTAINER_DLL_insert_tail (entry->nctxt_qhead, entry->nctxt_qtail,
481                                       cgh->nctxt);
482   }
483   LOG_DEBUG ("Calling notify for handle type %u\n", cgh->type);
484   cgh->cb (cgh->cb_cls, entry->core_handle, entry->transport_handle,
485            entry->peer_identity);
486 }
487
488
489 /**
490  * Function called from peer connect notify callbacks from CORE and TRANSPORT
491  * connections. This function calls the pendning peer connect notify callbacks
492  * which are queued in an entry.
493  *
494  * @param cls the cache entry
495  * @param peer the peer that connected
496  * @param type the type of the handle this notification corresponds to
497  */
498 static void
499 peer_connect_notify_cb (void *cls, const struct GNUNET_PeerIdentity *peer,
500                         const enum CacheGetType type)
501 {
502   struct CacheEntry *entry = cls;
503   struct ConnectNotifyContext *ctxt;
504   struct ConnectNotifyContext *ctxt2;
505   GST_cache_peer_connect_notify cb;
506   void *cb_cls;
507
508
509   for (ctxt = entry->nctxt_qhead; NULL != ctxt;)
510   {
511     GNUNET_assert (NULL != ctxt->cgh);
512     if (type != ctxt->cgh->type)
513     {
514       ctxt = ctxt->next;
515       continue;
516     }
517     if (0 != memcmp (ctxt->target, peer, sizeof (struct GNUNET_PeerIdentity)))
518     {
519       ctxt = ctxt->next;
520       continue;
521     }
522     cb = ctxt->cb;
523     cb_cls = ctxt->cb_cls;
524     ctxt->cgh->nctxt = NULL;
525     ctxt2 = ctxt->next;
526     GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail, ctxt);
527     GNUNET_free (ctxt);
528     ctxt = ctxt2;
529     cb (cb_cls, peer);
530   }
531   if (NULL == ctxt)
532     return;
533
534 }
535
536
537 /**
538  * Function called to notify transport users that another
539  * peer connected to us.
540  *
541  * @param cls closure
542  * @param peer the peer that connected
543  * @param ats performance data
544  * @param ats_count number of entries in ats (excluding 0-termination)
545  */
546 static void
547 transport_peer_connect_notify_cb (void *cls,
548                                   const struct GNUNET_PeerIdentity *peer,
549                                   const struct GNUNET_ATS_Information *ats,
550                                   uint32_t ats_count)
551 {
552   peer_connect_notify_cb (cls, peer, CGT_TRANSPORT_HANDLE);
553 }
554
555
556 /**
557  * Function called when resources for opening a connection to TRANSPORT are
558  * available.
559  *
560  * @param cls the cache entry
561  */
562 static void
563 opstart_get_handle_transport (void *cls)
564 {
565   struct CacheEntry *entry = cls;
566
567   GNUNET_assert (NULL != entry);
568   LOG_DEBUG ("Opening a transport connection to peer %u\n", entry->peer_id);
569   entry->transport_handle =
570       GNUNET_TRANSPORT_connect (entry->cfg, NULL, entry, NULL,
571                                 &transport_peer_connect_notify_cb, NULL);
572   if (NULL == entry->transport_handle)
573   {
574     GNUNET_break (0);
575     return;
576   }
577   if (0 == entry->demand)
578     return;
579   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
580     return;
581   if (NULL != search_suitable_cgh (entry, entry->cgh_qhead))
582     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
583 }
584
585
586 /**
587  * Function called when the operation responsible for opening a TRANSPORT
588  * connection is marked as done.
589  *
590  * @param cls the cache entry
591  */
592 static void
593 oprelease_get_handle_transport (void *cls)
594 {
595   struct CacheEntry *entry = cls;
596
597   if (NULL == entry->transport_handle)
598     return;
599   GNUNET_TRANSPORT_disconnect (entry->transport_handle);
600   entry->transport_handle = NULL;
601 }
602
603
604 /**
605  * Function called after GNUNET_CORE_connect has succeeded (or failed
606  * for good).  Note that the private key of the peer is intentionally
607  * not exposed here; if you need it, your process should try to read
608  * the private key file directly (which should work if you are
609  * authorized...).  Implementations of this function must not call
610  * GNUNET_CORE_disconnect (other than by scheduling a new task to
611  * do this later).
612  *
613  * @param cls closure
614  * @param server handle to the server, NULL if we failed
615  * @param my_identity ID of this peer, NULL if we failed
616  */
617 static void
618 core_startup_cb (void *cls, struct GNUNET_CORE_Handle *server,
619                  const struct GNUNET_PeerIdentity *my_identity)
620 {
621   struct CacheEntry *entry = cls;
622
623   if (NULL == my_identity)
624   {
625     GNUNET_break (0);
626     return;
627   }
628   GNUNET_assert (NULL == entry->peer_identity);
629   GNUNET_break (NULL != server);
630   entry->core_handle = server;
631   entry->peer_identity = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
632   memcpy (entry->peer_identity, my_identity,
633           sizeof (struct GNUNET_PeerIdentity));
634   if (0 == entry->demand)
635     return;
636   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
637     return;
638   if (NULL != search_suitable_cgh (entry, entry->cgh_qhead))
639     entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
640 }
641
642
643 /**
644  * Method called whenever a given peer connects at CORE level
645  *
646  * @param cls closure
647  * @param peer peer identity this notification is about
648  * @param atsi performance data for the connection
649  * @param atsi_count number of records in 'atsi'
650  */
651 static void
652 core_peer_connect_cb (void *cls, const struct GNUNET_PeerIdentity *peer,
653                       const struct GNUNET_ATS_Information *atsi,
654                       unsigned int atsi_count)
655 {
656   peer_connect_notify_cb (cls, peer, CGT_CORE_HANDLE);
657 }
658
659
660 /**
661  * Function called when resources for opening a connection to CORE are
662  * available.
663  *
664  * @param cls the cache entry
665  */
666 static void
667 opstart_get_handle_core (void *cls)
668 {
669   struct CacheEntry *entry = cls;
670
671   const struct GNUNET_CORE_MessageHandler no_handlers[] = {
672     {NULL, 0, 0}
673   };
674
675   GNUNET_assert (NULL != entry);
676   LOG_DEBUG ("Opening a CORE connection to peer %u\n", entry->peer_id);
677   entry->core_handle =
678       GNUNET_CORE_connect (entry->cfg, entry,        /* closure */
679                            &core_startup_cb, /* core startup notify */
680                            &core_peer_connect_cb,    /* peer connect notify */
681                            NULL,     /* peer disconnect notify */
682                            NULL,     /* inbound notify */
683                            GNUNET_NO,        /* inbound header only? */
684                            NULL,     /* outbound notify */
685                            GNUNET_NO,        /* outbound header only? */
686                            no_handlers);
687 }
688
689
690 /**
691  * Function called when the operation responsible for opening a TRANSPORT
692  * connection is marked as done.
693  *
694  * @param cls the cache entry
695  */
696 static void
697 oprelease_get_handle_core (void *cls)
698 {
699   struct CacheEntry *entry = cls;
700
701   if (NULL == entry->core_handle)
702     return;
703   GNUNET_CORE_disconnect (entry->core_handle);
704   entry->core_handle = NULL;
705   GNUNET_free_non_null (entry->peer_identity);
706   entry->peer_identity = NULL;
707 }
708
709
710 /**
711  * Function to get a handle with given configuration. The type of the handle is
712  * implicitly provided in the GSTCacheGetHandle. If the handle is already cached
713  * before, it will be retured in the given callback; the peer_id is used to
714  * lookup in the cache; if not, a new operation is started to open the transport
715  * handle and will be given in the callback when it is available.
716  *
717  * @param peer_id the index of the peer
718  * @param cgh the CacheGetHandle
719  * @param cfg the configuration with which the transport handle has to be
720  *          created if it was not present in the cache
721  * @param target the peer identify of the peer whose connection to
722  *          TRANSPORT/CORE (depending on the type of 'cgh') subsystem will be
723  *          notified through the connect_notify_cb. Can be NULL
724  * @param connect_notify_cb the callback to call when the given target peer is
725  *          connected. This callback will only be called once or never again (in
726  *          case the target peer cannot be connected). Can be NULL
727  * @param connect_notify_cb_cls the closure for the above callback
728  * @return the handle which can be used to cancel or mark that the handle is no
729  *           longer being used
730  */
731 static struct GSTCacheGetHandle *
732 cache_get_handle (unsigned int peer_id, struct GSTCacheGetHandle *cgh,
733                   const struct GNUNET_CONFIGURATION_Handle *cfg,
734                   const struct GNUNET_PeerIdentity *target,
735                   GST_cache_peer_connect_notify connect_notify_cb,
736                   void *connect_notify_cb_cls)
737 {
738   struct GNUNET_HashCode key;
739   void *handle;
740   struct CacheEntry *entry;
741   struct ConnectNotifyContext *ctxt;
742   struct GNUNET_TESTBED_Operation *op;
743
744   GNUNET_assert (0 != cgh->type);
745   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
746   handle = NULL;
747   entry = cache_lookup (&key);
748   if (NULL != entry)
749   {
750     if (GNUNET_YES == entry->in_lru)
751     {
752       GNUNET_assert (0 == entry->demand);
753       GNUNET_assert (0 < lru_cache_size);
754       if (GNUNET_SCHEDULER_NO_TASK != entry->expire_task)
755       {
756         GNUNET_SCHEDULER_cancel (entry->expire_task);
757         entry->expire_task = GNUNET_SCHEDULER_NO_TASK;
758       }
759       GNUNET_CONTAINER_DLL_remove (lru_cache_head, lru_cache_tail, entry);
760       lru_cache_size--;
761       entry->in_lru = GNUNET_NO;
762     }
763     switch (cgh->type)
764     {
765     case CGT_TRANSPORT_HANDLE:
766       handle = entry->transport_handle;
767       if (NULL != handle)
768         LOG_DEBUG ("Found TRANSPORT handle in cache for peer %u\n",
769                    entry->peer_id);
770       break;
771     case CGT_CORE_HANDLE:
772       handle = entry->core_handle;
773       if (NULL != handle)
774         LOG_DEBUG ("Found CORE handle in cache for peer %u\n", entry->peer_id);
775       break;
776     }
777   }
778   if (NULL == entry)
779     entry = add_entry (&key, peer_id);
780   if (NULL == entry->cfg)
781     entry->cfg = GNUNET_CONFIGURATION_dup (cfg);
782   entry->demand++;
783   cgh->entry = entry;
784   GNUNET_CONTAINER_DLL_insert (entry->cgh_qhead, entry->cgh_qtail, cgh);
785   if ((NULL != target) && (NULL != connect_notify_cb))
786   {
787     ctxt = GNUNET_malloc (sizeof (struct ConnectNotifyContext));
788     ctxt->target = target;
789     ctxt->cb = connect_notify_cb;
790     ctxt->cb_cls = connect_notify_cb_cls;
791     GNUNET_assert (NULL == cgh->nctxt);
792     cgh->nctxt = ctxt;
793     ctxt->cgh = cgh;
794   }
795   if (NULL != handle)
796   {
797     if (GNUNET_SCHEDULER_NO_TASK == entry->notify_task)
798     {
799       if (NULL != search_suitable_cgh (entry, entry->cgh_qhead))
800         entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
801     }
802     return cgh;
803   }
804   switch (cgh->type)
805   {
806   case CGT_TRANSPORT_HANDLE:
807     if (NULL != entry->transport_op)
808       return cgh;
809     op = GNUNET_TESTBED_operation_create_ (entry, &opstart_get_handle_transport,
810                                            &oprelease_get_handle_transport);
811     entry->transport_op = op;
812     break;
813   case CGT_CORE_HANDLE:
814     if (NULL != entry->core_op)
815       return cgh;
816     op = GNUNET_TESTBED_operation_create_ (entry, &opstart_get_handle_core,
817                                            &oprelease_get_handle_core);
818     entry->core_op = op;
819     break;
820   }
821   GNUNET_TESTBED_operation_queue_insert_ (GST_opq_openfds, op);
822   GNUNET_TESTBED_operation_begin_wait_ (op);
823   return cgh;
824 }
825
826
827 /**
828  * Iterator over hash map entries.
829  *
830  * @param cls closure
831  * @param key current key code
832  * @param value value in the hash map
833  * @return GNUNET_YES if we should continue to
834  *         iterate,
835  *         GNUNET_NO if not.
836  */
837 static int
838 cache_clear_iterator (void *cls, const struct GNUNET_HashCode *key, void *value)
839 {
840   struct CacheEntry *entry = value;
841   static unsigned int ncleared;
842
843   GNUNET_assert (NULL != entry);
844   GNUNET_break (0 == entry->demand);
845   LOG_DEBUG ("Clearing entry %u of %u\n", ++ncleared, cache_size);
846   GNUNET_CONTAINER_multihashmap_remove (cache, key, value);
847   close_handles (entry);
848   GNUNET_free_non_null (entry->hello);
849   GNUNET_break (GNUNET_SCHEDULER_NO_TASK == entry->expire_task);
850   GNUNET_assert (NULL == entry->transport_handle);
851   GNUNET_assert (NULL == entry->transport_op);
852   GNUNET_assert (NULL == entry->core_handle);
853   GNUNET_assert (NULL == entry->core_op);
854   GNUNET_assert (NULL == entry->cfg);
855   GNUNET_assert (NULL == entry->cgh_qhead);
856   GNUNET_assert (NULL == entry->cgh_qtail);
857   GNUNET_assert (NULL == entry->nctxt_qhead);
858   GNUNET_assert (NULL == entry->nctxt_qtail);
859   GNUNET_free (entry);
860   return GNUNET_YES;
861 }
862
863
864 /**
865  * Clear cache
866  */
867 void
868 GST_cache_clear ()
869 {
870   GNUNET_CONTAINER_multihashmap_iterate (cache, &cache_clear_iterator, NULL);
871   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (cache));
872   GNUNET_CONTAINER_multihashmap_destroy (cache);
873   cache = NULL;
874   lru_cache_size = 0;
875   lru_cache_threshold_size = 0;
876   cache_size = 0;
877   lru_cache_head = NULL;
878   lru_cache_tail = NULL;
879 }
880
881
882 /**
883  * Initializes the cache
884  *
885  * @param size the size of the cache
886  */
887 void
888 GST_cache_init (unsigned int size)
889 {
890   if (0 == size)
891     return;
892   lru_cache_threshold_size = size;
893   if (size > 1)
894     size = size / 2;
895   cache = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_YES);
896 }
897
898
899 /**
900  * Mark the GetCacheHandle as being done if a handle has been provided already
901  * or as being cancelled if the callback for the handle hasn't been called.
902  *
903  * @param cgh the CacheGetHandle handle
904  */
905 void
906 GST_cache_get_handle_done (struct GSTCacheGetHandle *cgh)
907 {
908   struct CacheEntry *entry;
909
910   entry = cgh->entry;
911   GNUNET_assert (NULL != entry);
912   GNUNET_assert (0 < entry->demand);
913   entry->demand--;
914   if (GNUNET_SCHEDULER_NO_TASK != entry->notify_task)
915   {
916     GNUNET_SCHEDULER_cancel (entry->notify_task);
917     entry->notify_task = GNUNET_SCHEDULER_NO_TASK;
918   }
919   GNUNET_CONTAINER_DLL_remove (entry->cgh_qhead, entry->cgh_qtail, cgh);
920   if (NULL != cgh->nctxt)
921   {
922     GNUNET_assert (cgh == cgh->nctxt->cgh);
923     if (GNUNET_YES == cgh->notify_called)
924       GNUNET_CONTAINER_DLL_remove (entry->nctxt_qhead, entry->nctxt_qtail,
925                                    cgh->nctxt);
926     GNUNET_free (cgh->nctxt);
927   }
928   GNUNET_free (cgh);
929   if (0 == entry->demand)
930   {
931     entry->expire_task =
932         GNUNET_SCHEDULER_add_delayed (CACHE_EXPIRY, &expire_cache_entry, entry);
933     GNUNET_CONTAINER_DLL_insert_tail (lru_cache_head, lru_cache_tail, entry);
934     lru_cache_size++;
935     entry->in_lru = GNUNET_YES;
936     if (lru_cache_size > lru_cache_threshold_size)
937       close_handles (lru_cache_head);
938   }
939   else
940   {
941     struct GSTCacheGetHandle *cgh2;
942
943     if (NULL != (cgh2 = search_suitable_cgh (entry, entry->cgh_qhead)))
944       entry->notify_task = GNUNET_SCHEDULER_add_now (&call_cgh_cb, entry);
945   }
946 }
947
948
949 /**
950  * Get a transport handle with the given configuration.  If the handle is
951  * already cached before, it will be retured in the given callback; the peer_id
952  * is used to lookup in the cache; if not, a new operation is started to open the
953  * transport handle and will be given in the callback when it is available.
954  *
955  * @param peer_id the index of the peer
956  * @param cfg the configuration with which the transport handle has to be
957  *          created if it was not present in the cache
958  * @param cb the callback to notify when the transport handle is available
959  * @param cb_cls the closure for the above callback
960  * @param target the peer identify of the peer whose connection to our TRANSPORT
961  *          subsystem will be notified through the connect_notify_cb. Can be NULL
962  * @param connect_notify_cb the callback to call when the given target peer is
963  *          connected. This callback will only be called once or never again (in
964  *          case the target peer cannot be connected). Can be NULL
965  * @param connect_notify_cb_cls the closure for the above callback
966  * @return the handle which can be used to cancel or mark that the handle is no
967  *           longer being used
968  */
969 struct GSTCacheGetHandle *
970 GST_cache_get_handle_transport (unsigned int peer_id,
971                                 const struct GNUNET_CONFIGURATION_Handle *cfg,
972                                 GST_cache_handle_ready_cb cb, void *cb_cls,
973                                 const struct GNUNET_PeerIdentity *target,
974                                 GST_cache_peer_connect_notify connect_notify_cb,
975                                 void *connect_notify_cb_cls)
976 {
977   struct GSTCacheGetHandle *cgh;
978
979   cgh = GNUNET_malloc (sizeof (struct GSTCacheGetHandle));
980   cgh->cb = cb;
981   cgh->cb_cls = cb_cls;
982   cgh->type = CGT_TRANSPORT_HANDLE;
983   return cache_get_handle (peer_id, cgh, cfg, target, connect_notify_cb,
984                            connect_notify_cb_cls);
985 }
986
987
988 /**
989  * Get a CORE handle with the given configuration. If the handle is already
990  * cached before, it will be retured in the given callback; the peer_id is used
991  * to lookup in the cache. If the handle is not cached before, a new operation
992  * is started to open the CORE handle and will be given in the callback when it
993  * is available along with the peer identity
994  *
995  * @param peer_id the index of the peer
996  * @param cfg the configuration with which the transport handle has to be
997  *          created if it was not present in the cache
998  * @param cb the callback to notify when the transport handle is available
999  * @param cb_cls the closure for the above callback
1000  * @param target the peer identify of the peer whose connection to our CORE
1001  *          subsystem will be notified through the connect_notify_cb. Can be NULL
1002  * @param connect_notify_cb the callback to call when the given target peer is
1003  *          connected. This callback will only be called once or never again (in
1004  *          case the target peer cannot be connected). Can be NULL
1005  * @param connect_notify_cb_cls the closure for the above callback
1006  * @return the handle which can be used to cancel or mark that the handle is no
1007  *           longer being used
1008  */
1009 struct GSTCacheGetHandle *
1010 GST_cache_get_handle_core (unsigned int peer_id,
1011                            const struct GNUNET_CONFIGURATION_Handle *cfg,
1012                            GST_cache_handle_ready_cb cb, void *cb_cls,
1013                            const struct GNUNET_PeerIdentity *target,
1014                            GST_cache_peer_connect_notify connect_notify_cb,
1015                            void *connect_notify_cb_cls)
1016 {
1017   struct GSTCacheGetHandle *cgh;
1018
1019   cgh = GNUNET_malloc (sizeof (struct GSTCacheGetHandle));
1020   cgh->cb = cb;
1021   cgh->cb_cls = cb_cls;
1022   cgh->type = CGT_CORE_HANDLE;
1023   return cache_get_handle (peer_id, cgh, cfg, target, connect_notify_cb,
1024                            connect_notify_cb_cls);
1025 }
1026
1027
1028 /**
1029  * Looks up in the hello cache and returns the HELLO of the given peer
1030  *
1031  * @param peer_id the index of the peer whose HELLO has to be looked up
1032  * @return the HELLO message; NULL if not found
1033  */
1034 const struct GNUNET_MessageHeader *
1035 GST_cache_lookup_hello (const unsigned int peer_id)
1036 {
1037   struct CacheEntry *entry;
1038   struct GNUNET_HashCode key;
1039
1040   LOG_DEBUG ("Looking up HELLO for peer %u\n", peer_id);
1041   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
1042   entry = cache_lookup (&key);
1043   if (NULL == entry)
1044     return NULL;
1045   if (NULL != entry->hello)
1046     LOG_DEBUG ("HELLO found for peer %u\n", peer_id);
1047   return entry->hello;
1048 }
1049
1050
1051 /**
1052  * Caches the HELLO of the given peer. Updates the HELLO if it was already
1053  * cached before
1054  *
1055  * @param peer_id the peer identity of the peer whose HELLO has to be cached
1056  * @param hello the HELLO message
1057  */
1058 void
1059 GST_cache_add_hello (const unsigned int peer_id,
1060                      const struct GNUNET_MessageHeader *hello)
1061 {
1062   struct CacheEntry *entry;
1063   struct GNUNET_HashCode key;
1064
1065   GNUNET_CRYPTO_hash (&peer_id, sizeof (peer_id), &key);
1066   entry = GNUNET_CONTAINER_multihashmap_get (cache, &key);
1067   if (NULL == entry)
1068     entry = add_entry (&key, peer_id);
1069   GNUNET_free_non_null (entry->hello);
1070   entry->hello = GNUNET_copy_message (hello);
1071 }
1072
1073 /* end of gnunet-service-testbed_hc.c */