2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
24 * A thread-safe pool of parsers that share characteristics.
28 #include "exceptions.h"
30 #include "util/CurlURLInputStream.h"
32 #include "util/PathResolver.h"
33 #include "util/ParserPool.h"
34 #include "util/Threads.h"
35 #include "util/XMLHelper.h"
37 #include <sys/types.h>
41 #include <boost/algorithm/string.hpp>
42 #include <boost/bind.hpp>
43 #include <xercesc/util/PlatformUtils.hpp>
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xercesc/sax/SAXException.hpp>
46 #include <xercesc/framework/MemBufInputSource.hpp>
47 #include <xercesc/framework/LocalFileInputSource.hpp>
48 #include <xercesc/framework/Wrapper4InputSource.hpp>
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
52 using namespace xercesc;
53 using namespace boost;
58 class MyErrorHandler : public DOMErrorHandler {
62 MyErrorHandler() : errors(0) {}
64 bool handleError(const DOMError& e)
67 xmltooling::NDC ndc("handleError");
69 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
71 DOMLocator* locator=e.getLocation();
72 auto_ptr_char temp(e.getMessage());
74 switch (e.getSeverity()) {
75 case DOMError::DOM_SEVERITY_WARNING:
76 log.warnStream() << "warning on line " << locator->getLineNumber()
77 << ", column " << locator->getColumnNumber()
78 << ", message: " << temp.get() << logging::eol;
81 case DOMError::DOM_SEVERITY_ERROR:
83 log.errorStream() << "error on line " << locator->getLineNumber()
84 << ", column " << locator->getColumnNumber()
85 << ", message: " << temp.get() << logging::eol;
88 case DOMError::DOM_SEVERITY_FATAL_ERROR:
90 log.errorStream() << "fatal error on line " << locator->getLineNumber()
91 << ", column " << locator->getColumnNumber()
92 << ", message: " << temp.get() << logging::eol;
97 log.errorStream() << "undefined error type on line " << locator->getLineNumber()
98 << ", column " << locator->getColumnNumber()
99 << ", message: " << temp.get() << logging::eol;
106 ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
107 : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(Mutex::create()), m_security(new SecurityManager()) {}
109 ParserPool::~ParserPool()
111 while(!m_pool.empty()) {
112 m_pool.top()->release();
117 DOMDocument* ParserPool::newDocument()
119 return DOMImplementationRegistry::getDOMImplementation(nullptr)->createDocument();
122 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
124 DOMDocument* ParserPool::parse(DOMLSInput& domsrc)
126 DOMLSParser* parser=checkoutBuilder();
127 XercesJanitor<DOMLSParser> janitor(parser);
130 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, dynamic_cast<DOMErrorHandler*>(&deh));
131 DOMDocument* doc=parser->parse(&domsrc);
135 throw XMLParserException("XML error(s) during parsing, check log for specifics");
137 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
138 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
139 checkinBuilder(janitor.release());
142 catch (XMLException& ex) {
143 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
144 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
145 checkinBuilder(janitor.release());
146 auto_ptr_char temp(ex.getMessage());
147 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
149 catch (XMLToolingException&) {
150 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
151 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
152 checkinBuilder(janitor.release());
159 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
161 DOMBuilder* parser=checkoutBuilder();
162 XercesJanitor<DOMBuilder> janitor(parser);
165 parser->setErrorHandler(&deh);
166 DOMDocument* doc=parser->parse(domsrc);
170 throw XMLParserException("XML error(s) during parsing, check log for specifics");
172 parser->setErrorHandler(nullptr);
173 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
174 checkinBuilder(janitor.release());
177 catch (XMLException& ex) {
178 parser->setErrorHandler(nullptr);
179 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
180 checkinBuilder(janitor.release());
181 auto_ptr_char temp(ex.getMessage());
182 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
184 catch (XMLToolingException&) {
185 parser->setErrorHandler(nullptr);
186 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
187 checkinBuilder(janitor.release());
194 DOMDocument* ParserPool::parse(istream& is)
196 StreamInputSource src(is);
197 Wrapper4InputSource domsrc(&src,false);
198 return parse(domsrc);
201 // Functor to double its argument separated by a character and append to a buffer
202 template <class T> class doubleit {
204 doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
205 void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
207 const typename T::value_type& sep;
210 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
212 // Just check the pathname and then directly register the pair into the map.
214 auto_ptr_char p(pathname);
216 struct _stat stat_buf;
217 if (_stat(p.get(), &stat_buf) != 0)
219 struct stat stat_buf;
220 if (stat(p.get(), &stat_buf) != 0)
224 xmltooling::NDC ndc("loadSchema");
226 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
227 auto_ptr_char n(nsURI);
228 log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
232 // Roundtrip to local code page and back to translate path as needed.
233 string topath(p.get());
234 XMLToolingConfig::getConfig().getPathResolver()->resolve(topath, PathResolver::XMLTOOLING_XML_FILE);
235 auto_ptr_XMLCh temp(topath.c_str());
238 m_schemaLocMap[nsURI] = temp.get();
239 m_schemaLocations.erase();
240 for_each(m_schemaLocMap.begin(), m_schemaLocMap.end(), doubleit<xstring>(m_schemaLocations,chSpace));
245 bool ParserPool::loadCatalogs(const char* pathnames)
247 string temp(pathnames);
248 vector<string> catpaths;
249 split(catpaths, temp, is_any_of(PATH_SEPARATOR_STR), algorithm::token_compress_on);
250 static bool (ParserPool::* lc)(const char*) = &ParserPool::loadCatalog;
251 for_each(catpaths.begin(), catpaths.end(), boost::bind(lc, this, boost::bind(&string::c_str, _1)));
252 return !catpaths.empty();
255 bool ParserPool::loadCatalog(const char* pathname)
258 XMLToolingConfig::getConfig().getPathResolver()->resolve(p, PathResolver::XMLTOOLING_XML_FILE);
259 auto_ptr_XMLCh temp(p.c_str());
260 return loadCatalog(temp.get());
263 bool ParserPool::loadCatalog(const XMLCh* pathname)
266 xmltooling::NDC ndc("loadCatalog");
268 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
271 static const XMLCh catalog[] = UNICODE_LITERAL_7(c,a,t,a,l,o,g);
272 static const XMLCh system[] = UNICODE_LITERAL_6(s,y,s,t,e,m);
273 static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
274 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
275 static const XMLCh CATALOG_NS[] = {
276 chLatin_u, chLatin_r, chLatin_n, chColon,
277 chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
278 chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
279 chLatin_t, chLatin_c, chColon,
280 chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
281 chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
282 chLatin_x, chLatin_m, chLatin_l, chColon,
283 chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
286 // Parse the catalog with the internal parser pool.
288 if (log.isDebugEnabled()) {
289 auto_ptr_char temp(pathname);
290 log.debug("loading XML catalog from %s", temp.get());
293 LocalFileInputSource fsrc(nullptr,pathname);
294 Wrapper4InputSource domsrc(&fsrc,false);
296 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
297 XercesJanitor<DOMDocument> janitor(doc);
299 // Check root element.
300 const DOMElement* root=doc->getDocumentElement();
301 if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
302 auto_ptr_char temp(pathname);
303 log.error("unknown root element, failed to load XML catalog from %s", temp.get());
307 // Fetch all the <system> elements.
308 DOMNodeList* mappings = root->getElementsByTagNameNS(CATALOG_NS,system);
310 for (XMLSize_t i = 0; i < mappings->getLength(); i++) {
311 root = static_cast<DOMElement*>(mappings->item(i));
312 const XMLCh* from = root->getAttributeNS(nullptr,systemId);
313 const XMLCh* to = root->getAttributeNS(nullptr,uri);
315 // Roundtrip to local code page and back to translate path as needed.
316 auto_ptr_char temp(to);
317 string topath(temp.get());
318 XMLToolingConfig::getConfig().getPathResolver()->resolve(topath, PathResolver::XMLTOOLING_XML_FILE);
319 auto_ptr_XMLCh temp2(topath.c_str());
321 m_schemaLocMap[from] = temp2.get();
323 m_schemaLocations.erase();
324 for_each(m_schemaLocMap.begin(), m_schemaLocMap.end(), doubleit<xstring>(m_schemaLocations,chSpace));
326 catch (std::exception& e) {
327 log.error("catalog loader caught exception: %s", e.what());
334 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
335 DOMLSInput* ParserPool::resolveResource(
336 const XMLCh *const resourceType,
337 const XMLCh *const namespaceUri,
338 const XMLCh *const publicId,
339 const XMLCh *const systemId,
340 const XMLCh *const baseURI
343 DOMInputSource* ParserPool::resolveEntity(
344 const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI
349 xmltooling::NDC ndc("resolveEntity");
353 xstring sysId(systemId);
355 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
356 if (log.isDebugEnabled()) {
357 auto_ptr_char sysId(systemId);
358 auto_ptr_char base(baseURI);
359 log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
362 // Find well-known schemas in the specified location.
363 map<xstring,xstring>::const_iterator i = m_schemaLocMap.find(sysId);
364 if (i != m_schemaLocMap.end())
365 return new Wrapper4InputSource(new LocalFileInputSource(baseURI, i->second.c_str()));
367 // Check for entity as a suffix of a value in the map.
368 bool (*p_ends_with)(const xstring&, const xstring&) = ends_with;
370 m_schemaLocMap.begin(), m_schemaLocMap.end(),
371 boost::bind(p_ends_with, boost::bind(&map<xstring,xstring>::value_type::second, _1), boost::ref(sysId))
373 if (i != m_schemaLocMap.end())
374 return new Wrapper4InputSource(new LocalFileInputSource(baseURI, i->second.c_str()));
376 // We'll allow anything without embedded slashes.
377 if (XMLString::indexOf(systemId, chForwardSlash) == -1 && XMLString::indexOf(systemId, chBackSlash) == -1)
378 return new Wrapper4InputSource(new LocalFileInputSource(baseURI, systemId));
380 // Shortcircuit the request.
381 auto_ptr_char temp(systemId);
382 log.debug("unauthorized entity request (%s), blocking it", temp.get());
383 static const XMLByte nullbuf[] = {0};
384 return new Wrapper4InputSource(new MemBufInputSource(nullbuf, 0, systemId));
387 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
389 DOMLSParser* ParserPool::createBuilder()
391 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
392 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
393 DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,nullptr);
394 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
396 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
397 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
398 parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
399 parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);
401 // We build a "fake" schema location hint that binds each namespace to itself.
402 // This ensures the entity resolver will be given the namespace as a systemId it can check.
403 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
405 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
406 parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
407 parser->getDomConfig()->setParameter(XMLUni::fgDOMResourceResolver, dynamic_cast<DOMLSResourceResolver*>(this));
408 parser->getDomConfig()->setParameter(XMLUni::fgXercesSecurityManager, m_security.get());
412 DOMLSParser* ParserPool::checkoutBuilder()
415 if (m_pool.empty()) {
416 DOMLSParser* builder=createBuilder();
419 DOMLSParser* p=m_pool.top();
422 p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
426 void ParserPool::checkinBuilder(DOMLSParser* builder)
430 m_pool.push(builder);
436 DOMBuilder* ParserPool::createBuilder()
438 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
439 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
440 DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
441 parser->setFeature(XMLUni::fgDOMNamespaces, m_namespaceAware);
443 parser->setFeature(XMLUni::fgDOMNamespaces, true);
444 parser->setFeature(XMLUni::fgXercesSchema, true);
445 parser->setFeature(XMLUni::fgDOMValidation, true);
446 parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
448 // We build a "fake" schema location hint that binds each namespace to itself.
449 // This ensures the entity resolver will be given the namespace as a systemId it can check.
450 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
452 parser->setProperty(XMLUni::fgXercesSecurityManager, m_security.get());
453 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
454 parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
455 parser->setEntityResolver(this);
459 DOMBuilder* ParserPool::checkoutBuilder()
462 if (m_pool.empty()) {
463 DOMBuilder* builder=createBuilder();
466 DOMBuilder* p=m_pool.top();
469 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
473 void ParserPool::checkinBuilder(DOMBuilder* builder)
477 m_pool.push(builder);
483 StreamInputSource::StreamInputSource(istream& is, const char* systemId) : InputSource(systemId), m_is(is)
487 BinInputStream* StreamInputSource::makeStream() const
489 return new StreamBinInputStream(m_is);
492 StreamInputSource::StreamBinInputStream::StreamBinInputStream(istream& is) : m_is(is), m_pos(0)
496 #ifdef XMLTOOLING_XERCESC_64BITSAFE
501 StreamInputSource::StreamBinInputStream::curPos() const
506 #ifdef XMLTOOLING_XERCESC_64BITSAFE
507 const XMLCh* StreamInputSource::StreamBinInputStream::getContentType() const
513 xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
515 XMLByte* target=toFill;
516 xsecsize_t bytes_read=0,request=maxToRead;
518 // Fulfill the rest by reading from the stream.
519 if (request && !m_is.eof() && !m_is.fail()) {
521 m_is.read(reinterpret_cast<char* const>(target),request);
522 m_pos+=m_is.gcount();
523 bytes_read+=m_is.gcount();
525 catch(ios_base::failure& e) {
526 Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
527 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
536 #ifdef XMLTOOLING_LITE
538 URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag) : InputSource(systemId), m_url(url)
542 URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag) : InputSource(systemId)
544 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
545 static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);
547 const XMLCh* attr = e->getAttributeNS(nullptr, url);
548 if (!attr || !*attr) {
549 attr = e->getAttributeNS(nullptr, uri);
551 throw IOException("No URL supplied via DOM to URLInputSource constructor.");
557 BinInputStream* URLInputSource::makeStream() const
559 // Ask the URL to create us an appropriate input stream
560 return m_url.makeNewStream();
565 URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag)
566 : InputSource(systemId), m_cacheTag(cacheTag), m_url(url), m_root(nullptr)
570 URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag)
571 : InputSource(systemId), m_cacheTag(cacheTag), m_root(e)
575 BinInputStream* URLInputSource::makeStream() const
577 return m_root ? new CurlURLInputStream(m_root, m_cacheTag) : new CurlURLInputStream(m_url.get(), m_cacheTag);
582 const char URLInputSource::asciiStatusCodeElementName[] = "URLInputSourceStatus";
584 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);