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