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