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