1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <utility>
#include <vector>
#include <iostream>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlIO.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <libxml/xmlstring.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libxslt/variables.h>
#include <libxslt/extensions.h>
#include <libexslt/exslt.h>
#include <cppuhelper/factory.hxx>
#include <osl/module.h>
#include <osl/file.hxx>
#include <osl/process.h>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include "LibXSLTTransformer.hxx"
#include "OleHandler.hxx"
#include <memory>
using namespace ::cppu;
using namespace ::osl;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using ::std::pair;
namespace XSLT
{
const char* const LibXSLTTransformer::PARAM_SOURCE_URL = "sourceURL";
const char* const LibXSLTTransformer::PARAM_SOURCE_BASE_URL =
"sourceBaseURL";
const char* const LibXSLTTransformer::PARAM_TARGET_URL = "targetURL";
const char* const LibXSLTTransformer::PARAM_TARGET_BASE_URL =
"targetBaseURL";
const char* const LibXSLTTransformer::PARAM_DOCTYPE_PUBLIC = "publicType";
const sal_Int32 Reader::OUTPUT_BUFFER_SIZE = 4096;
const sal_Int32 Reader::INPUT_BUFFER_SIZE = 4096;
/**
* ParserInputBufferCallback forwards IO call-backs to libxml stream IO.
*/
struct ParserInputBufferCallback
{
static int
on_read(void * context, char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->read(buffer, len);
}
static int
on_close(void * )
{
return 0;
}
};
/**
* ParserOutputBufferCallback forwards IO call-backs to libxml stream IO.
*/
struct ParserOutputBufferCallback
{
static int
on_write(void * context, const char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->write(buffer, len);
}
static int
on_close(void * context)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->closeOutput();
}
};
/**
* ExtFuncOleCB forwards XPath extension function calls registered with libxslt to the OleHandler instance that actually
* provides the implementation for those functions.
*
* The OLE extension module currently supplies two functions
* insertByName: registers an OLE object to be later inserted into the output tree.
* getByName: reads a previously registered OLE object and returns a base64 encoded string representation.
*/
struct ExtFuncOleCB
{
static void *
init(xsltTransformContextPtr, const xmlChar*)
{
return nullptr;
}
static void
insertByName(xmlXPathParserContextPtr ctxt, int nargs)
{
xsltTransformContextPtr tctxt;
void *data;
if (nargs != 2) {
xsltGenericError(xsltGenericErrorContext,
"insertByName: requires exactly 2 arguments\n");
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == nullptr) {
xsltGenericError(xsltGenericErrorContext,
"xsltExtFunctionTest: failed to get the transformation context\n");
return;
}
// XXX: someone with better knowledge of libxslt might come up with a better
// idea to pass the OleHandler than by attaching it to tctxt->_private. See also
// below.
data = tctxt->_private;
if (data == nullptr) {
xsltGenericError(xsltGenericErrorContext,
"xsltExtFunctionTest: failed to get module data\n");
return;
}
OleHandler * oh = static_cast<OleHandler*> (data);
xmlXPathObjectPtr value = valuePop(ctxt);
value = ensureStringValue(value, ctxt);
xmlXPathObjectPtr streamName = valuePop(ctxt);
streamName = ensureStringValue(streamName, ctxt);
oh->insertByName(OStringToOUString(reinterpret_cast<char*>(streamName->stringval), RTL_TEXTENCODING_UTF8),
OString(reinterpret_cast<char*>(value->stringval)));
valuePush(ctxt, xmlXPathNewCString(""));
}
static xmlXPathObjectPtr ensureStringValue(xmlXPathObjectPtr obj, const xmlXPathParserContextPtr ctxt)
{
if (obj->type != XPATH_STRING) {
valuePush(ctxt, obj);
xmlXPathStringFunction(ctxt, 1);
obj = valuePop(ctxt);
}
return obj;
}
static void getByName(xmlXPathParserContextPtr ctxt, int nargs)
{
xsltTransformContextPtr tctxt;
void *data;
if (nargs != 1) {
xsltGenericError(xsltGenericErrorContext,
"getByName: requires exactly 1 argument\n");
return;
}
tctxt = xsltXPathGetTransformContext(ctxt);
if (tctxt == nullptr) {
xsltGenericError(xsltGenericErrorContext,
"xsltExtFunctionTest: failed to get the transformation context\n");
return;
}
// XXX: someone with better knowledge of libxslt might come up with a better
// idea to pass the OleHandler than by attaching it to tctxt->_private
data = tctxt->_private;
if (data == nullptr) {
xsltGenericError(xsltGenericErrorContext,
"xsltExtFunctionTest: failed to get module data\n");
return;
}
OleHandler * oh = static_cast<OleHandler*> (data);
xmlXPathObjectPtr streamName = valuePop(ctxt);
streamName = ensureStringValue(streamName, ctxt);
const OString content = oh->getByName(OStringToOUString(reinterpret_cast<char*>(streamName->stringval), RTL_TEXTENCODING_UTF8));
valuePush(ctxt, xmlXPathNewCString(content.getStr()));
xmlXPathFreeObject(streamName);
}
};
Reader::Reader(LibXSLTTransformer* transformer) :
Thread("LibXSLTTransformer"), m_transformer(transformer),
m_readBuf(INPUT_BUFFER_SIZE), m_writeBuf(OUTPUT_BUFFER_SIZE),
m_tcontext(nullptr)
{
LIBXML_TEST_VERSION;
}
;
int
Reader::read(char * buffer, int len)
{
// const char *ptr = (const char *) context;
if (buffer == nullptr || len < 0)
return -1;
sal_Int32 n;
css::uno::Reference<XInputStream> xis = m_transformer->getInputStream();
n = xis.get()->readBytes(m_readBuf, len);
if (n > 0)
{
memcpy(buffer, m_readBuf.getArray(), n);
}
return n;
}
int
Reader::write(const char * buffer, int len)
{
if (buffer == nullptr || len < 0)
return -1;
if (len > 0)
{
css::uno::Reference<XOutputStream> xos = m_transformer->getOutputStream();
sal_Int32 writeLen = len;
sal_Int32 bufLen = ::std::min(writeLen, OUTPUT_BUFFER_SIZE);
const sal_uInt8* memPtr =
reinterpret_cast<const sal_uInt8*> (buffer);
while (writeLen > 0)
{
sal_Int32 n = ::std::min(writeLen, bufLen);
m_writeBuf.realloc(n);
memcpy(m_writeBuf.getArray(), memPtr,
static_cast<size_t> (n));
xos.get()->writeBytes(m_writeBuf);
memPtr += n;
writeLen -= n;
}
}
return len;
}
int
Reader::closeOutput()
{
css::uno::Reference<XOutputStream> xos = m_transformer->getOutputStream();
if (xos.is())
{
xos.get()->flush();
xos.get()->closeOutput();
}
m_transformer->done();
return 0;
}
void
Reader::execute()
{
OSL_ASSERT(m_transformer != nullptr);
OSL_ASSERT(m_transformer->getInputStream().is());
OSL_ASSERT(m_transformer->getOutputStream().is());
OSL_ASSERT(!m_transformer->getStyleSheetURL().isEmpty());
::std::map<const char*, OString> pmap = m_transformer->getParameters();
::std::vector< const char* > params( pmap.size() * 2 + 1 ); // build parameters
int paramIndex = 0;
for (auto const& elem : pmap)
{
params[paramIndex++] = elem.first;
params[paramIndex++] = elem.second.getStr();
}
params[paramIndex] = nullptr;
xmlDocPtr doc = xmlReadIO(&ParserInputBufferCallback::on_read,
&ParserInputBufferCallback::on_close,
static_cast<void*> (this), nullptr, nullptr, 0);
xsltStylesheetPtr styleSheet = xsltParseStylesheetFile(
reinterpret_cast<const xmlChar *>(m_transformer->getStyleSheetURL().getStr()));
xmlDocPtr result = nullptr;
exsltRegisterAll();
registerExtensionModule();
#ifdef DEBUG_FILTER_LIBXSLTTRANSFORMER
xsltSetGenericDebugFunc(stderr, NULL);
xsltDebugDumpExtensions(NULL);
#endif
std::unique_ptr<OleHandler> oh(new OleHandler(m_transformer->getComponentContext()));
if (styleSheet)
{
xsltTransformContextPtr tcontext = xsltNewTransformContext(
styleSheet, doc);
{
std::unique_lock<std::mutex> g(m_mutex);
m_tcontext = tcontext;
}
oh->registercontext(m_tcontext);
xsltQuoteUserParams(m_tcontext, ¶ms[0]);
result = xsltApplyStylesheetUser(styleSheet, doc, nullptr, nullptr, nullptr,
m_tcontext);
}
if (result)
{
xmlCharEncodingHandlerPtr encoder = xmlGetCharEncodingHandler(
XML_CHAR_ENCODING_UTF8);
xmlOutputBufferPtr outBuf = xmlAllocOutputBuffer(encoder);
outBuf->context = static_cast<void *> (this);
outBuf->writecallback = &ParserOutputBufferCallback::on_write;
outBuf->closecallback = &ParserOutputBufferCallback::on_close;
xsltSaveResultTo(outBuf, result, styleSheet);
xmlOutputBufferClose(outBuf);
}
else
{
xmlErrorPtr lastErr = xmlGetLastError();
OUString msg;
if (lastErr)
msg = OStringToOUString(lastErr->message, RTL_TEXTENCODING_UTF8);
else
msg = "Unknown XSLT transformation error";
m_transformer->error(msg);
}
closeOutput();
oh.reset();
xsltFreeStylesheet(styleSheet);
xsltTransformContextPtr tcontext = nullptr;
{
std::unique_lock<std::mutex> g(m_mutex);
std::swap(m_tcontext, tcontext);
}
xsltFreeTransformContext(tcontext);
xmlFreeDoc(doc);
xmlFreeDoc(result);
}
void
Reader::registerExtensionModule()
{
const xmlChar* oleModuleURI = reinterpret_cast<const xmlChar *>(EXT_MODULE_OLE_URI);
xsltRegisterExtModule(oleModuleURI, &ExtFuncOleCB::init, nullptr);
xsltRegisterExtModuleFunction(
reinterpret_cast<const xmlChar*>("insertByName"),
oleModuleURI,
&ExtFuncOleCB::insertByName);
xsltRegisterExtModuleFunction(
reinterpret_cast<const xmlChar*>("getByName"),
oleModuleURI,
&ExtFuncOleCB::getByName);
}
void Reader::forceStateStopped()
{
std::unique_lock<std::mutex> g(m_mutex);
if (!m_tcontext)
return;
//tdf#100057 If we force a cancel, libxslt will of course just keep on going unless something
//tells it to stop. Here we force the stopped state so that libxslt will stop processing
//and so Reader::execute will complete and we can join cleanly
m_tcontext->state = XSLT_STATE_STOPPED;
}
Reader::~Reader()
{
}
LibXSLTTransformer::LibXSLTTransformer(
const css::uno::Reference<XComponentContext> & rxContext) :
m_xContext(rxContext)
{
}
void
LibXSLTTransformer::setInputStream(
const css::uno::Reference<XInputStream>& inputStream)
{
m_rInputStream = inputStream;
}
css::uno::Reference<XInputStream>
LibXSLTTransformer::getInputStream()
{
return m_rInputStream;
}
void
LibXSLTTransformer::setOutputStream(
const css::uno::Reference<XOutputStream>& outputStream)
{
m_rOutputStream = outputStream;
}
css::uno::Reference<XOutputStream>
LibXSLTTransformer::getOutputStream()
{
return m_rOutputStream;
}
void
LibXSLTTransformer::addListener(const css::uno::Reference<XStreamListener>& listener)
{
m_listeners.insert(m_listeners.begin(), listener);
}
void
LibXSLTTransformer::removeListener(
const css::uno::Reference<XStreamListener>& listener)
{
m_listeners.remove(listener);
}
void
LibXSLTTransformer::start()
{
ListenerList* l = &m_listeners;
for (auto const& elem : *l)
{
css::uno::Reference<XStreamListener> xl = elem;
xl.get()->started();
}
OSL_ENSURE(!m_Reader.is(), "Somebody forgot to call terminate *and* holds a reference to this LibXSLTTransformer instance");
m_Reader = new Reader(this);
m_Reader->launch();
}
void
LibXSLTTransformer::error(const OUString& msg)
{
ListenerList* l = &m_listeners;
Any arg;
arg <<= Exception(msg, *this);
for (auto const& elem : *l)
{
css::uno::Reference<XStreamListener> xl = elem;
if (xl.is())
{
xl.get()->error(arg);
}
}
}
void
LibXSLTTransformer::done()
{
ListenerList* l = &m_listeners;
for (auto const& elem : *l)
{
css::uno::Reference<XStreamListener> xl = elem;
if (xl.is())
{
xl.get()->closed();
}
}
}
void
LibXSLTTransformer::terminate()
{
if (m_Reader.is())
{
m_Reader->terminate();
m_Reader->forceStateStopped();
m_Reader->join();
}
m_Reader.clear();
m_parameters.clear();
}
void
LibXSLTTransformer::initialize(const Sequence<Any>& args)
{
Sequence<Any> params;
if (!(args[0] >>= params))
{ // backward compatibility for old clients using createInstance
params = args;
}
xmlSubstituteEntitiesDefault(0);
m_parameters.clear();
for (int i = 0; i < params.getLength(); i++)
{
NamedValue nv;
params[i] >>= nv;
OString nameUTF8 = OUStringToOString(nv.Name,
RTL_TEXTENCODING_UTF8);
OUString value;
OString valueUTF8;
if (nv.Value >>= value)
{
valueUTF8 = OUStringToOString(value,
RTL_TEXTENCODING_UTF8);
}
else
{
// ignore non-string parameters
continue;
}
if (nameUTF8 == "StylesheetURL")
{
m_styleSheetURL = valueUTF8;
}
else if (nameUTF8 == "SourceURL")
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_URL, valueUTF8));
}
else if (nameUTF8 == "SourceBaseURL")
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_BASE_URL, valueUTF8));
}
else if (nameUTF8 == "TargetURL")
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_URL, valueUTF8));
}
else if (nameUTF8 == "TargetBaseURL")
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_BASE_URL, valueUTF8));
}
else if (nameUTF8 == "DoctypePublic")
{
m_parameters.insert(pair<const char*, OString> (
PARAM_DOCTYPE_PUBLIC, valueUTF8));
}
}
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|