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