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