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