Fixed application node filter.
[shibboleth/sp.git] / shib-target / shib-ini.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /*
51  * shib-ini.h -- config file handling, now XML-based
52  *
53  * $Id$
54  */
55
56 #include "internal.h"
57
58 #include <shib/shib-threads.h>
59 #include <log4cpp/Category.hh>
60 #include <log4cpp/PropertyConfigurator.hh>
61
62 #include <sys/types.h>
63 #include <sys/stat.h>
64
65 using namespace std;
66 using namespace saml;
67 using namespace shibboleth;
68 using namespace shibtarget;
69 using namespace log4cpp;
70
71 namespace shibtarget {
72
73     // Application configuration wrapper
74     class XMLApplication : public virtual IApplication, public XMLPropertySet, public DOMNodeFilter
75     {
76     public:
77         XMLApplication(const IConfig*, const Iterator<ICredentials*>& creds, const DOMElement* e, const XMLApplication* base=NULL);
78         ~XMLApplication() { cleanup(); }
79     
80         // IPropertySet
81         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
82         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
83         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
84         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
85         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
86         const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
87
88         // IApplication
89         const char* getId() const {return getString("id").second;}
90         const char* getHash() const {return m_hash.c_str();}
91         Iterator<SAMLAttributeDesignator*> getAttributeDesignators() const;
92         Iterator<IAAP*> getAAPProviders() const;
93         Iterator<IMetadata*> getMetadataProviders() const;
94         Iterator<ITrust*> getTrustProviders() const;
95         Iterator<IRevocation*> getRevocationProviders() const;
96         Iterator<const XMLCh*> getAudiences() const;
97         const IPropertySet* getCredentialUse(const IEntityDescriptor* provider) const;
98         const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
99         const SAMLBinding* getBinding(const XMLCh* binding) const
100             {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
101         SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const {return new STArtifactMapper(this);}
102         const IPropertySet* getDefaultSessionInitiator() const;
103         const IPropertySet* getSessionInitiatorById(const char* id) const;
104         const IPropertySet* getDefaultAssertionConsumerService() const;
105         const IPropertySet* getAssertionConsumerServiceByIndex(unsigned short index) const;
106         const IPropertySet* getHandler(const char* path) const;
107         
108         // Provides filter to exclude special config elements.
109         short acceptNode(const DOMNode* node) const;
110     
111     private:
112         void cleanup();
113         const IConfig* m_ini;   // this is ok because its locking scope includes us
114         const XMLApplication* m_base;
115         string m_hash;
116         vector<SAMLAttributeDesignator*> m_designators;
117         vector<IAAP*> m_aaps;
118         vector<IMetadata*> m_metadatas;
119         vector<ITrust*> m_trusts;
120         vector<IRevocation*> m_revocations;
121         vector<const XMLCh*> m_audiences;
122         ShibBrowserProfile* m_profile;
123         SAMLBinding* m_binding;
124         ShibHTTPHook* m_bindingHook;
125         map<string,XMLPropertySet*> m_handlerMap;
126         map<unsigned int,const IPropertySet*> m_acsMap;
127         const IPropertySet* m_acsDefault;
128         map<string,const IPropertySet*> m_sessionInitMap;
129         const IPropertySet* m_sessionInitDefault;
130         XMLPropertySet* m_credDefault;
131 #ifdef HAVE_GOOD_STL
132         map<xstring,XMLPropertySet*> m_credMap;
133 #else
134         map<const XMLCh*,XMLPropertySet*> m_credMap;
135 #endif
136     };
137
138     // Top-level configuration implementation
139     class XMLConfig;
140     class XMLConfigImpl : public ReloadableXMLFileImpl, public XMLPropertySet, public DOMNodeFilter
141     {
142     public:
143         XMLConfigImpl(const char* pathname, bool first, const XMLConfig* outer)
144             : ReloadableXMLFileImpl(pathname), m_outer(outer), m_requestMapper(NULL) { init(first); }
145         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer)
146             : ReloadableXMLFileImpl(e), m_outer(outer), m_requestMapper(NULL) { init(first); }
147         ~XMLConfigImpl();
148         
149         IRequestMapper* m_requestMapper;
150         map<string,IApplication*> m_appmap;
151         vector<ICredentials*> m_creds;
152         
153         // Provides filter to exclude special config elements.
154         short acceptNode(const DOMNode* node) const;
155
156     private:
157         void init(bool first);
158         const XMLConfig* m_outer;
159     };
160     
161     class XMLConfig : public IConfig, public ReloadableXMLFile
162     {
163     public:
164         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {}
165         ~XMLConfig() {delete m_listener; delete m_sessionCache; delete m_replayCache;}
166
167         // IPropertySet
168         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getBool(name,ns);}
169         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getString(name,ns);}
170         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getXMLString(name,ns);}
171         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getUnsignedInt(name,ns);}
172         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getInt(name,ns);}
173         const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const {return static_cast<XMLConfigImpl*>(m_impl)->getPropertySet(name,ns);}
174         const DOMElement* getElement() const {return static_cast<XMLConfigImpl*>(m_impl)->getElement();}
175
176         // IConfig
177         const IListener* getListener() const {return m_listener;}
178         ISessionCache* getSessionCache() const {return m_sessionCache;}
179         IReplayCache* getReplayCache() const {return m_replayCache;}
180         IRequestMapper* getRequestMapper() const {return static_cast<XMLConfigImpl*>(m_impl)->m_requestMapper;}
181         const IApplication* getApplication(const char* applicationId) const {
182             map<string,IApplication*>::const_iterator i=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.find(applicationId);
183             return (i!=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.end()) ? i->second : NULL;
184         }
185         Iterator<ICredentials*> getCredentialsProviders() const {return static_cast<XMLConfigImpl*>(m_impl)->m_creds;}
186
187     protected:
188         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
189         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
190
191     private:
192         friend class XMLConfigImpl;
193         mutable IListener* m_listener;
194         mutable ISessionCache* m_sessionCache;
195         mutable IReplayCache* m_replayCache;
196     };
197 }
198
199 IConfig* STConfig::ShibTargetConfigFactory(const DOMElement* e)
200 {
201     auto_ptr<XMLConfig> ret(new XMLConfig(e));
202     ret->getImplementation();
203     return ret.release();
204 }
205
206 XMLPropertySet::~XMLPropertySet()
207 {
208     for (map<string,pair<char*,const XMLCh*> >::iterator i=m_map.begin(); i!=m_map.end(); i++)
209         XMLString::release(&(i->second.first));
210     for (map<string,IPropertySet*>::iterator j=m_nested.begin(); j!=m_nested.end(); j++)
211         delete j->second;
212 }
213
214 void XMLPropertySet::load(
215     const DOMElement* e,
216     Category& log,
217     DOMNodeFilter* filter,
218     const std::map<std::string,std::string>* remapper
219     )
220 {
221 #ifdef _DEBUG
222     saml::NDC ndc("load");
223 #endif
224     m_root=e;
225
226     // Process each attribute as a property.
227     DOMNamedNodeMap* attrs=m_root->getAttributes();
228     for (XMLSize_t i=0; i<attrs->getLength(); i++) {
229         DOMNode* a=attrs->item(i);
230         if (!XMLString::compareString(a->getNamespaceURI(),saml::XML::XMLNS_NS))
231             continue;
232         char* val=XMLString::transcode(a->getNodeValue());
233         if (val && *val) {
234             auto_ptr_char ns(a->getNamespaceURI());
235             auto_ptr_char name(a->getLocalName());
236             const char* realname=name.get();
237             if (remapper) {
238                 map<string,string>::const_iterator remap=remapper->find(realname);
239                 if (remap!=remapper->end()) {
240                     log.debug("remapping property (%s) to (%s)",realname,remap->second.c_str());
241                     realname=remap->second.c_str();
242                 }
243             }
244             if (ns.get()) {
245                 m_map[string("{") + ns.get() + '}' + realname]=pair<char*,const XMLCh*>(val,a->getNodeValue());
246                 log.debug("added property {%s}%s (%s)",ns.get(),realname,val);
247             }
248             else {
249                 m_map[realname]=pair<char*,const XMLCh*>(val,a->getNodeValue());
250                 log.debug("added property %s (%s)",realname,val);
251             }
252         }
253     }
254     
255     // Process non-excluded elements as nested sets.
256     DOMTreeWalker* walker=
257         static_cast<DOMDocumentTraversal*>(
258             m_root->getOwnerDocument())->createTreeWalker(const_cast<DOMElement*>(m_root),DOMNodeFilter::SHOW_ELEMENT,filter,false
259             );
260     e=static_cast<DOMElement*>(walker->firstChild());
261     while (e) {
262         auto_ptr_char ns(e->getNamespaceURI());
263         auto_ptr_char name(e->getLocalName());
264         const char* realname=name.get();
265         if (remapper) {
266             map<string,string>::const_iterator remap=remapper->find(realname);
267             if (remap!=remapper->end()) {
268                 log.debug("remapping property set (%s) to (%s)",realname,remap->second.c_str());
269                 realname=remap->second.c_str();
270             }
271         }
272         string key;
273         if (ns.get())
274             key=string("{") + ns.get() + '}' + realname;
275         else
276             key=realname;
277         if (m_nested.find(key)!=m_nested.end())
278             log.warn("load() skipping duplicate property set: %s",key.c_str());
279         else {
280             XMLPropertySet* set=new XMLPropertySet();
281             set->load(e,log,filter,remapper);
282             m_nested[key]=set;
283             log.debug("added nested property set: %s",key.c_str());
284         }
285         e=static_cast<DOMElement*>(walker->nextSibling());
286     }
287     walker->release();
288 }
289
290 pair<bool,bool> XMLPropertySet::getBool(const char* name, const char* ns) const
291 {
292     pair<bool,bool> ret=pair<bool,bool>(false,false);
293     map<string,pair<char*,const XMLCh*> >::const_iterator i;
294
295     if (ns)
296         i=m_map.find(string("{") + ns + '}' + name);
297     else
298         i=m_map.find(name);
299
300     if (i!=m_map.end()) {
301         ret.first=true;
302         ret.second=(!strcmp(i->second.first,"true") || !strcmp(i->second.first,"1"));
303     }
304     return ret;
305 }
306
307 pair<bool,const char*> XMLPropertySet::getString(const char* name, const char* ns) const
308 {
309     pair<bool,const char*> ret=pair<bool,const char*>(false,NULL);
310     map<string,pair<char*,const XMLCh*> >::const_iterator i;
311
312     if (ns)
313         i=m_map.find(string("{") + ns + '}' + name);
314     else
315         i=m_map.find(name);
316
317     if (i!=m_map.end()) {
318         ret.first=true;
319         ret.second=i->second.first;
320     }
321     return ret;
322 }
323
324 pair<bool,const XMLCh*> XMLPropertySet::getXMLString(const char* name, const char* ns) const
325 {
326     pair<bool,const XMLCh*> ret=pair<bool,const XMLCh*>(false,NULL);
327     map<string,pair<char*,const XMLCh*> >::const_iterator i;
328
329     if (ns)
330         i=m_map.find(string("{") + ns + '}' + name);
331     else
332         i=m_map.find(name);
333
334     if (i!=m_map.end()) {
335         ret.first=true;
336         ret.second=i->second.second;
337     }
338     return ret;
339 }
340
341 pair<bool,unsigned int> XMLPropertySet::getUnsignedInt(const char* name, const char* ns) const
342 {
343     pair<bool,unsigned int> ret=pair<bool,unsigned int>(false,0);
344     map<string,pair<char*,const XMLCh*> >::const_iterator i;
345
346     if (ns)
347         i=m_map.find(string("{") + ns + '}' + name);
348     else
349         i=m_map.find(name);
350
351     if (i!=m_map.end()) {
352         ret.first=true;
353         ret.second=strtol(i->second.first,NULL,10);
354     }
355     return ret;
356 }
357
358 pair<bool,int> XMLPropertySet::getInt(const char* name, const char* ns) const
359 {
360     pair<bool,int> ret=pair<bool,int>(false,0);
361     map<string,pair<char*,const XMLCh*> >::const_iterator i;
362
363     if (ns)
364         i=m_map.find(string("{") + ns + '}' + name);
365     else
366         i=m_map.find(name);
367
368     if (i!=m_map.end()) {
369         ret.first=true;
370         ret.second=atoi(i->second.first);
371     }
372     return ret;
373 }
374
375 const IPropertySet* XMLPropertySet::getPropertySet(const char* name, const char* ns) const
376 {
377     map<string,IPropertySet*>::const_iterator i;
378
379     if (ns)
380         i=m_nested.find(string("{") + ns + '}' + name);
381     else
382         i=m_nested.find(name);
383
384     return (i!=m_nested.end()) ? i->second : NULL;
385 }
386
387 XMLApplication::XMLApplication(
388     const IConfig* ini,
389     const Iterator<ICredentials*>& creds,
390     const DOMElement* e,
391     const XMLApplication* base
392     ) : m_ini(ini), m_base(base), m_profile(NULL), m_binding(NULL), m_bindingHook(NULL),
393         m_credDefault(NULL), m_sessionInitDefault(NULL), m_acsDefault(NULL)
394 {
395 #ifdef _DEBUG
396     saml::NDC ndc("XMLApplication");
397 #endif
398     Category& log=Category::getInstance("shibtarget.XMLApplication");
399
400     try {
401         // First load any property sets.
402         map<string,string> root_remap;
403         root_remap["shire"]="session";
404         root_remap["shireURL"]="handlerURL";
405         root_remap["shireSSL"]="handlerSSL";
406         load(e,log,this,&root_remap);
407         const IPropertySet* propcheck=getPropertySet("Errors");
408         if (propcheck && !propcheck->getString("session").first)
409             throw ConfigurationException("<Errors> element requires 'session' (or deprecated 'shire') attribute");
410         propcheck=getPropertySet("Sessions");
411         if (propcheck && !propcheck->getString("handlerURL").first)
412             throw ConfigurationException("<Sessions> element requires 'handlerURL' (or deprecated 'shireURL') attribute");
413
414         m_hash=getId();
415         m_hash+=getString("providerId").second;
416         m_hash=SAMLArtifact::toHex(SAMLArtifactType0001::generateSourceId(m_hash.c_str()));
417
418         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
419         SAMLConfig& shibConf=SAMLConfig::getConfig();
420
421         if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
422             // Process handlers.
423             bool hardACS=false, hardSessionInit=false;
424             DOMElement* handler=saml::XML::getFirstChildElement(propcheck->getElement());
425             while (handler) {
426                 XMLPropertySet* hprops=new XMLPropertySet();
427                 hprops->load(handler,log,this); // filter irrelevant for now, no embedded elements expected
428                 m_handlerMap[hprops->getString("Location").second]=hprops;
429                 
430                 // If it's an ACS or SI, handle lookup mappings and defaulting.
431                 if (saml::XML::isElementNamed(handler,shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
432                     m_acsMap[hprops->getUnsignedInt("index").second]=hprops;
433                     if (!hardACS) {
434                         pair<bool,bool> defprop=hprops->getBool("isDefault");
435                         if (defprop.first) {
436                             if (defprop.second) {
437                                 hardACS=true;
438                                 m_acsDefault=hprops;
439                             }
440                         }
441                         else if (!m_acsDefault)
442                             m_acsDefault=hprops;
443                     }
444                 }
445                 else if (saml::XML::isElementNamed(handler,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
446                     pair<bool,const char*> si_id=hprops->getString("id");
447                     if (si_id.first && si_id.second)
448                         m_sessionInitMap[si_id.second]=hprops;
449                     if (!hardSessionInit) {
450                         pair<bool,bool> defprop=hprops->getBool("isDefault");
451                         if (defprop.first) {
452                             if (defprop.second) {
453                                 hardSessionInit=true;
454                                 m_sessionInitDefault=hprops;
455                             }
456                         }
457                         else if (!m_sessionInitDefault)
458                             m_sessionInitDefault=hprops;
459                     }
460                 }
461                 handler=saml::XML::getNextSiblingElement(handler);
462             }
463         }
464         
465         // Process general configuration elements.
466         int i;
467         DOMNodeList* nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(AttributeDesignator));
468         for (i=0; nlist && i<nlist->getLength(); i++)
469             m_designators.push_back(new SAMLAttributeDesignator(static_cast<DOMElement*>(nlist->item(i))));
470
471         nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(Audience));
472         for (i=0; nlist && i<nlist->getLength(); i++)
473             m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
474
475         // Always include our own providerId as an audience.
476         m_audiences.push_back(getXMLString("providerId").second);
477
478         if (conf.isEnabled(ShibTargetConfig::AAP)) {
479             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(AAPProvider));
480             for (i=0; nlist && i<nlist->getLength(); i++) {
481                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
482                 log.info("building AAP provider of type %s...",type.get());
483                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
484                 IAAP* aap=dynamic_cast<IAAP*>(plugin);
485                 if (aap)
486                     m_aaps.push_back(aap);
487                 else {
488                     delete plugin;
489                     log.fatal("plugin was not an AAP provider");
490                     throw UnsupportedExtensionException("plugin was not an AAP provider");
491                 }
492             }
493         }
494
495         if (conf.isEnabled(ShibTargetConfig::Metadata)) {
496             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(FederationProvider));
497             for (i=0; nlist && i<nlist->getLength(); i++) {
498                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
499                 log.info("building federation/metadata provider of type %s...",type.get());
500                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
501                 IMetadata* md=dynamic_cast<IMetadata*>(plugin);
502                 if (md)
503                     m_metadatas.push_back(md);
504                 else {
505                     delete plugin;
506                     log.fatal("plugin was not a federation/metadata provider");
507                     throw UnsupportedExtensionException("plugin was not a federation/metadata provider");
508                 }
509             }
510         }
511
512         if (conf.isEnabled(ShibTargetConfig::Trust)) {
513             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TrustProvider));
514             for (i=0; nlist && i<nlist->getLength(); i++) {
515                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
516                 log.info("building trust provider of type %s...",type.get());
517                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
518                 ITrust* trust=dynamic_cast<ITrust*>(plugin);
519                 if (trust)
520                     m_trusts.push_back(trust);
521                 else {
522                     delete plugin;
523                     log.fatal("plugin was not a trust provider");
524                     throw UnsupportedExtensionException("plugin was not a trust provider");
525                 }
526             }
527             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RevocationProvider));
528             for (i=0; nlist && i<nlist->getLength(); i++) {
529                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
530                 log.info("building revocation provider of type %s...",type.get());
531                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
532                 IRevocation* rev=dynamic_cast<IRevocation*>(plugin);
533                 if (rev)
534                     m_revocations.push_back(rev);
535                 else {
536                     delete plugin;
537                     log.fatal("plugin was not a revocation provider");
538                     throw UnsupportedExtensionException("plugin was not a revocation provider");
539                 }
540             }
541         }
542         
543         // Finally, load credential mappings.
544         const DOMElement* cu=saml::XML::getFirstChildElement(e,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialUse));
545         if (cu) {
546             m_credDefault=new XMLPropertySet();
547             m_credDefault->load(cu,log,this);
548             cu=saml::XML::getFirstChildElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
549             while (cu) {
550                 XMLPropertySet* rp=new XMLPropertySet();
551                 rp->load(cu,log,this);
552                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=rp;
553                 cu=saml::XML::getNextSiblingElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
554             }
555         }
556         
557         if (conf.isEnabled(ShibTargetConfig::Caching)) {
558             // Really finally, build local browser profile and binding objects.
559             m_profile=new ShibBrowserProfile(
560                 getMetadataProviders(),
561                 getRevocationProviders(),
562                 getTrustProviders()
563                 );
564             m_bindingHook=new ShibHTTPHook(
565                 getRevocationProviders(),
566                 getTrustProviders(),
567                 creds
568                 );
569             m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
570             SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
571             if (!bptr) {
572                 log.fatal("binding implementation was not SOAP over HTTP");
573                 throw UnsupportedExtensionException("binding implementation was not SOAP over HTTP");
574             }
575             bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
576         }
577     }
578     catch (SAMLException& e) {
579         log.errorStream() << "Error while processing applicaton element: " << e.what() << CategoryStream::ENDLINE;
580         cleanup();
581         throw;
582     }
583 #ifndef _DEBUG
584     catch (...) {
585         log.error("Unexpected error while processing application element");
586         cleanup();
587         throw;
588     }
589 #endif
590 }
591
592 void XMLApplication::cleanup()
593 {
594     delete m_bindingHook;
595     delete m_binding;
596     delete m_profile;
597     map<string,XMLPropertySet*>::iterator h=m_handlerMap.begin();
598     while (h!=m_handlerMap.end()) {
599         delete h->second;
600         h++;
601     }
602     delete m_credDefault;
603 #ifdef HAVE_GOOD_STL
604     map<xstring,XMLPropertySet*>::iterator c=m_credMap.begin();
605 #else
606     map<const XMLCh*,XMLPropertySet*>::iterator c=m_credMap.begin();
607 #endif
608     while (c!=m_credMap.end()) {
609         delete c->second;
610         c++;
611     }
612     Iterator<SAMLAttributeDesignator*> i(m_designators);
613     while (i.hasNext())
614         delete i.next();
615     Iterator<IAAP*> j(m_aaps);
616     while (j.hasNext())
617         delete j.next();
618     Iterator<IMetadata*> k(m_metadatas);
619     while (k.hasNext())
620         delete k.next();
621     Iterator<ITrust*> l(m_trusts);
622     while (l.hasNext())
623         delete l.next();
624     Iterator<IRevocation*> m(m_revocations);
625     while (m.hasNext())
626         delete m.next();
627 }
628
629 short XMLApplication::acceptNode(const DOMNode* node) const
630 {
631     if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(AttributeDesignator)))
632         return FILTER_REJECT;
633     else if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(Audience)))
634         return FILTER_REJECT;
635     const XMLCh* name=node->getLocalName();
636     if (!XMLString::compareString(name,SHIBT_L(Application)) ||
637         !XMLString::compareString(name,SHIBT_L(AssertionConsumerService)) ||
638         !XMLString::compareString(name,SHIBT_L(SingleLogoutService)) ||
639         !XMLString::compareString(name,SHIBT_L(SessionInitiator)) ||
640         !XMLString::compareString(name,SHIBT_L(AAPProvider)) ||
641         !XMLString::compareString(name,SHIBT_L(CredentialUse)) ||
642         !XMLString::compareString(name,SHIBT_L(RelyingParty)) ||
643         !XMLString::compareString(name,SHIBT_L(FederationProvider)) ||
644         !XMLString::compareString(name,SHIBT_L(RevocationProvider)) ||
645         !XMLString::compareString(name,SHIBT_L(TrustProvider)))
646         return FILTER_REJECT;
647
648     return FILTER_ACCEPT;
649 }
650
651 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
652 {
653     pair<bool,bool> ret=XMLPropertySet::getBool(name,ns);
654     if (ret.first)
655         return ret;
656     return m_base ? m_base->getBool(name,ns) : ret;
657 }
658
659 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
660 {
661     pair<bool,const char*> ret=XMLPropertySet::getString(name,ns);
662     if (ret.first)
663         return ret;
664     return m_base ? m_base->getString(name,ns) : ret;
665 }
666
667 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
668 {
669     pair<bool,const XMLCh*> ret=XMLPropertySet::getXMLString(name,ns);
670     if (ret.first)
671         return ret;
672     return m_base ? m_base->getXMLString(name,ns) : ret;
673 }
674
675 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
676 {
677     pair<bool,unsigned int> ret=XMLPropertySet::getUnsignedInt(name,ns);
678     if (ret.first)
679         return ret;
680     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
681 }
682
683 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
684 {
685     pair<bool,int> ret=XMLPropertySet::getInt(name,ns);
686     if (ret.first)
687         return ret;
688     return m_base ? m_base->getInt(name,ns) : ret;
689 }
690
691 const IPropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
692 {
693     const IPropertySet* ret=XMLPropertySet::getPropertySet(name,ns);
694     if (ret || !m_base)
695         return ret;
696     return m_base->getPropertySet(name,ns);
697 }
698
699 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
700 {
701     if (!m_designators.empty() || !m_base)
702         return m_designators;
703     return m_base->getAttributeDesignators();
704 }
705
706 Iterator<IAAP*> XMLApplication::getAAPProviders() const
707 {
708     return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
709 }
710
711 Iterator<IMetadata*> XMLApplication::getMetadataProviders() const
712 {
713     return (m_metadatas.empty() && m_base) ? m_base->getMetadataProviders() : m_metadatas;
714 }
715
716 Iterator<ITrust*> XMLApplication::getTrustProviders() const
717 {
718     return (m_trusts.empty() && m_base) ? m_base->getTrustProviders() : m_trusts;
719 }
720
721 Iterator<IRevocation*> XMLApplication::getRevocationProviders() const
722 {
723     return (m_revocations.empty() && m_base) ? m_base->getRevocationProviders() : m_revocations;
724 }
725
726 Iterator<const XMLCh*> XMLApplication::getAudiences() const
727 {
728     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
729 }
730
731 const IPropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
732 {
733     if (!m_credDefault && m_base)
734         return m_base->getCredentialUse(provider);
735         
736 #ifdef HAVE_GOOD_STL
737     map<xstring,XMLPropertySet*>::const_iterator i=m_credMap.find(provider->getId());
738     if (i!=m_credMap.end())
739         return i->second;
740     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
741     while (group) {
742         i=m_credMap.find(group->getName());
743         if (i!=m_credMap.end())
744             return i->second;
745         group=group->getEntitiesDescriptor();
746     }
747 #else
748     map<const XMLCh*,XMLPropertySet*>::const_iterator i=m_credMap.begin();
749     for (; i!=m_credMap.end(); i++) {
750         if (!XMLString::compareString(i->first,provider->getId()))
751             return i->second;
752         const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
753         while (group) {
754             if (!XMLString::compareString(i->first,group->getName()))
755                 return i->second;
756             group=group->getEntitiesDescriptor();
757         }
758     }
759 #endif
760     return m_credDefault;
761 }
762
763 const IPropertySet* XMLApplication::getDefaultSessionInitiator() const
764 {
765     if (m_sessionInitDefault) return m_sessionInitDefault;
766     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
767 }
768
769 const IPropertySet* XMLApplication::getSessionInitiatorById(const char* id) const
770 {
771     map<string,const IPropertySet*>::const_iterator i=m_sessionInitMap.find(id);
772     if (i!=m_sessionInitMap.end()) return i->second;
773     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
774 }
775
776 const IPropertySet* XMLApplication::getDefaultAssertionConsumerService() const
777 {
778     if (m_acsDefault) return m_acsDefault;
779     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
780 }
781
782 const IPropertySet* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
783 {
784     map<unsigned int,const IPropertySet*>::const_iterator i=m_acsMap.find(index);
785     if (i!=m_acsMap.end()) return i->second;
786     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
787 }
788
789 const IPropertySet* XMLApplication::getHandler(const char* path) const
790 {
791     string wrap(path);
792     map<string,XMLPropertySet*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
793     return (i!=m_handlerMap.end()) ? i->second : NULL;
794 }
795
796 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
797 {
798     return new XMLConfigImpl(pathname,first,this);
799 }
800
801 ReloadableXMLFileImpl* XMLConfig::newImplementation(const DOMElement* e, bool first) const
802 {
803     return new XMLConfigImpl(e,first,this);
804 }
805
806 short XMLConfigImpl::acceptNode(const DOMNode* node) const
807 {
808     if (XMLString::compareString(node->getNamespaceURI(),ShibTargetConfig::SHIBTARGET_NS))
809         return FILTER_ACCEPT;
810     const XMLCh* name=node->getLocalName();
811     if (!XMLString::compareString(name,SHIBT_L(Applications)) ||
812         !XMLString::compareString(name,SHIBT_L(CredentialsProvider)) ||
813         !XMLString::compareString(name,SHIBT_L(Extensions)) ||
814         !XMLString::compareString(name,SHIBT_L(Implementation)) ||
815         !XMLString::compareString(name,SHIBT_L(Listener)) ||
816         !XMLString::compareString(name,SHIBT_L(MemorySessionCache)) ||
817         !XMLString::compareString(name,SHIBT_L(MySQLReplayCache)) ||
818         !XMLString::compareString(name,SHIBT_L(MySQLSessionCache)) ||
819         !XMLString::compareString(name,SHIBT_L(RequestMap)) ||
820         !XMLString::compareString(name,SHIBT_L(RequestMapProvider)) ||
821         !XMLString::compareString(name,SHIBT_L(ReplayCache)) ||
822         !XMLString::compareString(name,SHIBT_L(SessionCache)) ||
823         !XMLString::compareString(name,SHIBT_L(TCPListener)) ||
824         !XMLString::compareString(name,SHIBT_L(UnixListener)))
825         return FILTER_REJECT;
826
827     return FILTER_ACCEPT;
828 }
829
830 void XMLConfigImpl::init(bool first)
831 {
832 #ifdef _DEBUG
833     saml::NDC ndc("init");
834 #endif
835     Category& log=Category::getInstance("shibtarget.XMLConfig");
836
837     try {
838         if (!saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(ShibbolethTargetConfig)) &&
839             !saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SPConfig))) {
840             log.error("Construction requires a valid configuration file: (conf:SPConfig as root element)");
841             throw ConfigurationException("Construction requires a valid configuration file: (conf:SPConfig as root element)");
842         }
843
844         SAMLConfig& shibConf=SAMLConfig::getConfig();
845         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
846         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHAR));
847         if (!SHAR)
848             SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Global));
849         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHIRE));
850         if (!SHIRE)
851             SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Local));
852
853         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
854         if (conf.isEnabled(ShibTargetConfig::Logging)) {
855             const XMLCh* logger=NULL;
856             if (conf.isEnabled(ShibTargetConfig::GlobalExtensions))
857                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
858             else if (conf.isEnabled(ShibTargetConfig::LocalExtensions))
859                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
860             if (!logger || !*logger)
861                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
862             if (logger && *logger) {
863                 auto_ptr_char logpath(logger);
864                 cerr << "loading new logging configuration from " << logpath.get() << "\n";
865                 try {
866                     PropertyConfigurator::configure(logpath.get());
867                     cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
868                 }
869                 catch (ConfigureFailure& e) {
870                     cerr << "Error reading logging configuration: " << e.what() << "\n";
871                 }
872             }
873         }
874         
875         // First load any property sets.
876         map<string,string> root_remap;
877         root_remap["SHAR"]="Global";
878         root_remap["SHIRE"]="Local";
879         load(ReloadableXMLFileImpl::m_root,log,this,&root_remap);
880
881         // Much of the processing can only occur on the first instantiation.
882         if (first) {
883             // Now load any extensions to insure any needed plugins are registered.
884             DOMElement* exts=
885                 saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
886             if (exts) {
887                 exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
888                 while (exts) {
889                     auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
890                     try {
891                         SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
892                         log.debug("loaded global extension library %s",path.get());
893                     }
894                     catch (SAMLException& e) {
895                         const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
896                         if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
897                             log.fatal("unable to load mandatory global extension library %s: %s", path.get(), e.what());
898                             throw;
899                         }
900                         else
901                             log.crit("unable to load optional global extension library %s: %s", path.get(), e.what());
902                     }
903                     exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
904                 }
905             }
906             
907             if (conf.isEnabled(ShibTargetConfig::GlobalExtensions)) {
908                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
909                 if (exts) {
910                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
911                     while (exts) {
912                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
913                         try {
914                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
915                             log.debug("loaded Global extension library %s",path.get());
916                         }
917                         catch (SAMLException& e) {
918                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
919                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
920                                 log.fatal("unable to load mandatory Global extension library %s: %s", path.get(), e.what());
921                                 throw;
922                             }
923                             else
924                                 log.crit("unable to load optional Global extension library %s: %s", path.get(), e.what());
925                         }
926                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
927                     }
928                 }
929             }
930
931             if (conf.isEnabled(ShibTargetConfig::LocalExtensions)) {
932                 exts=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
933                 if (exts) {
934                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
935                     while (exts) {
936                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
937                         try {
938                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
939                             log.debug("loaded Local extension library %s",path.get());
940                         }
941                         catch (SAMLException& e) {
942                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
943                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
944                                 log.fatal("unable to load mandatory Local extension library %s: %s", path.get(), e.what());
945                                 throw;
946                             }
947                             else
948                                 log.crit("unable to load optional Local extension library %s: %s", path.get(), e.what());
949                         }
950                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
951                     }
952                 }
953             }
954             
955             // Instantiate the Listener and SessionCache objects.
956             if (conf.isEnabled(ShibTargetConfig::Listener)) {
957                 IPlugIn* plugin=NULL;
958                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(UnixListener));
959                 if (exts) {
960                     log.info("building Listener of type %s...",shibtarget::XML::UnixListenerType);
961                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::UnixListenerType,exts);
962                 }
963                 else {
964                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TCPListener));
965                     if (exts) {
966                         log.info("building Listener of type %s...",shibtarget::XML::TCPListenerType);
967                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::TCPListenerType,exts);
968                     }
969                     else {
970                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Listener));
971                         if (exts) {
972                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
973                             log.info("building Listener of type %s...",type.get());
974                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
975                         }
976                         else {
977                             log.fatal("can't build Listener object, missing conf:Listener element?");
978                             throw ConfigurationException("can't build Listener object, missing conf:Listener element?");
979                         }
980                     }
981                 }
982                 if (plugin) {
983                     IListener* listen=dynamic_cast<IListener*>(plugin);
984                     if (listen)
985                         m_outer->m_listener=listen;
986                     else {
987                         delete plugin;
988                         log.fatal("plugin was not a Listener object");
989                         throw UnsupportedExtensionException("plugin was not a Listener object");
990                     }
991                 }
992             }
993
994             if (conf.isEnabled(ShibTargetConfig::Caching)) {
995                 IPlugIn* plugin=NULL;
996                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
997                 if (exts) {
998                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
999                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
1000                 }
1001                 else {
1002                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
1003                     if (exts) {
1004                         log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
1005                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
1006                     }
1007                     else {
1008                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionCache));
1009                         if (exts) {
1010                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1011                             log.info("building Session Cache of type %s...",type.get());
1012                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
1013                         }
1014                         else {
1015                             log.fatal("can't build Session Cache object, missing conf:SessionCache element?");
1016                             throw ConfigurationException("can't build Session Cache object, missing conf:SessionCache element?");
1017                         }
1018                     }
1019                 }
1020                 if (plugin) {
1021                     ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
1022                     if (cache)
1023                         m_outer->m_sessionCache=cache;
1024                     else {
1025                         delete plugin;
1026                         log.fatal("plugin was not a Session Cache object");
1027                         throw UnsupportedExtensionException("plugin was not a Session Cache object");
1028                     }
1029                 }
1030                 
1031                 // Replay cache.
1032                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MySQLReplayCache));
1033                 if (exts) {
1034                     log.info("building Replay Cache of type %s...",shibtarget::XML::MySQLReplayCacheType);
1035                     m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::MySQLSessionCacheType,exts);
1036                 }
1037                 else {
1038                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(ReplayCache));
1039                     if (exts) {
1040                         auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1041                         log.info("building Replay Cache of type %s...",type.get());
1042                         m_outer->m_replayCache=IReplayCache::getInstance(type.get(),exts);
1043                     }
1044                     else {
1045                         // OpenSAML default provider.
1046                         log.info("building default Replay Cache...");
1047                         m_outer->m_replayCache=IReplayCache::getInstance();
1048                     }
1049                 }
1050             }
1051         }
1052         
1053         // Back to the fully dynamic stuff...next up is the Request Mapper.
1054         if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
1055             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
1056             if (child) {
1057                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
1058                 log.info("building Request Mapper of type %s...",type.get());
1059                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1060                 if (plugin) {
1061                     IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
1062                     if (reqmap)
1063                         m_requestMapper=reqmap;
1064                     else {
1065                         delete plugin;
1066                         log.fatal("plugin was not a Request Mapper object");
1067                         throw UnsupportedExtensionException("plugin was not a Request Mapper object");
1068                     }
1069                 }
1070             }
1071             else {
1072                 log.fatal("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1073                 throw ConfigurationException("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1074             }
1075         }
1076         
1077         // Now we load any credentials providers.
1078         DOMNodeList* nlist;
1079         if (conf.isEnabled(ShibTargetConfig::Credentials)) {
1080             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(
1081                 ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialsProvider)
1082                 );
1083             for (int i=0; nlist && i<nlist->getLength(); i++) {
1084                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
1085                 log.info("building Credentials provider of type %s...",type.get());
1086                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
1087                 if (plugin) {
1088                     ICredentials* creds=dynamic_cast<ICredentials*>(plugin);
1089                     if (creds)
1090                         m_creds.push_back(creds);
1091                     else {
1092                         delete plugin;
1093                         log.fatal("plugin was not a Credentials provider");
1094                         throw UnsupportedExtensionException("plugin was not a Credentials provider");
1095                     }
1096                 }
1097             }
1098         }
1099
1100         // Load the default application. This actually has a fixed ID of "default". ;-)
1101         const DOMElement* app=saml::XML::getFirstChildElement(
1102             ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Applications)
1103             );
1104         if (!app) {
1105             log.fatal("can't build default Application object, missing conf:Applications element?");
1106             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1107         }
1108         XMLApplication* defapp=new XMLApplication(m_outer, m_creds, app);
1109         m_appmap[defapp->getId()]=defapp;
1110         
1111         // Load any overrides.
1112         nlist=app->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Application));
1113         for (int i=0; nlist && i<nlist->getLength(); i++) {
1114             XMLApplication* iapp=new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(i)),defapp);
1115             if (m_appmap.find(iapp->getId())!=m_appmap.end()) {
1116                 log.fatal("found conf:Application element with duplicate Id attribute");
1117                 throw ConfigurationException("found conf:Application element with duplicate Id attribute");
1118             }
1119             m_appmap[iapp->getId()]=iapp;
1120         }
1121     }
1122     catch (SAMLException& e) {
1123         log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
1124         throw;
1125     }
1126 #ifndef _DEBUG
1127     catch (...) {
1128         log.error("Unexpected error while loading SP configuration");
1129         throw;
1130     }
1131 #endif
1132 }
1133
1134 XMLConfigImpl::~XMLConfigImpl()
1135 {
1136     delete m_requestMapper;
1137     for (map<string,IApplication*>::iterator i=m_appmap.begin(); i!=m_appmap.end(); i++)
1138         delete i->second;
1139     for (vector<ICredentials*>::iterator j=m_creds.begin(); j!=m_creds.end(); j++)
1140         delete (*j);
1141 }