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