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