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