Trap errors when building some plugins
[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                 try {
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.crit("plugin was not an AAP provider");
490                     }
491                 }
492                 catch (SAMLException& ex) {
493                     log.crit("error building AAP provider: %s",ex.what());
494                 }
495             }
496         }
497
498         if (conf.isEnabled(ShibTargetConfig::Metadata)) {
499             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MetadataProvider));
500             for (i=0; nlist && i<nlist->getLength(); i++) {
501                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
502                 log.info("building metadata provider of type %s...",type.get());
503                 try {
504                     IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
505                     IMetadata* md=dynamic_cast<IMetadata*>(plugin);
506                     if (md)
507                         m_metadatas.push_back(md);
508                     else {
509                         delete plugin;
510                         log.crit("plugin was not a metadata provider");
511                     }
512                 }
513                 catch (SAMLException& ex) {
514                     log.crit("error building metadata provider: %s",ex.what());
515                 }
516             }
517             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(FederationProvider));
518             for (i=0; nlist && i<nlist->getLength(); i++) {
519                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
520                 log.info("building metadata provider of type %s...",type.get());
521                 try {
522                     IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
523                     IMetadata* md=dynamic_cast<IMetadata*>(plugin);
524                     if (md)
525                         m_metadatas.push_back(md);
526                     else {
527                         delete plugin;
528                         log.crit("plugin was not a metadata provider");
529                     }
530                 }
531                 catch (SAMLException& ex) {
532                     log.crit("error building metadata provider: %s",ex.what());
533                 }
534             }
535         }
536
537         if (conf.isEnabled(ShibTargetConfig::Trust)) {
538             nlist=e->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TrustProvider));
539             for (i=0; nlist && i<nlist->getLength(); i++) {
540                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
541                 log.info("building trust provider of type %s...",type.get());
542                 try {
543                     IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
544                     ITrust* trust=dynamic_cast<ITrust*>(plugin);
545                     if (trust)
546                         m_trusts.push_back(trust);
547                     else {
548                         delete plugin;
549                         log.crit("plugin was not a trust provider");
550                     }
551                 }
552                 catch (SAMLException& ex) {
553                     log.crit("error building trust provider: %s",ex.what());
554                 }
555             }
556         }
557         
558         // Finally, load credential mappings.
559         const DOMElement* cu=saml::XML::getFirstChildElement(e,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialUse));
560         if (cu) {
561             m_credDefault=new XMLPropertySet();
562             m_credDefault->load(cu,log,this);
563             cu=saml::XML::getFirstChildElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
564             while (cu) {
565                 XMLPropertySet* rp=new XMLPropertySet();
566                 rp->load(cu,log,this);
567                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=rp;
568                 cu=saml::XML::getNextSiblingElement(cu,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RelyingParty));
569             }
570         }
571         
572         if (conf.isEnabled(ShibTargetConfig::Caching)) {
573             // Really finally, build local browser profile and binding objects.
574             m_profile=new ShibBrowserProfile(
575                 getMetadataProviders(),
576                 getTrustProviders()
577                 );
578             m_bindingHook=new ShibHTTPHook(
579                 getTrustProviders(),
580                 creds
581                 );
582             m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
583             SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
584             if (!bptr) {
585                 log.fatal("binding implementation was not SOAP over HTTP");
586                 throw UnsupportedExtensionException("binding implementation was not SOAP over HTTP");
587             }
588             bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
589         }
590     }
591     catch (SAMLException& e) {
592         log.errorStream() << "Error while processing applicaton element: " << e.what() << CategoryStream::ENDLINE;
593         cleanup();
594         throw;
595     }
596 #ifndef _DEBUG
597     catch (...) {
598         log.error("Unexpected error while processing application element");
599         cleanup();
600         throw;
601     }
602 #endif
603 }
604
605 void XMLApplication::cleanup()
606 {
607     delete m_bindingHook;
608     delete m_binding;
609     delete m_profile;
610     map<string,XMLPropertySet*>::iterator h=m_handlerMap.begin();
611     while (h!=m_handlerMap.end()) {
612         delete h->second;
613         h++;
614     }
615     delete m_credDefault;
616 #ifdef HAVE_GOOD_STL
617     map<xstring,XMLPropertySet*>::iterator c=m_credMap.begin();
618 #else
619     map<const XMLCh*,XMLPropertySet*>::iterator c=m_credMap.begin();
620 #endif
621     while (c!=m_credMap.end()) {
622         delete c->second;
623         c++;
624     }
625     Iterator<SAMLAttributeDesignator*> i(m_designators);
626     while (i.hasNext())
627         delete i.next();
628     Iterator<IAAP*> j(m_aaps);
629     while (j.hasNext())
630         delete j.next();
631     Iterator<IMetadata*> k(m_metadatas);
632     while (k.hasNext())
633         delete k.next();
634     Iterator<ITrust*> l(m_trusts);
635     while (l.hasNext())
636         delete l.next();
637 }
638
639 short XMLApplication::acceptNode(const DOMNode* node) const
640 {
641     if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(AttributeDesignator)))
642         return FILTER_REJECT;
643     else if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(Audience)))
644         return FILTER_REJECT;
645     const XMLCh* name=node->getLocalName();
646     if (!XMLString::compareString(name,SHIBT_L(Application)) ||
647         !XMLString::compareString(name,SHIBT_L(AssertionConsumerService)) ||
648         !XMLString::compareString(name,SHIBT_L(SingleLogoutService)) ||
649         !XMLString::compareString(name,SHIBT_L(DiagnosticService)) ||
650         !XMLString::compareString(name,SHIBT_L(SessionInitiator)) ||
651         !XMLString::compareString(name,SHIBT_L(AAPProvider)) ||
652         !XMLString::compareString(name,SHIBT_L(CredentialUse)) ||
653         !XMLString::compareString(name,SHIBT_L(RelyingParty)) ||
654         !XMLString::compareString(name,SHIBT_L(FederationProvider)) ||
655         !XMLString::compareString(name,SHIBT_L(MetadataProvider)) ||
656         !XMLString::compareString(name,SHIBT_L(TrustProvider)))
657         return FILTER_REJECT;
658
659     return FILTER_ACCEPT;
660 }
661
662 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
663 {
664     pair<bool,bool> ret=XMLPropertySet::getBool(name,ns);
665     if (ret.first)
666         return ret;
667     return m_base ? m_base->getBool(name,ns) : ret;
668 }
669
670 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
671 {
672     pair<bool,const char*> ret=XMLPropertySet::getString(name,ns);
673     if (ret.first)
674         return ret;
675     return m_base ? m_base->getString(name,ns) : ret;
676 }
677
678 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
679 {
680     pair<bool,const XMLCh*> ret=XMLPropertySet::getXMLString(name,ns);
681     if (ret.first)
682         return ret;
683     return m_base ? m_base->getXMLString(name,ns) : ret;
684 }
685
686 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
687 {
688     pair<bool,unsigned int> ret=XMLPropertySet::getUnsignedInt(name,ns);
689     if (ret.first)
690         return ret;
691     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
692 }
693
694 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
695 {
696     pair<bool,int> ret=XMLPropertySet::getInt(name,ns);
697     if (ret.first)
698         return ret;
699     return m_base ? m_base->getInt(name,ns) : ret;
700 }
701
702 const IPropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
703 {
704     const IPropertySet* ret=XMLPropertySet::getPropertySet(name,ns);
705     if (ret || !m_base)
706         return ret;
707     return m_base->getPropertySet(name,ns);
708 }
709
710 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
711 {
712     if (!m_designators.empty() || !m_base)
713         return m_designators;
714     return m_base->getAttributeDesignators();
715 }
716
717 Iterator<IAAP*> XMLApplication::getAAPProviders() const
718 {
719     return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
720 }
721
722 Iterator<IMetadata*> XMLApplication::getMetadataProviders() const
723 {
724     return (m_metadatas.empty() && m_base) ? m_base->getMetadataProviders() : m_metadatas;
725 }
726
727 Iterator<ITrust*> XMLApplication::getTrustProviders() const
728 {
729     return (m_trusts.empty() && m_base) ? m_base->getTrustProviders() : m_trusts;
730 }
731
732 Iterator<const XMLCh*> XMLApplication::getAudiences() const
733 {
734     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
735 }
736
737 const IPropertySet* XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
738 {
739     if (!m_credDefault && m_base)
740         return m_base->getCredentialUse(provider);
741         
742 #ifdef HAVE_GOOD_STL
743     map<xstring,XMLPropertySet*>::const_iterator i=m_credMap.find(provider->getId());
744     if (i!=m_credMap.end())
745         return i->second;
746     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
747     while (group) {
748         if (group->getName()) {
749             i=m_credMap.find(group->getName());
750             if (i!=m_credMap.end())
751                 return i->second;
752         }
753         group=group->getEntitiesDescriptor();
754     }
755 #else
756     map<const XMLCh*,XMLPropertySet*>::const_iterator i=m_credMap.begin();
757     for (; i!=m_credMap.end(); i++) {
758         if (!XMLString::compareString(i->first,provider->getId()))
759             return i->second;
760         const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
761         while (group) {
762             if (!XMLString::compareString(i->first,group->getName()))
763                 return i->second;
764             group=group->getEntitiesDescriptor();
765         }
766     }
767 #endif
768     return m_credDefault;
769 }
770
771 const IPropertySet* XMLApplication::getDefaultSessionInitiator() const
772 {
773     if (m_sessionInitDefault) return m_sessionInitDefault;
774     return m_base ? m_base->getDefaultSessionInitiator() : NULL;
775 }
776
777 const IPropertySet* XMLApplication::getSessionInitiatorById(const char* id) const
778 {
779     map<string,const IPropertySet*>::const_iterator i=m_sessionInitMap.find(id);
780     if (i!=m_sessionInitMap.end()) return i->second;
781     return m_base ? m_base->getSessionInitiatorById(id) : NULL;
782 }
783
784 const IPropertySet* XMLApplication::getDefaultAssertionConsumerService() const
785 {
786     if (m_acsDefault) return m_acsDefault;
787     return m_base ? m_base->getDefaultAssertionConsumerService() : NULL;
788 }
789
790 const IPropertySet* XMLApplication::getAssertionConsumerServiceByIndex(unsigned short index) const
791 {
792     map<unsigned int,const IPropertySet*>::const_iterator i=m_acsMap.find(index);
793     if (i!=m_acsMap.end()) return i->second;
794     return m_base ? m_base->getAssertionConsumerServiceByIndex(index) : NULL;
795 }
796
797 const IPropertySet* XMLApplication::getHandler(const char* path) const
798 {
799     string wrap(path);
800     map<string,XMLPropertySet*>::const_iterator i=m_handlerMap.find(wrap.substr(0,wrap.find('?')));
801     return (i!=m_handlerMap.end()) ? i->second : NULL;
802 }
803
804 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
805 {
806     return new XMLConfigImpl(pathname,first,this);
807 }
808
809 ReloadableXMLFileImpl* XMLConfig::newImplementation(const DOMElement* e, bool first) const
810 {
811     return new XMLConfigImpl(e,first,this);
812 }
813
814 short XMLConfigImpl::acceptNode(const DOMNode* node) const
815 {
816     if (XMLString::compareString(node->getNamespaceURI(),shibtarget::XML::SHIBTARGET_NS))
817         return FILTER_ACCEPT;
818     const XMLCh* name=node->getLocalName();
819     if (!XMLString::compareString(name,SHIBT_L(Applications)) ||
820         !XMLString::compareString(name,SHIBT_L(AttributeFactory)) ||
821         !XMLString::compareString(name,SHIBT_L(CredentialsProvider)) ||
822         !XMLString::compareString(name,SHIBT_L(Extensions)) ||
823         !XMLString::compareString(name,SHIBT_L(Implementation)) ||
824         !XMLString::compareString(name,SHIBT_L(Listener)) ||
825         !XMLString::compareString(name,SHIBT_L(MemorySessionCache)) ||
826         !XMLString::compareString(name,SHIBT_L(MySQLReplayCache)) ||
827         !XMLString::compareString(name,SHIBT_L(MySQLSessionCache)) ||
828         !XMLString::compareString(name,SHIBT_L(RequestMap)) ||
829         !XMLString::compareString(name,SHIBT_L(RequestMapProvider)) ||
830         !XMLString::compareString(name,SHIBT_L(ReplayCache)) ||
831         !XMLString::compareString(name,SHIBT_L(SessionCache)) ||
832         !XMLString::compareString(name,SHIBT_L(TCPListener)) ||
833         !XMLString::compareString(name,SHIBT_L(UnixListener)))
834         return FILTER_REJECT;
835
836     return FILTER_ACCEPT;
837 }
838
839 void XMLConfigImpl::init(bool first)
840 {
841 #ifdef _DEBUG
842     saml::NDC ndc("init");
843 #endif
844     Category& log=Category::getInstance("shibtarget.Config");
845
846     try {
847         if (!saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ShibbolethTargetConfig)) &&
848             !saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SPConfig))) {
849             log.error("Construction requires a valid configuration file: (conf:SPConfig as root element)");
850             throw ConfigurationException("Construction requires a valid configuration file: (conf:SPConfig as root element)");
851         }
852
853         SAMLConfig& shibConf=SAMLConfig::getConfig();
854         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
855         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHAR));
856         if (!SHAR)
857             SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Global));
858         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SHIRE));
859         if (!SHIRE)
860             SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Local));
861
862         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
863         if (conf.isEnabled(ShibTargetConfig::Logging)) {
864             const XMLCh* logger=NULL;
865             if (conf.isEnabled(ShibTargetConfig::GlobalExtensions))
866                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
867             else if (conf.isEnabled(ShibTargetConfig::LocalExtensions))
868                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
869             if (!logger || !*logger)
870                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
871             if (logger && *logger) {
872                 auto_ptr_char logpath(logger);
873                 cerr << "loading new logging configuration from " << logpath.get() << "\n";
874                 try {
875                     PropertyConfigurator::configure(logpath.get());
876                     cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
877                 }
878                 catch (ConfigureFailure& e) {
879                     cerr << "Error reading logging configuration: " << e.what() << "\n";
880                 }
881             }
882         }
883         
884         // First load any property sets.
885         map<string,string> root_remap;
886         root_remap["SHAR"]="Global";
887         root_remap["SHIRE"]="Local";
888         load(ReloadableXMLFileImpl::m_root,log,this,&root_remap);
889
890         // Much of the processing can only occur on the first instantiation.
891         if (first) {
892             // Now load any extensions to insure any needed plugins are registered.
893             DOMElement* exts=
894                 saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
895             if (exts) {
896                 exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
897                 while (exts) {
898                     auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
899                     try {
900                         SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
901                         log.debug("loaded global extension library %s",path.get());
902                     }
903                     catch (SAMLException& e) {
904                         const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
905                         if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
906                             log.fatal("unable to load mandatory global extension library %s: %s", path.get(), e.what());
907                             throw;
908                         }
909                         else
910                             log.crit("unable to load optional global extension library %s: %s", path.get(), e.what());
911                     }
912                     exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
913                 }
914             }
915             
916             if (conf.isEnabled(ShibTargetConfig::GlobalExtensions)) {
917                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
918                 if (exts) {
919                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
920                     while (exts) {
921                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
922                         try {
923                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
924                             log.debug("loaded Global extension library %s",path.get());
925                         }
926                         catch (SAMLException& e) {
927                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
928                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
929                                 log.fatal("unable to load mandatory Global extension library %s: %s", path.get(), e.what());
930                                 throw;
931                             }
932                             else
933                                 log.crit("unable to load optional Global extension library %s: %s", path.get(), e.what());
934                         }
935                         exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
936                     }
937                 }
938             }
939
940             if (conf.isEnabled(ShibTargetConfig::LocalExtensions)) {
941                 exts=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Extensions));
942                 if (exts) {
943                     exts=saml::XML::getFirstChildElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
944                     while (exts) {
945                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
946                         try {
947                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
948                             log.debug("loaded Local extension library %s",path.get());
949                         }
950                         catch (SAMLException& e) {
951                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
952                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
953                                 log.fatal("unable to load mandatory Local extension library %s: %s", path.get(), e.what());
954                                 throw;
955                             }
956                             else
957                                 log.crit("unable to load optional Local extension library %s: %s", path.get(), e.what());
958                         }
959                         exts=saml::XML::getNextSiblingElement(exts,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Library));
960                     }
961                 }
962             }
963             
964             // Instantiate the Listener and SessionCache objects.
965             if (conf.isEnabled(ShibTargetConfig::Listener)) {
966                 IPlugIn* plugin=NULL;
967                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(UnixListener));
968                 if (exts) {
969                     log.info("building Listener of type %s...",shibtarget::XML::UnixListenerType);
970                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::UnixListenerType,exts);
971                 }
972                 else {
973                     exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(TCPListener));
974                     if (exts) {
975                         log.info("building Listener of type %s...",shibtarget::XML::TCPListenerType);
976                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::TCPListenerType,exts);
977                     }
978                     else {
979                         exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Listener));
980                         if (exts) {
981                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
982                             log.info("building Listener of type %s...",type.get());
983                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
984                         }
985                         else {
986                             log.fatal("can't build Listener object, missing conf:Listener element?");
987                             throw ConfigurationException("can't build Listener object, missing conf:Listener element?");
988                         }
989                     }
990                 }
991                 if (plugin) {
992                     IListener* listen=dynamic_cast<IListener*>(plugin);
993                     if (listen)
994                         m_outer->m_listener=listen;
995                     else {
996                         delete plugin;
997                         log.fatal("plugin was not a Listener object");
998                         throw UnsupportedExtensionException("plugin was not a Listener object");
999                     }
1000                 }
1001             }
1002
1003             if (conf.isEnabled(ShibTargetConfig::Caching)) {
1004                 IPlugIn* plugin=NULL;
1005                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
1006                 if (exts) {
1007                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
1008                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
1009                 }
1010                 else {
1011                     exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
1012                     if (exts) {
1013                         log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
1014                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
1015                     }
1016                     else {
1017                         exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionCache));
1018                         if (exts) {
1019                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1020                             log.info("building Session Cache of type %s...",type.get());
1021                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
1022                         }
1023                         else {
1024                             log.fatal("can't build Session Cache object, missing conf:SessionCache element?");
1025                             throw ConfigurationException("can't build Session Cache object, missing conf:SessionCache element?");
1026                         }
1027                     }
1028                 }
1029                 if (plugin) {
1030                     ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
1031                     if (cache)
1032                         m_outer->m_sessionCache=cache;
1033                     else {
1034                         delete plugin;
1035                         log.fatal("plugin was not a Session Cache object");
1036                         throw UnsupportedExtensionException("plugin was not a Session Cache object");
1037                     }
1038                 }
1039                 
1040                 // Replay cache.
1041                 exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(MySQLReplayCache));
1042                 if (exts) {
1043                     log.info("building Replay Cache of type %s...",shibtarget::XML::MySQLReplayCacheType);
1044                     m_outer->m_replayCache=IReplayCache::getInstance(shibtarget::XML::MySQLSessionCacheType,exts);
1045                 }
1046                 else {
1047                     exts=saml::XML::getFirstChildElement(SHAR,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(ReplayCache));
1048                     if (exts) {
1049                         auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
1050                         log.info("building Replay Cache of type %s...",type.get());
1051                         m_outer->m_replayCache=IReplayCache::getInstance(type.get(),exts);
1052                     }
1053                     else {
1054                         // OpenSAML default provider.
1055                         log.info("building default Replay Cache...");
1056                         m_outer->m_replayCache=IReplayCache::getInstance();
1057                     }
1058                 }
1059             }
1060         }
1061         
1062         // Back to the fully dynamic stuff...next up is the Request Mapper.
1063         if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
1064             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
1065             if (child) {
1066                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
1067                 log.info("building Request Mapper of type %s...",type.get());
1068                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
1069                 if (plugin) {
1070                     IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
1071                     if (reqmap)
1072                         m_requestMapper=reqmap;
1073                     else {
1074                         delete plugin;
1075                         log.fatal("plugin was not a Request Mapper object");
1076                         throw UnsupportedExtensionException("plugin was not a Request Mapper object");
1077                     }
1078                 }
1079             }
1080             else {
1081                 log.fatal("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1082                 throw ConfigurationException("can't build Request Mapper object, missing conf:RequestMapProvider element?");
1083             }
1084         }
1085         
1086         // Now we load any credentials providers.
1087         DOMNodeList* nlist;
1088         if (conf.isEnabled(ShibTargetConfig::Credentials)) {
1089             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(CredentialsProvider));
1090             for (int i=0; nlist && i<nlist->getLength(); i++) {
1091                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
1092                 log.info("building credentials provider of type %s...",type.get());
1093                 try {
1094                     IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
1095                     if (plugin) {
1096                         ICredentials* creds=dynamic_cast<ICredentials*>(plugin);
1097                         if (creds)
1098                             m_creds.push_back(creds);
1099                         else {
1100                             delete plugin;
1101                             log.crit("plugin was not a credentials provider");
1102                         }
1103                     }
1104                 }
1105                 catch (SAMLException& ex) {
1106                     log.crit("error building credentials provider: %s",ex.what());
1107                 }
1108             }
1109         }
1110
1111         // Now we load any attribute factories
1112         nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(AttributeFactory));
1113         for (int i=0; nlist && i<nlist->getLength(); i++) {
1114             auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
1115             log.info("building Attribute factory of type %s...",type.get());
1116             try {
1117                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
1118                 if (plugin) {
1119                     IAttributeFactory* fact=dynamic_cast<IAttributeFactory*>(plugin);
1120                     if (fact) {
1121                         m_attrFactories.push_back(fact);
1122                         ShibConfig::getConfig().regAttributeMapping(
1123                             static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,L(AttributeName)),
1124                             fact
1125                             );
1126                     }
1127                     else {
1128                         delete plugin;
1129                         log.crit("plugin was not an Attribute factory");
1130                     }
1131                 }
1132             }
1133             catch (SAMLException& ex) {
1134                 log.crit("error building Attribute factory: %s",ex.what());
1135             }
1136         }
1137
1138         // Load the default application. This actually has a fixed ID of "default". ;-)
1139         const DOMElement* app=saml::XML::getFirstChildElement(
1140             ReloadableXMLFileImpl::m_root,shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Applications)
1141             );
1142         if (!app) {
1143             log.fatal("can't build default Application object, missing conf:Applications element?");
1144             throw ConfigurationException("can't build default Application object, missing conf:Applications element?");
1145         }
1146         XMLApplication* defapp=new XMLApplication(m_outer, m_creds, app);
1147         m_appmap[defapp->getId()]=defapp;
1148         
1149         // Load any overrides.
1150         nlist=app->getElementsByTagNameNS(shibtarget::XML::SHIBTARGET_NS,SHIBT_L(Application));
1151         for (int j=0; nlist && j<nlist->getLength(); j++) {
1152             XMLApplication* iapp=new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(j)),defapp);
1153             if (m_appmap.find(iapp->getId())!=m_appmap.end()) {
1154                 log.fatal("found conf:Application element with duplicate Id attribute");
1155                 throw ConfigurationException("found conf:Application element with duplicate Id attribute");
1156             }
1157             m_appmap[iapp->getId()]=iapp;
1158         }
1159     }
1160     catch (SAMLException& e) {
1161         log.errorStream() << "Error while loading SP configuration: " << e.what() << CategoryStream::ENDLINE;
1162         throw;
1163     }
1164 #ifndef _DEBUG
1165     catch (...) {
1166         log.error("Unexpected error while loading SP configuration");
1167         throw;
1168     }
1169 #endif
1170 }
1171
1172 XMLConfigImpl::~XMLConfigImpl()
1173 {
1174     delete m_requestMapper;
1175     for (map<string,IApplication*>::iterator i=m_appmap.begin(); i!=m_appmap.end(); i++)
1176         delete i->second;
1177     for (vector<ICredentials*>::iterator j=m_creds.begin(); j!=m_creds.end(); j++)
1178         delete (*j);
1179     ShibConfig::getConfig().clearAttributeMappings();
1180     for (vector<IAttributeFactory*>::iterator k=m_attrFactories.begin(); k!=m_attrFactories.end(); k++)
1181         delete (*k);
1182 }