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