New profile API, consolidated RPCs, simplified cache.
[shibboleth/cpp-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 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         SAMLBrowserProfile* getBrowserProfile() const {return m_profile;}
99         
100         // Provides filter to exclude special config elements.
101         short acceptNode(const DOMNode* node) const;
102     
103     private:
104         const IConfig* m_ini;   // this is ok because its locking scope includes us
105         const XMLApplication* m_base;
106         vector<SAMLAttributeDesignator*> m_designators;
107         vector<IAAP*> m_aaps;
108         vector<IMetadata*> m_metadatas;
109         vector<ITrust*> m_trusts;
110         vector<IRevocation*> m_revocations;
111         vector<const XMLCh*> m_audiences;
112         pair<string,string> m_credDefault;
113         ShibBrowserProfile* m_profile;
114 #ifdef HAVE_GOOD_STL
115         map<xstring,pair<string,string> > m_credMap;
116 #else
117         map<const XMLCh*,pair<string,string> > m_credMap;
118 #endif
119         const pair<string,string>& getCredentialUse(const IEntityDescriptor* provider) const;
120     };
121
122     // Top-level configuration implementation
123     class XMLConfig;
124     class XMLConfigImpl : public ReloadableXMLFileImpl, public XMLPropertySet, public DOMNodeFilter
125     {
126     public:
127         XMLConfigImpl(const char* pathname, bool first, const XMLConfig* outer)
128             : ReloadableXMLFileImpl(pathname), m_outer(outer), m_requestMapper(NULL) { init(first); }
129         XMLConfigImpl(const DOMElement* e, bool first, const XMLConfig* outer)
130             : ReloadableXMLFileImpl(e), m_outer(outer), m_requestMapper(NULL) { init(first); }
131         ~XMLConfigImpl();
132         
133         IRequestMapper* m_requestMapper;
134         map<string,IApplication*> m_appmap;
135         vector<ICredentials*> m_creds;
136         
137         // Provides filter to exclude special config elements.
138         short acceptNode(const DOMNode* node) const;
139
140     private:
141         void init(bool first);
142         const XMLConfig* m_outer;
143     };
144     
145     class XMLConfig : public IConfig, public ReloadableXMLFile
146     {
147     public:
148         XMLConfig(const DOMElement* e) : ReloadableXMLFile(e), m_listener(NULL), m_sessionCache(NULL), m_replayCache(NULL) {}
149         ~XMLConfig() {delete m_listener; delete m_sessionCache; delete m_replayCache;}
150
151         // IPropertySet
152         pair<bool,bool> getBool(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getBool(name,ns);}
153         pair<bool,const char*> getString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getString(name,ns);}
154         pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getXMLString(name,ns);}
155         pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getUnsignedInt(name,ns);}
156         pair<bool,int> getInt(const char* name, const char* ns=NULL) const {return static_cast<XMLConfigImpl*>(m_impl)->getInt(name,ns);}
157         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);}
158         const DOMElement* getElement() const {return static_cast<XMLConfigImpl*>(m_impl)->getElement();}
159
160         // IConfig
161         const IListener* getListener() const {return m_listener;}
162         ISessionCache* getSessionCache() const {return m_sessionCache;}
163         IReplayCache* getReplayCache() const {return m_replayCache;}
164         IRequestMapper* getRequestMapper() const {return static_cast<XMLConfigImpl*>(m_impl)->m_requestMapper;}
165         const IApplication* getApplication(const char* applicationId) const
166         {
167             map<string,IApplication*>::const_iterator i=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.find(applicationId);
168             return (i!=static_cast<XMLConfigImpl*>(m_impl)->m_appmap.end()) ? i->second : NULL;
169         }
170         Iterator<ICredentials*> getCredentialsProviders() const {return static_cast<XMLConfigImpl*>(m_impl)->m_creds;}
171
172     protected:
173         virtual ReloadableXMLFileImpl* newImplementation(const char* pathname, bool first=true) const;
174         virtual ReloadableXMLFileImpl* newImplementation(const DOMElement* e, bool first=true) const;
175
176     private:
177         friend class XMLConfigImpl;
178         mutable IListener* m_listener;
179         mutable ISessionCache* m_sessionCache;
180         mutable IReplayCache* m_replayCache;
181     };
182 }
183
184 IConfig* STConfig::ShibTargetConfigFactory(const DOMElement* e)
185 {
186     XMLConfig* ret=new XMLConfig(e);
187     try {
188         ret->getImplementation();
189     }
190     catch (...) {
191         delete ret;
192         throw;
193     }
194     return ret;
195 }
196
197 XMLPropertySet::~XMLPropertySet()
198 {
199     for (map<string,pair<char*,const XMLCh*> >::iterator i=m_map.begin(); i!=m_map.end(); i++)
200         XMLString::release(&(i->second.first));
201     for (map<string,IPropertySet*>::iterator j=m_nested.begin(); j!=m_nested.end(); j++)
202         delete j->second;
203 }
204
205 void XMLPropertySet::load(const DOMElement* e, Category& log, DOMNodeFilter* filter)
206 {
207     NDC ndc("load");
208     m_root=e;
209
210     // Process each attribute as a property.
211     DOMNamedNodeMap* attrs=m_root->getAttributes();
212     for (XMLSize_t i=0; i<attrs->getLength(); i++) {
213         DOMNode* a=attrs->item(i);
214         if (!XMLString::compareString(a->getNamespaceURI(),saml::XML::XMLNS_NS))
215             continue;
216         char* val=XMLString::transcode(a->getNodeValue());
217         if (val && *val) {
218             auto_ptr_char ns(a->getNamespaceURI());
219             auto_ptr_char name(a->getLocalName());
220             if (ns.get()) {
221                 m_map[string("{") + ns.get() + '}' + name.get()]=pair<char*,const XMLCh*>(val,a->getNodeValue());
222                 log.debug("added property {%s}%s (%s)",ns.get(),name.get(),val);
223             }
224             else {
225                 m_map[name.get()]=pair<char*,const XMLCh*>(val,a->getNodeValue());
226                 log.debug("added property %s (%s)",name.get(),val);
227             }
228         }
229     }
230     
231     // Process non-excluded elements as nested sets.
232     DOMTreeWalker* walker=
233         static_cast<DOMDocumentTraversal*>(
234             m_root->getOwnerDocument())->createTreeWalker(const_cast<DOMElement*>(m_root),DOMNodeFilter::SHOW_ELEMENT,filter,false
235             );
236     e=static_cast<DOMElement*>(walker->firstChild());
237     while (e) {
238         auto_ptr_char ns(e->getNamespaceURI());
239         auto_ptr_char name(e->getLocalName());
240         string key;
241         if (ns.get())
242             key=string("{") + ns.get() + '}' + name.get();
243         else
244             key=name.get();
245         if (m_nested.find(key)!=m_nested.end())
246             log.warn("load() skipping duplicate property set: %s",key.c_str());
247         else {
248             XMLPropertySet* set=new XMLPropertySet();
249             set->load(e,log,filter);
250             m_nested[key]=set;
251             log.debug("added nested property set: %s",key.c_str());
252         }
253         e=static_cast<DOMElement*>(walker->nextSibling());
254     }
255     walker->release();
256 }
257
258 pair<bool,bool> XMLPropertySet::getBool(const char* name, const char* ns) const
259 {
260     pair<bool,bool> ret=pair<bool,bool>(false,false);
261     map<string,pair<char*,const XMLCh*> >::const_iterator i;
262
263     if (ns)
264         i=m_map.find(string("{") + ns + '}' + name);
265     else
266         i=m_map.find(name);
267
268     if (i!=m_map.end()) {
269         ret.first=true;
270         ret.second=(!strcmp(i->second.first,"true") || !strcmp(i->second.first,"1"));
271     }
272     return ret;
273 }
274
275 pair<bool,const char*> XMLPropertySet::getString(const char* name, const char* ns) const
276 {
277     pair<bool,const char*> ret=pair<bool,const char*>(false,NULL);
278     map<string,pair<char*,const XMLCh*> >::const_iterator i;
279
280     if (ns)
281         i=m_map.find(string("{") + ns + '}' + name);
282     else
283         i=m_map.find(name);
284
285     if (i!=m_map.end()) {
286         ret.first=true;
287         ret.second=i->second.first;
288     }
289     return ret;
290 }
291
292 pair<bool,const XMLCh*> XMLPropertySet::getXMLString(const char* name, const char* ns) const
293 {
294     pair<bool,const XMLCh*> ret=pair<bool,const XMLCh*>(false,NULL);
295     map<string,pair<char*,const XMLCh*> >::const_iterator i;
296
297     if (ns)
298         i=m_map.find(string("{") + ns + '}' + name);
299     else
300         i=m_map.find(name);
301
302     if (i!=m_map.end()) {
303         ret.first=true;
304         ret.second=i->second.second;
305     }
306     return ret;
307 }
308
309 pair<bool,unsigned int> XMLPropertySet::getUnsignedInt(const char* name, const char* ns) const
310 {
311     pair<bool,unsigned int> ret=pair<bool,unsigned int>(false,0);
312     map<string,pair<char*,const XMLCh*> >::const_iterator i;
313
314     if (ns)
315         i=m_map.find(string("{") + ns + '}' + name);
316     else
317         i=m_map.find(name);
318
319     if (i!=m_map.end()) {
320         ret.first=true;
321         ret.second=strtol(i->second.first,NULL,10);
322     }
323     return ret;
324 }
325
326 pair<bool,int> XMLPropertySet::getInt(const char* name, const char* ns) const
327 {
328     pair<bool,int> ret=pair<bool,int>(false,0);
329     map<string,pair<char*,const XMLCh*> >::const_iterator i;
330
331     if (ns)
332         i=m_map.find(string("{") + ns + '}' + name);
333     else
334         i=m_map.find(name);
335
336     if (i!=m_map.end()) {
337         ret.first=true;
338         ret.second=atoi(i->second.first);
339     }
340     return ret;
341 }
342
343 const IPropertySet* XMLPropertySet::getPropertySet(const char* name, const char* ns) const
344 {
345     map<string,IPropertySet*>::const_iterator i;
346
347     if (ns)
348         i=m_nested.find(string("{") + ns + '}' + name);
349     else
350         i=m_nested.find(name);
351
352     return (i!=m_nested.end()) ? i->second : NULL;
353 }
354
355 XMLApplication::XMLApplication(const IConfig* ini, const DOMElement* e, const XMLApplication* base)
356     : m_ini(ini), m_base(base), m_profile(NULL)
357 {
358     NDC ndc("XMLApplication");
359     Category& log=Category::getInstance("shibtarget.XMLApplication");
360
361     try {
362         // First load any property sets.
363         load(e,log,this);
364
365         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
366         SAMLConfig& shibConf=SAMLConfig::getConfig();
367         int i;
368         DOMNodeList* nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(AttributeDesignator));
369         for (i=0; nlist && i<nlist->getLength(); i++) {
370             m_designators.push_back(new SAMLAttributeDesignator(static_cast<DOMElement*>(nlist->item(i))));
371         }
372
373         nlist=e->getElementsByTagNameNS(saml::XML::SAML_NS,L(Audience));
374         for (i=0; nlist && i<nlist->getLength(); i++) {
375             m_audiences.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
376         }
377         // Always include our own providerId as an audience.
378         m_audiences.push_back(getXMLString("providerId").second);
379
380         if (conf.isEnabled(ShibTargetConfig::AAP)) {
381             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(AAPProvider));
382             for (i=0; nlist && i<nlist->getLength(); i++) {
383                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
384                 log.info("building AAP provider of type %s...",type.get());
385                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
386                 IAAP* aap=dynamic_cast<IAAP*>(plugin);
387                 if (aap)
388                     m_aaps.push_back(aap);
389                 else {
390                     delete plugin;
391                     log.fatal("plugin was not an AAP provider");
392                     throw UnsupportedExtensionException("plugin was not an AAP provider");
393                 }
394             }
395         }
396
397         if (conf.isEnabled(ShibTargetConfig::Metadata)) {
398             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(FederationProvider));
399             for (i=0; nlist && i<nlist->getLength(); i++) {
400                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
401                 log.info("building federation/metadata provider of type %s...",type.get());
402                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
403                 IMetadata* md=dynamic_cast<IMetadata*>(plugin);
404                 if (md)
405                     m_metadatas.push_back(md);
406                 else {
407                     delete plugin;
408                     log.fatal("plugin was not a federation/metadata provider");
409                     throw UnsupportedExtensionException("plugin was not a federation/metadata provider");
410                 }
411             }
412         }
413
414         if (conf.isEnabled(ShibTargetConfig::Trust)) {
415             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TrustProvider));
416             for (i=0; nlist && i<nlist->getLength(); i++) {
417                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
418                 log.info("building trust provider of type %s...",type.get());
419                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
420                 ITrust* trust=dynamic_cast<ITrust*>(plugin);
421                 if (trust)
422                     m_trusts.push_back(trust);
423                 else {
424                     delete plugin;
425                     log.fatal("plugin was not a trust provider");
426                     throw UnsupportedExtensionException("plugin was not a trust provider");
427                 }
428             }
429             nlist=e->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RevocationProvider));
430             for (i=0; nlist && i<nlist->getLength(); i++) {
431                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
432                 log.info("building revocation provider of type %s...",type.get());
433                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
434                 IRevocation* rev=dynamic_cast<IRevocation*>(plugin);
435                 if (rev)
436                     m_revocations.push_back(rev);
437                 else {
438                     delete plugin;
439                     log.fatal("plugin was not a revocation provider");
440                     throw UnsupportedExtensionException("plugin was not a revocation provider");
441                 }
442             }
443         }
444         
445         // Finally, load credential mappings.
446         const DOMElement* cu=saml::XML::getFirstChildElement(e,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialUse));
447         if (cu) {
448             auto_ptr_char TLS(cu->getAttributeNS(NULL,SHIBT_L(TLS)));
449             auto_ptr_char Signing(cu->getAttributeNS(NULL,SHIBT_L(Signing)));
450             m_credDefault.first=TLS.get();
451             m_credDefault.second=Signing.get();
452             cu=saml::XML::getFirstChildElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
453             while (cu) {
454                 auto_ptr_char TLS2(cu->getAttributeNS(NULL,SHIBT_L(TLS)));
455                 auto_ptr_char Signing2(cu->getAttributeNS(NULL,SHIBT_L(Signing)));
456                 m_credMap[cu->getAttributeNS(NULL,SHIBT_L(Name))]=pair<string,string>(TLS2.get(),Signing2.get());
457                 cu=saml::XML::getNextSiblingElement(cu,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RelyingParty));
458             }
459         }
460         
461         if (conf.isEnabled(ShibTargetConfig::SessionCache)) {
462             // Really finally, build a local browser profile object.
463             m_profile=new ShibBrowserProfile(
464                 getMetadataProviders(),
465                 getRevocationProviders(),
466                 getTrustProviders()
467                 );
468         }
469     }
470     catch (...) {
471         this->~XMLApplication();    // does this work?
472         throw;
473     }
474 }
475
476 XMLApplication::~XMLApplication()
477 {
478     delete m_profile;
479     Iterator<SAMLAttributeDesignator*> i(m_designators);
480     while (i.hasNext())
481         delete i.next();
482     Iterator<IAAP*> j(m_aaps);
483     while (j.hasNext())
484         delete j.next();
485     Iterator<IMetadata*> k(m_metadatas);
486     while (k.hasNext())
487         delete k.next();
488     Iterator<ITrust*> l(m_trusts);
489     while (l.hasNext())
490         delete l.next();
491     Iterator<IRevocation*> m(m_revocations);
492     while (m.hasNext())
493         delete m.next();
494 }
495
496 short XMLApplication::acceptNode(const DOMNode* node) const
497 {
498     if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(AttributeDesignator)))
499         return FILTER_REJECT;
500     else if (saml::XML::isElementNamed(static_cast<const DOMElement*>(node),saml::XML::SAML_NS,L(Audience)))
501         return FILTER_REJECT;
502     if (XMLString::compareString(node->getNamespaceURI(),ShibTargetConfig::SHIBTARGET_NS))
503         return FILTER_ACCEPT;
504     const XMLCh* name=node->getLocalName();
505     if (!XMLString::compareString(name,SHIBT_L(Application)) ||
506         !XMLString::compareString(name,SHIBT_L(AAPProvider)) ||
507         !XMLString::compareString(name,SHIBT_L(CredentialUse)) ||
508         !XMLString::compareString(name,SHIBT_L(FederationProvider)) ||
509         !XMLString::compareString(name,SHIBT_L(RevocationProvider)) ||
510         !XMLString::compareString(name,SHIBT_L(TrustProvider)))
511         return FILTER_REJECT;
512
513     return FILTER_ACCEPT;
514 }
515
516 pair<bool,bool> XMLApplication::getBool(const char* name, const char* ns) const
517 {
518     pair<bool,bool> ret=XMLPropertySet::getBool(name,ns);
519     if (ret.first)
520         return ret;
521     return m_base ? m_base->getBool(name,ns) : ret;
522 }
523
524 pair<bool,const char*> XMLApplication::getString(const char* name, const char* ns) const
525 {
526     pair<bool,const char*> ret=XMLPropertySet::getString(name,ns);
527     if (ret.first)
528         return ret;
529     return m_base ? m_base->getString(name,ns) : ret;
530 }
531
532 pair<bool,const XMLCh*> XMLApplication::getXMLString(const char* name, const char* ns) const
533 {
534     pair<bool,const XMLCh*> ret=XMLPropertySet::getXMLString(name,ns);
535     if (ret.first)
536         return ret;
537     return m_base ? m_base->getXMLString(name,ns) : ret;
538 }
539
540 pair<bool,unsigned int> XMLApplication::getUnsignedInt(const char* name, const char* ns) const
541 {
542     pair<bool,unsigned int> ret=XMLPropertySet::getUnsignedInt(name,ns);
543     if (ret.first)
544         return ret;
545     return m_base ? m_base->getUnsignedInt(name,ns) : ret;
546 }
547
548 pair<bool,int> XMLApplication::getInt(const char* name, const char* ns) const
549 {
550     pair<bool,int> ret=XMLPropertySet::getInt(name,ns);
551     if (ret.first)
552         return ret;
553     return m_base ? m_base->getInt(name,ns) : ret;
554 }
555
556 const IPropertySet* XMLApplication::getPropertySet(const char* name, const char* ns) const
557 {
558     const IPropertySet* ret=XMLPropertySet::getPropertySet(name,ns);
559     if (ret || !m_base)
560         return ret;
561     return m_base->getPropertySet(name,ns);
562 }
563
564 Iterator<SAMLAttributeDesignator*> XMLApplication::getAttributeDesignators() const
565 {
566     if (!m_designators.empty() || !m_base)
567         return m_designators;
568     return m_base->getAttributeDesignators();
569 }
570
571 Iterator<IAAP*> XMLApplication::getAAPProviders() const
572 {
573     return (m_aaps.empty() && m_base) ? m_base->getAAPProviders() : m_aaps;
574 }
575
576 Iterator<IMetadata*> XMLApplication::getMetadataProviders() const
577 {
578     return (m_metadatas.empty() && m_base) ? m_base->getMetadataProviders() : m_metadatas;
579 }
580
581 Iterator<ITrust*> XMLApplication::getTrustProviders() const
582 {
583     return (m_trusts.empty() && m_base) ? m_base->getTrustProviders() : m_trusts;
584 }
585
586 Iterator<IRevocation*> XMLApplication::getRevocationProviders() const
587 {
588     return (m_revocations.empty() && m_base) ? m_base->getRevocationProviders() : m_revocations;
589 }
590
591 Iterator<const XMLCh*> XMLApplication::getAudiences() const
592 {
593     return (m_audiences.empty() && m_base) ? m_base->getAudiences() : m_audiences;
594 }
595
596 const pair<string,string>& XMLApplication::getCredentialUse(const IEntityDescriptor* provider) const
597 {
598     if (m_credDefault.first.empty() && m_base)
599         return m_base->getCredentialUse(provider);
600         
601 #ifdef HAVE_GOOD_STL
602     map<xstring,pair<string,string> >::const_iterator i=m_credMap.find(provider->getId());
603     if (i!=m_credMap.end())
604         return i->second;
605     const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
606     while (group) {
607         i=m_credMap.find(group->getName());
608         if (i!=m_credMap.end())
609             return i->second;
610         group=group->getEntitiesDescriptor();
611     }
612 #else
613     map<const XMLCh*,pair<string,string> >::const_iterator i=m_credMap.begin();
614     for (; i!=m_credMap.end(); i++) {
615         if (!XMLString::compareString(i->first,provider->getId()))
616             return i->second;
617         const IEntitiesDescriptor* group=provider->getEntitiesDescriptor();
618         while (group) {
619             if (!XMLString::compareString(i->first,group->getName()))
620                 return i->second;
621             group=group->getEntitiesDescriptor();
622         }
623     }
624 #endif
625     return m_credDefault;
626 }
627
628 ReloadableXMLFileImpl* XMLConfig::newImplementation(const char* pathname, bool first) const
629 {
630     return new XMLConfigImpl(pathname,first,this);
631 }
632
633 ReloadableXMLFileImpl* XMLConfig::newImplementation(const DOMElement* e, bool first) const
634 {
635     return new XMLConfigImpl(e,first,this);
636 }
637
638 short XMLConfigImpl::acceptNode(const DOMNode* node) const
639 {
640     if (XMLString::compareString(node->getNamespaceURI(),ShibTargetConfig::SHIBTARGET_NS))
641         return FILTER_ACCEPT;
642     const XMLCh* name=node->getLocalName();
643     if (!XMLString::compareString(name,SHIBT_L(Applications)) ||
644         !XMLString::compareString(name,SHIBT_L(CredentialsProvider)) ||
645         !XMLString::compareString(name,SHIBT_L(Extensions)) ||
646         !XMLString::compareString(name,SHIBT_L(Implementation)) ||
647         !XMLString::compareString(name,SHIBT_L(Listener)) ||
648         !XMLString::compareString(name,SHIBT_L(MemorySessionCache)) ||
649         !XMLString::compareString(name,SHIBT_L(MySQLSessionCache)) ||
650         !XMLString::compareString(name,SHIBT_L(RequestMap)) ||
651         !XMLString::compareString(name,SHIBT_L(RequestMapProvider)) ||
652         !XMLString::compareString(name,SHIBT_L(SessionCache)) ||
653         !XMLString::compareString(name,SHIBT_L(TCPListener)) ||
654         !XMLString::compareString(name,SHIBT_L(UnixListener)))
655         return FILTER_REJECT;
656
657     return FILTER_ACCEPT;
658 }
659
660 void XMLConfigImpl::init(bool first)
661 {
662     NDC ndc("XMLConfigImpl");
663     Category& log=Category::getInstance("shibtarget.XMLConfig");
664
665     try {
666         if (!saml::XML::isElementNamed(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(ShibbolethTargetConfig))) {
667             log.error("Construction requires a valid configuration file: (conf:ShibbolethTargetConfig as root element)");
668             throw MalformedException("Construction requires a valid configuration file: (conf:ShibbolethTargetConfig as root element)");
669         }
670
671         SAMLConfig& shibConf=SAMLConfig::getConfig();
672         ShibTargetConfig& conf=ShibTargetConfig::getConfig();
673         const DOMElement* SHAR=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHAR));
674         const DOMElement* SHIRE=saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SHIRE));
675
676         // Initialize log4cpp manually in order to redirect log messages as soon as possible.
677         if (conf.isEnabled(ShibTargetConfig::Logging)) {
678             const XMLCh* logger=NULL;
679             if (conf.isEnabled(ShibTargetConfig::SHARExtensions))
680                 logger=SHAR->getAttributeNS(NULL,SHIBT_L(logger));
681             else if (conf.isEnabled(ShibTargetConfig::SHIREExtensions))
682                 logger=SHIRE->getAttributeNS(NULL,SHIBT_L(logger));
683             if (!logger || !*logger)
684                 logger=ReloadableXMLFileImpl::m_root->getAttributeNS(NULL,SHIBT_L(logger));
685             if (logger && *logger) {
686                 auto_ptr_char logpath(logger);
687                 cerr << "loading new logging configuration from " << logpath.get() << "\n";
688                 try {
689                     PropertyConfigurator::configure(logpath.get());
690                     cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
691                 }
692                 catch (ConfigureFailure& e) {
693                     cerr << "Error reading logging configuration: " << e.what() << "\n";
694                 }
695             }
696         }
697         
698         // First load any property sets.
699         load(ReloadableXMLFileImpl::m_root,log,this);
700
701         // Much of the processing can only occur on the first instantiation.
702         if (first) {
703             // Now load any extensions to insure any needed plugins are registered.
704             DOMElement* exts=
705                 saml::XML::getFirstChildElement(ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
706             if (exts) {
707                 exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
708                 while (exts) {
709                     auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
710                     try {
711                         SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
712                         log.debug("loaded global extension library %s",path.get());
713                     }
714                     catch (SAMLException& e) {
715                         const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
716                         if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
717                             log.fatal("unable to load mandatory global extension library %s: %s", path.get(), e.what());
718                             throw;
719                         }
720                         else
721                             log.crit("unable to load optional global extension library %s: %s", path.get(), e.what());
722                     }
723                     exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
724                 }
725             }
726             
727             if (conf.isEnabled(ShibTargetConfig::SHARExtensions)) {
728                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
729                 if (exts) {
730                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
731                     while (exts) {
732                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
733                         try {
734                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
735                             log.debug("loaded SHAR extension library %s",path.get());
736                         }
737                         catch (SAMLException& e) {
738                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
739                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
740                                 log.fatal("unable to load mandatory SHAR extension library %s: %s", path.get(), e.what());
741                                 throw;
742                             }
743                             else
744                                 log.crit("unable to load optional SHAR extension library %s: %s", path.get(), e.what());
745                         }
746                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
747                     }
748                 }
749             }
750
751             if (conf.isEnabled(ShibTargetConfig::SHIREExtensions)) {
752                 exts=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Extensions));
753                 if (exts) {
754                     exts=saml::XML::getFirstChildElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
755                     while (exts) {
756                         auto_ptr_char path(exts->getAttributeNS(NULL,SHIBT_L(path)));
757                         try {
758                             SAMLConfig::getConfig().saml_register_extension(path.get(),exts);
759                             log.debug("loaded SHIRE extension library %s",path.get());
760                         }
761                         catch (SAMLException& e) {
762                             const XMLCh* fatal=exts->getAttributeNS(NULL,SHIBT_L(fatal));
763                             if (fatal && (*fatal==chLatin_t || *fatal==chDigit_1)) {
764                                 log.fatal("unable to load mandatory SHIRE extension library %s: %s", path.get(), e.what());
765                                 throw;
766                             }
767                             else
768                                 log.crit("unable to load optional SHIRE extension library %s: %s", path.get(), e.what());
769                         }
770                         exts=saml::XML::getNextSiblingElement(exts,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Library));
771                     }
772                 }
773             }
774             
775             // Instantiate the Listener and SessionCache objects.
776             if (conf.isEnabled(ShibTargetConfig::Listener)) {
777                 IPlugIn* plugin=NULL;
778                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(UnixListener));
779                 if (exts) {
780                     log.info("building Listener of type %s...",shibtarget::XML::UnixListenerType);
781                     plugin=shibConf.m_plugMgr.newPlugin(shibtarget::XML::UnixListenerType,exts);
782                 }
783                 else {
784                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(TCPListener));
785                     if (exts) {
786                         log.info("building Listener of type %s...",shibtarget::XML::TCPListenerType);
787                         plugin=shibConf.m_plugMgr.newPlugin(shibtarget::XML::TCPListenerType,exts);
788                     }
789                     else {
790                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Listener));
791                         if (exts) {
792                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
793                             log.info("building Listener of type %s...",type.get());
794                             plugin=shibConf.m_plugMgr.newPlugin(type.get(),exts);
795                         }
796                         else {
797                             log.fatal("can't build Listener object, missing conf:Listener element?");
798                             throw MalformedException("can't build Listener object, missing conf:Listener element?");
799                         }
800                     }
801                 }
802                 if (plugin) {
803                     IListener* listen=dynamic_cast<IListener*>(plugin);
804                     if (listen)
805                         m_outer->m_listener=listen;
806                     else {
807                         delete plugin;
808                         log.fatal("plugin was not a Listener object");
809                         throw UnsupportedExtensionException("plugin was not a Listener object");
810                     }
811                 }
812             }
813
814             if (conf.isEnabled(ShibTargetConfig::SessionCache)) {
815                 IPlugIn* plugin=NULL;
816                 exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MemorySessionCache));
817                 if (exts) {
818                     log.info("building Session Cache of type %s...",shibtarget::XML::MemorySessionCacheType);
819                     plugin=shibConf.m_plugMgr.newPlugin(shibtarget::XML::MemorySessionCacheType,exts);
820                 }
821                 else {
822                     exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(MySQLSessionCache));
823                     if (exts) {
824                         log.info("building Session Cache of type %s...",shibtarget::XML::MySQLSessionCacheType);
825                         plugin=shibConf.m_plugMgr.newPlugin(shibtarget::XML::MySQLSessionCacheType,exts);
826                     }
827                     else {
828                         exts=saml::XML::getFirstChildElement(SHAR,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(SessionCache));
829                         if (exts) {
830                             auto_ptr_char type(exts->getAttributeNS(NULL,SHIBT_L(type)));
831                             log.info("building Session Cache of type %s...",type.get());
832                             plugin=shibConf.m_plugMgr.newPlugin(type.get(),exts);
833                         }
834                         else {
835                             log.fatal("can't build Session Cache object, missing conf:SessionCache element?");
836                             throw MalformedException("can't build Session Cache object, missing conf:SessionCache element?");
837                         }
838                     }
839                 }
840                 if (plugin) {
841                     ISessionCache* cache=dynamic_cast<ISessionCache*>(plugin);
842                     if (cache)
843                         m_outer->m_sessionCache=cache;
844                     else {
845                         delete plugin;
846                         log.fatal("plugin was not a Session Cache object");
847                         throw UnsupportedExtensionException("plugin was not a Session Cache object");
848                     }
849                 }
850                 
851                 // For now, just default the replay cache.
852                 // TODO: make it configurable/pluggable
853                 m_outer->m_replayCache=IReplayCache::getInstance();
854             }
855         }
856         
857         // Back to the fully dynamic stuff...next up is the Request Mapper.
858         if (conf.isEnabled(ShibTargetConfig::RequestMapper)) {
859             const DOMElement* child=saml::XML::getFirstChildElement(SHIRE,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(RequestMapProvider));
860             if (child) {
861                 auto_ptr_char type(child->getAttributeNS(NULL,SHIBT_L(type)));
862                 log.info("building Request Mapper of type %s...",type.get());
863                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),child);
864                 if (plugin) {
865                     IRequestMapper* reqmap=dynamic_cast<IRequestMapper*>(plugin);
866                     if (reqmap)
867                         m_requestMapper=reqmap;
868                     else {
869                         delete plugin;
870                         log.fatal("plugin was not a Request Mapper object");
871                         throw UnsupportedExtensionException("plugin was not a Request Mapper object");
872                     }
873                 }
874             }
875             else {
876                 log.fatal("can't build Request Mapper object, missing conf:RequestMapProvider element?");
877                 throw MalformedException("can't build Request Mapper object, missing conf:RequestMapProvider element?");
878             }
879         }
880         
881         // Now we load any credentials providers.
882         DOMNodeList* nlist;
883         if (conf.isEnabled(ShibTargetConfig::Credentials)) {
884             nlist=ReloadableXMLFileImpl::m_root->getElementsByTagNameNS(
885                 ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(CredentialsProvider)
886                 );
887             for (int i=0; nlist && i<nlist->getLength(); i++) {
888                 auto_ptr_char type(static_cast<DOMElement*>(nlist->item(i))->getAttributeNS(NULL,SHIBT_L(type)));
889                 log.info("building Credentials provider of type %s...",type.get());
890                 IPlugIn* plugin=shibConf.m_plugMgr.newPlugin(type.get(),static_cast<DOMElement*>(nlist->item(i)));
891                 if (plugin) {
892                     ICredentials* creds=dynamic_cast<ICredentials*>(plugin);
893                     if (creds)
894                         m_creds.push_back(creds);
895                     else {
896                         delete plugin;
897                         log.fatal("plugin was not a Credentials provider");
898                         throw UnsupportedExtensionException("plugin was not a Credentials provider");
899                     }
900                 }
901             }
902         }
903
904         // Load the default application. This actually has a fixed ID of "default". ;-)
905         const DOMElement* app=saml::XML::getFirstChildElement(
906             ReloadableXMLFileImpl::m_root,ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Applications)
907             );
908         if (!app) {
909             log.fatal("can't build default Application object, missing conf:Applications element?");
910             throw SAMLException("can't build default Application object, missing conf:Applications element?");
911         }
912         XMLApplication* defapp=new XMLApplication(m_outer, app);
913         m_appmap[defapp->getId()]=defapp;
914         
915         // Load any overrides.
916         nlist=app->getElementsByTagNameNS(ShibTargetConfig::SHIBTARGET_NS,SHIBT_L(Application));
917         for (int i=0; nlist && i<nlist->getLength(); i++) {
918             XMLApplication* iapp=new XMLApplication(m_outer,static_cast<DOMElement*>(nlist->item(i)),defapp);
919             if (m_appmap.find(iapp->getId())!=m_appmap.end()) {
920                 log.fatal("found conf:Application element with duplicate Id attribute");
921                 throw SAMLException("found conf:Application element with duplicate Id attribute");
922             }
923             m_appmap[iapp->getId()]=iapp;
924         }
925     }
926     catch (SAMLException& e) {
927         log.errorStream() << "Error while loading target configuration: " << e.what() << CategoryStream::ENDLINE;
928         this->~XMLConfigImpl();
929         throw;
930     }
931 #ifndef _DEBUG
932     catch (...) {
933         log.error("Unexpected error while loading target configuration");
934         this->~XMLConfigImpl();
935         throw;
936     }
937 #endif
938 }
939
940 XMLConfigImpl::~XMLConfigImpl()
941 {
942     delete m_requestMapper;
943     for (map<string,IApplication*>::iterator i=m_appmap.begin(); i!=m_appmap.end(); i++)
944         delete i->second;
945     for (vector<ICredentials*>::iterator j=m_creds.begin(); j!=m_creds.end(); j++)
946         delete (*j);
947 }