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