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