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