Move Shib constants to new lib, fixed symbol conflicts.
[shibboleth/cpp-sp.git] / shib-target / shib-config.cpp
index 0854e47..263e216 100644 (file)
@@ -1,50 +1,17 @@
 /*
- * The Shibboleth License, Version 1.
- * Copyright (c) 2002
- * University Corporation for Advanced Internet Development, Inc.
- * All rights reserved
+ *  Copyright 2001-2005 Internet2
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution, if any, must include
- * the following acknowledgment: "This product includes software developed by
- * the University Corporation for Advanced Internet Development
- * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
- * may appear in the software itself, if and wherever such third-party
- * acknowledgments normally appear.
- *
- * Neither the name of Shibboleth nor the names of its contributors, nor
- * Internet2, nor the University Corporation for Advanced Internet Development,
- * Inc., nor UCAID may be used to endorse or promote products derived from this
- * software without specific prior written permission. For written permission,
- * please contact shibboleth@shibboleth.org
- *
- * Products derived from this software may not be called Shibboleth, Internet2,
- * UCAID, or the University Corporation for Advanced Internet Development, nor
- * may Shibboleth appear in their name, without prior written permission of the
- * University Corporation for Advanced Internet Development.
- *
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
- * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
- * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
- * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 /*
  */
 
 #include "internal.h"
+#include <shibsp/SPConfig.h>
+#include <shibsp/SPConstants.h>
+#include <xmltooling/XMLToolingConfig.h>
+#include <xmltooling/util/NDC.h>
 
-#include <shib/shib-threads.h>
+#include <log4cpp/OstreamAppender.hh>
 
-#include <log4cpp/PropertyConfigurator.hh>
-#include <log4cpp/Category.hh>
-
-#ifndef SHIBTARGET_INIFILE
-#define SHIBTARGET_INIFILE "/opt/shibboleth/etc/shibboleth/shibboleth.ini"
-#endif
-
-using namespace std;
-using namespace log4cpp;
-using namespace saml;
-using namespace shibboleth;
+using namespace shibsp;
 using namespace shibtarget;
+using namespace shibboleth;
+using namespace saml;
+using namespace log4cpp;
+using namespace std;
 
-namespace {
-  STConfig * g_Config = NULL;
-  Mutex * g_lock = NULL;
-}
-
-CCache* shibtarget::g_shibTargetCCache = NULL;
-
-
-/****************************************************************************/
-// External Interface
-
+using xmltooling::XMLToolingConfig;
 
-void ShibTargetConfig::preinit()
-{
-  if (g_lock) return;
-  g_lock = Mutex::create();
+namespace {
+    STConfig g_Config;
 }
 
-ShibTargetConfig& ShibTargetConfig::init(const char* app_name, const char* inifile)
-{
-  if (!g_lock)
-    throw runtime_error ("ShibTargetConfig not pre-initialized");
-
-  if (!app_name)
-    throw runtime_error ("No Application name");
-  Lock lock(g_lock);
-
-  if (g_Config) {
-    g_Config->ref();
-    return *g_Config;
-  }
-
-  g_Config = new STConfig(app_name, inifile);
-  g_Config->init();
-  return *g_Config;
-}
+// Factories for built-in plugins we can manufacture. Actual definitions
+// will be with the actual object implementation.
+#ifndef WIN32
+PlugManager::Factory UnixListenerFactory;
+#endif
+PlugManager::Factory TCPListenerFactory;
+//PlugManager::Factory MemoryListenerFactory;
+PlugManager::Factory MemoryCacheFactory;
+PlugManager::Factory XMLRequestMapFactory;
+PlugManager::Factory ShibSessionInitiatorFactory;
+PlugManager::Factory SAML1POSTFactory;
+PlugManager::Factory SAML1ArtifactFactory;
+PlugManager::Factory ShibLogoutFactory;
+//PlugManager::Factory htaccessFactory;
+
+SAML_EXCEPTION_FACTORY(ListenerException);
+SAML_EXCEPTION_FACTORY(ConfigurationException);
 
 ShibTargetConfig& ShibTargetConfig::getConfig()
 {
-    if (!g_Config)
-        throw SAMLException("ShibTargetConfig::getConfig() called with NULL configuration");
-    return *g_Config;
+    return g_Config;
 }
 
-/****************************************************************************/
-// STConfig
-
-STConfig::STConfig(const char* app_name, const char* inifile)
-  :  samlConf(SAMLConfig::getConfig()), shibConf(ShibConfig::getConfig()),
-     m_app_name(app_name), m_applicationMapper(NULL), refcount(0)
+bool STConfig::init(const char* schemadir)
 {
-  try {
-    ini = new ShibINI((inifile ? inifile : SHIBTARGET_INIFILE));
-  } catch (...) {
-    cerr << "Unable to load the INI file: " << 
-      (inifile ? inifile : SHIBTARGET_INIFILE) << endl;
-    throw;
-  }
-}
-
-void STConfig::init()
-{
-  string app = m_app_name;
-  string tag;
+#ifdef _DEBUG
+    xmltooling::NDC ndc("init");
+#endif
+    Category& log = Category::getInstance("shibtarget.Config");
 
-  // Initialize Log4cpp
-  if (ini->get_tag (app, SHIBTARGET_TAG_LOGGER, true, &tag)) {
-    cerr << "Loading new logging configuration from " << tag << "\n";
-    try {
-      PropertyConfigurator::configure(tag);
-      cerr << "New logging configuration loaded, check log destination for process status..." << "\n";
-    } catch (ConfigureFailure& e) {
-      cerr << "Error reading configuration: " << e.what() << "\n";
+    if (!schemadir) {
+        log.fatal("XML schema directory not supplied");
+        return false;
     }
-  } else {
-    Category& category = Category::getRoot();
-    category.setPriority(log4cpp::Priority::DEBUG);
-    cerr << "No logger configuration found\n";
-  }
-
-  Category& log = Category::getInstance("shibtarget.STConfig");
-
-  saml::NDC ndc("STConfig::init");
-
-  // Init SAML Configuration
-  if (ini->get_tag (app, SHIBTARGET_TAG_SAMLCOMPAT, true, &tag))
-    samlConf.compatibility_mode = ShibINI::boolean(tag);
-  if (ini->get_tag (app, SHIBTARGET_TAG_SCHEMAS, true, &tag))
-    samlConf.schema_dir = tag;
-
-  // Init SAML Binding Configuration
-  if (ini->get_tag (app, SHIBTARGET_TAG_AATIMEOUT, true, &tag))
-    samlConf.binding_defaults.timeout = atoi(tag.c_str());
-  if (ini->get_tag (app, SHIBTARGET_TAG_AACONNECTTO, true, &tag))
-    samlConf.binding_defaults.conn_timeout = atoi(tag.c_str());
-  if (ini->get_tag (app, SHIBTARGET_TAG_CERTFILE, true, &tag))
-      log.error("using OBSOLETE certfile setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
-  if (ini->get_tag (app, SHIBTARGET_TAG_KEYFILE, true, &tag))
-      log.error("using OBSOLETE keyfile setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
-  if (ini->get_tag (app, SHIBTARGET_TAG_KEYPASS, true, &tag))
-      log.error("using OBSOLETE keypass setting, please migrate to the XML-based credential format (see the latest target deploy guide)");
-  if (ini->get_tag (app, SHIBTARGET_TAG_CALIST, true, &tag))
-      log.error("using OBSOLETE calist setting, please use the XML-based trust format (see the latest target deploy guide)");
 
-  try {
-    if (!samlConf.init()) {
-      log.fatal ("Failed to initialize SAML Library");
-      throw runtime_error ("Failed to initialize SAML Library");
-    } else
-      log.debug ("SAML Initialized");
-  } catch (...) {
-    log.crit ("Died initializing SAML Library");
-    throw;    
-  }
+    // This will cause some extra console logging, but for now,
+    // initialize the underlying libraries.
+    SAMLConfig& samlConf=SAMLConfig::getConfig();
+    if (schemadir)
+        samlConf.schema_dir = schemadir;
+    if (!samlConf.init() || !SPConfig::getConfig().init(NULL)) {
+        log.fatal("failed to initialize SP library");
+        return false;
+    }
 
-  // Init Shib
-  try { 
+    ShibConfig& shibConf=ShibConfig::getConfig();
     if (!shibConf.init()) {
-      log.fatal ("Failed to initialize Shib library");
-      throw runtime_error ("Failed to initialize Shib Library");
-    } else
-      log.debug ("Shib Initialized");
-  } catch (...) {
-    log.crit ("Failed initializing Shib library.");
-    throw;
-  }
-
-  // Load any SAML extensions
-  string ext = "extensions:saml";
-  if (ini->exists(ext)) {
-    saml::NDC ndc("load_extensions");
-    ShibINI::Iterator* iter = ini->tag_iterator(ext);
-
-    for (const string* str = iter->begin(); str; str = iter->next()) {
-      string file = ini->get(ext, *str);
-      try
-      {
-        samlConf.saml_register_extension(file.c_str(),ini);
-        log.debug("%s: loading %s", str->c_str(), file.c_str());
-      }
-      catch (SAMLException& e)
-      {
-        log.crit("%s: %s", str->c_str(), e.what());
-      }
+        log.fatal("Failed to initialize Shib library");
+        samlConf.term();
+        return false;
     }
-    delete iter;
-  }
 
-    DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(NULL);
-    DOMDocument* dummydoc=impl->createDocument();
-    DOMElement* dummy = dummydoc->createElementNS(NULL,XML::Literals::ApplicationMap);
-
-    // Load the specified metadata, trust, creds, and aap sources.
-    const string* prov;
-    ShibINI::Iterator* iter=ini->tag_iterator(SHIBTARGET_TAG_METADATA);
-    for (prov=iter->begin(); prov; prov=iter->next()) {
-        string source=ini->get(SHIBTARGET_TAG_METADATA,*prov);
-        log.info("building metadata provider: type=%s, source=%s",prov->c_str(),source.c_str());
-        try {
-            auto_ptr_XMLCh src(source.c_str());
-            dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
-            metadatas.push_back(shibConf.newMetadata(prov->c_str(),dummy));
-        }
-        catch (exception& e) {
-            log.crit("error building metadata provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
-            if (app == SHIBTARGET_SHAR)
-                throw;
-        }
-    }
-    delete iter;
+    // Register built-in plugin types.
+    REGISTER_EXCEPTION_FACTORY(ListenerException);
+    REGISTER_EXCEPTION_FACTORY(ConfigurationException);
 
-    iter=ini->tag_iterator(SHIBTARGET_TAG_AAP);
-    for (prov=iter->begin(); prov; prov=iter->next()) {
-        string source=ini->get(SHIBTARGET_TAG_AAP,*prov);
-        log.info("building AAP provider: type=%s, source=%s",prov->c_str(),source.c_str());
-        try {
-            auto_ptr_XMLCh src(source.c_str());
-            dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
-            aaps.push_back(shibConf.newAAP(prov->c_str(),dummy));
-        }
-        catch (exception& e) {
-            log.crit("error building AAP provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
-            if (app == SHIBTARGET_SHAR)
-                throw;
-        }
-    }
-    delete iter;
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::MemorySessionCacheType,&MemoryCacheFactory);
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&XMLRequestMapFactory);
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::XMLRequestMapType,&XMLRequestMapFactory);
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&XMLRequestMapFactory);
     
-    if (app == SHIBTARGET_SHAR) {
-        iter=ini->tag_iterator(SHIBTARGET_TAG_TRUST);
-        for (prov=iter->begin(); prov; prov=iter->next()) {
-            string source=ini->get(SHIBTARGET_TAG_TRUST,*prov);
-            log.info("building trust provider: type=%s, source=%s",prov->c_str(),source.c_str());
-            try {
-                auto_ptr_XMLCh src(source.c_str());
-                dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
-                trusts.push_back(shibConf.newTrust(prov->c_str(),dummy));
-            }
-            catch (exception& e) {
-                log.crit("error building trust provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
-                throw;
-            }
-        }
-        delete iter;
+    auto_ptr_char temp1(shibspconstants::SHIB1_SESSIONINIT_PROFILE_URI);
+    samlConf.getPlugMgr().regFactory(temp1.get(),&ShibSessionInitiatorFactory);
+    samlConf.getPlugMgr().regFactory(samlconstants::SAML1_PROFILE_BROWSER_POST,&SAML1POSTFactory);
+    samlConf.getPlugMgr().regFactory(samlconstants::SAML1_PROFILE_BROWSER_ARTIFACT,&SAML1ArtifactFactory);
+    auto_ptr_char temp4(shibspconstants::SHIB1_LOGOUT_PROFILE_URI);
+    samlConf.getPlugMgr().regFactory(temp4.get(),&ShibLogoutFactory);
     
-        iter=ini->tag_iterator(SHIBTARGET_TAG_CREDS);
-        for (prov=iter->begin(); prov; prov=iter->next()) {
-            string source=ini->get(SHIBTARGET_TAG_CREDS,*prov);
-            log.info("building creds provider: type=%s, source=%s",prov->c_str(),source.c_str());
-            try {
-                auto_ptr_XMLCh src(source.c_str());
-                dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
-                creds.push_back(shibConf.newCredentials(prov->c_str(),dummy));
-            }
-            catch (exception& e) {
-                log.crit("error building creds provider: type=%s, source=%s (%s)",prov->c_str(),source.c_str(),e.what());
-                throw;
-            }
-        }
-        delete iter;
-    }
-  
-  // Load SAML policies.
-  if (ini->exists(SHIBTARGET_POLICIES)) {
-    log.info("loading SAML policies");
-    ShibINI::Iterator* iter = ini->tag_iterator(SHIBTARGET_POLICIES);
+    saml::XML::registerSchema(shibtarget::XML::SHIBTARGET_NS,shibtarget::XML::SHIBTARGET_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(samlconstants::SAML20MD_NS,shibtarget::XML::SAML2META_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(samlconstants::SAML20_NS,shibtarget::XML::SAML2ASSERT_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(xmlconstants::XMLENC_NS,shibtarget::XML::XMLENC_SCHEMA_ID,NULL,false);
+    
+    log.info("finished initializing");
+    return true;
+}
+
+bool STConfig::load(const char* config)
+{
+#ifdef _DEBUG
+    xmltooling::NDC ndc("load");
+#endif
+    Category& log = Category::getInstance("shibtarget.Config");
 
-    for (const string* str = iter->begin(); str; str = iter->next()) {
-        policies.push_back(XMLString::transcode(ini->get(SHIBTARGET_POLICIES, *str).c_str()));
+    if (!config) {
+        log.fatal("path to configuration file not supplied");
+        shutdown();
+        return false;
     }
-    delete iter;
-  }
-  
-  if (app == SHIBTARGET_SHIRE && ini->get_tag(app, SHIBTARGET_TAG_APPMAPPER, false, &tag)) {
-    saml::XML::registerSchema(shibtarget::XML::APPMAP_NS,shibtarget::XML::APPMAP_SCHEMA_ID);
+
     try {
-        auto_ptr_XMLCh src(tag.c_str());
-        dummy->setAttributeNS(NULL,shibboleth::XML::Literals::url,src.get());
-        m_applicationMapper=new XMLApplicationMapper(dummy);
-        dynamic_cast<XMLApplicationMapper*>(m_applicationMapper)->getImplementation();
+        log.info("loading configuration file: %s", config);
+        static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
+        DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(NULL);
+        DOMDocument* dummydoc=impl->createDocument();
+        DOMElement* dummy = dummydoc->createElementNS(NULL,XML::Literals::ShibbolethTargetConfig);
+        auto_ptr_XMLCh src(config);
+        dummy->setAttributeNS(NULL,uri,src.get());
+        m_ini=ShibTargetConfigFactory(dummy);
+        dummydoc->release();
+        m_ini->init();
+        
+        pair<bool,unsigned int> skew=m_ini->getUnsignedInt("clockSkew");
+        SAMLConfig::getConfig().clock_skew_secs=skew.first ? skew.second : 180;
+        if (skew.first)
+            XMLToolingConfig::getConfig().clock_skew_secs=skew.second;
+        
+        m_tranLog=new FixedContextCategory(SHIBTRAN_LOGCAT);
+        m_tranLog->info("opened transaction log");
+        m_tranLogLock = xmltooling::Mutex::create();
     }
-    catch (exception& e) {
-        log.crit("caught exception while loading URL->Application mapping file (%s)", e.what());
+    catch (SAMLException& ex) {
+        log.fatal("caught exception while loading/initializing configuration: %s",ex.what());
+        shutdown();
+        return false;
     }
+#ifndef _DEBUG
     catch (...) {
-        log.crit("caught unknown exception while loading URL->Application mapping file");
-    }
-  }
-  
-    dummydoc->release();
-
-  // Initialize the SHAR Cache
-  if (app == SHIBTARGET_SHAR) {
-    const char * cache_type = NULL;
-    if (ini->get_tag (app, SHIBTARGET_TAG_CACHETYPE, true, &tag))
-      cache_type = tag.c_str();
-
-    g_shibTargetCCache = CCache::getInstance(cache_type);
-  }
-
-  // Process socket settings.
-  m_SocketName=ini->get(SHIBTARGET_GENERAL, "sharsocket");
-  if (m_SocketName.empty())
-    m_SocketName=SHIB_SHAR_SOCKET;
-
-#ifdef WANT_TCP_SHAR
-  string sockacl=ini->get(SHIBTARGET_SHAR, "sharacl");
-  if (sockacl.length()>0)
-  {
-    int j = 0;
-    for (int i = 0;  i < sockacl.length();  i++)
-    {
-        if (sockacl.at(i)==' ')
-        {
-            string addr=sockacl.substr(j, i-j);
-            j = i+1;
-            m_SocketACL.push_back(addr);
-        }
+        log.fatal("caught exception while loading/initializing configuration");
+        shutdown();
+        return false;
     }
-    string addr=sockacl.substr(j, sockacl.length()-j);
-    m_SocketACL.push_back(addr);
-  }
-  else
-    m_SocketACL.push_back("127.0.0.1");
 #endif
 
-  ref();
-  log.debug("finished");
-}
-
-STConfig::~STConfig()
-{
-  delete m_applicationMapper;
-
-  for (vector<const XMLCh*>::iterator i=policies.begin(); i!=policies.end(); i++)
-    delete const_cast<XMLCh*>(*i);
-
-  for (vector<IMetadata*>::iterator j=metadatas.begin(); j!=metadatas.end(); j++)
-    delete (*j);
-
-  for (vector<ITrust*>::iterator k=trusts.begin(); k!=trusts.end(); k++)
-    delete (*k);
-    
-  for (vector<ICredentials*>::iterator l=creds.begin(); l!=creds.end(); l++)
-    delete (*l);
-
-  for (vector<IAAP*>::iterator m=aaps.begin(); m!=aaps.end(); m++)
-    delete (*m);
-
-  delete g_shibTargetCCache;
-  delete ini;
-
-  shibConf.term();
-  samlConf.term();
-}
-
-void STConfig::ref()
-{
-  refcount++;
+    log.info("finished loading configuration");
+    return true;
 }
 
 void STConfig::shutdown()
 {
-  refcount--;
-  if (!refcount) {
-    delete g_Config;
-    g_Config = NULL;
-  }
-}
-
-extern "C" const char* shib_target_sockname(void)
-{
-    return g_Config ? g_Config->m_SocketName.c_str() : NULL;
-}
-
-extern "C" const char* shib_target_sockacl(unsigned int index)
-{
-#ifdef WANT_TCP_SHAR
-    if (g_Config && index<g_Config->m_SocketACL.size())
-        return g_Config->m_SocketACL[index].c_str();
+#ifdef _DEBUG
+    xmltooling::NDC ndc("shutdown");
 #endif
-    return NULL;
-}
-
-ApplicationMapper::ApplicationMapper() : m_mapper(ShibTargetConfig::getConfig().getApplicationMapper())
-{
-    if (!m_mapper)
-        throw runtime_error("application mapper not initialized, check log for errors");
-    m_mapper->lock();
+    Category& log = Category::getInstance("shibtarget.Config");
+    log.info("shutting down the library");
+    delete m_tranLogLock;
+    m_tranLogLock = NULL;
+    //delete m_tranLog; // This is crashing for some reason, but we're shutting down anyway.
+    delete m_ini;
+    m_ini = NULL;
+    ShibConfig::getConfig().term();
+    SAMLConfig::getConfig().term();
+    SPConfig::getConfig().term();
+    log.info("library shutdown complete");
 }