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