Added const to binding/profile methods
[shibboleth/sp.git] / shib-target / shib-ini.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /*
51  * shib-ini.h -- config file handling, now XML-based
52  *
53  * $Id$
54  */
55
56 #include "internal.h"
57
58 #include <shib/shib-threads.h>
59 #include <log4cpp/Category.hh>
60 #include <log4cpp/PropertyConfigurator.hh>
61
62 #include <sys/types.h>
63 #include <sys/stat.h>
64
65 using namespace std;
66 using namespace saml;
67 using namespace shibboleth;
68 using namespace shibtarget;
69 using namespace log4cpp;
70
71 namespace shibtarget {
72
73     // Application configuration wrapper
74     class XMLApplication : public virtual IApplication, public XMLPropertySet, public DOMNodeFilter
75     {
76     public:
77         XMLApplication(const IConfig*, const Iterator<ICredentials*>& creds, const DOMElement* e, const XMLApplication* base=NULL);
78         ~XMLApplication();
79     
80         // IPropertySet
81         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
82         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
83         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
84         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
85         pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
86         const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
87
88         // IApplication
89         const char* getId() const {return getString("id").second;}
90         Iterator<SAMLAttributeDesignator*> getAttributeDesignators() const;
91         Iterator<IAAP*> getAAPProviders() const;
92         Iterator<IMetadata*> getMetadataProviders() const;
93         Iterator<ITrust*> getTrustProviders() const;
94         Iterator<IRevocation*> getRevocationProviders() const;
95         Iterator<const XMLCh*> getAudiences() const;
96         const char* getTLSCred(const IEntityDescriptor* provider) const {return getCredentialUse(provider).first.c_str();}
97         const char* getSigningCred(const IEntityDescriptor* provider) const {return getCredentialUse(provider).second.c_str();}
98         const SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
99         const SAMLBinding* getBinding(const XMLCh* binding) const
100             {return XMLString::compareString(SAMLBinding::SOAP,binding) ? NULL : m_binding;}
101         
102         // Provides filter to exclude special config elements.
103         short acceptNode(const DOMNode* node) const;
104     
105     private:
106         const IConfig* m_ini;   // this is ok because its locking scope includes us
107         const XMLApplication* m_base;
108         vector<SAMLAttributeDesignator*> m_designators;
109         vector<IAAP*> m_aaps;
110         vector<IMetadata*> m_metadatas;
111         vector<ITrust*> m_trusts;
112         vector<IRevocation*> m_revocations;
113         vector<const XMLCh*> m_audiences;
114         pair<string,string> m_credDefault;
115         ShibBrowserProfile* m_profile;
116         SAMLBinding* m_binding;
117         ShibHTTPHook* m_bindingHook;
118 #ifdef HAVE_GOOD_STL
119         map<xstring,pair<string,string> > m_credMap;
120 #else
121         map<const XMLCh*,pair<string,string> > m_credMap;
122 #endif
123         const pair<string,string>& getCredentialUse(const IEntityDescriptor* provider) const;
124     };
125
126     // Top-level configuration implementation
127     class XMLConfig;
128     class XMLConfigImpl : public ReloadableXMLFileImpl, public XMLPropertySet, public DOMNodeFilter
129     {
130     public:
131         XMLConfigImpl(const char* pathname, bool first, const XMLConfig* outer)
132             : ReloadableXMLFileImpl(pathname), m_outer(outer), m_requestMapper(NULL) { init(first); }
133         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer)
134             : ReloadableXMLFileImpl(e), m_outer(outer), m_requestMapper(NULL) { init(first); }
135         ~XMLConfigImpl();
136         
137         IRequestMapper* m_requestMapper;
138         map<string,IApplication*> m_appmap;
139         vector<ICredentials*> m_creds;
140         
141         // Provides filter to exclude special config elements.
142         short acceptNode(const DOMNode* node) const;
143
144     private:
145         void init(bool first);
146         const XMLConfig* m_outer;
147     };
148     
149     class XMLConfig : public IConfig, public ReloadableXMLFile
150     {
151     public:
152         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {}
153         ~XMLConfig() {delete m_listener; delete m_sessionCache; delete m_replayCache;}
154
155         // IPropertySet
156         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getBool(name,ns);}
157         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getString(name,ns);}
158         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getXMLString(name,ns);}
159         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getUnsignedInt(name,ns);}
160         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getInt(name,ns);}
161         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);}
162         const DOMElement* getElement() const {return static_cast<XMLConfigImpl*>(m_impl)->getElement();}
163
164         // IConfig
165         const IListener* getListener() const {return m_listener;}
166         ISessionCache* getSessionCache() const {return m_sessionCache;}
167         IReplayCache* getReplayCache() const {return m_replayCache;}
168         IRequestMapper* getRequestMapper() const {return static_cast<XMLConfigImpl*>(m_impl)->m_requestMapper;}
169         const IApplication* getApplication(const char* applicationId) const
170         {
171             map<string,IApplication*>::const_iterator i=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.find(applicationId);
172             return (i!=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.end()) ? i->second : NULL;
173         }
174         Iterator<ICredentials*> getCredentialsProviders() const {return static_cast<XMLConfigImpl*>(m_impl)->m_creds;}
175
176     protected:
177         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
178         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
179
180     private:
181         friend class XMLConfigImpl;
182         mutable IListener* m_listener;
183         mutable ISessionCache* m_sessionCache;
184         mutable IReplayCache* m_replayCache;
185     };
186 }
187
188 IConfig* STConfig::ShibTargetConfigFactory(const DOMElement* e)
189 {
190     XMLConfig* ret=new XMLConfig(e);
191     try {
192         ret->getImplementation();
193     }
194     catch (...) {
195         delete ret;
196         throw;
197     }
198     return ret;
199 }
200
201 XMLPropertySet::~XMLPropertySet()
202 {
203     for (map<string,pair<char*,const XMLCh*> >::iterator i=m_map.begin(); i!=m_map.end(); i++)
204         XMLString::release(&(i->second.first));
205     for (map<string,IPropertySet*>::iterator j=m_nested.begin(); j!=m_nested.end(); j++)
206         delete j->second;
207 }
208
209 void XMLPropertySet::load(const DOMElement* e, Category& log, DOMNodeFilter* filter)
210 {
211     NDC ndc("load");
212     m_root=e;
213
214     // Process each attribute as a property.
215     DOMNamedNodeMap* attrs=m_root->getAttributes();
216     for (XMLSize_t i=0; i<attrs->getLength(); i++) {
217         DOMNode* a=attrs->item(i);
218         if (!XMLString::compareString(a->getNamespaceURI(),saml::XML::XMLNS_NS))
219             continue;
220         char* val=XMLString::transcode(a->getNodeValue());
221         if (val && *val) {
222             auto_ptr_char ns(a->getNamespaceURI());
223             auto_ptr_char name(a->getLocalName());
224             if (ns.get()) {
225                 m_map[string("{") + ns.get() + '}' + name.get()]=pair<char*,const XMLCh*>(val,a->getNodeValue());
226                 log.debug("added property {%s}%s (%s)",ns.get(),name.get(),val);
227             }
228             else {
229                 m_map[name.get()]=pair<char*,const XMLCh*>(val,a->getNodeValue());
230                 log.debug("added property %s (%s)",name.get(),val);
231             }
232         }
233     }
234     
235     // Process non-excluded elements as nested sets.
236     DOMTreeWalker* walker=
237         static_cast<DOMDocumentTraversal*>(
238             m_root->getOwnerDocument())->createTreeWalker(const_cast<DOMElement*>(m_root),DOMNodeFilter::SHOW_ELEMENT,filter,false
239             );
240     e=static_cast<DOMElement*>(walker->firstChild());
241     while (e) {
242         auto_ptr_char ns(e->getNamespaceURI());
243         auto_ptr_char name(e->getLocalName());
244         string key;
245         if (ns.get())
246             key=string("{") + ns.get() + '}' + name.get();
247         else
248             key=name.get();
249         if (m_nested.find(key)!=m_nested.end())
250             log.warn("load() skipping duplicate property set: %s",key.c_str());
251         else {
252             XMLPropertySet* set=new XMLPropertySet();
253             set->load(e,log,filter);
254             m_nested[key]=set;
255             log.debug("added nested property set: %s",key.c_str());
256         }
257         e=static_cast<DOMElement*>(walker->nextSibling());
258     }
259     walker->release();
260 }
261
262 pair<bool,bool> XMLPropertySet::getBool(const char* name, const char* ns) const
263 {
264     pair<bool,bool> ret=pair<bool,bool>(false,false);
265     map<string,pair<char*,const XMLCh*> >::const_iterator i;
266
267     if (ns)
268         i=m_map.find(string("{") + ns + '}' + name);
269     else
270         i=m_map.find(name);
271
272     if (i!=m_map.end()) {
273         ret.first=true;
274         ret.second=(!strcmp(i->second.first,"true") || !strcmp(i->second.first,"1"));
275     }
276     return ret;
277 }
278
279 pair<bool,const char*> XMLPropertySet::getString(const char* name, const char* ns) const
280 {
281     pair<bool,const char*> ret=pair<bool,const char*>(false,NULL);
282     map<string,pair<char*,const XMLCh*> >::const_iterator i;
283
284     if (ns)
285         i=m_map.find(string("{") + ns + '}' + name);
286     else
287         i=m_map.find(name);
288
289     if (i!=m_map.end()) {
290         ret.first=true;
291         ret.second=i->second.first;
292     }
293     return ret;
294 }
295
296 pair<bool,const XMLCh*> XMLPropertySet::getXMLString(const char* name, const char* ns) const
297 {
298     pair<bool,const XMLCh*> ret=pair<bool,const XMLCh*>(false,NULL);
299     map<string,pair<char*,const XMLCh*> >::const_iterator i;
300
301     if (ns)
302         i=m_map.find(string("{") + ns + '}' + name);
303     else
304         i=m_map.find(name);
305
306     if (i!=m_map.end()) {
307         ret.first=true;
308         ret.second=i->second.second;
309     }
310     return ret;
311 }
312
313 pair<bool,unsigned int> XMLPropertySet::getUnsignedInt(const char* name, const char* ns) const
314 {
315     pair<bool,unsigned int> ret=pair<bool,unsigned int>(false,0);
316     map<string,pair<char*,const XMLCh*> >::const_iterator i;
317
318     if (ns)
319         i=m_map.find(string("{") + ns + '}' + name);
320     else
321         i=m_map.find(name);
322
323     if (i!=m_map.end()) {
324         ret.first=true;
325         ret.second=strtol(i->second.first,NULL,10);
326     }
327     return ret;
328 }
329
330 pair<bool,int> XMLPropertySet::getInt(const char* name, const char* ns) const
331 {
332     pair<bool,int> ret=pair<bool,int>(false,0);
333     map<string,pair<char*,const XMLCh*> >::const_iterator i;
334
335     if (ns)
336         i=m_map.find(string("{") + ns + '}' + name);
337     else
338         i=m_map.find(name);
339
340     if (i!=m_map.end()) {
341         ret.first=true;
342         ret.second=atoi(i->second.first);
343     }
344     return ret;
345 }
346
347 const IPropertySet* XMLPropertySet::getPropertySet(const char* name, const char* ns) const
348 {
349     map<string,IPropertySet*>::const_iterator i;
350
351     if (ns)
352         i=m_nested.find(string("{") + ns + '}' + name);
353     else
354         i=m_nested.find(name);
355
356     return (i!=m_nested.end()) ? i->second : NULL;
357 }
358
359 XMLApplication::XMLApplication(const IConfig* ini, const Iterator<ICredentials*>& creds, const DOMElement* e, const XMLApplication* base)
360     : m_ini(ini), m_base(base), m_profile(NULL)
361 {
362     NDC ndc("XMLApplication");
363     Category& log=Category::getInstance("shibtarget.XMLApplication");
364
365     try {
366         // First load any property sets.
367         load(e,log,this);
368
369         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
370         SAMLConfig& shibConf=SAMLConfig::getConfig();
371         int i;
372         DOMNodeList* nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(AttributeDesignator));
373         for (i=0; nlist && i<nlist->getLength(); i++) {
374             m_designators.push_back(new SAMLAttributeDesignator(static_cast<DOMElement*>(nlist->item(i))));
375         }
376
377         nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(Audience));
378         for (i=0; nlist && i<nlist->getLength(); i++) {
379             m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
380         }
381         // Always include our own providerId as an audience.
382         m_audiences.push_back(getXMLString("providerId").second);
383
384         if (conf.isEnabled(ShibTargetConfig::AAP)) {
385             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(AAPProvider));
386             for (i=0; nlist && i<nlist->getLength(); i++) {
387                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
388                 log.info("building AAP provider of type %s...",type.get());
389                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
390                 IAAP* aap=dynamic_cast<IAAP*>(plugin);
391                 if (aap)
392                     m_aaps.push_back(aap);
393                 else {
394                     delete plugin;
395                     log.fatal("plugin was not an AAP provider");
396                     throw UnsupportedExtensionException("plugin was not an AAP provider");
397                 }
398             }
399         }
400
401         if (conf.isEnabled(ShibTargetConfig::Metadata)) {
402             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(FederationProvider));
403             for (i=0; nlist && i<nlist->getLength(); i++) {
404                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
405                 log.info("building federation/metadata provider of type %s...",type.get());
406                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
407                 IMetadata* md=dynamic_cast<IMetadata*>(plugin);
408                 if (md)
409                     m_metadatas.push_back(md);
410                 else {
411                     delete plugin;
412                     log.fatal("plugin was not a federation/metadata provider");
413                     throw UnsupportedExtensionException("plugin was not a federation/metadata provider");
414                 }
415             }
416         }
417
418         if (conf.isEnabled(ShibTargetConfig::Trust)) {
419             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TrustProvider));
420             for (i=0; nlist && i<nlist->getLength(); i++) {
421                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
422                 log.info("building trust provider of type %s...",type.get());
423                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
424                 ITrust* trust=dynamic_cast<ITrust*>(plugin);
425                 if (trust)
426                     m_trusts.push_back(trust);
427                 else {
428                     delete plugin;
429                     log.fatal("plugin was not a trust provider");
430                     throw UnsupportedExtensionException("plugin was not a trust provider");
431                 }
432             }
433             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RevocationProvider));
434             for (i=0; nlist && i<nlist->getLength(); i++) {
435                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
436                 log.info("building revocation provider of type %s...",type.get());
437                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
438                 IRevocation* rev=dynamic_cast<IRevocation*>(plugin);
439                 if (rev)
440                     m_revocations.push_back(rev);
441                 else {
442                     delete plugin;
443                     log.fatal("plugin was not a revocation provider");
444                     throw UnsupportedExtensionException("plugin was not a revocation provider");
445                 }
446             }
447         }
448         
449         // Finally, load credential mappings.
450         const DOMElement* cu=saml::XML::getFirstChildElement(e,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialUse));
451         if (cu) {
452             auto_ptr_char TLS(cu->getAttributeNS(NULL,SHIBT_L(TLS)));
453             auto_ptr_char Signing(cu->getAttributeNS(NULL,SHIBT_L(Signing)));
454             m_credDefault.first=TLS.get();
455             m_credDefault.second=Signing.get();
456             cu=saml::XML::getFirstChildElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
457             while (cu) {
458                 auto_ptr_char TLS2(cu->getAttributeNS(NULL,SHIBT_L(TLS)));
459                 auto_ptr_char Signing2(cu->getAttributeNS(NULL,SHIBT_L(Signing)));
460                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=pair<string,string>(TLS2.get(),Signing2.get());
461                 cu=saml::XML::getNextSiblingElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
462             }
463         }
464         
465         if (conf.isEnabled(ShibTargetConfig::SessionCache)) {
466             // Really finally, build local browser profile and binding objects.
467             m_profile=new ShibBrowserProfile(
468                 getMetadataProviders(),
469                 getRevocationProviders(),
470                 getTrustProviders()
471                 );
472             m_bindingHook=new ShibHTTPHook(
473                 getRevocationProviders(),
474                 getTrustProviders(),
475                 creds
476                 );
477             m_binding=SAMLBinding::getInstance(SAMLBinding::SOAP);
478             SAMLSOAPHTTPBinding* bptr=dynamic_cast<SAMLSOAPHTTPBinding*>(m_binding);
479             if (!bptr) {
480                 log.fatal("binding implementation was not SOAP over HTTP");
481                 throw UnsupportedExtensionException("binding implementation was not SOAP over HTTP");
482             }
483             bptr->addHook(m_bindingHook,m_bindingHook); // the hook is its own global context
484         }
485     }
486     catch (...) {
487         this->~XMLApplication();    // does this work?
488         throw;
489     }
490 }
491
492 XMLApplication::~XMLApplication()
493 {
494     delete m_bindingHook;
495     delete m_binding;
496     delete m_profile;
497     Iterator<SAMLAttributeDesignator*> i(m_designators);
498     while (i.hasNext())
499         delete i.next();
500     Iterator<IAAP*> j(m_aaps);
501     while (j.hasNext())
502         delete j.next();
503     Iterator<IMetadata*> k(m_metadatas);
504     while (k.hasNext())
505         delete k.next();
506     Iterator<ITrust*> l(m_trusts);
507     while (l.hasNext())
508         delete l.next();
509     Iterator<IRevocation*> m(m_revocations);
510     while (m.hasNext())
511         delete m.next();
512 }
513
514 short XMLApplication::acceptNode(const DOMNode* node) const
515 {
516     if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(AttributeDesignator)))
517         return FILTER_REJECT;
518     else if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(Audience)))
519         return FILTER_REJECT;
520     if (XMLString::compareString(node->getNamespaceURI(),ShibTargetConfig::SHIBTARGET_NS))
521         return FILTER_ACCEPT;
522     const XMLCh* name=node->getLocalName();
523     if (!XMLString::compareString(name,SHIBT_L(Application)) ||
524         !XMLString::compareString(name,SHIBT_L(AAPProvider)) ||
525         !XMLString::compareString(name,SHIBT_L(CredentialUse)) ||
526         !XMLString::compareString(name,SHIBT_L(FederationProvider)) ||
527         !XMLString::compareString(name,SHIBT_L(RevocationProvider)) ||
528         !XMLString::compareString(name,SHIBT_L(TrustProvider)))
529         return FILTER_REJECT;
530
531     return FILTER_ACCEPT;
532 }
533
534 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
535 {
536     pair<bool,bool> ret=XMLPropertySet::getBool(name,ns);
537     if (ret.first)
538         return ret;
539     return m_base ? m_base->getBool(name,ns) : ret;
540 }
541
542 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
543 {
544     pair<bool,const char*> ret=XMLPropertySet::getString(name,ns);
545     if (ret.first)
546         return ret;
547     return m_base ? m_base->getString(name,ns) : ret;
548 }
549
550 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
551 {
552     pair<bool,const XMLCh*> ret=XMLPropertySet::getXMLString(name,ns);
553     if (ret.first)
554         return ret;
555     return m_base ? m_base->getXMLString(name,ns) : ret;
556 }
557
558 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
559 {
560     pair<bool,unsigned int> ret=XMLPropertySet::getUnsignedInt(name,ns);
561     if (ret.first)
562         return ret;
563     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
564 }
565
566 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
567 {
568     pair<bool,int> ret=XMLPropertySet::getInt(name,ns);
569     if (ret.first)
570         return ret;
571     return m_base ? m_base->getInt(name,ns) : ret;
572 }
573
574 const IPropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
575 {
576     const IPropertySet* ret=XMLPropertySet::getPropertySet(name,ns);
577     if (ret || !m_base)
578         return ret;
579     return m_base->getPropertySet(name,ns);
580 }
581
582 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
583 {
584     if (!m_designators.empty() || !m_base)
585         return m_designators;
586     return m_base->getAttributeDesignators();
587 }
588
589 Iterator<IAAP*> XMLApplication::getAAPProviders() const
590 {
591     return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
592 }
593
594 Iterator<IMetadata*> XMLApplication::getMetadataProviders() const
595 {
596     return (m_metadatas.empty() && m_base) ? m_base->getMetadataProviders() : m_metadatas;
597 }
598
599 Iterator<ITrust*> XMLApplication::getTrustProviders() const
600 {
601     return (m_trusts.empty() && m_base) ? m_base->getTrustProviders() : m_trusts;
602 }
603
604 Iterator<IRevocation*> XMLApplication::getRevocationProviders() const
605 {
606     return (m_revocations.empty() && m_base) ? m_base->getRevocationProviders() : m_revocations;
607 }
608
609 Iterator<const XMLCh*> XMLApplication::getAudiences() const
610 {
611     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
612 }
613
614 const pair<string,string>& XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
615 {
616     if (m_credDefault.first.empty() && m_base)
617         return m_base->getCredentialUse(provider);
618         
619 #ifdef HAVE_GOOD_STL
620     map<xstring,pair<string,string> >::const_iterator i=m_credMap.find(provider->getId());
621     if (i!=m_credMap.end())
622         return i->second;
623     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
624     while (group) {
625         i=m_credMap.find(group->getName());
626         if (i!=m_credMap.end())
627             return i->second;
628         group=group->getEntitiesDescriptor();
629     }
630 #else
631     map<const XMLCh*,pair<string,string> >::const_iterator i=m_credMap.begin();
632     for (; i!=m_credMap.end(); i++) {
633         if (!XMLString::compareString(i->first,provider->getId()))
634             return i->second;
635         const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
636         while (group) {
637             if (!XMLString::compareString(i->first,group->getName()))
638                 return i->second;
639             group=group->getEntitiesDescriptor();
640         }
641     }
642 #endif
643     return m_credDefault;
644 }
645
646 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
647 {
648     return new XMLConfigImpl(pathname,first,this);
649 }
650
651 ReloadableXMLFileImpl* XMLConfig::newImplementation(const DOMElement* e, bool first) const
652 {
653     return new XMLConfigImpl(e,first,this);
654 }
655
656 short XMLConfigImpl::acceptNode(const DOMNode* node) const
657 {
658     if (XMLString::compareString(node->getNamespaceURI(),ShibTargetConfig::SHIBTARGET_NS))
659         return FILTER_ACCEPT;
660     const XMLCh* name=node->getLocalName();
661     if (!XMLString::compareString(name,SHIBT_L(Applications)) ||
662         !XMLString::compareString(name,SHIBT_L(CredentialsProvider)) ||
663         !XMLString::compareString(name,SHIBT_L(Extensions)) ||
664         !XMLString::compareString(name,SHIBT_L(Implementation)) ||
665         !XMLString::compareString(name,SHIBT_L(Listener)) ||
666         !XMLString::compareString(name,SHIBT_L(MemorySessionCache)) ||
667         !XMLString::compareString(name,SHIBT_L(MySQLSessionCache)) ||
668         !XMLString::compareString(name,SHIBT_L(RequestMap)) ||
669         !XMLString::compareString(name,SHIBT_L(RequestMapProvider)) ||
670         !XMLString::compareString(name,SHIBT_L(SessionCache)) ||
671         !XMLString::compareString(name,SHIBT_L(TCPListener)) ||
672         !XMLString::compareString(name,SHIBT_L(UnixListener)))
673         return FILTER_REJECT;
674
675     return FILTER_ACCEPT;
676 }
677
678 void XMLConfigImpl::init(bool first)
679 {
680     NDC ndc("XMLConfigImpl");
681     Category& log=Category::getInstance("shibtarget.XMLConfig");
682
683     try {
684         if (!saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(ShibbolethTargetConfig))) {
685             log.error("Construction requires a valid configuration file: (conf:ShibbolethTargetConfig as root element)");
686             throw MalformedException("Construction requires a valid configuration file: (conf:ShibbolethTargetConfig as root element)");
687         }
688
689         SAMLConfig& shibConf=SAMLConfig::getConfig();
690         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
691         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHAR));
692         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHIRE));
693
694         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
695         if (conf.isEnabled(ShibTargetConfig::Logging)) {
696             const XMLCh* logger=NULL;
697             if (conf.isEnabled(ShibTargetConfig::SHARExtensions))
698                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
699             else if (conf.isEnabled(ShibTargetConfig::SHIREExtensions))
700                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
701             if (!logger || !*logger)
702                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
703             if (logger && *logger) {
704                 auto_ptr_char logpath(logger);
705                 cerr << "loading new logging configuration from " << logpath.get() << "\n";
706                 try {
707                     PropertyConfigurator::configure(logpath.get());
708                     cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
709                 }
710                 catch (ConfigureFailure& e) {
711                     cerr << "Error reading logging configuration: " << e.what() << "\n";
712                 }
713             }
714         }
715         
716         // First load any property sets.
717         load(ReloadableXMLFileImpl::m_root,log,this);
718
719         // Much of the processing can only occur on the first instantiation.
720         if (first) {
721             // Now load any extensions to insure any needed plugins are registered.
722             DOMElement* exts=
723                 saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
724             if (exts) {
725                 exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
726                 while (exts) {
727                     auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
728                     try {
729                         SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
730                         log.debug("loaded global extension library %s",path.get());
731                     }
732                     catch (SAMLException& e) {
733                         const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
734                         if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
735                             log.fatal("unable to load mandatory global extension library %s: %s", path.get(), e.what());
736                             throw;
737                         }
738                         else
739                             log.crit("unable to load optional global extension library %s: %s", path.get(), e.what());
740                     }
741                     exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
742                 }
743             }
744             
745             if (conf.isEnabled(ShibTargetConfig::SHARExtensions)) {
746                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
747                 if (exts) {
748                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
749                     while (exts) {
750                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
751                         try {
752                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
753                             log.debug("loaded SHAR extension library %s",path.get());
754                         }
755                         catch (SAMLException& e) {
756                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
757                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
758                                 log.fatal("unable to load mandatory SHAR extension library %s: %s", path.get(), e.what());
759                                 throw;
760                             }
761                             else
762                                 log.crit("unable to load optional SHAR extension library %s: %s", path.get(), e.what());
763                         }
764                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
765                     }
766                 }
767             }
768
769             if (conf.isEnabled(ShibTargetConfig::SHIREExtensions)) {
770                 exts=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
771                 if (exts) {
772                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
773                     while (exts) {
774                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
775                         try {
776                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
777                             log.debug("loaded SHIRE extension library %s",path.get());
778                         }
779                         catch (SAMLException& e) {
780                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
781                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
782                                 log.fatal("unable to load mandatory SHIRE extension library %s: %s", path.get(), e.what());
783                                 throw;
784                             }
785                             else
786                                 log.crit("unable to load optional SHIRE extension library %s: %s", path.get(), e.what());
787                         }
788                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
789                     }
790                 }
791             }
792             
793             // Instantiate the Listener and SessionCache objects.
794             if (conf.isEnabled(ShibTargetConfig::Listener)) {
795                 IPlugIn* plugin=NULL;
796                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(UnixListener));
797                 if (exts) {
798                     log.info("building Listener of type %s...",shibtarget::XML::UnixListenerType);
799                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::UnixListenerType,exts);
800                 }
801                 else {
802                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TCPListener));
803                     if (exts) {
804                         log.info("building Listener of type %s...",shibtarget::XML::TCPListenerType);
805                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::TCPListenerType,exts);
806                     }
807                     else {
808                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Listener));
809                         if (exts) {
810                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
811                             log.info("building Listener of type %s...",type.get());
812                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
813                         }
814                         else {
815                             log.fatal("can't build Listener object, missing conf:Listener element?");
816                             throw MalformedException("can't build Listener object, missing conf:Listener element?");
817                         }
818                     }
819                 }
820                 if (plugin) {
821                     IListener* listen=dynamic_cast<IListener*>(plugin);
822                     if (listen)
823                         m_outer->m_listener=listen;
824                     else {
825                         delete plugin;
826                         log.fatal("plugin was not a Listener object");
827                         throw UnsupportedExtensionException("plugin was not a Listener object");
828                     }
829                 }
830             }
831
832             if (conf.isEnabled(ShibTargetConfig::SessionCache)) {
833                 IPlugIn* plugin=NULL;
834                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
835                 if (exts) {
836                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
837                     plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
838                 }
839                 else {
840                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
841                     if (exts) {
842                         log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
843                         plugin=shibConf.getPlugMgr().newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
844                     }
845                     else {
846                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionCache));
847                         if (exts) {
848                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
849                             log.info("building Session Cache of type %s...",type.get());
850                             plugin=shibConf.getPlugMgr().newPlugin(type.get(),exts);
851                         }
852                         else {
853                             log.fatal("can't build Session Cache object, missing conf:SessionCache element?");
854                             throw MalformedException("can't build Session Cache object, missing conf:SessionCache element?");
855                         }
856                     }
857                 }
858                 if (plugin) {
859                     ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
860                     if (cache)
861                         m_outer->m_sessionCache=cache;
862                     else {
863                         delete plugin;
864                         log.fatal("plugin was not a Session Cache object");
865                         throw UnsupportedExtensionException("plugin was not a Session Cache object");
866                     }
867                 }
868                 
869                 // For now, just default the replay cache.
870                 // TODO: make it configurable/pluggable
871                 m_outer->m_replayCache=IReplayCache::getInstance();
872             }
873         }
874         
875         // Back to the fully dynamic stuff...next up is the Request Mapper.
876         if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
877             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
878             if (child) {
879                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
880                 log.info("building Request Mapper of type %s...",type.get());
881                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),child);
882                 if (plugin) {
883                     IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
884                     if (reqmap)
885                         m_requestMapper=reqmap;
886                     else {
887                         delete plugin;
888                         log.fatal("plugin was not a Request Mapper object");
889                         throw UnsupportedExtensionException("plugin was not a Request Mapper object");
890                     }
891                 }
892             }
893             else {
894                 log.fatal("can't build Request Mapper object, missing conf:RequestMapProvider element?");
895                 throw MalformedException("can't build Request Mapper object, missing conf:RequestMapProvider element?");
896             }
897         }
898         
899         // Now we load any credentials providers.
900         DOMNodeList* nlist;
901         if (conf.isEnabled(ShibTargetConfig::Credentials)) {
902             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(
903                 ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialsProvider)
904                 );
905             for (int i=0; nlist && i<nlist->getLength(); i++) {
906                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
907                 log.info("building Credentials provider of type %s...",type.get());
908                 IPlugIn* plugin=shibConf.getPlugMgr().newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
909                 if (plugin) {
910                     ICredentials* creds=dynamic_cast<ICredentials*>(plugin);
911                     if (creds)
912                         m_creds.push_back(creds);
913                     else {
914                         delete plugin;
915                         log.fatal("plugin was not a Credentials provider");
916                         throw UnsupportedExtensionException("plugin was not a Credentials provider");
917                     }
918                 }
919             }
920         }
921
922         // Load the default application. This actually has a fixed ID of "default". ;-)
923         const DOMElement* app=saml::XML::getFirstChildElement(
924             ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Applications)
925             );
926         if (!app) {
927             log.fatal("can't build default Application object, missing conf:Applications element?");
928             throw SAMLException("can't build default Application object, missing conf:Applications element?");
929         }
930         XMLApplication* defapp=new XMLApplication(m_outer, m_creds, app);
931         m_appmap[defapp->getId()]=defapp;
932         
933         // Load any overrides.
934         nlist=app->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Application));
935         for (int i=0; nlist && i<nlist->getLength(); i++) {
936             XMLApplication* iapp=new XMLApplication(m_outer,m_creds,static_cast<DOMElement*>(nlist->item(i)),defapp);
937             if (m_appmap.find(iapp->getId())!=m_appmap.end()) {
938                 log.fatal("found conf:Application element with duplicate Id attribute");
939                 throw SAMLException("found conf:Application element with duplicate Id attribute");
940             }
941             m_appmap[iapp->getId()]=iapp;
942         }
943     }
944     catch (SAMLException& e) {
945         log.errorStream() << "Error while loading target configuration: " << e.what() << CategoryStream::ENDLINE;
946         this->~XMLConfigImpl();
947         throw;
948     }
949 #ifndef _DEBUG
950     catch (...) {
951         log.error("Unexpected error while loading target configuration");
952         this->~XMLConfigImpl();
953         throw;
954     }
955 #endif
956 }
957
958 XMLConfigImpl::~XMLConfigImpl()
959 {
960     delete m_requestMapper;
961     for (map<string,IApplication*>::iterator i=m_appmap.begin(); i!=m_appmap.end(); i++)
962         delete i->second;
963     for (vector<ICredentials*>::iterator j=m_creds.begin(); j!=m_creds.end(); j++)
964         delete (*j);
965 }