1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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"
24 #include <libxml/xmlerror.h>
28 #include <sal/log.hxx>
29 #include <comphelper/diagnose_ex.hxx>
31 #include <comphelper/processfactory.hxx>
32 #include <cppuhelper/implbase.hxx>
33 #include <cppuhelper/supportsservice.hxx>
35 #include <com/sun/star/xml/sax/SAXParseException.hpp>
36 #include <com/sun/star/ucb/XCommandEnvironment.hpp>
37 #include <com/sun/star/task/XInteractionHandler.hpp>
38 #include <com/sun/star/ucb/SimpleFileAccess.hpp>
40 #include <ucbhelper/content.hxx>
41 #include <ucbhelper/commandenvironment.hxx>
43 #include "document.hxx"
45 using namespace css::io
;
46 using namespace css::lang
;
47 using namespace css::ucb
;
48 using namespace css::uno
;
49 using namespace css::xml::dom
;
50 using namespace css::xml::sax
;
51 using namespace ucbhelper
;
52 using css::task::XInteractionHandler
;
53 using css::xml::sax::InputSource
;
60 class CDefaultEntityResolver
: public cppu::WeakImplHelper
< XEntityResolver
>
63 virtual InputSource SAL_CALL
resolveEntity( const OUString
& sPublicId
, const OUString
& sSystemId
) override
66 is
.sPublicId
= sPublicId
;
67 is
.sSystemId
= sSystemId
;
71 Reference
< XCommandEnvironment
> aEnvironment(
72 new CommandEnvironment(Reference
< XInteractionHandler
>(),
73 Reference
< XProgressHandler
>() ));
74 Content
aContent(sSystemId
, aEnvironment
, comphelper::getProcessComponentContext());
76 is
.aInputStream
= aContent
.openStream();
77 } catch (const css::uno::Exception
&) {
78 TOOLS_WARN_EXCEPTION( "unoxml", "exception in default entity resolver");
79 is
.aInputStream
.clear();
88 CDocumentBuilder::CDocumentBuilder()
89 : m_xEntityResolver(new CDefaultEntityResolver
)
91 // init libxml. libxml will protect itself against multiple
92 // initializations so there is no problem here if this gets
93 // called multiple times.
97 Sequence
< OUString
> SAL_CALL
CDocumentBuilder::getSupportedServiceNames()
99 return { "com.sun.star.xml.dom.DocumentBuilder" };
102 OUString SAL_CALL
CDocumentBuilder::getImplementationName()
104 return "com.sun.star.comp.xml.dom.DocumentBuilder";
107 sal_Bool SAL_CALL
CDocumentBuilder::supportsService(const OUString
& aServiceName
)
109 return cppu::supportsService(this, aServiceName
);
112 Reference
< XDOMImplementation
> SAL_CALL
CDocumentBuilder::getDOMImplementation()
115 return Reference
< XDOMImplementation
>();
118 sal_Bool SAL_CALL
CDocumentBuilder::isNamespaceAware()
123 sal_Bool SAL_CALL
CDocumentBuilder::isValidating()
128 Reference
< XDocument
> SAL_CALL
CDocumentBuilder::newDocument()
130 std::scoped_lock
const g(m_Mutex
);
132 // create a new document
133 xmlDocPtr pDocument
= xmlNewDoc(reinterpret_cast<const xmlChar
*>("1.0"));
134 return CDocument::CreateCDocument(pDocument
);
137 static OUString
make_error_message(xmlParserCtxtPtr ctxt
)
139 return OUString(ctxt
->lastError
.message
, strlen(ctxt
->lastError
.message
), RTL_TEXTENCODING_ASCII_US
) +
141 OUString::number(static_cast<sal_Int32
>(ctxt
->lastError
.line
)) +
143 OUString::number(static_cast<sal_Int32
>(ctxt
->lastError
.int2
));
146 // -- callbacks and context struct for parsing from stream
147 // -- c-linkage, so the callbacks can be used by libxml
152 // context struct passed to IO functions
153 typedef struct context
{
154 Reference
< XInputStream
> rInputStream
;
161 static int xmlIO_read_func( void *context
, char *buffer
, int len
)
163 // get the context...
164 context_t
*pctx
= static_cast<context_t
*>(context
);
165 if (!pctx
->rInputStream
.is())
168 // try to read the requested number of bytes
169 Sequence
< sal_Int8
> chunk(len
);
170 int nread
= pctx
->rInputStream
->readBytes(chunk
, len
);
172 // copy bytes to the provided buffer
173 memcpy(buffer
, chunk
.getConstArray(), nread
);
175 } catch (const css::uno::Exception
&) {
176 TOOLS_WARN_EXCEPTION( "unoxml", "");
181 static int xmlIO_close_func(void* context
)
183 // get the context...
184 context_t
*pctx
= static_cast<context_t
*>(context
);
185 if (!pctx
->rInputStream
.is())
190 pctx
->rInputStream
->closeInput();
191 if (pctx
->freeOnClose
)
194 } catch (const css::uno::Exception
&) {
195 TOOLS_WARN_EXCEPTION( "unoxml", "");
200 static xmlParserInputPtr
resolve_func(void *ctx
,
201 const xmlChar
*publicId
,
202 const xmlChar
*systemId
)
204 // get the CDocumentBuilder object
205 xmlParserCtxtPtr ctxt
= static_cast<xmlParserCtxtPtr
>(ctx
);
206 CDocumentBuilder
*builder
= static_cast< CDocumentBuilder
* >(ctxt
->_private
);
207 Reference
< XEntityResolver
> resolver
= builder
->getEntityResolver();
209 if (systemId
!= nullptr)
210 sysid
= OUString(reinterpret_cast<char const *>(systemId
), strlen(reinterpret_cast<char const *>(systemId
)), RTL_TEXTENCODING_UTF8
);
212 if (publicId
!= nullptr)
213 pubid
= OUString(reinterpret_cast<char const *>(publicId
), strlen(reinterpret_cast<char const *>(publicId
)), RTL_TEXTENCODING_UTF8
);
215 // resolve the entity
216 InputSource src
= resolver
->resolveEntity(pubid
, sysid
);
218 // create IO context on heap because this call will no longer be on the stack
219 // when IO is actually performed through the callbacks. The close function must
220 // free the memory which is indicated by the freeOnClose field in the context struct
221 context_t
*c
= new context_t
;
222 c
->rInputStream
= src
.aInputStream
;
224 c
->freeOnClose
= true;
226 // set up the inputBuffer and inputPtr for libxml
227 xmlParserInputBufferPtr pBuffer
=
228 xmlParserInputBufferCreateIO(xmlIO_read_func
, xmlIO_close_func
, c
, XML_CHAR_ENCODING_NONE
);
229 xmlParserInputPtr pInput
=
230 xmlNewIOInputStream(ctxt
, pBuffer
, XML_CHAR_ENCODING_NONE
);
235 static xmlParserInputPtr
external_entity_loader(const char *URL
, const char * /*ID*/, xmlParserCtxtPtr ctxt
)
237 // just call our resolver function using the URL as systemId
238 return resolve_func(ctxt
, 0, (const xmlChar
*)URL
);
242 // default warning handler does not trigger assertion
243 static void warning_func(void * ctx
, const char * /*msg*/, ...)
247 xmlParserCtxtPtr
const pctx
= static_cast<xmlParserCtxtPtr
>(ctx
);
252 << make_error_message(pctx
));
254 CDocumentBuilder
* const pDocBuilder
= static_cast<CDocumentBuilder
*>(pctx
->_private
);
256 if (pDocBuilder
->getErrorHandler().is()) // if custom error handler is set (using setErrorHandler ())
258 // Prepare SAXParseException to be passed to custom XErrorHandler::warning function
259 css::xml::sax::SAXParseException saxex
;
260 saxex
.Message
= make_error_message(pctx
);
261 saxex
.LineNumber
= static_cast<sal_Int32
>(pctx
->lastError
.line
);
262 saxex
.ColumnNumber
= static_cast<sal_Int32
>(pctx
->lastError
.int2
);
264 // Call custom warning function
265 pDocBuilder
->getErrorHandler()->warning(::css::uno::Any(saxex
));
268 catch (const css::uno::Exception
&)
270 // Protect lib2xml from UNO Exception
271 TOOLS_WARN_EXCEPTION("unoxml", "DOM::warning_func");
275 // default error handler triggers assertion
276 static void error_func(void * ctx
, const char * /*msg*/, ...)
280 xmlParserCtxtPtr
const pctx
= static_cast<xmlParserCtxtPtr
>(ctx
);
284 << make_error_message(pctx
));
286 CDocumentBuilder
* const pDocBuilder
= static_cast<CDocumentBuilder
*>(pctx
->_private
);
288 if (pDocBuilder
->getErrorHandler().is()) // if custom error handler is set (using setErrorHandler ())
290 // Prepare SAXParseException to be passed to custom XErrorHandler::error function
291 css::xml::sax::SAXParseException saxex
;
292 saxex
.Message
= make_error_message(pctx
);
293 saxex
.LineNumber
= static_cast<sal_Int32
>(pctx
->lastError
.line
);
294 saxex
.ColumnNumber
= static_cast<sal_Int32
>(pctx
->lastError
.int2
);
296 // Call custom warning function
297 pDocBuilder
->getErrorHandler()->error(::css::uno::Any(saxex
));
300 catch (const css::uno::Exception
&)
302 // Protect lib2xml from UNO Exception
303 TOOLS_WARN_EXCEPTION("unoxml", "DOM::error_func");
308 static void throwEx(xmlParserCtxtPtr ctxt
)
310 css::xml::sax::SAXParseException saxex
;
311 saxex
.Message
= make_error_message(ctxt
);
312 saxex
.LineNumber
= static_cast<sal_Int32
>(ctxt
->lastError
.line
);
313 saxex
.ColumnNumber
= static_cast<sal_Int32
>(ctxt
->lastError
.int2
);
319 struct XmlFreeParserCtxt
{
320 void operator ()(xmlParserCtxt
* p
) const { xmlFreeParserCtxt(p
); }
325 Reference
< XDocument
> SAL_CALL
CDocumentBuilder::parse(const Reference
< XInputStream
>& is
)
328 throw RuntimeException();
331 std::scoped_lock
const g(m_Mutex
);
333 // IO context struct. Must outlive pContext, as destroying that via
334 // xmlFreeParserCtxt may still access this context_t
337 // we did not open the stream, thus we do not close it.
339 c
.freeOnClose
= false;
341 std::unique_ptr
<xmlParserCtxt
, XmlFreeParserCtxt
> const pContext(
344 // register error functions to prevent errors being printed
346 pContext
->_private
= this;
347 pContext
->sax
->error
= error_func
;
348 pContext
->sax
->warning
= warning_func
;
349 pContext
->sax
->resolveEntity
= resolve_func
;
351 xmlDocPtr
const pDoc
= xmlCtxtReadIO(pContext
.get(),
352 xmlIO_read_func
, xmlIO_close_func
, &c
, nullptr, nullptr, 0);
354 if (pDoc
== nullptr) {
355 throwEx(pContext
.get());
357 return CDocument::CreateCDocument(pDoc
);
360 Reference
< XDocument
> SAL_CALL
CDocumentBuilder::parseURI(const OUString
& sUri
)
362 std::scoped_lock
const g(m_Mutex
);
364 std::unique_ptr
<xmlParserCtxt
, XmlFreeParserCtxt
> const pContext(
366 pContext
->_private
= this;
367 pContext
->sax
->error
= error_func
;
368 pContext
->sax
->warning
= warning_func
;
369 pContext
->sax
->resolveEntity
= resolve_func
;
370 // xmlSetExternalEntityLoader(external_entity_loader);
371 OString oUri
= OUStringToOString(sUri
, RTL_TEXTENCODING_UTF8
);
372 char *uri
= const_cast<char*>(oUri
.getStr());
373 xmlDocPtr pDoc
= xmlCtxtReadFile(pContext
.get(), uri
, nullptr, 0);
375 Reference
< XDocument
> xRet
;
377 // if we failed to parse the URI as a simple file, lets try via a ucb stream.
378 // For Android file:///assets/ URLs which must go via the osl/ file API.
379 if (pDoc
== nullptr) {
380 Reference
< XSimpleFileAccess3
> xStreamAccess(
381 SimpleFileAccess::create( comphelper::getProcessComponentContext() ) );
382 Reference
< XInputStream
> xInStream
= xStreamAccess
->openFileRead( sUri
);
384 throwEx(pContext
.get());
386 // loop over every layout entry in current file
387 xRet
= parse( xInStream
);
389 xInStream
->closeInput();
393 xRet
= CDocument::CreateCDocument(pDoc
).get();
399 CDocumentBuilder::setEntityResolver(Reference
< XEntityResolver
> const& xER
)
401 std::scoped_lock
const g(m_Mutex
);
403 m_xEntityResolver
= xER
;
406 Reference
< XEntityResolver
> CDocumentBuilder::getEntityResolver()
408 std::scoped_lock
const g(m_Mutex
);
410 return m_xEntityResolver
;
414 CDocumentBuilder::setErrorHandler(Reference
< XErrorHandler
> const& xEH
)
416 std::scoped_lock
const g(m_Mutex
);
418 m_xErrorHandler
= xEH
;
422 extern "C" SAL_DLLPUBLIC_EXPORT
css::uno::XInterface
*
423 unoxml_CDocumentBuilder_get_implementation(
424 css::uno::XComponentContext
* , css::uno::Sequence
<css::uno::Any
> const&)
426 return cppu::acquire(new DOM::CDocumentBuilder());
429 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */