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