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