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