Move Shib constants to new lib, fixed symbol conflicts.
[shibboleth/cpp-sp.git] / shib-target / shib-ini.cpp
1 /*
2  *  Copyright 2001-2005 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  * shib-ini.h -- config file handling, now XML-based
19  *
20  * $Id$
21  */
22
23 #include "internal.h"
24
25 #include <shibsp/DOMPropertySet.h>
26 #include <shibsp/SPConfig.h>
27 #include <shibsp/SPConstants.h>
28 #include <log4cpp/Category.hh>
29 #include <log4cpp/PropertyConfigurator.hh>
30 #include <algorithm>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33
34 using namespace shibsp;
35 using namespace shibtarget;
36 using namespace shibboleth;
37 using namespace saml;
38 using namespace log4cpp;
39 using namespace std;
40
41 using xmltooling::TrustEngine;
42 using opensaml::saml2md::MetadataProvider;
43
44 namespace shibtarget {
45
46     // Application configuration wrapper
47     class XMLApplication : public virtual IApplication, public DOMPropertySet, public DOMNodeFilter
48     {
49     public:
50         XMLApplication(const IConfig*, const Iterator<ICredentials*>& creds, const DOMElement* e, const XMLApplication* base=NULL);
51         ~XMLApplication() { cleanup(); }
52     
53         // PropertySet
54         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
55         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
56         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
57         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
58         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
59         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
60
61         // IApplication
62         const char* getId() const {return getString("id").second;}
63         const char* getHash() const {return m_hash.c_str();}
64         Iterator<SAMLAttributeDesignator*> getAttributeDesignators() const;
65         Iterator<IAAP*> getAAPProviders() const;
66         Iterator<IMetadata*> getMetadataProviders() const;
67         Iterator<ITrust*> getTrustProviders() const;
68         Iterator<const XMLCh*> getAudiences() const;
69         const PropertySet* getCredentialUse(const IEntityDescriptor* provider) const;
70
71         const MetadataProvider* getMetadataProvider() const;
72         const TrustEngine* getTrustEngine() const;
73         
74         const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
75         const SAMLBinding* getBinding(const XMLCh* binding) const
76             {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
77         SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
78         void validateToken(
79             SAMLAssertion* token,
80             time_t t=0,
81             const IRoleDescriptor* role=NULL,
82             const Iterator<ITrust*>& trusts=EMPTY(ITrust*)
83             ) const;
84         const IHandler* getDefaultSessionInitiator() const;
85         const IHandler* getSessionInitiatorById(const char* id) const;
86         const IHandler* getDefaultAssertionConsumerService() const;
87         const IHandler* getAssertionConsumerServiceByIndex(unsigned short index) const;
88         Iterator<const IHandler*> getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
89         const IHandler* getHandler(const char* path) const;
90         
91         // Provides filter to exclude special config elements.
92         short acceptNode(const DOMNode* node) const;
93     
94     private:
95         void cleanup();
96         const IConfig* m_ini;   // this is ok because its locking scope includes us
97         const XMLApplication* m_base;
98         string m_hash;
99         vector<SAMLAttributeDesignator*> m_designators;
100         vector<IAAP*> m_aaps;
101         vector<IMetadata*> m_metadatas;
102         vector<ITrust*> m_trusts;
103         MetadataProvider* m_metadata;
104         TrustEngine* m_trust;
105         vector<const XMLCh*> m_audiences;
106         ShibBrowserProfile* m_profile;
107         SAMLBinding* m_binding;
108         ShibHTTPHook* m_bindingHook;
109
110         // vectors manage object life for handlers and their property sets
111         vector<IHandler*> m_handlers;
112         vector<PropertySet*> m_handlerProps;
113
114         // maps location (path info) to applicable handlers
115         map<string,const IHandler*> m_handlerMap;
116
117         // maps unique indexes to consumer services
118         map<unsigned int,const IHandler*> m_acsIndexMap;
119         
120         // pointer to default consumer service
121         const IHandler* m_acsDefault;
122
123         // maps binding strings to supporting consumer service(s)
124 #ifdef HAVE_GOOD_STL
125         typedef map<xstring,vector<const IHandler*> > ACSBindingMap;
126 #else
127         typedef map<string,vector<const IHandler*> > ACSBindingMap;
128 #endif
129         ACSBindingMap m_acsBindingMap;
130
131         // maps unique ID strings to session initiators
132         map<string,const IHandler*> m_sessionInitMap;
133
134         // pointer to default session initiator
135         const IHandler* m_sessionInitDefault;
136
137         DOMPropertySet* m_credDefault;
138 #ifdef HAVE_GOOD_STL
139         map<xstring,PropertySet*> m_credMap;
140 #else
141         map<const XMLCh*,PropertySet*> m_credMap;
142 #endif
143     };
144
145     // Top-level configuration implementation
146     class XMLConfig;
147     class XMLConfigImpl : public ReloadableXMLFileImpl, public DOMPropertySet, public DOMNodeFilter
148     {
149     public:
150         XMLConfigImpl(const char* pathname, bool first, const XMLConfig* outer)
151             : ReloadableXMLFileImpl(pathname), m_outer(outer), m_requestMapper(NULL) { init(first); }
152         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer)
153             : ReloadableXMLFileImpl(e), m_outer(outer), m_requestMapper(NULL) { init(first); }
154         ~XMLConfigImpl();
155         
156         IRequestMapper* m_requestMapper;
157         map<string,IApplication*> m_appmap;
158         vector<ICredentials*> m_creds;
159         vector<IAttributeFactory*> m_attrFactories;
160         
161         // Provides filter to exclude special config elements.
162         short acceptNode(const DOMNode* node) const;
163
164     private:
165         void init(bool first);
166         const XMLConfig* m_outer;
167     };
168     
169     class XMLConfig : public IConfig, public ReloadableXMLFile
170     {
171     public:
172         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {}
173         ~XMLConfig() {
174             delete m_impl;
175             m_impl=NULL;
176             delete m_sessionCache;
177             m_sessionCache=NULL;
178             delete m_replayCache;
179             m_replayCache=NULL;
180             delete m_listener;
181             m_listener=NULL;
182         }
183
184         void init() { getImplementation(); }
185
186         // PropertySet
187         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getBool(name,ns);}
188         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getString(name,ns);}
189         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getXMLString(name,ns);}
190         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getUnsignedInt(name,ns);}
191         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getInt(name,ns);}
192         const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return static_cast<XMLConfigImpl*>(m_impl)->getPropertySet(name,ns);}
193         const DOMElement* getElement() const {return static_cast<XMLConfigImpl*>(m_impl)->getElement();}
194
195         // IConfig
196         ListenerService* getListener() const {return m_listener;}
197         ISessionCache* getSessionCache() const {return m_sessionCache;}
198         IReplayCache* getReplayCache() const {return m_replayCache;}
199         IRequestMapper* getRequestMapper() const {return static_cast<XMLConfigImpl*>(m_impl)->m_requestMapper;}
200         const IApplication* getApplication(const char* applicationId) const {
201             map<string,IApplication*>::const_iterator i=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.find(applicationId);
202             return (i!=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.end()) ? i->second : NULL;
203         }
204         Iterator<ICredentials*> getCredentialsProviders() const {return static_cast<XMLConfigImpl*>(m_impl)->m_creds;}
205
206     protected:
207         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
208         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
209
210     private:
211         friend class XMLConfigImpl;
212         mutable ListenerService* m_listener;
213         mutable ISessionCache* m_sessionCache;
214         mutable IReplayCache* m_replayCache;
215     };
216 }
217
218 IConfig* STConfig::ShibTargetConfigFactory(const DOMElement* e)
219 {
220     return new XMLConfig(e);
221 }
222
223 XMLApplication::XMLApplication(
224     const IConfig* ini,
225     const Iterator<ICredentials*>& creds,
226     const DOMElement* e,
227     const XMLApplication* base
228     ) : m_ini(ini), m_base(base), m_metadata(NULL), m_trust(NULL), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
229         m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
230 {
231 #ifdef _DEBUG
232     NDC ndc("XMLApplication");
233 #endif
234     Category& log=Category::getInstance("shibtarget.XMLApplication");
235
236     try {
237         // First load any property sets.
238         map<string,string> root_remap;
239         root_remap["shire"]="session";
240         root_remap["shireURL"]="handlerURL";
241         root_remap["shireSSL"]="handlerSSL";
242         load(e,log,this,&root_remap);
243         const PropertySet* propcheck=getPropertySet("Errors");
244         if (propcheck && !propcheck->getString("session").first)
245             throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
246         propcheck=getPropertySet("Sessions");
247         if (propcheck && !propcheck->getString("handlerURL").first)
248             throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
249
250         m_hash=getId();
251         m_hash+=getString("providerId").second;
252         m_hash=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(m_hash.c_str()));
253
254         SPConfig& conf=SPConfig::getConfig();
255         SAMLConfig& shibConf=SAMLConfig::getConfig();
256
257         // Process handlers.
258         bool hardACS=false, hardSessionInit=false;
259         DOMElement* handler=saml::XML::getFirstChildElement(propcheck->getElement());
260         while (handler) {
261             // A handler is split across a property set and the plugin itself, which is based on the Binding property.
262             // We build both objects first and then insert them into various structures for lookup.
263             IHandler* hobj=NULL;
264             DOMPropertySet* hprops=new DOMPropertySet();
265             try {
266                 hprops->load(handler,log,this); // filter irrelevant for now, no embedded elements expected
267                 const char* bindprop=hprops->getString("Binding").second;
268                 if (!bindprop)
269                     throw ConfigurationException("Handler element has no Binding attribute, skipping it...");
270                 IPlugIn* hplug=shibConf.getPlugMgr().newPlugin(bindprop,handler);
271                 hobj=dynamic_cast<IHandler*>(hplug);
272                 if (!hobj) {
273                     delete hplug;
274                     throw UnsupportedProfileException(
275                         "Plugin for binding ($1) does not implement IHandler interface.",params(1,bindprop)
276                         );
277                 }
278             }
279             catch (SAMLException& ex) {
280                 // If we get here, the handler's not built, so dispose of the property set.
281                 log.error("caught exception processing a handler element: %s",ex.what());
282                 delete hprops;
283                 hprops=NULL;
284             }
285             
286             const char* location=hprops ? hprops->getString("Location").second : NULL;
287             if (!location) {
288                 delete hprops;
289                 hprops=NULL;
290                 handler=saml::XML::getNextSiblingElement(handler);
291                 continue;
292             }
293             
294             // Save off the objects after giving the property set to the handler for its use.
295             hobj->setProperties(hprops);
296             m_handlers.push_back(hobj);
297             m_handlerProps.push_back(hprops);
298
299             // Insert into location map.
300             if (*location == '/')
301                 m_handlerMap[location]=hobj;
302             else
303                 m_handlerMap[string("/") + location]=hobj;
304
305             // If it's an ACS or SI, handle index/id mappings and defaulting.
306             if (saml::XML::isElementNamed(handler,shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
307                 // Map it.
308 #ifdef HAVE_GOOD_STL
309                 const XMLCh* binding=hprops->getXMLString("Binding").second;
310 #else
311                 const char* binding=hprops->getString("Binding").second;
312 #endif
313                 if (m_acsBindingMap.count(binding)==0)
314                     m_acsBindingMap[binding]=vector<const IHandler*>(1,hobj);
315                 else
316                     m_acsBindingMap[binding].push_back(hobj);
317                 m_acsIndexMap[hprops->getUnsignedInt("index").second]=hobj;
318                 
319                 if (!hardACS) {
320                     pair<bool,bool> defprop=hprops->getBool("isDefault");
321                     if (defprop.first) {
322                         if (defprop.second) {
323                             hardACS=true;
324                             m_acsDefault=hobj;
325                         }
326                     }
327                     else if (!m_acsDefault)
328                         m_acsDefault=hobj;
329                 }
330             }
331             else if (saml::XML::isElementNamed(handler,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
332                 pair<bool,const char*> si_id=hprops->getString("id");
333                 if (si_id.first && si_id.second)
334                     m_sessionInitMap[si_id.second]=hobj;
335                 if (!hardSessionInit) {
336                     pair<bool,bool> defprop=hprops->getBool("isDefault");
337                     if (defprop.first) {
338                         if (defprop.second) {
339                             hardSessionInit=true;
340                             m_sessionInitDefault=hobj;
341                         }
342                     }
343                     else if (!m_sessionInitDefault)
344                         m_sessionInitDefault=hobj;
345                 }
346             }
347             handler=saml::XML::getNextSiblingElement(handler);
348         }
349
350         // If no handlers defined at the root, assume a legacy configuration.
351         if (!m_base && m_handlers.empty()) {
352             // A legacy config installs a SAML POST handler at the root handler location.
353             // We use the Sessions element itself as the PropertySet.
354
355             auto_ptr_char b1(shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI);
356             IPlugIn* hplug=shibConf.getPlugMgr().newPlugin(b1.get(),propcheck->getElement());
357             IHandler* h1=dynamic_cast<IHandler*>(hplug);
358             if (!h1) {
359                 delete hplug;
360                 throw UnsupportedProfileException(
361                     "Plugin for binding ($1) does not implement IHandler interface.",params(1,b1.get())
362                     );
363             }
364             h1->setProperties(propcheck);
365             m_handlers.push_back(h1);
366             m_sessionInitDefault=h1;
367
368             auto_ptr_char b2(SAMLBrowserProfile::BROWSER_POST);
369             hplug=shibConf.getPlugMgr().newPlugin(b2.get(),propcheck->getElement());
370             IHandler* h2=dynamic_cast<IHandler*>(hplug);
371             if (!h2) {
372                 delete hplug;
373                 throw UnsupportedProfileException(
374                     "Plugin for binding ($1) does not implement IHandler interface.",params(1,b2.get())
375                     );
376             }
377             h2->setProperties(propcheck);
378             m_handlers.push_back(h2);
379             m_handlerMap[""] = h2;
380             m_acsDefault=h2;
381         }
382         
383         // Process general configuration elements.
384         unsigned int i;
385         DOMNodeList* nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(AttributeDesignator));
386         for (i=0; nlist && i<nlist->getLength(); i++)
387             if (nlist->item(i)->getParentNode()->isSameNode(e))
388                 m_designators.push_back(new SAMLAttributeDesignator(static_cast<DOMElement*>(nlist->item(i))));
389
390         nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(Audience));
391         for (i=0; nlist && i<nlist->getLength(); i++)
392             if (nlist->item(i)->getParentNode()->isSameNode(e))
393                 m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
394
395         // Always include our own providerId as an audience.
396         m_audiences.push_back(getXMLString("providerId").second);
397
398         if (conf.isEnabled(SPConfig::AAP)) {
399             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(AAPProvider));
400             for (i=0; nlist && i<nlist->getLength(); i++) {
401                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
402                     auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
403                     log.info("building AAP provider of type %s...",type.get());
404                     try {
405                         IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
406                         IAAP* aap=dynamic_cast<IAAP*>(plugin);
407                         if (aap)
408                             m_aaps.push_back(aap);
409                         else {
410                             delete plugin;
411                             log.crit("plugin was not an AAP provider");
412                         }
413                     }
414                     catch (SAMLException& ex) {
415                         log.crit("error building AAP provider: %s",ex.what());
416                     }
417                 }
418             }
419         }
420
421         if (conf.isEnabled(SPConfig::Metadata)) {
422             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MetadataProvider));
423             for (i=0; nlist && i<nlist->getLength(); i++) {
424                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
425                     auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
426                     log.info("building metadata provider of type %s...",type.get());
427                     try {
428                         IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
429                         IMetadata* md=dynamic_cast<IMetadata*>(plugin);
430                         if (md)
431                             m_metadatas.push_back(md);
432                         else {
433                             delete plugin;
434                             log.crit("plugin was not a metadata provider");
435                         }
436                     }
437                     catch (SAMLException& ex) {
438                         log.crit("error building metadata provider: %s",ex.what());
439                     }
440                 }
441             }
442             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(FederationProvider));
443             for (i=0; nlist && i<nlist->getLength(); i++) {
444                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
445                     auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
446                     log.info("building metadata provider of type %s...",type.get());
447                     try {
448                         IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
449                         IMetadata* md=dynamic_cast<IMetadata*>(plugin);
450                         if (md)
451                             m_metadatas.push_back(md);
452                         else {
453                             delete plugin;
454                             log.crit("plugin was not a metadata provider");
455                         }
456                     }
457                     catch (SAMLException& ex) {
458                         log.crit("error building metadata provider: %s",ex.what());
459                     }
460                 }
461             }
462         }
463
464         if (conf.isEnabled(SPConfig::Trust)) {
465             // First build the old plugins.
466             // TODO: remove this later
467             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TrustProvider));
468             for (i=0; nlist && i<nlist->getLength(); i++) {
469                 if (nlist->item(i)->getParentNode()->isSameNode(e)) {
470                     auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
471                     log.info("building trust provider of type %s...",type.get());
472                     try {
473                         IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
474                         ITrust* trust=dynamic_cast<ITrust*>(plugin);
475                         if (trust)
476                             m_trusts.push_back(trust);
477                         else {
478                             delete plugin;
479                             log.crit("plugin was not a trust provider");
480                         }
481                     }
482                     catch (SAMLException& ex) {
483                         log.crit("error building trust provider: %s",ex.what());
484                     }
485                 }
486             }
487         }
488         
489         // Finally, load credential mappings.
490         const DOMElement* cu=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialUse));
491         if (cu) {
492             m_credDefault=new DOMPropertySet();
493             m_credDefault->load(cu,log,this);
494             cu=saml::XML::getFirstChildElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
495             while (cu) {
496                 DOMPropertySet* rp=new DOMPropertySet();
497                 rp->load(cu,log,this);
498                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=rp;
499                 cu=saml::XML::getNextSiblingElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
500             }
501         }
502         
503         if (conf.isEnabled(SPConfig::OutOfProcess)) {
504             // Really finally, build local browser profile and binding objects.
505             m_profile=new ShibBrowserProfile(
506                 this,
507                 getMetadataProviders(),
508                 getTrustProviders()
509                 );
510             m_bindingHook=new ShibHTTPHook(
511                 getTrustProviders(),
512                 creds
513                 );
514             m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
515             SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
516             if (!bptr) {
517                 log.fatal("binding implementation was not SOAP over HTTP");
518                 throw UnsupportedExtensionException("binding implementation was not SOAP over HTTP");
519             }
520             bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
521         }
522     }
523     catch (SAMLException& e) {
524         log.errorStream() << "Error while processing applicaton element: " << e.what() << CategoryStream::ENDLINE;
525         cleanup();
526         throw;
527     }
528 #ifndef _DEBUG
529     catch (...) {
530         log.error("Unexpected error while processing application element");
531         cleanup();
532         throw;
533     }
534 #endif
535 }
536
537 void XMLApplication::cleanup()
538 {
539     delete m_bindingHook;
540     delete m_binding;
541     delete m_profile;
542     for_each(m_handlers.begin(),m_handlers.end(),xmltooling::cleanup<IHandler>());
543         
544     delete m_credDefault;
545 #ifdef HAVE_GOOD_STL
546     for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<xstring,PropertySet>());
547 #else
548     for_each(m_credMap.begin(),m_credMap.end(),xmltooling::cleanup_pair<const XMLCh*,PropertySet>());
549 #endif
550     for_each(m_designators.begin(),m_designators.end(),xmltooling::cleanup<SAMLAttributeDesignator>());
551     for_each(m_aaps.begin(),m_aaps.end(),xmltooling::cleanup<IAAP>());
552     for_each(m_metadatas.begin(),m_metadatas.end(),xmltooling::cleanup<IMetadata>());
553     for_each(m_trusts.begin(),m_trusts.end(),xmltooling::cleanup<ITrust>());
554 }
555
556 short XMLApplication::acceptNode(const DOMNode* node) const
557 {
558     if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(AttributeDesignator)))
559         return FILTER_REJECT;
560     else if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(Audience)))
561         return FILTER_REJECT;
562     const XMLCh* name=node->getLocalName();
563     if (!XMLString::compareString(name,SHIBT_L(Application)) ||
564         !XMLString::compareString(name,SHIBT_L(AssertionConsumerService)) ||
565         !XMLString::compareString(name,SHIBT_L(SingleLogoutService)) ||
566         !XMLString::compareString(name,SHIBT_L(DiagnosticService)) ||
567         !XMLString::compareString(name,SHIBT_L(SessionInitiator)) ||
568         !XMLString::compareString(name,SHIBT_L(AAPProvider)) ||
569         !XMLString::compareString(name,SHIBT_L(CredentialUse)) ||
570         !XMLString::compareString(name,SHIBT_L(RelyingParty)) ||
571         !XMLString::compareString(name,SHIBT_L(FederationProvider)) ||
572         !XMLString::compareString(name,SHIBT_L(MetadataProvider)) ||
573         !XMLString::compareString(name,SHIBT_L(TrustProvider)))
574         return FILTER_REJECT;
575
576     return FILTER_ACCEPT;
577 }
578
579 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
580 {
581     pair<bool,bool> ret=DOMPropertySet::getBool(name,ns);
582     if (ret.first)
583         return ret;
584     return m_base ? m_base->getBool(name,ns) : ret;
585 }
586
587 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
588 {
589     pair<bool,const char*> ret=DOMPropertySet::getString(name,ns);
590     if (ret.first)
591         return ret;
592     return m_base ? m_base->getString(name,ns) : ret;
593 }
594
595 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
596 {
597     pair<bool,const XMLCh*> ret=DOMPropertySet::getXMLString(name,ns);
598     if (ret.first)
599         return ret;
600     return m_base ? m_base->getXMLString(name,ns) : ret;
601 }
602
603 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
604 {
605     pair<bool,unsigned int> ret=DOMPropertySet::getUnsignedInt(name,ns);
606     if (ret.first)
607         return ret;
608     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
609 }
610
611 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
612 {
613     pair<bool,int> ret=DOMPropertySet::getInt(name,ns);
614     if (ret.first)
615         return ret;
616     return m_base ? m_base->getInt(name,ns) : ret;
617 }
618
619 const PropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
620 {
621     const PropertySet* ret=DOMPropertySet::getPropertySet(name,ns);
622     if (ret || !m_base)
623         return ret;
624     return m_base->getPropertySet(name,ns);
625 }
626
627 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
628 {
629     if (!m_designators.empty() || !m_base)
630         return m_designators;
631     return m_base->getAttributeDesignators();
632 }
633
634 Iterator<IAAP*> XMLApplication::getAAPProviders() const
635 {
636     return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
637 }
638
639 Iterator<IMetadata*> XMLApplication::getMetadataProviders() const
640 {
641     return (m_metadatas.empty() && m_base) ? m_base->getMetadataProviders() : m_metadatas;
642 }
643
644 Iterator<ITrust*> XMLApplication::getTrustProviders() const
645 {
646     return (m_trusts.empty() && m_base) ? m_base->getTrustProviders() : m_trusts;
647 }
648
649 Iterator<const XMLCh*> XMLApplication::getAudiences() const
650 {
651     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
652 }
653
654 const PropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
655 {
656     if (!m_credDefault && m_base)
657         return m_base->getCredentialUse(provider);
658         
659 #ifdef HAVE_GOOD_STL
660     map<xstring,PropertySet*>::const_iterator i=m_credMap.find(provider->getId());
661     if (i!=m_credMap.end())
662         return i->second;
663     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
664     while (group) {
665         if (group->getName()) {
666             i=m_credMap.find(group->getName());
667             if (i!=m_credMap.end())
668                 return i->second;
669         }
670         group=group->getEntitiesDescriptor();
671     }
672 #else
673     map<const XMLCh*,PropertySet*>::const_iterator i=m_credMap.begin();
674     for (; i!=m_credMap.end(); i++) {
675         if (!XMLString::compareString(i->first,provider->getId()))
676             return i->second;
677         const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
678         while (group) {
679             if (!XMLString::compareString(i->first,group->getName()))
680                 return i->second;
681             group=group->getEntitiesDescriptor();
682         }
683     }
684 #endif
685     return m_credDefault;
686 }
687
688 const MetadataProvider* XMLApplication::getMetadataProvider() const
689 {
690     return (!m_metadata && m_base) ? m_base->getMetadataProvider() : m_metadata;
691 }
692
693 const TrustEngine* XMLApplication::getTrustEngine() const
694 {
695     return (!m_trust && m_base) ? m_base->getTrustEngine() : m_trust;
696 }
697
698 void XMLApplication::validateToken(SAMLAssertion* token, time_t ts, const IRoleDescriptor* role, const Iterator<ITrust*>& trusts) const
699 {
700 #ifdef _DEBUG
701     saml::NDC ndc("validateToken");
702 #endif
703     Category& log=Category::getInstance("shibtarget.XMLApplication");
704
705     // First we verify the time conditions, using the specified timestamp, if non-zero.
706     SAMLConfig& config=SAMLConfig::getConfig();
707     if (ts>0) {
708         const SAMLDateTime* notBefore=token->getNotBefore();
709         if (notBefore && ts+config.clock_skew_secs < notBefore->getEpoch())
710             throw ExpiredAssertionException("Assertion is not yet valid.");
711         const SAMLDateTime* notOnOrAfter=token->getNotOnOrAfter();
712         if (notOnOrAfter && notOnOrAfter->getEpoch() <= ts-config.clock_skew_secs)
713             throw ExpiredAssertionException("Assertion is no longer valid.");
714     }
715
716     // Now we process conditions. Only audience restrictions at the moment.
717     Iterator<SAMLCondition*> conditions=token->getConditions();
718     while (conditions.hasNext()) {
719         SAMLCondition* cond=conditions.next();
720         const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
721         if (!ac) {
722             ostringstream os;
723             os << *cond;
724             log.error("unrecognized Condition in assertion (%s)",os.str().c_str());
725             throw UnsupportedExtensionException("Assertion contains an unrecognized condition.");
726         }
727         else if (!ac->eval(getAudiences())) {
728             ostringstream os;
729             os << *ac;
730             log.error("unacceptable AudienceRestrictionCondition in assertion (%s)",os.str().c_str());
731             throw UnsupportedProfileException("Assertion contains an unacceptable AudienceRestrictionCondition.");
732         }
733     }
734
735     if (!role) {
736         log.warn("no metadata provided, so no signature validation was performed");
737         return;
738     }
739
740     const PropertySet* credUse=getCredentialUse(role->getEntityDescriptor());
741     pair<bool,bool> signedAssertions=credUse ? credUse->getBool("signedAssertions") : make_pair(false,false);
742     Trust t(trusts);
743
744     if (token->isSigned() && !t.validate(*token,role))
745         throw TrustException("Assertion signature did not validate.");
746     else if (signedAssertions.first && signedAssertions.second)
747         throw TrustException("Assertion was unsigned, violating policy based on the issuer.");
748 }
749
750 const IHandler* XMLApplication::getDefaultSessionInitiator() const
751 {
752     if (m_sessionInitDefault) return m_sessionInitDefault;
753     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
754 }
755
756 const IHandler* XMLApplication::getSessionInitiatorById(const char* id) const
757 {
758     map<string,const IHandler*>::const_iterator i=m_sessionInitMap.find(id);
759     if (i!=m_sessionInitMap.end()) return i->second;
760     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
761 }
762
763 const IHandler* XMLApplication::getDefaultAssertionConsumerService() const
764 {
765     if (m_acsDefault) return m_acsDefault;
766     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
767 }
768
769 const IHandler* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
770 {
771     map<unsigned int,const IHandler*>::const_iterator i=m_acsIndexMap.find(index);
772     if (i!=m_acsIndexMap.end()) return i->second;
773     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
774 }
775
776 Iterator<const IHandler*> XMLApplication::getAssertionConsumerServicesByBinding(const XMLCh* binding) const
777 {
778 #ifdef HAVE_GOOD_STL
779     ACSBindingMap::const_iterator i=m_acsBindingMap.find(binding);
780 #else
781     auto_ptr_char temp(binding);
782     ACSBindingMap::const_iterator i=m_acsBindingMap.find(temp.get());
783 #endif
784     if (i!=m_acsBindingMap.end())
785         return i->second;
786     return m_base ? m_base->getAssertionConsumerServicesByBinding(binding) : EMPTY(const IHandler*);
787 }
788
789 const IHandler* XMLApplication::getHandler(const char* path) const
790 {
791     string wrap(path);
792     map<string,const IHandler*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
793     if (i!=m_handlerMap.end())
794         return i->second;
795     return m_base ? m_base->getHandler(path) : NULL;
796 }
797
798 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
799 {
800     return new XMLConfigImpl(pathname,first,this);
801 }
802
803 ReloadableXMLFileImpl* XMLConfig::newImplementation(const DOMElement* e, bool first) const
804 {
805     return new XMLConfigImpl(e,first,this);
806 }
807
808 short XMLConfigImpl::acceptNode(const DOMNode* node) const
809 {
810     if (XMLString::compareString(node->getNamespaceURI(),shibtarget::XML::SHIBTARGET_NS))
811         return FILTER_ACCEPT;
812     const XMLCh* name=node->getLocalName();
813     if (!XMLString::compareString(name,SHIBT_L(Applications)) ||
814         !XMLString::compareString(name,SHIBT_L(AttributeFactory)) ||
815         !XMLString::compareString(name,SHIBT_L(CredentialsProvider)) ||
816         !XMLString::compareString(name,SHIBT_L(Extensions)) ||
817         !XMLString::compareString(name,SHIBT_L(Implementation)) ||
818         !XMLString::compareString(name,SHIBT_L(Listener)) ||
819         !XMLString::compareString(name,SHIBT_L(MemorySessionCache)) ||
820         !XMLString::compareString(name,SHIBT_L(MySQLReplayCache)) ||
821         !XMLString::compareString(name,SHIBT_L(MySQLSessionCache)) ||
822         !XMLString::compareString(name,SHIBT_L(RequestMap)) ||
823         !XMLString::compareString(name,SHIBT_L(RequestMapProvider)) ||
824         !XMLString::compareString(name,SHIBT_L(ReplayCache)) ||
825         !XMLString::compareString(name,SHIBT_L(SessionCache)) ||
826         !XMLString::compareString(name,SHIBT_L(TCPListener)) ||
827         !XMLString::compareString(name,SHIBT_L(UnixListener)))
828         return FILTER_REJECT;
829
830     return FILTER_ACCEPT;
831 }
832
833 void XMLConfigImpl::init(bool first)
834 {
835 #ifdef _DEBUG
836     saml::NDC ndc("init");
837 #endif
838     Category& log=Category::getInstance("shibtarget.Config");
839
840     try {
841         if (!saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ShibbolethTargetConfig)) &&
842             !saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SPConfig))) {
843             log.error("Construction requires a valid configuration file: (conf:SPConfig as root element)");
844             throw ConfigurationException("Construction requires a valid configuration file: (conf:SPConfig as root element)");
845         }
846
847         SAMLConfig& shibConf=SAMLConfig::getConfig();
848         SPConfig& conf=SPConfig::getConfig();
849         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHAR));
850         if (!SHAR)
851             SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Global));
852         if (!SHAR)
853             SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(OutOfProcess));
854         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHIRE));
855         if (!SHIRE)
856             SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Local));
857         if (!SHIRE)
858             SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(InProcess));
859
860         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
861         if (conf.isEnabled(SPConfig::Logging)) {
862             const XMLCh* logger=NULL;
863             if (conf.isEnabled(SPConfig::OutOfProcess))
864                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
865             else if (conf.isEnabled(SPConfig::InProcess))
866                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
867             if (!logger || !*logger)
868                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
869             if (logger && *logger) {
870                 auto_ptr_char logpath(logger);
871                 log.debug("loading new logging configuration from (%s), check log destination for status of configuration",logpath.get());
872                 try {
873                     PropertyConfigurator::configure(logpath.get());
874                 }
875                 catch (ConfigureFailure& e) {
876                     log.error("Error reading logging configuration: %s",e.what());
877                 }
878             }
879         }
880         
881         // First load any property sets.
882         map<string,string> root_remap;
883         root_remap["SHAR"]="OutOfProcess";
884         root_remap["SHIRE"]="InProcess";
885         root_remap["Global"]="OutOfProcess";
886         root_remap["Local"]="InProcess";
887         load(ReloadableXMLFileImpl::m_root,log,this,&root_remap);
888
889         // Much of the processing can only occur on the first instantiation.
890         if (first) {
891             // Now load any extensions to insure any needed plugins are registered.
892             DOMElement* exts=
893                 saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
894             if (exts) {
895                 exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
896                 while (exts) {
897                     auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
898                     try {
899                         SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
900                         log.debug("loaded global extension library %s",path.get());
901                     }
902                     catch (SAMLException& e) {
903                         const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
904                         if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
905                             log.fatal("unable to load mandatory global extension library %s: %s", path.get(), e.what());
906                             throw;
907                         }
908                         else
909                             log.crit("unable to load optional global extension library %s: %s", path.get(), e.what());
910                     }
911                     exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
912                 }
913             }
914             
915             if (conf.isEnabled(SPConfig::OutOfProcess)) {
916                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
917                 if (exts) {
918                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
919                     while (exts) {
920                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
921                         try {
922                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
923                             log.debug("loaded Global extension library %s",path.get());
924                         }
925                         catch (SAMLException& e) {
926                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
927                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
928                                 log.fatal("unable to load mandatory Global extension library %s: %s", path.get(), e.what());
929                                 throw;
930                             }
931                             else
932                                 log.crit("unable to load optional Global extension library %s: %s", path.get(), e.what());
933                         }
934                         exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
935                     }
936                 }
937             }
938
939             if (conf.isEnabled(SPConfig::InProcess)) {
940                 exts=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
941                 if (exts) {
942                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
943                     while (exts) {
944                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
945                         try {
946                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
947                             log.debug("loaded Local extension library %s",path.get());
948                         }
949                         catch (SAMLException& e) {
950                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
951                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
952                                 log.fatal("unable to load mandatory Local extension library %s: %s", path.get(), e.what());
953                                 throw;
954                             }
955                             else
956                                 log.crit("unable to load optional Local extension library %s: %s", path.get(), e.what());
957                         }
958                         exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
959                     }
960                 }
961             }
962             
963             // Instantiate the ListenerService and SessionCache objects.
964             if (conf.isEnabled(SPConfig::Listener)) {
965                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(UnixListener));
966                 if (exts) {
967                     log.info("building Listener of type %s...",UNIX_LISTENER_SERVICE);
968                     m_outer->m_listener=conf.ListenerServiceManager.newPlugin(UNIX_LISTENER_SERVICE,exts);
969                 }
970                 else {
971                     exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TCPListener));
972                     if (exts) {
973                         log.info("building Listener of type %s...",TCP_LISTENER_SERVICE);
974                         m_outer->m_listener=conf.ListenerServiceManager.newPlugin(TCP_LISTENER_SERVICE,exts);
975                     }
976                     else {
977                         exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Listener));
978                         if (exts) {
979                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
980                             log.info("building Listener of type %s...",type.get());
981                             m_outer->m_listener=conf.ListenerServiceManager.newPlugin(type.get(),exts);
982                         }
983                         else {
984                             log.fatal("can't build Listener object, missing conf:Listener element?");
985                             throw ConfigurationException("can't build Listener object, missing conf:Listener element?");
986                         }
987                     }
988                 }
989             }
990
991             if (conf.isEnabled(SPConfig::Caching)) {
992                 IPlugIn* plugin=NULL;
993                 const DOMElement* container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
994                 exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
995                 if (exts) {
996                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
997                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
998                 }
999                 else {
1000                     exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ODBCSessionCache));
1001                     if (exts) {
1002                         log.info("building Session Cache of type %s...",shibtarget::XML::ODBCSessionCacheType);
1003                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::ODBCSessionCacheType,exts);
1004                     }
1005                     else {
1006                         exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
1007                         if (exts) {
1008                             log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
1009                             plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
1010                         }
1011                         else {
1012                             exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionCache));
1013                             if (exts) {
1014                                 auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1015                                 log.info("building Session Cache of type %s...",type.get());
1016                                 plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
1017                             }
1018                             else {
1019                                 log.info("session cache not specified, building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
1020                                 plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
1021                             }
1022                         }
1023                     }
1024                 }
1025                 if (plugin) {
1026                     ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
1027                     if (cache)
1028                         m_outer->m_sessionCache=cache;
1029                     else {
1030                         delete plugin;
1031                         log.fatal("plugin was not a Session Cache object");
1032                         throw UnsupportedExtensionException("plugin was not a Session Cache object");
1033                     }
1034                 }
1035                 
1036                 // Replay cache.
1037                 container=conf.isEnabled(SPConfig::OutOfProcess) ? SHAR : SHIRE;
1038                 exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ODBCReplayCache));
1039                 if (exts) {
1040                     log.info("building Replay Cache of type %s...",shibtarget::XML::ODBCReplayCacheType);
1041                     m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::ODBCReplayCacheType,exts);
1042                 }
1043                 else {
1044                     exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLReplayCache));
1045                     if (exts) {
1046                         log.info("building Replay Cache of type %s...",shibtarget::XML::MySQLReplayCacheType);
1047                         m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::MySQLReplayCacheType,exts);
1048                     }
1049                     else {
1050                         exts=saml::XML::getFirstChildElement(container,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ReplayCache));
1051                         if (exts) {
1052                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1053                             log.info("building Replay Cache of type %s...",type.get());
1054                             m_outer->m_replayCache=IReplayCache::getInstance(type.get(),exts);
1055                         }
1056                         else {
1057                             // OpenSAML default provider.
1058                             log.info("building default Replay Cache...");
1059                             m_outer->m_replayCache=IReplayCache::getInstance();
1060                         }
1061                     }
1062                 }
1063             }
1064         }
1065         
1066         // Back to the fully dynamic stuff...next up is the Request Mapper.
1067         if (conf.isEnabled(SPConfig::RequestMapper)) {
1068             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
1069             if (child) {
1070                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
1071                 log.info("building Request Mapper of type %s...",type.get());
1072                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1073                 if (plugin) {
1074                     IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
1075                     if (reqmap)
1076                         m_requestMapper=reqmap;
1077                     else {
1078                         delete plugin;
1079                         log.fatal("plugin was not a Request Mapper object");
1080                         throw UnsupportedExtensionException("plugin was not a Request Mapper object");
1081                     }
1082                 }
1083             }
1084             else {
1085                 log.fatal("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1086                 throw ConfigurationException("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1087             }
1088         }
1089         
1090         // Now we load any credentials providers.
1091         DOMNodeList* nlist;
1092         if (conf.isEnabled(SPConfig::Credentials)) {
1093             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialsProvider));
1094             for (unsigned int i=0; nlist && i<nlist->getLength(); i++) {
1095                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
1096                 log.info("building credentials provider of type %s...",type.get());
1097                 try {
1098                     IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
1099                     if (plugin) {
1100                         ICredentials* creds=dynamic_cast<ICredentials*>(plugin);
1101                         if (creds)
1102                             m_creds.push_back(creds);
1103                         else {
1104                             delete plugin;
1105                             log.crit("plugin was not a credentials provider");
1106                         }
1107                     }
1108                 }
1109                 catch (SAMLException& ex) {
1110                     log.crit("error building credentials provider: %s",ex.what());
1111                 }
1112             }
1113         }
1114
1115         // Now we load any attribute factories
1116         nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(AttributeFactory));
1117         for (unsigned int i=0; nlist && i<nlist->getLength(); i++) {
1118             auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
1119             log.info("building Attribute factory of type %s...",type.get());
1120             try {
1121                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
1122                 if (plugin) {
1123                     IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1124                     if (fact) {
1125                         m_attrFactories.push_back(fact);
1126                         ShibConfig::getConfig().regAttributeMapping(
1127                             static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(AttributeName)),
1128                             fact
1129                             );
1130                     }
1131                     else {
1132                         delete plugin;
1133                         log.crit("plugin was not an Attribute factory");
1134                     }
1135                 }
1136             }
1137             catch (SAMLException& ex) {
1138                 log.crit("error building Attribute factory: %s",ex.what());
1139             }
1140         }
1141
1142         // Load the default application. This actually has a fixed ID of "default". ;-)
1143         const DOMElement* app=saml::XML::getFirstChildElement(
1144             ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Applications)
1145             );
1146         if (!app) {
1147             log.fatal("can't build default Application object, missing conf:Applications element?");
1148             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1149         }
1150         XMLApplication* defapp=new XMLApplication(m_outer, m_creds, app);
1151         m_appmap[defapp->getId()]=defapp;
1152         
1153         // Load any overrides.
1154         nlist=app->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Application));
1155         for (unsigned int j=0; nlist && j<nlist->getLength(); j++) {
1156             auto_ptr<XMLApplication> iapp(new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(j)),defapp));
1157             if (m_appmap.find(iapp->getId())!=m_appmap.end())
1158                 log.crit("found conf:Application element with duplicate Id attribute, ignoring it");
1159             else
1160                 m_appmap[iapp->getId()]=iapp.release();
1161         }
1162     }
1163     catch (xmltooling::XMLToolingException& e) {
1164         log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
1165         throw ConfigurationException(e.what());
1166     }
1167     catch (SAMLException& e) {
1168         log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
1169         throw ConfigurationException(e.what());
1170     }
1171 #ifndef _DEBUG
1172     catch (...) {
1173         log.error("Unexpected error while loading SP configuration");
1174         throw;
1175     }
1176 #endif
1177 }
1178
1179 XMLConfigImpl::~XMLConfigImpl()
1180 {
1181     delete m_requestMapper;
1182     for_each(m_appmap.begin(),m_appmap.end(),xmltooling::cleanup_pair<string,IApplication>());
1183     for_each(m_creds.begin(),m_creds.end(),xmltooling::cleanup<ICredentials>());
1184     ShibConfig::getConfig().clearAttributeMappings();
1185     for_each(m_attrFactories.begin(),m_attrFactories.end(),xmltooling::cleanup<IAttributeFactory>());
1186 }