port scott's cgiparse code into a C++ class.
[shibboleth/cpp-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   // Init SAML Binding Configuration
166   if (ini->get_tag (app, SHIBTARGET_TAG_AATIMEOUT, true, &tag))
167     samlConf.binding_defaults.timeout = atoi(tag.c_str());
168   if (ini->get_tag (app, SHIBTARGET_TAG_AACONNECTTO, true, &tag))
169     samlConf.binding_defaults.conn_timeout = atoi(tag.c_str());
170   if (ini->get_tag (app, SHIBTARGET_TAG_CERTFILE, true, &tag))
171       log.error("using OBSOLETE certfile setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
172   if (ini->get_tag (app, SHIBTARGET_TAG_KEYFILE, true, &tag))
173       log.error("using OBSOLETE keyfile setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
174   if (ini->get_tag (app, SHIBTARGET_TAG_KEYPASS, true, &tag))
175       log.error("using OBSOLETE keypass setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
176   if (ini->get_tag (app, SHIBTARGET_TAG_CALIST, true, &tag))
177       log.error("using OBSOLETE calist setting, please use the XML-based trust format (see the latest target deploy guide)");
178
179   try {
180     if (!samlConf.init()) {
181       log.fatal ("Failed to initialize SAML Library");
182       throw runtime_error ("Failed to initialize SAML Library");
183     } else
184       log.debug ("SAML Initialized");
185   } catch (...) {
186     log.crit ("Died initializing SAML Library");
187     throw;    
188   }
189
190   // Init Shib
191   try { 
192     if (!shibConf.init()) {
193       log.fatal ("Failed to initialize Shib library");
194       throw runtime_error ("Failed to initialize Shib Library");
195     } else
196       log.debug ("Shib Initialized");
197   } catch (...) {
198     log.crit ("Failed initializing Shib library.");
199     throw;
200   }
201
202   // Load any SAML extensions
203   string ext = "extensions:saml";
204   if (ini->exists(ext)) {
205     saml::NDC ndc("load_extensions");
206     ShibINI::Iterator* iter = ini->tag_iterator(ext);
207
208     for (const string* str = iter->begin(); str; str = iter->next()) {
209       string file = ini->get(ext, *str);
210       try
211       {
212         samlConf.saml_register_extension(file.c_str(),ini);
213         log.debug("%s: loading %s", str->c_str(), file.c_str());
214       }
215       catch (SAMLException& e)
216       {
217         log.crit("%s: %s", str->c_str(), e.what());
218       }
219     }
220     delete iter;
221   }
222
223     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(NULL);
224     DOMDocument* dummydoc=impl->createDocument();
225     DOMElement* dummy = dummydoc->createElementNS(NULL,XML::Literals::ApplicationMap);
226
227     // Load the specified metadata, trust, creds, and aap sources.
228     const string* prov;
229     ShibINI::Iterator* iter=ini->tag_iterator(SHIBTARGET_TAG_METADATA);
230     for (prov=iter->begin(); prov; prov=iter->next()) {
231         string source=ini->get(SHIBTARGET_TAG_METADATA,*prov);
232         log.info("building metadata provider: type=%s, source=%s",prov->c_str(),source.c_str());
233         try {
234             auto_ptr_XMLCh src(source.c_str());
235             dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
236             metadatas.push_back(shibConf.newMetadata(prov->c_str(),dummy));
237         }
238         catch (exception& e) {
239             log.crit("error building metadata provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
240             if (app == SHIBTARGET_SHAR)
241                 throw;
242         }
243     }
244     delete iter;
245
246     iter=ini->tag_iterator(SHIBTARGET_TAG_AAP);
247     for (prov=iter->begin(); prov; prov=iter->next()) {
248         string source=ini->get(SHIBTARGET_TAG_AAP,*prov);
249         log.info("building AAP provider: type=%s, source=%s",prov->c_str(),source.c_str());
250         try {
251             auto_ptr_XMLCh src(source.c_str());
252             dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
253             aaps.push_back(shibConf.newAAP(prov->c_str(),dummy));
254         }
255         catch (exception& e) {
256             log.crit("error building AAP provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
257             if (app == SHIBTARGET_SHAR)
258                 throw;
259         }
260     }
261     delete iter;
262     
263     if (app == SHIBTARGET_SHAR) {
264         iter=ini->tag_iterator(SHIBTARGET_TAG_TRUST);
265         for (prov=iter->begin(); prov; prov=iter->next()) {
266             string source=ini->get(SHIBTARGET_TAG_TRUST,*prov);
267             log.info("building trust provider: type=%s, source=%s",prov->c_str(),source.c_str());
268             try {
269                 auto_ptr_XMLCh src(source.c_str());
270                 dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
271                 trusts.push_back(shibConf.newTrust(prov->c_str(),dummy));
272             }
273             catch (exception& e) {
274                 log.crit("error building trust provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
275                 throw;
276             }
277         }
278         delete iter;
279     
280         iter=ini->tag_iterator(SHIBTARGET_TAG_CREDS);
281         for (prov=iter->begin(); prov; prov=iter->next()) {
282             string source=ini->get(SHIBTARGET_TAG_CREDS,*prov);
283             log.info("building creds provider: type=%s, source=%s",prov->c_str(),source.c_str());
284             try {
285                 auto_ptr_XMLCh src(source.c_str());
286                 dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
287                 creds.push_back(shibConf.newCredentials(prov->c_str(),dummy));
288             }
289             catch (exception& e) {
290                 log.crit("error building creds provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
291                 throw;
292             }
293         }
294         delete iter;
295     }
296   
297   // Load SAML policies.
298   if (ini->exists(SHIBTARGET_POLICIES)) {
299     log.info("loading SAML policies");
300     ShibINI::Iterator* iter = ini->tag_iterator(SHIBTARGET_POLICIES);
301
302     for (const string* str = iter->begin(); str; str = iter->next()) {
303         policies.push_back(XMLString::transcode(ini->get(SHIBTARGET_POLICIES, *str).c_str()));
304     }
305     delete iter;
306   }
307   
308   log.debug("about to test for AppMapper -- are we SHIRE...");
309   if (app == SHIBTARGET_SHIRE) {
310     log.debug("yep, we're a shire -- try loading the map...");
311     if (ini->get_tag(app, SHIBTARGET_TAG_APPMAPPER, false, &tag)) {
312       log.debug("loading Application Mapper");
313       saml::XML::registerSchema(shibtarget::XML::APPMAP_NS,shibtarget::XML::APPMAP_SCHEMA_ID);
314       try {
315         auto_ptr_XMLCh src(tag.c_str());
316         dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
317         m_applicationMapper=new XMLApplicationMapper(dummy);
318         dynamic_cast<XMLApplicationMapper*>(m_applicationMapper)->getImplementation();
319       }
320       catch (exception& e) {
321         log.crit("caught exception while loading URL->Application mapping file (%s)", e.what());
322       }
323       catch (...) {
324         log.crit("caught unknown exception while loading URL->Application mapping file");
325       }
326     }
327   }
328   
329     dummydoc->release();
330
331   // Initialize the SHAR Cache
332   if (app == SHIBTARGET_SHAR) {
333     const char * cache_type = NULL;
334     if (ini->get_tag (app, SHIBTARGET_TAG_CACHETYPE, true, &tag))
335       cache_type = tag.c_str();
336
337     g_shibTargetCCache = CCache::getInstance(cache_type);
338   }
339
340   // Process socket settings.
341   m_SocketName=ini->get(SHIBTARGET_GENERAL, "sharsocket");
342   if (m_SocketName.empty())
343     m_SocketName=SHIB_SHAR_SOCKET;
344
345 #ifdef WANT_TCP_SHAR
346   string sockacl=ini->get(SHIBTARGET_SHAR, "sharacl");
347   if (sockacl.length()>0)
348   {
349     int j = 0;
350     for (int i = 0;  i < sockacl.length();  i++)
351     {
352         if (sockacl.at(i)==' ')
353         {
354             string addr=sockacl.substr(j, i-j);
355             j = i+1;
356             m_SocketACL.push_back(addr);
357         }
358     }
359     string addr=sockacl.substr(j, sockacl.length()-j);
360     m_SocketACL.push_back(addr);
361   }
362   else
363     m_SocketACL.push_back("127.0.0.1");
364 #endif
365
366   ref();
367   log.debug("finished");
368 }
369
370 STConfig::~STConfig()
371 {
372   delete m_applicationMapper;
373
374   for (vector<const XMLCh*>::iterator i=policies.begin(); i!=policies.end(); i++)
375     delete const_cast<XMLCh*>(*i);
376
377   for (vector<IMetadata*>::iterator j=metadatas.begin(); j!=metadatas.end(); j++)
378     delete (*j);
379
380   for (vector<ITrust*>::iterator k=trusts.begin(); k!=trusts.end(); k++)
381     delete (*k);
382     
383   for (vector<ICredentials*>::iterator l=creds.begin(); l!=creds.end(); l++)
384     delete (*l);
385
386   for (vector<IAAP*>::iterator m=aaps.begin(); m!=aaps.end(); m++)
387     delete (*m);
388
389   delete g_shibTargetCCache;
390   delete ini;
391
392   shibConf.term();
393   samlConf.term();
394 }
395
396 void STConfig::ref()
397 {
398   refcount++;
399 }
400
401 void STConfig::shutdown()
402 {
403   refcount--;
404   if (!refcount) {
405     delete g_Config;
406     g_Config = NULL;
407   }
408 }
409
410 extern "C" const char* shib_target_sockname(void)
411 {
412     return g_Config ? g_Config->m_SocketName.c_str() : NULL;
413 }
414
415 extern "C" const char* shib_target_sockacl(unsigned int index)
416 {
417 #ifdef WANT_TCP_SHAR
418     if (g_Config && index<g_Config->m_SocketACL.size())
419         return g_Config->m_SocketACL[index].c_str();
420 #endif
421     return NULL;
422 }
423
424 ApplicationMapper::ApplicationMapper() : m_mapper(ShibTargetConfig::getConfig().getApplicationMapper())
425 {
426     if (!m_mapper)
427         throw runtime_error("application mapper not initialized, check log for errors");
428     m_mapper->lock();
429 }