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);
126 throw XMLParserException("XML error(s) during parsing, check log for specifics");
128 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
129 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
130 checkinBuilder(janitor.release());
133 catch (XMLException& ex) {
134 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
135 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
136 checkinBuilder(janitor.release());
137 auto_ptr_char temp(ex.getMessage());
138 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
140 catch (XMLToolingException&) {
141 parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)NULL);
142 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
143 checkinBuilder(janitor.release());
150 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
152 DOMBuilder* parser=checkoutBuilder();
153 XercesJanitor<DOMBuilder> janitor(parser);
156 parser->setErrorHandler(&deh);
157 DOMDocument* doc=parser->parse(domsrc);
160 throw XMLParserException("XML error(s) during parsing, check log for specifics");
162 parser->setErrorHandler(NULL);
163 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
164 checkinBuilder(janitor.release());
167 catch (XMLException& ex) {
168 parser->setErrorHandler(NULL);
169 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
170 checkinBuilder(janitor.release());
171 auto_ptr_char temp(ex.getMessage());
172 throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
174 catch (XMLToolingException&) {
175 parser->setErrorHandler(NULL);
176 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
177 checkinBuilder(janitor.release());
184 DOMDocument* ParserPool::parse(istream& is)
186 StreamInputSource src(is);
187 Wrapper4InputSource domsrc(&src,false);
188 return parse(domsrc);
191 // Functor to double its argument separated by a character and append to a buffer
192 template <class T> class doubleit
195 doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
196 void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
198 const typename T::value_type& sep;
201 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
203 // Just check the pathname and then directly register the pair into the map.
205 auto_ptr_char p(pathname);
207 struct _stat stat_buf;
208 if (_stat(p.get(), &stat_buf) != 0)
210 struct stat stat_buf;
211 if (stat(p.get(), &stat_buf) != 0)
215 xmltooling::NDC ndc("loadSchema");
217 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
218 auto_ptr_char n(nsURI);
219 log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
225 m_schemaLocMap[nsURI]=pathname;
226 m_schemaLocations.erase();
227 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
229 auto_ptr_char n(nsURI);
230 m_schemaLocMap[n.get()]=p.get();
231 m_schemaLocations.erase();
232 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
238 bool ParserPool::loadCatalog(const XMLCh* pathname)
241 xmltooling::NDC ndc("loadCatalog");
243 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
246 static const XMLCh catalog[] = UNICODE_LITERAL_7(c,a,t,a,l,o,g);
247 static const XMLCh system[] = UNICODE_LITERAL_6(s,y,s,t,e,m);
248 static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
249 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
250 static const XMLCh CATALOG_NS[] = {
251 chLatin_u, chLatin_r, chLatin_n, chColon,
252 chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
253 chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
254 chLatin_t, chLatin_c, chColon,
255 chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
256 chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
257 chLatin_x, chLatin_m, chLatin_l, chColon,
258 chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
261 // Parse the catalog with the internal parser pool.
263 if (log.isDebugEnabled()) {
264 auto_ptr_char temp(pathname);
265 log.debug("loading XML catalog from %s", temp.get());
268 LocalFileInputSource fsrc(NULL,pathname);
269 Wrapper4InputSource domsrc(&fsrc,false);
271 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
272 XercesJanitor<DOMDocument> janitor(doc);
274 // Check root element.
275 const DOMElement* root=doc->getDocumentElement();
276 if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
277 auto_ptr_char temp(pathname);
278 log.error("unknown root element, failed to load XML catalog from %s", temp.get());
282 // Fetch all the <system> elements.
283 DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
285 for (XMLSize_t i=0; i<mappings->getLength(); i++) {
286 root=static_cast<DOMElement*>(mappings->item(i));
287 const XMLCh* from=root->getAttributeNS(NULL,systemId);
288 const XMLCh* to=root->getAttributeNS(NULL,uri);
290 m_schemaLocMap[from]=to;
292 auto_ptr_char f(from);
294 m_schemaLocMap[f.get()]=t.get();
297 m_schemaLocations.erase();
299 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
301 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
304 catch (exception& e) {
305 log.error("catalog loader caught exception: %s", e.what());
312 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
313 DOMLSInput* ParserPool::resolveResource(
314 const XMLCh *const resourceType,
315 const XMLCh *const namespaceUri,
316 const XMLCh *const publicId,
317 const XMLCh *const systemId,
318 const XMLCh *const baseURI
321 DOMInputSource* ParserPool::resolveEntity(
322 const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI
327 xmltooling::NDC ndc("resolveEntity");
332 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
333 if (log.isDebugEnabled()) {
334 auto_ptr_char sysId(systemId);
335 auto_ptr_char base(baseURI);
336 log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
340 // Find well-known schemas in the specified location.
341 map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
342 if (i!=m_schemaLocMap.end())
343 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
345 // Check for entity as a value in the map.
346 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
347 if (XMLString::endsWith(i->second.c_str(), systemId))
348 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
351 // We'll allow anything without embedded slashes.
352 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
353 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
355 // Find well-known schemas in the specified location.
356 auto_ptr_char temp(systemId);
357 map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
358 if (i!=m_schemaLocMap.end()) {
359 auto_ptr_XMLCh temp2(i->second.c_str());
360 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
363 // Check for entity as a value in the map.
364 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
365 auto_ptr_XMLCh temp2(i->second.c_str());
366 if (XMLString::endsWith(temp2.get(), systemId))
367 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
370 // We'll allow anything without embedded slashes.
371 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
372 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
375 // Shortcircuit the request.
377 auto_ptr_char temp(systemId);
379 log.debug("unauthorized entity request (%s), blocking it", temp.get());
380 static const XMLByte nullbuf[] = {0};
381 return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
384 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
386 DOMLSParser* ParserPool::createBuilder()
388 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
389 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
390 DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,NULL);
391 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
393 parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
394 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
395 parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
396 parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);
398 // We build a "fake" schema location hint that binds each namespace to itself.
399 // This ensures the entity resolver will be given the namespace as a systemId it can check.
401 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
403 auto_ptr_XMLCh temp(m_schemaLocations.c_str());
404 parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp.get()));
407 parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
408 parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
409 parser->getDomConfig()->setParameter(XMLUni::fgDOMResourceResolver, dynamic_cast<DOMLSResourceResolver*>(this));
410 parser->getDomConfig()->setParameter(XMLUni::fgXercesSecurityManager, m_security);
414 DOMLSParser* ParserPool::checkoutBuilder()
417 if (m_pool.empty()) {
418 DOMLSParser* builder=createBuilder();
421 DOMLSParser* p=m_pool.top();
425 p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
427 auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
428 p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(temp2.get()));
434 void ParserPool::checkinBuilder(DOMLSParser* builder)
438 m_pool.push(builder);
444 DOMBuilder* ParserPool::createBuilder()
446 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
447 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
448 DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
449 parser->setFeature(XMLUni::fgDOMNamespaces, m_namespaceAware);
451 parser->setFeature(XMLUni::fgDOMNamespaces, true);
452 parser->setFeature(XMLUni::fgXercesSchema, true);
453 parser->setFeature(XMLUni::fgDOMValidation, true);
454 parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
456 // We build a "fake" schema location hint that binds each namespace to itself.
457 // This ensures the entity resolver will be given the namespace as a systemId it can check.
459 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
461 auto_ptr_XMLCh temp(m_schemaLocations.c_str());
462 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
465 parser->setProperty(XMLUni::fgXercesSecurityManager, m_security);
466 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
467 parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
468 parser->setEntityResolver(this);
472 DOMBuilder* ParserPool::checkoutBuilder()
475 if (m_pool.empty()) {
476 DOMBuilder* builder=createBuilder();
479 DOMBuilder* p=m_pool.top();
483 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
485 auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
486 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
492 void ParserPool::checkinBuilder(DOMBuilder* builder)
496 m_pool.push(builder);
502 xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
504 XMLByte* target=toFill;
505 xsecsize_t bytes_read=0,request=maxToRead;
507 // Fulfill the rest by reading from the stream.
508 if (request && !m_is.eof() && !m_is.fail()) {
510 m_is.read(reinterpret_cast<char* const>(target),request);
511 m_pos+=m_is.gcount();
512 bytes_read+=m_is.gcount();
514 catch(ios_base::failure& e) {
515 Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
516 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()