2 * Copyright 2001-2008 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * A thread-safe pool of parsers that share characteristics.
24 #include "exceptions.h"
27 #include "util/ParserPool.h"
28 #include "util/XMLHelper.h"
32 #include <sys/types.h>
34 #include <xercesc/util/PlatformUtils.hpp>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xercesc/sax/SAXException.hpp>
37 #include <xercesc/framework/MemBufInputSource.hpp>
38 #include <xercesc/framework/LocalFileInputSource.hpp>
39 #include <xercesc/framework/Wrapper4InputSource.hpp>
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
43 using namespace xercesc;
48 class MyErrorHandler : public DOMErrorHandler {
52 MyErrorHandler() : errors(0) {}
54 bool handleError(const DOMError& e)
57 xmltooling::NDC ndc("handleError");
59 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
61 DOMLocator* locator=e.getLocation();
62 auto_ptr_char temp(e.getMessage());
64 switch (e.getSeverity()) {
65 case DOMError::DOM_SEVERITY_WARNING:
66 log.warnStream() << "warning on line " << locator->getLineNumber()
67 << ", column " << locator->getColumnNumber()
68 << ", message: " << temp.get() << logging::eol;
71 case DOMError::DOM_SEVERITY_ERROR:
73 log.errorStream() << "error on line " << locator->getLineNumber()
74 << ", column " << locator->getColumnNumber()
75 << ", message: " << temp.get() << logging::eol;
78 case DOMError::DOM_SEVERITY_FATAL_ERROR:
80 log.errorStream() << "fatal error on line " << locator->getLineNumber()
81 << ", column " << locator->getColumnNumber()
82 << ", message: " << temp.get() << logging::eol;
87 log.errorStream() << "undefined error type on line " << locator->getLineNumber()
88 << ", column " << locator->getColumnNumber()
89 << ", message: " << temp.get() << logging::eol;
96 ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
97 : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(Mutex::create()), m_security(new SecurityManager()) {}
99 ParserPool::~ParserPool()
101 while(!m_pool.empty()) {
102 m_pool.top()->release();
109 DOMDocument* ParserPool::newDocument()
111 return DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
114 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
116 DOMDocument* ParserPool::parse(DOMLSInput& domsrc)
118 DOMLSParser* parser=checkoutBuilder();
119 XercesJanitor<DOMLSParser> janitor(parser);
122 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, dynamic_cast<DOMErrorHandler*>(&deh));
123 DOMDocument* doc=parser->parse(&domsrc);
127 throw XMLParserException("XML error(s) during parsing, check log for specifics");
129 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
130 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
131 checkinBuilder(janitor.release());
134 catch (XMLException& ex) {
135 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
136 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
137 checkinBuilder(janitor.release());
138 auto_ptr_char temp(ex.getMessage());
139 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
141 catch (XMLToolingException&) {
142 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
143 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
144 checkinBuilder(janitor.release());
151 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
153 DOMBuilder* parser=checkoutBuilder();
154 XercesJanitor<DOMBuilder> janitor(parser);
157 parser->setErrorHandler(&deh);
158 DOMDocument* doc=parser->parse(domsrc);
162 throw XMLParserException("XML error(s) during parsing, check log for specifics");
164 parser->setErrorHandler(NULL);
165 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
166 checkinBuilder(janitor.release());
169 catch (XMLException& ex) {
170 parser->setErrorHandler(NULL);
171 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
172 checkinBuilder(janitor.release());
173 auto_ptr_char temp(ex.getMessage());
174 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
176 catch (XMLToolingException&) {
177 parser->setErrorHandler(NULL);
178 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
179 checkinBuilder(janitor.release());
186 DOMDocument* ParserPool::parse(istream& is)
188 StreamInputSource src(is);
189 Wrapper4InputSource domsrc(&src,false);
190 return parse(domsrc);
193 // Functor to double its argument separated by a character and append to a buffer
194 template <class T> class doubleit
197 doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
198 void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
200 const typename T::value_type& sep;
203 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
205 // Just check the pathname and then directly register the pair into the map.
207 auto_ptr_char p(pathname);
209 struct _stat stat_buf;
210 if (_stat(p.get(), &stat_buf) != 0)
212 struct stat stat_buf;
213 if (stat(p.get(), &stat_buf) != 0)
217 xmltooling::NDC ndc("loadSchema");
219 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
220 auto_ptr_char n(nsURI);
221 log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
227 m_schemaLocMap[nsURI]=pathname;
228 m_schemaLocations.erase();
229 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
231 auto_ptr_char n(nsURI);
232 m_schemaLocMap[n.get()]=p.get();
233 m_schemaLocations.erase();
234 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
240 bool ParserPool::loadCatalog(const XMLCh* pathname)
243 xmltooling::NDC ndc("loadCatalog");
245 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
248 static const XMLCh catalog[] = UNICODE_LITERAL_7(c,a,t,a,l,o,g);
249 static const XMLCh system[] = UNICODE_LITERAL_6(s,y,s,t,e,m);
250 static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
251 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
252 static const XMLCh CATALOG_NS[] = {
253 chLatin_u, chLatin_r, chLatin_n, chColon,
254 chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
255 chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
256 chLatin_t, chLatin_c, chColon,
257 chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
258 chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
259 chLatin_x, chLatin_m, chLatin_l, chColon,
260 chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
263 // Parse the catalog with the internal parser pool.
265 if (log.isDebugEnabled()) {
266 auto_ptr_char temp(pathname);
267 log.debug("loading XML catalog from %s", temp.get());
270 LocalFileInputSource fsrc(NULL,pathname);
271 Wrapper4InputSource domsrc(&fsrc,false);
273 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
274 XercesJanitor<DOMDocument> janitor(doc);
276 // Check root element.
277 const DOMElement* root=doc->getDocumentElement();
278 if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
279 auto_ptr_char temp(pathname);
280 log.error("unknown root element, failed to load XML catalog from %s", temp.get());
284 // Fetch all the <system> elements.
285 DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
287 for (XMLSize_t i=0; i<mappings->getLength(); i++) {
288 root=static_cast<DOMElement*>(mappings->item(i));
289 const XMLCh* from=root->getAttributeNS(NULL,systemId);
290 const XMLCh* to=root->getAttributeNS(NULL,uri);
292 m_schemaLocMap[from]=to;
294 auto_ptr_char f(from);
296 m_schemaLocMap[f.get()]=t.get();
299 m_schemaLocations.erase();
301 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
303 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
306 catch (exception& e) {
307 log.error("catalog loader caught exception: %s", e.what());
314 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
315 DOMLSInput* ParserPool::resolveResource(
316 const XMLCh *const resourceType,
317 const XMLCh *const namespaceUri,
318 const XMLCh *const publicId,
319 const XMLCh *const systemId,
320 const XMLCh *const baseURI
323 DOMInputSource* ParserPool::resolveEntity(
324 const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI
329 xmltooling::NDC ndc("resolveEntity");
334 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
335 if (log.isDebugEnabled()) {
336 auto_ptr_char sysId(systemId);
337 auto_ptr_char base(baseURI);
338 log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
342 // Find well-known schemas in the specified location.
343 map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
344 if (i!=m_schemaLocMap.end())
345 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
347 // Check for entity as a value in the map.
348 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
349 if (XMLString::endsWith(i->second.c_str(), systemId))
350 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
353 // We'll allow anything without embedded slashes.
354 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
355 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
357 // Find well-known schemas in the specified location.
358 auto_ptr_char temp(systemId);
359 map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
360 if (i!=m_schemaLocMap.end()) {
361 auto_ptr_XMLCh temp2(i->second.c_str());
362 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
365 // Check for entity as a value in the map.
366 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
367 auto_ptr_XMLCh temp2(i->second.c_str());
368 if (XMLString::endsWith(temp2.get(), systemId))
369 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
372 // We'll allow anything without embedded slashes.
373 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
374 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
377 // Shortcircuit the request.
379 auto_ptr_char temp(systemId);
381 log.debug("unauthorized entity request (%s), blocking it", temp.get());
382 static const XMLByte nullbuf[] = {0};
383 return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
386 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
388 DOMLSParser* ParserPool::createBuilder()
390 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
391 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
392 DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,NULL);
393 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
395 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
396 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
397 parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
398 parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);
400 // We build a "fake" schema location hint that binds each namespace to itself.
401 // 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 auto_ptr_XMLCh temp(m_schemaLocations.c_str());
406 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp.get()));
409 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
410 parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
411 parser->getDomConfig()->setParameter(XMLUni::fgDOMResourceResolver, dynamic_cast<DOMLSResourceResolver*>(this));
412 parser->getDomConfig()->setParameter(XMLUni::fgXercesSecurityManager, m_security);
416 DOMLSParser* ParserPool::checkoutBuilder()
419 if (m_pool.empty()) {
420 DOMLSParser* builder=createBuilder();
423 DOMLSParser* p=m_pool.top();
427 p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
429 auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
430 p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp2.get()));
436 void ParserPool::checkinBuilder(DOMLSParser* builder)
440 m_pool.push(builder);
446 DOMBuilder* ParserPool::createBuilder()
448 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
449 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
450 DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
451 parser->setFeature(XMLUni::fgDOMNamespaces, m_namespaceAware);
453 parser->setFeature(XMLUni::fgDOMNamespaces, true);
454 parser->setFeature(XMLUni::fgXercesSchema, true);
455 parser->setFeature(XMLUni::fgDOMValidation, true);
456 parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
458 // We build a "fake" schema location hint that binds each namespace to itself.
459 // This ensures the entity resolver will be given the namespace as a systemId it can check.
461 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
463 auto_ptr_XMLCh temp(m_schemaLocations.c_str());
464 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
467 parser->setProperty(XMLUni::fgXercesSecurityManager, m_security);
468 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
469 parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
470 parser->setEntityResolver(this);
474 DOMBuilder* ParserPool::checkoutBuilder()
477 if (m_pool.empty()) {
478 DOMBuilder* builder=createBuilder();
481 DOMBuilder* p=m_pool.top();
485 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
487 auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
488 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
494 void ParserPool::checkinBuilder(DOMBuilder* builder)
498 m_pool.push(builder);
504 xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
506 XMLByte* target=toFill;
507 xsecsize_t bytes_read=0,request=maxToRead;
509 // Fulfill the rest by reading from the stream.
510 if (request && !m_is.eof() && !m_is.fail()) {
512 m_is.read(reinterpret_cast<char* const>(target),request);
513 m_pos+=m_is.gcount();
514 bytes_read+=m_is.gcount();
516 catch(ios_base::failure& e) {
517 Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
518 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()