Version 6.4.0.0.beta1, tag libreoffice-6.4.0.0.beta1
[LibreOffice.git] / unoxml / source / dom / documentbuilder.cxx
blob5a03cf0bcf2df50278add4af5b375987cb309915
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include "documentbuilder.hxx"
22 #include <string.h>
23 #include <stdio.h>
24 #include <stdarg.h>
26 #include <libxml/xmlerror.h>
27 #include <libxml/tree.h>
29 #include <memory>
31 #include <rtl/alloc.h>
32 #include <rtl/ustrbuf.hxx>
33 #include <osl/diagnose.h>
34 #include <sal/log.hxx>
35 #include <tools/diagnose_ex.h>
37 #include <comphelper/processfactory.hxx>
38 #include <cppuhelper/implbase.hxx>
39 #include <cppuhelper/supportsservice.hxx>
41 #include <com/sun/star/xml/sax/SAXParseException.hpp>
42 #include <com/sun/star/ucb/XCommandEnvironment.hpp>
43 #include <com/sun/star/task/XInteractionHandler.hpp>
45 #include <ucbhelper/content.hxx>
46 #include <ucbhelper/commandenvironment.hxx>
48 #include <node.hxx>
49 #include "document.hxx"
51 using namespace css::io;
52 using namespace css::lang;
53 using namespace css::ucb;
54 using namespace css::uno;
55 using namespace css::xml::dom;
56 using namespace css::xml::sax;
57 using namespace ucbhelper;
58 using css::task::XInteractionHandler;
59 using css::xml::sax::InputSource;
62 namespace DOM
65 class CDefaultEntityResolver : public cppu::WeakImplHelper< XEntityResolver >
67 public:
68 virtual InputSource SAL_CALL resolveEntity( const OUString& sPublicId, const OUString& sSystemId ) override
70 InputSource is;
71 is.sPublicId = sPublicId;
72 is.sSystemId = sSystemId;
73 is.sEncoding.clear();
75 try {
76 Reference< XCommandEnvironment > aEnvironment(
77 new CommandEnvironment(Reference< XInteractionHandler >(),
78 Reference< XProgressHandler >() ));
79 Content aContent(sSystemId, aEnvironment, comphelper::getProcessComponentContext());
81 is.aInputStream = aContent.openStream();
82 } catch (const css::uno::Exception&) {
83 OSL_FAIL("exception in default entity resolver");
84 is.aInputStream.clear();
86 return is;
91 CDocumentBuilder::CDocumentBuilder()
92 : m_xEntityResolver(new CDefaultEntityResolver)
94 // init libxml. libxml will protect itself against multiple
95 // initializations so there is no problem here if this gets
96 // called multiple times.
97 xmlInitParser();
100 Reference< XInterface > CDocumentBuilder::_getInstance(const Reference< XMultiServiceFactory >& )
102 return static_cast< XDocumentBuilder* >(new CDocumentBuilder);
105 OUString CDocumentBuilder::_getImplementationName()
107 return "com.sun.star.comp.xml.dom.DocumentBuilder";
109 Sequence<OUString> CDocumentBuilder::_getSupportedServiceNames()
111 return { "com.sun.star.xml.dom.DocumentBuilder" };
114 Sequence< OUString > SAL_CALL CDocumentBuilder::getSupportedServiceNames()
116 return CDocumentBuilder::_getSupportedServiceNames();
119 OUString SAL_CALL CDocumentBuilder::getImplementationName()
121 return CDocumentBuilder::_getImplementationName();
124 sal_Bool SAL_CALL CDocumentBuilder::supportsService(const OUString& aServiceName)
126 return cppu::supportsService(this, aServiceName);
129 Reference< XDOMImplementation > SAL_CALL CDocumentBuilder::getDOMImplementation()
132 return Reference< XDOMImplementation >();
135 sal_Bool SAL_CALL CDocumentBuilder::isNamespaceAware()
137 return true;
140 sal_Bool SAL_CALL CDocumentBuilder::isValidating()
142 return false;
145 Reference< XDocument > SAL_CALL CDocumentBuilder::newDocument()
147 ::osl::MutexGuard const g(m_Mutex);
149 // create a new document
150 xmlDocPtr pDocument = xmlNewDoc(reinterpret_cast<const xmlChar*>("1.0"));
151 Reference< XDocument > const xRet(
152 CDocument::CreateCDocument(pDocument).get());
153 return xRet;
156 static OUString make_error_message(xmlParserCtxtPtr ctxt)
158 OUStringBuffer buf;
159 buf.appendAscii(ctxt->lastError.message);
160 buf.append("Line: ");
161 buf.append(static_cast<sal_Int32>(ctxt->lastError.line));
162 buf.append("\nColumn: ");
163 buf.append(static_cast<sal_Int32>(ctxt->lastError.int2));
164 OUString msg = buf.makeStringAndClear();
165 return msg;
168 // -- callbacks and context struct for parsing from stream
169 // -- c-linkage, so the callbacks can be used by libxml
170 extern "C" {
172 // context struct passed to IO functions
173 typedef struct context {
174 Reference< XInputStream > rInputStream;
175 bool close;
176 bool freeOnClose;
177 } context_t;
179 static int xmlIO_read_func( void *context, char *buffer, int len)
181 // get the context...
182 context_t *pctx = static_cast<context_t*>(context);
183 if (!pctx->rInputStream.is())
184 return -1;
185 try {
186 // try to read the requested number of bytes
187 Sequence< sal_Int8 > chunk(len);
188 int nread = pctx->rInputStream->readBytes(chunk, len);
190 // copy bytes to the provided buffer
191 memcpy(buffer, chunk.getConstArray(), nread);
192 return nread;
193 } catch (const css::uno::Exception&) {
194 TOOLS_WARN_EXCEPTION( "unoxml", "");
195 return -1;
199 static int xmlIO_close_func(void* context)
201 // get the context...
202 context_t *pctx = static_cast<context_t*>(context);
203 if (!pctx->rInputStream.is())
204 return 0;
207 if (pctx->close)
208 pctx->rInputStream->closeInput();
209 if (pctx->freeOnClose)
210 delete pctx;
211 return 0;
212 } catch (const css::uno::Exception&) {
213 TOOLS_WARN_EXCEPTION( "unoxml", "");
214 return -1;
218 static xmlParserInputPtr resolve_func(void *ctx,
219 const xmlChar *publicId,
220 const xmlChar *systemId)
222 // get the CDocumentBuilder object
223 xmlParserCtxtPtr ctxt = static_cast<xmlParserCtxtPtr>(ctx);
224 CDocumentBuilder *builder = static_cast< CDocumentBuilder* >(ctxt->_private);
225 Reference< XEntityResolver > resolver = builder->getEntityResolver();
226 OUString sysid;
227 if (systemId != nullptr)
228 sysid = OUString(reinterpret_cast<char const *>(systemId), strlen(reinterpret_cast<char const *>(systemId)), RTL_TEXTENCODING_UTF8);
229 OUString pubid;
230 if (publicId != nullptr)
231 pubid = OUString(reinterpret_cast<char const *>(publicId), strlen(reinterpret_cast<char const *>(publicId)), RTL_TEXTENCODING_UTF8);
233 // resolve the entity
234 InputSource src = resolver->resolveEntity(pubid, sysid);
236 // create IO context on heap because this call will no longer be on the stack
237 // when IO is actually performed through the callbacks. The close function must
238 // free the memory which is indicated by the freeOnClose field in the context struct
239 context_t *c = new context_t;
240 c->rInputStream = src.aInputStream;
241 c->close = true;
242 c->freeOnClose = true;
244 // set up the inputBuffer and inputPtr for libxml
245 xmlParserInputBufferPtr pBuffer =
246 xmlParserInputBufferCreateIO(xmlIO_read_func, xmlIO_close_func, c, XML_CHAR_ENCODING_NONE);
247 xmlParserInputPtr pInput =
248 xmlNewIOInputStream(ctxt, pBuffer, XML_CHAR_ENCODING_NONE);
249 return pInput;
252 #if 0
253 static xmlParserInputPtr external_entity_loader(const char *URL, const char * /*ID*/, xmlParserCtxtPtr ctxt)
255 // just call our resolver function using the URL as systemId
256 return resolve_func(ctxt, 0, (const xmlChar*)URL);
258 #endif
260 // default warning handler does not trigger assertion
261 static void warning_func(void * ctx, const char * /*msg*/, ...)
265 xmlParserCtxtPtr const pctx = static_cast<xmlParserCtxtPtr>(ctx);
267 SAL_INFO(
268 "unoxml",
269 "libxml2 warning: "
270 << make_error_message(pctx));
272 CDocumentBuilder * const pDocBuilder = static_cast<CDocumentBuilder*>(pctx->_private);
274 if (pDocBuilder->getErrorHandler().is()) // if custom error handler is set (using setErrorHandler ())
276 // Prepare SAXParseException to be passed to custom XErrorHandler::warning function
277 css::xml::sax::SAXParseException saxex;
278 saxex.Message = make_error_message(pctx);
279 saxex.LineNumber = static_cast<sal_Int32>(pctx->lastError.line);
280 saxex.ColumnNumber = static_cast<sal_Int32>(pctx->lastError.int2);
282 // Call custom warning function
283 pDocBuilder->getErrorHandler()->warning(::css::uno::Any(saxex));
286 catch (const css::uno::Exception &)
288 // Protect lib2xml from UNO Exception
289 TOOLS_WARN_EXCEPTION("unoxml", "DOM::warning_func");
293 // default error handler triggers assertion
294 static void error_func(void * ctx, const char * /*msg*/, ...)
298 xmlParserCtxtPtr const pctx = static_cast<xmlParserCtxtPtr>(ctx);
299 SAL_WARN(
300 "unoxml",
301 "libxml2 error: "
302 << make_error_message(pctx));
304 CDocumentBuilder * const pDocBuilder = static_cast<CDocumentBuilder*>(pctx->_private);
306 if (pDocBuilder->getErrorHandler().is()) // if custom error handler is set (using setErrorHandler ())
308 // Prepare SAXParseException to be passed to custom XErrorHandler::error function
309 css::xml::sax::SAXParseException saxex;
310 saxex.Message = make_error_message(pctx);
311 saxex.LineNumber = static_cast<sal_Int32>(pctx->lastError.line);
312 saxex.ColumnNumber = static_cast<sal_Int32>(pctx->lastError.int2);
314 // Call custom warning function
315 pDocBuilder->getErrorHandler()->error(::css::uno::Any(saxex));
318 catch (const css::uno::Exception &)
320 // Protect lib2xml from UNO Exception
321 TOOLS_WARN_EXCEPTION("unoxml", "DOM::error_func");
324 } // extern "C"
326 static void throwEx(xmlParserCtxtPtr ctxt)
328 css::xml::sax::SAXParseException saxex;
329 saxex.Message = make_error_message(ctxt);
330 saxex.LineNumber = static_cast<sal_Int32>(ctxt->lastError.line);
331 saxex.ColumnNumber = static_cast<sal_Int32>(ctxt->lastError.int2);
332 throw saxex;
335 namespace {
337 struct XmlFreeParserCtxt {
338 void operator ()(xmlParserCtxt * p) const { xmlFreeParserCtxt(p); }
343 Reference< XDocument > SAL_CALL CDocumentBuilder::parse(const Reference< XInputStream >& is)
345 if (!is.is()) {
346 throw RuntimeException();
349 ::osl::MutexGuard const g(m_Mutex);
351 // IO context struct. Must outlive pContext, as destroying that via
352 // xmlFreeParserCtxt may still access this context_t
353 context_t c;
354 c.rInputStream = is;
355 // we did not open the stream, thus we do not close it.
356 c.close = false;
357 c.freeOnClose = false;
359 std::unique_ptr<xmlParserCtxt, XmlFreeParserCtxt> const pContext(
360 xmlNewParserCtxt());
362 // register error functions to prevent errors being printed
363 // on the console
364 pContext->_private = this;
365 pContext->sax->error = error_func;
366 pContext->sax->warning = warning_func;
367 pContext->sax->resolveEntity = resolve_func;
369 xmlDocPtr const pDoc = xmlCtxtReadIO(pContext.get(),
370 xmlIO_read_func, xmlIO_close_func, &c, nullptr, nullptr, 0);
372 if (pDoc == nullptr) {
373 throwEx(pContext.get());
375 Reference< XDocument > const xRet(
376 CDocument::CreateCDocument(pDoc).get());
377 return xRet;
380 Reference< XDocument > SAL_CALL CDocumentBuilder::parseURI(const OUString& sUri)
382 ::osl::MutexGuard const g(m_Mutex);
384 std::unique_ptr<xmlParserCtxt, XmlFreeParserCtxt> const pContext(
385 xmlNewParserCtxt());
386 pContext->_private = this;
387 pContext->sax->error = error_func;
388 pContext->sax->warning = warning_func;
389 pContext->sax->resolveEntity = resolve_func;
390 // xmlSetExternalEntityLoader(external_entity_loader);
391 OString oUri = OUStringToOString(sUri, RTL_TEXTENCODING_UTF8);
392 char *uri = const_cast<char*>(oUri.getStr());
393 xmlDocPtr pDoc = xmlCtxtReadFile(pContext.get(), uri, nullptr, 0);
394 if (pDoc == nullptr) {
395 throwEx(pContext.get());
397 Reference< XDocument > const xRet(
398 CDocument::CreateCDocument(pDoc).get());
399 return xRet;
402 void SAL_CALL
403 CDocumentBuilder::setEntityResolver(Reference< XEntityResolver > const& xER)
405 ::osl::MutexGuard const g(m_Mutex);
407 m_xEntityResolver = xER;
410 Reference< XEntityResolver > CDocumentBuilder::getEntityResolver()
412 ::osl::MutexGuard const g(m_Mutex);
414 return m_xEntityResolver;
417 void SAL_CALL
418 CDocumentBuilder::setErrorHandler(Reference< XErrorHandler > const& xEH)
420 ::osl::MutexGuard const g(m_Mutex);
422 m_xErrorHandler = xEH;
426 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */