Allow DOM-based construction.
[shibboleth/cpp-opensaml.git] / saml / binding / impl / ArtifactMap.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * ArtifactMap.cpp
19  * 
20  * Helper class for SAMLArtifact mapping and retrieval. 
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/ArtifactMap.h"
26 #include "binding/SAMLArtifact.h"
27
28 #include <log4cpp/Category.hh>
29 #include <xercesc/util/XMLUniDefs.hpp>
30 #include <xmltooling/XMLObjectBuilder.h>
31 #include <xmltooling/util/NDC.h>
32 #include <xmltooling/util/XMLHelper.h>
33
34 using namespace opensaml;
35 using namespace xmltooling;
36 using namespace log4cpp;
37 using namespace std;
38
39 namespace opensaml {
40     // In-memory storage of mappings instead of using storage API.
41     class SAML_DLLLOCAL ArtifactMappings
42     {
43     public:
44         ArtifactMappings() : m_lock(Mutex::create()) {}
45         ~ArtifactMappings() {
46             delete m_lock;
47             for (map<string,Mapping>::iterator i=m_artMap.begin(); i!=m_artMap.end(); ++i)
48                 delete i->second.m_xml;
49         }
50         void storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty, int TTL);
51         XMLObject* retrieveContent(const SAMLArtifact* artifact, const char* relyingParty);
52     
53     private:
54         struct SAML_DLLLOCAL Mapping {
55             Mapping() : m_xml(NULL), m_expires(0) {}
56             XMLObject* m_xml;
57             string m_relying;
58             time_t m_expires;
59         };
60
61         void removeMapping(const map<string,Mapping>::iterator& i);
62         
63         Mutex* m_lock;
64         map<string,Mapping> m_artMap;
65         multimap<time_t,string> m_expMap;
66     };
67
68     static const XMLCh artifactTTL[] =  UNICODE_LITERAL_11(a,r,t,i,f,a,c,t,T,T,L);
69     static const XMLCh context[] =      UNICODE_LITERAL_7(c,o,n,t,e,x,t);
70     static const XMLCh Mapping[] =      UNICODE_LITERAL_7(M,a,p,p,i,n,g);
71     static const XMLCh _relyingParty[] = UNICODE_LITERAL_12(r,e,l,y,i,n,g,P,a,r,t,y);
72 };
73
74 void ArtifactMappings::removeMapping(const map<string,Mapping>::iterator& i)
75 {
76     // Update secondary map.
77     pair<multimap<time_t,string>::iterator,multimap<time_t,string>::iterator> range =
78         m_expMap.equal_range(i->second.m_expires);
79     for (; range.first != range.second; ++range.first) {
80         if (range.first->second == i->first) {
81             m_expMap.erase(range.first);
82             break;
83         }
84     }
85     delete i->second.m_xml;
86     m_artMap.erase(i);
87 }
88
89 void ArtifactMappings::storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty, int TTL)
90 {
91     Lock wrapper(m_lock);
92
93     // Garbage collect any expired artifacts.
94     time_t now=time(NULL);
95     multimap<time_t,string>::iterator stop=m_expMap.upper_bound(now);
96     for (multimap<time_t,string>::iterator i=m_expMap.begin(); i!=stop; m_expMap.erase(i++)) {
97         delete m_artMap[i->second].m_xml;
98         m_artMap.erase(i->second);
99     }
100     
101     // Key is the hexed handle.
102     string hexed = SAMLArtifact::toHex(artifact->getMessageHandle());
103     Mapping& m = m_artMap[hexed];
104     m.m_xml = content;
105     if (relyingParty)
106         m.m_relying = relyingParty;
107     m.m_expires = now + TTL;
108     m_expMap.insert(make_pair(m.m_expires,hexed));
109 }
110
111 XMLObject* ArtifactMappings::retrieveContent(const SAMLArtifact* artifact, const char* relyingParty)
112 {
113     Category& log=Category::getInstance(SAML_LOGCAT".ArtifactMap");
114     Lock wrapper(m_lock);
115
116     map<string,Mapping>::iterator i=m_artMap.find(SAMLArtifact::toHex(artifact->getMessageHandle()));
117     if (i==m_artMap.end())
118         throw BindingException("Requested artifact not in map or may have expired.");
119     
120     if (!(i->second.m_relying.empty())) {
121         if (!relyingParty || i->second.m_relying != relyingParty) {
122             log.warn(
123                 "request from (%s) for artifact issued to (%s)",
124                 relyingParty ? relyingParty : "unknown", i->second.m_relying.c_str()
125                 );
126             removeMapping(i);
127             throw BindingException("Unauthorized artifact mapping request.");
128         }
129     }
130     
131     if (time(NULL) >= i->second.m_expires) {
132         removeMapping(i);
133         throw BindingException("Requested artifact has expired.");
134     }
135     
136     log.debug("resolved artifact for (%s)", relyingParty ? relyingParty : "unknown");
137     XMLObject* ret = i->second.m_xml;
138     i->second.m_xml = NULL; // clear member so it doesn't get deleted
139     removeMapping(i);
140     return ret;
141 }
142
143 ArtifactMap::ArtifactMap(xmltooling::StorageService* storage, const char* context, unsigned int artifactTTL)
144     : m_storage(storage), m_context(context ? context : "opensaml::ArtifactMap"), m_mappings(NULL), m_artifactTTL(artifactTTL)
145 {
146     if (!m_storage)
147         m_mappings = new ArtifactMappings();
148 }
149
150 ArtifactMap::ArtifactMap(const DOMElement* e, xmltooling::StorageService* storage)
151     : m_storage(storage), m_mappings(NULL), m_artifactTTL(180)
152 {
153     if (e) {
154         auto_ptr_char c(e->getAttributeNS(NULL, context));
155         if (c.get() && *c.get())
156             m_context = c.get();
157         
158         const XMLCh* TTL = e->getAttributeNS(NULL, artifactTTL);
159         if (TTL) {
160             m_artifactTTL = XMLString::parseInt(TTL);
161             if (!m_artifactTTL)
162                 m_artifactTTL = 180;
163         }
164     }
165     
166     if (!m_storage)
167         m_mappings = new ArtifactMappings();
168 }
169
170 ArtifactMap::~ArtifactMap()
171 {
172     delete m_mappings;
173 }
174
175 void ArtifactMap::storeContent(XMLObject* content, const SAMLArtifact* artifact, const char* relyingParty)
176 {
177     if (content->getParent())
178         throw BindingException("Cannot store artifact mapping for XML content with parent.");
179     else if (!m_storage)
180         return m_mappings->storeContent(content, artifact, relyingParty, m_artifactTTL);
181     
182     // Marshall with defaulted document, to reuse existing DOM and/or create a bound Document.
183     DOMElement* root = content->marshall();
184     
185     // Build a DOM with the same document to store the relyingParty mapping.
186     if (relyingParty) {
187         auto_ptr_XMLCh temp(relyingParty);
188         root = root->getOwnerDocument()->createElementNS(NULL,Mapping);
189         root->setAttributeNS(NULL,_relyingParty,temp.get());
190         root->appendChild(content->getDOM());
191     }
192     
193     // Serialize the root element, whatever it is, for storage.
194     string xmlbuf;
195     XMLHelper::serialize(root, xmlbuf);
196     m_storage->createText(
197         m_context.c_str(), SAMLArtifact::toHex(artifact->getMessageHandle()).c_str(), xmlbuf.c_str(), time(NULL) + m_artifactTTL
198         );
199         
200     // Cleanup by destroying XML.
201     delete content;
202 }
203
204 XMLObject* ArtifactMap::retrieveContent(const SAMLArtifact* artifact, const char* relyingParty)
205 {
206 #ifdef _DEBUG
207     xmltooling::NDC ndc("retrieveContent");
208 #endif
209
210     if (!m_storage)
211         return m_mappings->retrieveContent(artifact, relyingParty);
212     
213     string xmlbuf;
214     string key = SAMLArtifact::toHex(artifact->getMessageHandle());
215     if (!m_storage->readText(m_context.c_str(), key.c_str(), &xmlbuf))
216         throw BindingException("Artifact not found in mapping database.");
217     
218     istringstream is(xmlbuf);
219     DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(is);
220     XercesJanitor<DOMDocument> janitor(doc);
221
222     Category& log=Category::getInstance(SAML_LOGCAT".ArtifactMap");
223     m_storage->deleteText(m_context.c_str(), key.c_str());
224     
225     // Check the root element.
226     DOMElement* messageRoot = doc->getDocumentElement();
227     if (XMLHelper::isNodeNamed(messageRoot, NULL, Mapping)) {
228         auto_ptr_char temp(messageRoot->getAttributeNS(NULL,_relyingParty));
229         if (!relyingParty || strcmp(temp.get(),relyingParty)) {
230             log.warn("request from (%s) for artifact issued to (%s)", relyingParty ? relyingParty : "unknown", temp.get());
231             throw BindingException("Unauthorized artifact mapping request.");
232         }
233         messageRoot = XMLHelper::getFirstChildElement(messageRoot);
234     }
235     
236     // Unmarshall...
237     XMLObject* xmlObject = XMLObjectBuilder::buildOneFromElement(messageRoot, true);    // bind document
238     janitor.release();
239     
240     log.debug("resolved artifact for (%s)", relyingParty ? relyingParty : "unknown");
241     return xmlObject;
242 }