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