59e65da6a371ce8a82b0c4dff681ec692fd071fd
[gssweb.git] / json_gssapi / src / cache / GSSNameCache.cpp
1 /*
2  * Copyright (c) 2014 <copyright holder> <email>
3  *
4  * For license details, see the LICENSE file in the root of this project.
5  *
6  */
7 #include <stdexcept>
8 #include "GSSNameCache.h"
9 #include "util_base64.h"
10 #include "util_random.h"
11
12 #define KEYLEN 128
13
14 GSSNameCache* GSSNameCache::_instance = 0;
15
16 GSSNameCache::GSSNameCache()
17 {
18
19 }
20
21 GSSNameCache::GSSNameCache ( const GSSNameCache& other )
22 {
23   names = other.names;
24 }
25
26 GSSNameCache::~GSSNameCache()
27 {
28
29 }
30
31 GSSNameCache& GSSNameCache::operator= ( const GSSNameCache& other )
32 {
33   names = other.names;
34   
35   return *this;
36 }
37
38
39 std::string GSSNameCache::store ( GSSName& data, std::string inKey )
40 {
41   /* Variables      */
42   std::string key;
43   
44   /* Error checking */
45   /* Setup          */
46   /* Main           */
47   // Generate a key
48   if ( inKey.length() > 0 )
49   {
50     key = inKey;
51   }
52   else if ( !generateKey(key) )
53   {
54     // Key generation failed.  Eeek!
55     throw std::runtime_error("Could not generate random data for an ID");
56   }
57   
58   // Store the key/value pair in the map
59   // Store the key in the context for convenience
60 //   std::cout << "\n==> In GSSNameCache::store, about to store data in the names hash.\n";
61   names[key] = &data;
62   
63   /* Cleanup        */
64   /* Return         */
65   // Return the key for future reference
66   return(key);
67 }
68
69 /*************************************
70  * Generate random bytes, and base64 *
71  * encode them to be JSONable keys   *
72  *************************************/
73 bool GSSNameCache::generateKey(std::string &key)
74 {
75   /* Variables      */
76   unsigned char theKey[KEYLEN];
77   
78   /* Setup          */
79   /* Main           */
80   // Generate random byte string
81   if (!randGenPseudoRandom(theKey, KEYLEN))
82     return(false);
83
84   // Encode the binary string
85   base64EncodeStr(theKey, KEYLEN, key);
86   /* Cleanup        */
87   /* Return         */
88   return(true);
89 }
90
91 GSSName& GSSNameCache::retrieve ( std::string key )
92 {
93   /* Variables      */
94   //GSSName data;
95   
96   /* Error checking */
97   /* Setup          */
98   /* Main           */
99   // Maybe do something about data entries that are expired?
100   
101   /* Cleanup        */
102   /* Return         */
103   return *(names[key]);
104 }
105
106 GSSNameCache* GSSNameCache::instance()
107 {
108     if (_instance == 0)
109       _instance = new GSSNameCache;
110     
111     return _instance;
112 }
113
114
115
116   /* Variables      */
117   /* Error checking */
118   /* Setup          */
119   /* Main           */
120   /* Cleanup        */
121   /* Return         */