Merge branch '1.x' of ssh://authdev.it.ohio-state.edu/~scantor/git/cpp-xmltooling...
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ParserPool.cpp
index 7001a86..576f3f7 100644 (file)
@@ -1,30 +1,36 @@
-/*
- *  Copyright 2001-2008 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
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
+ *
+ * UCAID licenses this file to you 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
+ * 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.
+ * 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.
  */
 
 /**
  * ParserPool.cpp
- * 
+ *
  * A thread-safe pool of parsers that share characteristics.
  */
 
 #include "internal.h"
 #include "exceptions.h"
 #include "logging.h"
+#include "util/CurlURLInputStream.h"
 #include "util/NDC.h"
 #include "util/ParserPool.h"
+#include "util/Threads.h"
 #include "util/XMLHelper.h"
 
 #include <algorithm>
@@ -108,7 +114,7 @@ ParserPool::~ParserPool()
 
 DOMDocument* ParserPool::newDocument()
 {
-    return DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
+    return DOMImplementationRegistry::getDOMImplementation(nullptr)->createDocument();
 }
 
 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
@@ -122,23 +128,24 @@ DOMDocument* ParserPool::parse(DOMLSInput& domsrc)
         parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, dynamic_cast<DOMErrorHandler*>(&deh));
         DOMDocument* doc=parser->parse(&domsrc);
         if (deh.errors) {
-            doc->release();
+            if (doc)
+                doc->release();
             throw XMLParserException("XML error(s) during parsing, check log for specifics");
         }
-        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
+        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         return doc;
     }
     catch (XMLException& ex) {
-        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
+        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         auto_ptr_char temp(ex.getMessage());
         throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
     }
     catch (XMLToolingException&) {
-        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
+        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         throw;
@@ -156,23 +163,24 @@ DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
         parser->setErrorHandler(&deh);
         DOMDocument* doc=parser->parse(domsrc);
         if (deh.errors) {
-            doc->release();
+            if (doc)
+                doc->release();
             throw XMLParserException("XML error(s) during parsing, check log for specifics");
         }
-        parser->setErrorHandler(NULL);
+        parser->setErrorHandler(nullptr);
         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         return doc;
     }
     catch (XMLException& ex) {
-        parser->setErrorHandler(NULL);
+        parser->setErrorHandler(nullptr);
         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         auto_ptr_char temp(ex.getMessage());
         throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
     }
     catch (XMLToolingException&) {
-        parser->setErrorHandler(NULL);
+        parser->setErrorHandler(nullptr);
         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
         checkinBuilder(janitor.release());
         throw;
@@ -201,7 +209,7 @@ public:
 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
 {
     // Just check the pathname and then directly register the pair into the map.
-    
+
     auto_ptr_char p(pathname);
 #ifdef WIN32
     struct _stat stat_buf;
@@ -221,16 +229,9 @@ bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
     }
 
     Lock lock(m_lock);
-#ifdef HAVE_GOOD_STL
     m_schemaLocMap[nsURI]=pathname;
     m_schemaLocations.erase();
     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
-#else
-    auto_ptr_char n(nsURI);
-    m_schemaLocMap[n.get()]=p.get();
-    m_schemaLocations.erase();
-    for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
-#endif
 
     return true;
 }
@@ -265,12 +266,12 @@ bool ParserPool::loadCatalog(const XMLCh* pathname)
         log.debug("loading XML catalog from %s", temp.get());
     }
 
-    LocalFileInputSource fsrc(NULL,pathname);
+    LocalFileInputSource fsrc(nullptr,pathname);
     Wrapper4InputSource domsrc(&fsrc,false);
     try {
         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
         XercesJanitor<DOMDocument> janitor(doc);
-        
+
         // Check root element.
         const DOMElement* root=doc->getDocumentElement();
         if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
@@ -278,28 +279,18 @@ bool ParserPool::loadCatalog(const XMLCh* pathname)
             log.error("unknown root element, failed to load XML catalog from %s", temp.get());
             return false;
         }
-        
+
         // Fetch all the <system> elements.
         DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
         Lock lock(m_lock);
         for (XMLSize_t i=0; i<mappings->getLength(); i++) {
             root=static_cast<DOMElement*>(mappings->item(i));
-            const XMLCh* from=root->getAttributeNS(NULL,systemId);
-            const XMLCh* to=root->getAttributeNS(NULL,uri);
-#ifdef HAVE_GOOD_STL
+            const XMLCh* from=root->getAttributeNS(nullptr,systemId);
+            const XMLCh* to=root->getAttributeNS(nullptr,uri);
             m_schemaLocMap[from]=to;
-#else
-            auto_ptr_char f(from);
-            auto_ptr_char t(to);
-            m_schemaLocMap[f.get()]=t.get();
-#endif
         }
         m_schemaLocations.erase();
-#ifdef HAVE_GOOD_STL
         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
-#else
-        for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
-#endif
     }
     catch (exception& e) {
         log.error("catalog loader caught exception: %s", e.what());
@@ -327,7 +318,7 @@ DOMInputSource* ParserPool::resolveEntity(
     xmltooling::NDC ndc("resolveEntity");
 #endif
     if (!systemId)
-        return NULL;
+        return nullptr;
 
     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
     if (log.isDebugEnabled()) {
@@ -336,7 +327,6 @@ DOMInputSource* ParserPool::resolveEntity(
         log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
     }
 
-#ifdef HAVE_GOOD_STL
     // Find well-known schemas in the specified location.
     map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
     if (i!=m_schemaLocMap.end())
@@ -351,31 +341,9 @@ DOMInputSource* ParserPool::resolveEntity(
     // We'll allow anything without embedded slashes.
     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
-#else
-    // Find well-known schemas in the specified location.
-    auto_ptr_char temp(systemId);
-    map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
-    if (i!=m_schemaLocMap.end()) {
-        auto_ptr_XMLCh temp2(i->second.c_str());
-        return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
-    }
-
-    // Check for entity as a value in the map.
-    for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
-        auto_ptr_XMLCh temp2(i->second.c_str());
-        if (XMLString::endsWith(temp2.get(), systemId))
-            return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
-    }
-
-    // We'll allow anything without embedded slashes.
-    if (XMLString::indexOf(systemId, chForwardSlash)==-1)
-        return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
-#endif    
 
     // Shortcircuit the request.
-#ifdef HAVE_GOOD_STL
     auto_ptr_char temp(systemId);
-#endif
     log.debug("unauthorized entity request (%s), blocking it", temp.get());
     static const XMLByte nullbuf[] = {0};
     return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
@@ -387,22 +355,17 @@ DOMLSParser* ParserPool::createBuilder()
 {
     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
-    DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,NULL);
+    DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,nullptr);
     parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
     if (m_schemaAware) {
         parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
         parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
         parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
         parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);
-        
+
         // We build a "fake" schema location hint that binds each namespace to itself.
-        // This ensures the entity resolver will be given the namespace as a systemId it can check. 
-#ifdef HAVE_GOOD_STL
+        // This ensures the entity resolver will be given the namespace as a systemId it can check.
         parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
-#else
-        auto_ptr_XMLCh temp(m_schemaLocations.c_str());
-        parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp.get()));
-#endif
     }
     parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
     parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
@@ -420,14 +383,8 @@ DOMLSParser* ParserPool::checkoutBuilder()
     }
     DOMLSParser* p=m_pool.top();
     m_pool.pop();
-    if (m_schemaAware) {
-#ifdef HAVE_GOOD_STL
+    if (m_schemaAware)
         p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
-#else
-        auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
-        p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp2.get()));
-#endif
-    }
     return p;
 }
 
@@ -452,18 +409,14 @@ DOMBuilder* ParserPool::createBuilder()
         parser->setFeature(XMLUni::fgXercesSchema, true);
         parser->setFeature(XMLUni::fgDOMValidation, true);
         parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
-        
+
         // We build a "fake" schema location hint that binds each namespace to itself.
-        // This ensures the entity resolver will be given the namespace as a systemId it can check. 
-#ifdef HAVE_GOOD_STL
+        // This ensures the entity resolver will be given the namespace as a systemId it can check.
         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
-#else
-        auto_ptr_XMLCh temp(m_schemaLocations.c_str());
-        parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
-#endif
     }
     parser->setProperty(XMLUni::fgXercesSecurityManager, m_security);
     parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
+    parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
     parser->setEntityResolver(this);
     return parser;
 }
@@ -477,14 +430,8 @@ DOMBuilder* ParserPool::checkoutBuilder()
     }
     DOMBuilder* p=m_pool.top();
     m_pool.pop();
-    if (m_schemaAware) {
-#ifdef HAVE_GOOD_STL
+    if (m_schemaAware)
         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
-#else
-        auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
-        p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
-#endif
-    }
     return p;
 }
 
@@ -498,6 +445,36 @@ void ParserPool::checkinBuilder(DOMBuilder* builder)
 
 #endif
 
+StreamInputSource::StreamInputSource(istream& is, const char* systemId) : InputSource(systemId), m_is(is)
+{
+}
+
+BinInputStream* StreamInputSource::makeStream() const
+{
+    return new StreamBinInputStream(m_is);
+}
+
+StreamInputSource::StreamBinInputStream::StreamBinInputStream(istream& is) : m_is(is), m_pos(0)
+{
+}
+
+#ifdef XMLTOOLING_XERCESC_64BITSAFE
+XMLFilePos
+#else
+unsigned int
+#endif
+StreamInputSource::StreamBinInputStream::curPos() const
+{
+    return m_pos;
+}
+
+#ifdef XMLTOOLING_XERCESC_64BITSAFE
+const XMLCh* StreamInputSource::StreamBinInputStream::getContentType() const
+{
+    return nullptr;
+}
+#endif
+
 xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
 {
     XMLByte* target=toFill;
@@ -520,3 +497,53 @@ xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toF
     }
     return bytes_read;
 }
+
+#ifdef XMLTOOLING_LITE
+
+URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag) : InputSource(systemId), m_url(url)
+{
+}
+
+URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag) : InputSource(systemId)
+{
+    static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
+    static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);
+
+    const XMLCh* attr = e->getAttributeNS(nullptr, url);
+    if (!attr || !*attr) {
+        attr = e->getAttributeNS(nullptr, uri);
+        if (!attr || !*attr)
+            throw IOException("No URL supplied via DOM to URLInputSource constructor.");
+    }
+
+    m_url.setURL(attr);
+}
+
+BinInputStream* URLInputSource::makeStream() const
+{
+    // Ask the URL to create us an appropriate input stream
+    return m_url.makeNewStream();
+}
+
+#else
+
+URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag)
+    : InputSource(systemId), m_cacheTag(cacheTag), m_url(url), m_root(nullptr)
+{
+}
+
+URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag)
+    : InputSource(systemId), m_cacheTag(cacheTag), m_root(e)
+{
+}
+
+BinInputStream* URLInputSource::makeStream() const
+{
+    return m_root ? new CurlURLInputStream(m_root, m_cacheTag) : new CurlURLInputStream(m_url.get(), m_cacheTag);
+}
+
+#endif
+
+const char URLInputSource::asciiStatusCodeElementName[] = "URLInputSourceStatus";
+
+const XMLCh URLInputSource::utf16StatusCodeElementName[] = UNICODE_LITERAL_20(U,R,L,I,n,p,u,t,S,o,u,r,c,e,S,t,a,t,u,s);