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