Metadata revisions, fixed lack of per-thread binding config.
[shibboleth/sp.git] / shib-target / shib-config.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-config.cpp -- ShibTarget initialization and finalization routines
52  *
53  * Created By:  Derek Atkins <derek@ihtfp.com>
54  *
55  * $Id$
56  */
57
58 #include "internal.h"
59
60 #include <shib/shib-threads.h>
61
62 #include <log4cpp/PropertyConfigurator.hh>
63 #include <log4cpp/Category.hh>
64
65 #ifndef SHIBTARGET_INIFILE
66 #define SHIBTARGET_INIFILE "/opt/shibboleth/etc/shibboleth/shibboleth.ini"
67 #endif
68
69 using namespace std;
70 using namespace log4cpp;
71 using namespace saml;
72 using namespace shibboleth;
73 using namespace shibtarget;
74
75 namespace {
76   STConfig * g_Config = NULL;
77   Mutex * g_lock = NULL;
78 }
79
80 CCache* shibtarget::g_shibTargetCCache = NULL;
81
82
83 /****************************************************************************/
84 // External Interface
85
86
87 void ShibTargetConfig::preinit()
88 {
89   if (g_lock) return;
90   g_lock = Mutex::create();
91 }
92
93 ShibTargetConfig& ShibTargetConfig::init(const char* app_name, const char* inifile)
94 {
95   if (!g_lock)
96     throw runtime_error ("ShibTargetConfig not pre-initialized");
97
98   if (!app_name)
99     throw runtime_error ("No Application name");
100   Lock lock(g_lock);
101
102   if (g_Config) {
103     g_Config->ref();
104     return *g_Config;
105   }
106
107   g_Config = new STConfig(app_name, inifile);
108   g_Config->init();
109   return *g_Config;
110 }
111
112 ShibTargetConfig& ShibTargetConfig::getConfig()
113 {
114     if (!g_Config)
115         throw SAMLException("ShibTargetConfig::getConfig() called with NULL configuration");
116     return *g_Config;
117 }
118
119 /****************************************************************************/
120 // STConfig
121
122 STConfig::STConfig(const char* app_name, const char* inifile)
123   :  samlConf(SAMLConfig::getConfig()), shibConf(ShibConfig::getConfig()),
124      m_app_name(app_name), m_applicationMapper(NULL), refcount(0)
125 {
126   try {
127     ini = new ShibINI((inifile ? inifile : SHIBTARGET_INIFILE));
128   } catch (...) {
129     cerr << "Unable to load the INI file: " << 
130       (inifile ? inifile : SHIBTARGET_INIFILE) << endl;
131     throw;
132   }
133 }
134
135 void STConfig::init()
136 {
137   string app = m_app_name;
138   string tag;
139
140   // Initialize Log4cpp
141   if (ini->get_tag (app, SHIBTARGET_TAG_LOGGER, true, &tag)) {
142     cerr << "Loading new logging configuration from " << tag << "\n";
143     try {
144       PropertyConfigurator::configure(tag);
145       cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
146     } catch (ConfigureFailure& e) {
147       cerr << "Error reading configuration: " << e.what() << "\n";
148     }
149   } else {
150     Category& category = Category::getRoot();
151     category.setPriority(log4cpp::Priority::DEBUG);
152     cerr << "No logger configuration found\n";
153   }
154
155   Category& log = Category::getInstance("shibtarget.STConfig");
156
157   saml::NDC ndc("STConfig::init");
158
159   // Init SAML Configuration
160   if (ini->get_tag (app, SHIBTARGET_TAG_SAMLCOMPAT, true, &tag))
161     samlConf.compatibility_mode = ShibINI::boolean(tag);
162   if (ini->get_tag (app, SHIBTARGET_TAG_SCHEMAS, true, &tag))
163     samlConf.schema_dir = tag;
164
165   try {
166     if (!samlConf.init()) {
167       log.fatal ("Failed to initialize SAML Library");
168       throw runtime_error ("Failed to initialize SAML Library");
169     } else
170       log.debug ("SAML Initialized");
171   } catch (...) {
172     log.crit ("Died initializing SAML Library");
173     throw;    
174   }
175
176   // Init Shib
177   try { 
178     if (!shibConf.init()) {
179       log.fatal ("Failed to initialize Shib library");
180       throw runtime_error ("Failed to initialize Shib Library");
181     } else
182       log.debug ("Shib Initialized");
183   } catch (...) {
184     log.crit ("Failed initializing Shib library.");
185     throw;
186   }
187
188   // Load any SAML extensions
189   string ext = "extensions:saml";
190   if (ini->exists(ext)) {
191     saml::NDC ndc("load_extensions");
192     ShibINI::Iterator* iter = ini->tag_iterator(ext);
193
194     for (const string* str = iter->begin(); str; str = iter->next()) {
195       string file = ini->get(ext, *str);
196       try
197       {
198         samlConf.saml_register_extension(file.c_str(),ini);
199         log.debug("%s: loading %s", str->c_str(), file.c_str());
200       }
201       catch (SAMLException& e)
202       {
203         log.crit("%s: %s", str->c_str(), e.what());
204       }
205     }
206     delete iter;
207   }
208
209     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(NULL);
210     DOMDocument* dummydoc=impl->createDocument();
211     DOMElement* dummy = dummydoc->createElementNS(NULL,XML::Literals::ApplicationMap);
212
213     // Load the specified metadata, trust, creds, and aap sources.
214     static const XMLCh url[] = { chLatin_u, chLatin_r, chLatin_l, chNull };
215     const string* prov;
216     ShibINI::Iterator* iter=ini->tag_iterator(SHIBTARGET_TAG_METADATA);
217     for (prov=iter->begin(); prov; prov=iter->next()) {
218         string source=ini->get(SHIBTARGET_TAG_METADATA,*prov);
219         log.info("building metadata provider: type=%s, source=%s",prov->c_str(),source.c_str());
220         try {
221             auto_ptr_XMLCh src(source.c_str());
222             dummy->setAttributeNS(NULL,url,src.get());
223             metadatas.push_back(shibConf.newMetadata(prov->c_str(),dummy));
224         }
225         catch (exception& e) {
226             log.crit("error building metadata provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
227             if (app == SHIBTARGET_SHAR)
228                 throw;
229         }
230     }
231     delete iter;
232
233     iter=ini->tag_iterator(SHIBTARGET_TAG_AAP);
234     for (prov=iter->begin(); prov; prov=iter->next()) {
235         string source=ini->get(SHIBTARGET_TAG_AAP,*prov);
236         log.info("building AAP provider: type=%s, source=%s",prov->c_str(),source.c_str());
237         try {
238             auto_ptr_XMLCh src(source.c_str());
239             dummy->setAttributeNS(NULL,url,src.get());
240             aaps.push_back(shibConf.newAAP(prov->c_str(),dummy));
241         }
242         catch (exception& e) {
243             log.crit("error building AAP provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
244             if (app == SHIBTARGET_SHAR)
245                 throw;
246         }
247     }
248     delete iter;
249     
250     if (app == SHIBTARGET_SHAR) {
251         iter=ini->tag_iterator(SHIBTARGET_TAG_TRUST);
252         for (prov=iter->begin(); prov; prov=iter->next()) {
253             string source=ini->get(SHIBTARGET_TAG_TRUST,*prov);
254             log.info("building trust provider: type=%s, source=%s",prov->c_str(),source.c_str());
255             try {
256                 auto_ptr_XMLCh src(source.c_str());
257                 dummy->setAttributeNS(NULL,url,src.get());
258                 trusts.push_back(shibConf.newTrust(prov->c_str(),dummy));
259             }
260             catch (exception& e) {
261                 log.crit("error building trust provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
262                 throw;
263             }
264         }
265         delete iter;
266     
267         iter=ini->tag_iterator(SHIBTARGET_TAG_CREDS);
268         for (prov=iter->begin(); prov; prov=iter->next()) {
269             string source=ini->get(SHIBTARGET_TAG_CREDS,*prov);
270             log.info("building creds provider: type=%s, source=%s",prov->c_str(),source.c_str());
271             try {
272                 auto_ptr_XMLCh src(source.c_str());
273                 dummy->setAttributeNS(NULL,url,src.get());
274                 creds.push_back(shibConf.newCredentials(prov->c_str(),dummy));
275             }
276             catch (exception& e) {
277                 log.crit("error building creds provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
278                 throw;
279             }
280         }
281         delete iter;
282
283         iter=ini->tag_iterator(SHIBTARGET_TAG_REVOCATION);
284         for (prov=iter->begin(); prov; prov=iter->next()) {
285             string source=ini->get(SHIBTARGET_TAG_REVOCATION,*prov);
286             log.info("building revocation provider: type=%s, source=%s",prov->c_str(),source.c_str());
287             try {
288                 auto_ptr_XMLCh src(source.c_str());
289                 dummy->setAttributeNS(NULL,url,src.get());
290                 revocations.push_back(shibConf.newRevocation(prov->c_str(),dummy));
291             }
292             catch (exception& e) {
293                 log.crit("error building revocation provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
294                 throw;
295             }
296         }
297         delete iter;
298     }
299   
300   // Load SAML policies.
301   if (ini->exists(SHIBTARGET_POLICIES)) {
302     log.info("loading SAML policies");
303     ShibINI::Iterator* iter = ini->tag_iterator(SHIBTARGET_POLICIES);
304
305     for (const string* str = iter->begin(); str; str = iter->next()) {
306         policies.push_back(XMLString::transcode(ini->get(SHIBTARGET_POLICIES, *str).c_str()));
307     }
308     delete iter;
309   }
310   
311   if (app == SHIBTARGET_SHIRE && ini->get_tag(app, SHIBTARGET_TAG_APPMAPPER, false, &tag)) {
312     saml::XML::registerSchema(shibtarget::XML::APPMAP_NS,shibtarget::XML::APPMAP_SCHEMA_ID);
313     try {
314         auto_ptr_XMLCh src(tag.c_str());
315         dummy->setAttributeNS(NULL,url,src.get());
316         m_applicationMapper=new XMLApplicationMapper(dummy);
317         dynamic_cast<XMLApplicationMapper*>(m_applicationMapper)->getImplementation();
318     }
319     catch (exception& e) {
320         log.crit("caught exception while loading URL->Application mapping file (%s)", e.what());
321     }
322     catch (...) {
323         log.crit("caught unknown exception while loading URL->Application mapping file");
324     }
325   }
326   
327     dummydoc->release();
328
329   // Initialize the SHAR Cache
330   if (app == SHIBTARGET_SHAR) {
331     const char * cache_type = NULL;
332     if (ini->get_tag (app, SHIBTARGET_TAG_CACHETYPE, true, &tag))
333       cache_type = tag.c_str();
334
335     g_shibTargetCCache = CCache::getInstance(cache_type);
336   }
337
338   // Process socket settings.
339   m_SocketName=ini->get(SHIBTARGET_GENERAL, "sharsocket");
340   if (m_SocketName.empty())
341     m_SocketName=SHIB_SHAR_SOCKET;
342
343 #ifdef WANT_TCP_SHAR
344   string sockacl=ini->get(SHIBTARGET_SHAR, "sharacl");
345   if (sockacl.length()>0)
346   {
347     int j = 0;
348     for (int i = 0;  i < sockacl.length();  i++)
349     {
350         if (sockacl.at(i)==' ')
351         {
352             string addr=sockacl.substr(j, i-j);
353             j = i+1;
354             m_SocketACL.push_back(addr);
355         }
356     }
357     string addr=sockacl.substr(j, sockacl.length()-j);
358     m_SocketACL.push_back(addr);
359   }
360   else
361     m_SocketACL.push_back("127.0.0.1");
362 #endif
363
364   ref();
365   log.debug("finished");
366 }
367
368 STConfig::~STConfig()
369 {
370   delete m_applicationMapper;
371
372   for (vector<const XMLCh*>::iterator i=policies.begin(); i!=policies.end(); i++)
373     delete const_cast<XMLCh*>(*i);
374
375   for (vector<IMetadata*>::iterator j=metadatas.begin(); j!=metadatas.end(); j++)
376     delete (*j);
377
378   for (vector<ITrust*>::iterator k=trusts.begin(); k!=trusts.end(); k++)
379     delete (*k);
380     
381   for (vector<ICredentials*>::iterator l=creds.begin(); l!=creds.end(); l++)
382     delete (*l);
383
384   for (vector<IAAP*>::iterator m=aaps.begin(); m!=aaps.end(); m++)
385     delete (*m);
386
387   delete g_shibTargetCCache;
388   delete ini;
389
390   shibConf.term();
391   samlConf.term();
392 }
393
394 void STConfig::ref()
395 {
396   refcount++;
397 }
398
399 void STConfig::shutdown()
400 {
401   refcount--;
402   if (!refcount) {
403     delete g_Config;
404     g_Config = NULL;
405   }
406 }
407
408 extern "C" const char* shib_target_sockname(void)
409 {
410     return g_Config ? g_Config->m_SocketName.c_str() : NULL;
411 }
412
413 extern "C" const char* shib_target_sockacl(unsigned int index)
414 {
415 #ifdef WANT_TCP_SHAR
416     if (g_Config && index<g_Config->m_SocketACL.size())
417         return g_Config->m_SocketACL[index].c_str();
418 #endif
419     return NULL;
420 }
421
422 ApplicationMapper::ApplicationMapper() : m_mapper(ShibTargetConfig::getConfig().getApplicationMapper())
423 {
424     if (!m_mapper)
425         throw runtime_error("application mapper not initialized, check log for errors");
426     m_mapper->lock();
427 }