Switched remaining files to Apache license.
[shibboleth/sp.git] / shib-target / shib-config.cpp
index a559064..49c45f3 100644 (file)
@@ -1,4 +1,20 @@
 /*
+ *  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
+ *
+ * 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.
+ */
+
+/*
  * shib-config.cpp -- ShibTarget initialization and finalization routines
  *
  * Created By: Derek Atkins <derek@ihtfp.com>
  * $Id$
  */
 
-#include "shib-target.h"
+#include "internal.h"
 
-#include <log4cpp/PropertyConfigurator.hh>
-#include <log4cpp/Category.hh>
+#include <log4cpp/OstreamAppender.hh>
 
+using namespace std;
+using namespace log4cpp;
 using namespace saml;
 using namespace shibboleth;
 using namespace shibtarget;
-using namespace std;
-
-#ifndef SHIBTARGET_INIFILE
-#define SHIBTARGET_INIFILE "/etc/shibboleth.ini"
-#endif
-
-class STConfig : public ShibTargetConfig
-{
-public:
-  STConfig(const char* app_name, const char* inifile);
-  ~STConfig();
-  void shutdown();
-  ShibINI& getINI() { return *ini; }
-
-  void ref();
-private:
-  SAMLConfig& samlConf;
-  ShibConfig& shibConf;
-  ShibINI* ini;
-  int refcount;
-};
 
 namespace {
-  STConfig * g_Config = NULL;
+    STConfig g_Config;
 }
 
-CCache* shibtarget::g_shibTargetCCache = NULL;
-
-/****************************************************************************/
-// External Interface
-
-
-ShibTargetConfig& ShibTargetConfig::init(const char* app_name, const char* inifile)
+// 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 (!app_name)
-    throw runtime_error ("No Application name");
-
-  if (g_Config) {
-    g_Config->ref();
-    return *g_Config;
-  }
-
-  g_Config = new STConfig(app_name, inifile);
-  return *g_Config;
+    return g_Config;
 }
 
-
-
-/****************************************************************************/
-// Mapper
-
-class DummyMapper : public IOriginSiteMapper
-{
-public:
-    DummyMapper();
-    ~DummyMapper();
-    virtual Iterator<xstring> getHandleServiceNames(const XMLCh* originSite) { return Iterator<xstring>(m_hsnames); }
-    virtual Key* getHandleServiceKey(const XMLCh* handleService) { return NULL; }
-    virtual Iterator<xstring> getSecurityDomains(const XMLCh* originSite);
-    virtual const char* getTrustedRoots() { return SAMLConfig::getConfig().ssl_calist.c_str(); }
-
-private:
-    typedef map<xstring,vector<xstring>*> domains_t;
-    domains_t m_domains;
-    vector<xstring> m_hsnames;
-};
-
-DummyMapper::DummyMapper()
+bool STConfig::init(const char* schemadir)
 {
-    auto_ptr<XMLCh> buf(XMLString::transcode("wayf.internet2.edu"));
-    m_hsnames.push_back(buf.get());
-}
+    // With new build of log4cpp, we need to establish a "default"
+    // logging appender to stderr up front.
+    const char* loglevel=getenv("SHIB_LOGGING");
+    if (!loglevel)
+        loglevel = SHIB_LOGGING;    
+    Category& root = Category::getRoot();
+    if (!strcmp(loglevel,"DEBUG"))
+        root.setPriority(Priority::DEBUG);
+    else if (!strcmp(loglevel,"INFO"))
+        root.setPriority(Priority::INFO);
+    else if (!strcmp(loglevel,"NOTICE"))
+        root.setPriority(Priority::NOTICE);
+    else if (!strcmp(loglevel,"WARN"))
+        root.setPriority(Priority::WARN);
+    else if (!strcmp(loglevel,"ERROR"))
+        root.setPriority(Priority::ERROR);
+    else if (!strcmp(loglevel,"CRIT"))
+        root.setPriority(Priority::CRIT);
+    else if (!strcmp(loglevel,"ALERT"))
+        root.setPriority(Priority::ALERT);
+    else if (!strcmp(loglevel,"EMERG"))
+        root.setPriority(Priority::EMERG);
+    else if (!strcmp(loglevel,"FATAL"))
+        root.setPriority(Priority::FATAL);
+    root.setAppender(new OstreamAppender("default",&cerr));
+#ifdef _DEBUG
+    saml::NDC ndc("init");
+#endif
+    Category& log = Category::getInstance("shibtarget.Config");
 
-Iterator<xstring> DummyMapper::getSecurityDomains(const XMLCh* originSite)
-{
-    domains_t::iterator i=m_domains.find(originSite);
-    if (i==m_domains.end())
-    {
-        vector<xstring>* pv=new vector<xstring>();
-        pv->push_back(originSite);
-        pair<domains_t::iterator,bool> p=m_domains.insert(domains_t::value_type(originSite,pv));
-       i=p.first;
+    if (!schemadir) {
+        log.fatal("XML schema directory not supplied");
+        return false;
     }
-    return Iterator<xstring>(*(i->second));
-}
-
-DummyMapper::~DummyMapper()
-{
-    for (domains_t::iterator i=m_domains.begin(); i!=m_domains.end(); i++)
-        delete i->second;
-}
-
-
 
+    // This will cause some extra console logging, but for now,
+    // initialize the underlying libraries.
+    SAMLConfig& samlConf=SAMLConfig::getConfig();
+    if (schemadir)
+        samlConf.schema_dir = schemadir;
+    try {
+        if (!samlConf.init()) {
+            log.fatal("Failed to initialize SAML Library");
+            return false;
+        }
+    }
+    catch (...) {
+        log.fatal("Died initializing SAML Library");
+        return false;
+    }
+    
+    ShibConfig& shibConf=ShibConfig::getConfig();
+    try { 
+        if (!shibConf.init()) {
+            log.fatal("Failed to initialize Shib library");
+            samlConf.term();
+            return false;
+        }
+    }
+    catch (...) {
+        log.fatal("Died initializing Shib library.");
+        samlConf.term();
+        return false;
+    }
 
-/****************************************************************************/
-// STConfig
+    // Register built-in plugin types.
+    REGISTER_EXCEPTION_FACTORY(ListenerException);
+    REGISTER_EXCEPTION_FACTORY(ConfigurationException);
+#ifndef WIN32
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::UnixListenerType,&UnixListenerFactory);
+#endif
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::TCPListenerType,&TCPListenerFactory);
+    samlConf.getPlugMgr().regFactory(shibtarget::XML::MemoryListenerType,&MemoryListenerFactory);
+    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);
+    
+    auto_ptr_char temp1(Constants::SHIB_SESSIONINIT_PROFILE_URI);
+    samlConf.getPlugMgr().regFactory(temp1.get(),&ShibSessionInitiatorFactory);
+    auto_ptr_char temp2(SAMLBrowserProfile::BROWSER_POST);
+    samlConf.getPlugMgr().regFactory(temp2.get(),&SAML1POSTFactory);
+    auto_ptr_char temp3(SAMLBrowserProfile::BROWSER_ARTIFACT);
+    samlConf.getPlugMgr().regFactory(temp3.get(),&SAML1ArtifactFactory);
+    auto_ptr_char temp4(Constants::SHIB_LOGOUT_PROFILE_URI);
+    samlConf.getPlugMgr().regFactory(temp4.get(),&ShibLogoutFactory);
+    
+    saml::XML::registerSchema(shibtarget::XML::SHIBTARGET_NS,shibtarget::XML::SHIBTARGET_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(shibtarget::XML::SAML2META_NS,shibtarget::XML::SAML2META_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(shibtarget::XML::SAML2ASSERT_NS,shibtarget::XML::SAML2ASSERT_SCHEMA_ID,NULL,false);
+    saml::XML::registerSchema(shibtarget::XML::XMLENC_NS,shibtarget::XML::XMLENC_SCHEMA_ID,NULL,false);
+    
+    log.info("finished initializing");
+    return true;
+}
 
-STConfig::STConfig(const char* app_name, const char* inifile)
-  :  samlConf(SAMLConfig::getConfig()), shibConf(ShibConfig::getConfig())
+bool STConfig::load(const char* config)
 {
-  ini = new ShibINI((inifile ? inifile : SHIBTARGET_INIFILE));
+#ifdef _DEBUG
+    saml::NDC ndc("load");
+#endif
+    Category& log = Category::getInstance("shibtarget.Config");
 
-  string app = app_name;
-  string tag;
+    if (!config) {
+        log.fatal("path to configuration file not supplied");
+        shutdown();
+        return false;
+    }
 
-  // Initialize Log4cpp
-  if (ini->get_tag (app, SHIBTARGET_TAG_LOGGER, true, &tag)) {
-    cerr << "Trying to load logger configuration: " << tag << "\n";
     try {
-      log4cpp::PropertyConfigurator::configure(tag);
-    } catch (log4cpp::ConfigureFailure& e) {
-      cerr << "Error reading configuration: " << e.what() << "\n";
+        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();
+        
+        pair<bool,unsigned int> skew=m_ini->getUnsignedInt("clockSkew");
+        SAMLConfig::getConfig().clock_skew_secs=skew.first ? skew.second : 180;
+        
+        m_tranLog=new FixedContextCategory(SHIBTRAN_LOGCAT);
+        m_tranLog->info("opened transaction log");
+        m_tranLogLock = Mutex::create();
     }
-  } else {
-    log4cpp::Category& category = log4cpp::Category::getRoot();
-    category.setPriority(log4cpp::Priority::DEBUG);
-    cerr << "No logger configuration found\n";
-  }
-
-  log4cpp::Category& log = log4cpp::Category::getInstance("shibtarget.STConfig");
-
-  // Init SAML
-  if (ini->get_tag (app, SHIBTARGET_TAG_SCHEMAS, true, &tag))
-    samlConf.schema_dir = tag;
-  if (ini->get_tag (app, SHIBTARGET_TAG_CERTFILE, true, &tag))
-    samlConf.ssl_certfile = tag;
-  if (ini->get_tag (app, SHIBTARGET_TAG_KEYFILE, true, &tag))
-    samlConf.ssl_keyfile = tag;
-  if (ini->get_tag (app, SHIBTARGET_TAG_KEYPASS, true, &tag))
-    samlConf.ssl_keypass = tag;
-  if (ini->get_tag (app, SHIBTARGET_TAG_CALIST, true, &tag))
-    samlConf.ssl_calist = tag;
-
-  if (!samlConf.init()) {
-    log.error ("Failed to initialize SAML Library");
-    throw runtime_error ("Failed to initialize SAML Library");
-  } else
-    log.debug ("SAML Initialized");
-
-  // Init Shib
-  if (! ini->get_tag (app, SHIBTARGET_TAG_SITES, true, &tag)) {
-    log.crit("No Sites File found in configuration");
-    throw runtime_error ("No Sites File found in configuration");
-  }
-
-  shibConf.origin_mapper = new XMLOriginSiteMapper(tag.c_str(),samlConf.ssl_calist.c_str());
-  
-  if (!shibConf.init()) {
-    log.error ("Failed to initialize Shib library");
-    throw runtime_error ("Failed to initialize Shib Library");
-  } else
-    log.debug ("Shib Initialized");
-
-  // Initialize the SHAR Cache
-  if (!strcmp (app_name, SHIBTARGET_SHAR))
-    g_shibTargetCCache = CCache::getInstance();  
-
-  // Load any extensions
-  string ext = "extensions";
-  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());
-       log.debug("%s: loading %s", str->c_str(), file.c_str());
-      }
-      catch (SAMLException& e)
-      {
-       log.error("%s: %s", str->c_str(), e.what());
-      }
+    catch (SAMLException& ex) {
+        log.fatal("caught exception while loading/initializing configuration: %s",ex.what());
+        shutdown();
+        return false;
     }
-    delete iter;
-  }
-
-  ref();
-  log.debug("finished");
-}
-
-STConfig::~STConfig()
-{
-  if (ini) delete ini;
-  
-  if (g_shibTargetCCache)
-    delete g_shibTargetCCache;
-
-  delete shibConf.origin_mapper;
-  shibConf.term();
-  samlConf.term();
-}
+#ifndef _DEBUG
+    catch (...) {
+        log.fatal("caught exception while loading/initializing configuration");
+        shutdown();
+        return false;
+    }
+#endif
 
-void STConfig::ref()
-{
-  refcount++;
+    log.info("finished loading configuration");
+    return true;
 }
 
 void STConfig::shutdown()
 {
-  refcount--;
-  if (!refcount) {
-    delete g_Config;
-    g_Config = NULL;
-  }
+#ifdef _DEBUG
+    saml::NDC ndc("shutdown");
+#endif
+    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();
+    log.info("library shutdown complete");
 }