2 * Copyright 2001-2007 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.
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;
45 ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
46 : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(Mutex::create()) {}
48 ParserPool::~ParserPool()
50 while(!m_pool.empty()) {
51 m_pool.top()->release();
57 DOMDocument* ParserPool::newDocument()
59 return DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
62 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
64 DOMBuilder* parser=checkoutBuilder();
65 XercesJanitor<DOMBuilder> janitor(parser);
67 DOMDocument* doc=parser->parse(domsrc);
68 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
69 checkinBuilder(janitor.release());
72 catch (XMLException&) {
73 checkinBuilder(janitor.release());
76 catch (XMLToolingException&) {
77 checkinBuilder(janitor.release());
82 DOMDocument* ParserPool::parse(istream& is)
84 StreamInputSource src(is);
85 Wrapper4InputSource domsrc(&src,false);
89 // Functor to double its argument separated by a character and append to a buffer
90 template <class T> class doubleit
93 doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
94 void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
96 const typename T::value_type& sep;
99 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
101 // Just check the pathname and then directly register the pair into the map.
103 auto_ptr_char p(pathname);
105 struct _stat stat_buf;
106 if (_stat(p.get(), &stat_buf) != 0)
108 struct stat stat_buf;
109 if (stat(p.get(), &stat_buf) != 0)
113 xmltooling::NDC ndc("loadSchema");
115 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
116 auto_ptr_char n(nsURI);
117 log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
123 m_schemaLocMap[nsURI]=pathname;
124 m_schemaLocations.erase();
125 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
127 auto_ptr_char n(nsURI);
128 m_schemaLocMap[n.get()]=p.get();
129 m_schemaLocations.erase();
130 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
136 bool ParserPool::loadCatalog(const XMLCh* pathname)
139 xmltooling::NDC ndc("loadCatalog");
141 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
144 static const XMLCh catalog[] = UNICODE_LITERAL_7(c,a,t,a,l,o,g);
145 static const XMLCh system[] = UNICODE_LITERAL_6(s,y,s,t,e,m);
146 static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
147 static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
148 static const XMLCh CATALOG_NS[] = {
149 chLatin_u, chLatin_r, chLatin_n, chColon,
150 chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
151 chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
152 chLatin_t, chLatin_c, chColon,
153 chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
154 chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
155 chLatin_x, chLatin_m, chLatin_l, chColon,
156 chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
159 // Parse the catalog with the internal parser pool.
161 if (log.isDebugEnabled()) {
162 auto_ptr_char temp(pathname);
163 log.debug("loading XML catalog from %s", temp.get());
166 LocalFileInputSource fsrc(NULL,pathname);
167 Wrapper4InputSource domsrc(&fsrc,false);
169 DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
170 XercesJanitor<DOMDocument> janitor(doc);
172 // Check root element.
173 const DOMElement* root=doc->getDocumentElement();
174 if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
175 auto_ptr_char temp(pathname);
176 log.error("unknown root element, failed to load XML catalog from %s", temp.get());
180 // Fetch all the <system> elements.
181 DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
183 for (XMLSize_t i=0; i<mappings->getLength(); i++) {
184 root=static_cast<DOMElement*>(mappings->item(i));
185 const XMLCh* from=root->getAttributeNS(NULL,systemId);
186 const XMLCh* to=root->getAttributeNS(NULL,uri);
188 m_schemaLocMap[from]=to;
190 auto_ptr_char f(from);
192 m_schemaLocMap[f.get()]=t.get();
195 m_schemaLocations.erase();
197 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
199 for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
202 catch (exception& e) {
203 log.error("catalog loader caught exception: %s", e.what());
210 DOMInputSource* ParserPool::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI)
213 xmltooling::NDC ndc("resolveEntity");
218 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
219 if (log.isDebugEnabled()) {
220 auto_ptr_char sysId(systemId);
221 auto_ptr_char base(baseURI);
222 log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
226 // Find well-known schemas in the specified location.
227 map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
228 if (i!=m_schemaLocMap.end())
229 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
231 // Check for entity as a value in the map.
232 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
233 if (XMLString::endsWith(i->second.c_str(), systemId))
234 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
237 // We'll allow anything without embedded slashes.
238 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
239 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
241 // Find well-known schemas in the specified location.
242 auto_ptr_char temp(systemId);
243 map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
244 if (i!=m_schemaLocMap.end()) {
245 auto_ptr_XMLCh temp2(i->second.c_str());
246 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
249 // Check for entity as a value in the map.
250 for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
251 auto_ptr_XMLCh temp2(i->second.c_str());
252 if (XMLString::endsWith(temp2.get(), systemId))
253 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
256 // We'll allow anything without embedded slashes.
257 if (XMLString::indexOf(systemId, chForwardSlash)==-1)
258 return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
261 // Shortcircuit the request.
263 auto_ptr_char temp(systemId);
265 log.debug("unauthorized entity request (%s), blocking it", temp.get());
266 static const XMLByte nullbuf[] = {0};
267 return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
270 bool ParserPool::handleError(const DOMError& e)
273 xmltooling::NDC ndc("handleError");
275 Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
276 DOMLocator* locator=e.getLocation();
277 auto_ptr_char temp(e.getMessage());
279 switch (e.getSeverity()) {
280 case DOMError::DOM_SEVERITY_WARNING:
281 log.warnStream() << "warning on line " << locator->getLineNumber()
282 << ", column " << locator->getColumnNumber()
283 << ", message: " << temp.get() << CategoryStream::ENDLINE;
286 case DOMError::DOM_SEVERITY_ERROR:
287 log.errorStream() << "error on line " << locator->getLineNumber()
288 << ", column " << locator->getColumnNumber()
289 << ", message: " << temp.get() << CategoryStream::ENDLINE;
290 throw XMLParserException(string("error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
292 case DOMError::DOM_SEVERITY_FATAL_ERROR:
293 log.critStream() << "fatal error on line " << locator->getLineNumber()
294 << ", column " << locator->getColumnNumber()
295 << ", message: " << temp.get() << CategoryStream::ENDLINE;
296 throw XMLParserException(string("fatal error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
298 throw XMLParserException(string("unclassified error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
301 DOMBuilder* ParserPool::createBuilder()
303 static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
304 DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
305 DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
306 if (m_namespaceAware)
307 parser->setFeature(XMLUni::fgDOMNamespaces,true);
309 parser->setFeature(XMLUni::fgXercesSchema,true);
310 parser->setFeature(XMLUni::fgDOMValidation,true);
311 parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse,true);
312 parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal,true);
314 // We build a "fake" schema location hint that binds each namespace to itself.
315 // This ensures the entity resolver will be given the namespace as a systemId it can check.
317 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
319 auto_ptr_XMLCh temp(m_schemaLocations.c_str());
320 parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
323 parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
324 parser->setEntityResolver(this);
325 parser->setErrorHandler(this);
329 DOMBuilder* ParserPool::checkoutBuilder()
332 if (m_pool.empty()) {
333 DOMBuilder* builder=createBuilder();
336 DOMBuilder* p=m_pool.top();
340 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
342 auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
343 p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
349 void ParserPool::checkinBuilder(DOMBuilder* builder)
353 m_pool.push(builder);
357 unsigned int StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const unsigned int maxToRead)
359 XMLByte* target=toFill;
360 unsigned int bytes_read=0,request=maxToRead;
362 // Fulfill the rest by reading from the stream.
363 if (request && !m_is.eof() && !m_is.fail()) {
365 m_is.read(reinterpret_cast<char* const>(target),request);
366 m_pos+=m_is.gcount();
367 bytes_read+=m_is.gcount();
369 catch(ios_base::failure& e) {
370 Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
371 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
372 << CategoryStream::ENDLINE;