File: ParserPool.cpp

package info (click to toggle)
xmltooling 1.6.0-4+deb9u2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,928 kB
  • sloc: cpp: 22,289; sh: 11,065; makefile: 337; xml: 170; ansic: 49
file content (614 lines) | stat: -rw-r--r-- 22,686 bytes parent folder | download
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/**
 * Licensed to the University Corporation for Advanced Internet
 * Development, Inc. (UCAID) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * UCAID licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the
 * License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

/**
 * ParserPool.cpp
 *
 * A thread-safe pool of parsers that share characteristics.
 */

#include "internal.h"
#include "exceptions.h"
#include "logging.h"
#include "util/CloneInputStream.h"
#include "util/CurlURLInputStream.h"
#include "util/NDC.h"
#include "util/PathResolver.h"
#include "util/ParserPool.h"
#include "util/Threads.h"
#include "util/XMLHelper.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <algorithm>
#include <functional>
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/sax/SAXException.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>
#include <xercesc/framework/Wrapper4InputSource.hpp>

using namespace xmltooling::logging;
using namespace xmltooling;
using namespace xercesc;
using namespace boost;
using namespace std;


namespace {
    class MyErrorHandler : public DOMErrorHandler {
    public:
        unsigned int errors;

        MyErrorHandler() : errors(0) {}

        bool handleError(const DOMError& e)
        {
#ifdef _DEBUG
            xmltooling::NDC ndc("handleError");
#endif
            Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".ParserPool");

            DOMLocator* locator=e.getLocation();
            auto_ptr_char temp(e.getMessage());

            switch (e.getSeverity()) {
                case DOMError::DOM_SEVERITY_WARNING:
                    log.warnStream() << "warning on line " << locator->getLineNumber()
                        << ", column " << locator->getColumnNumber()
                        << ", message: " << temp.get() << logging::eol;
                    return true;

                case DOMError::DOM_SEVERITY_ERROR:
                    ++errors;
                    log.errorStream() << "error on line " << locator->getLineNumber()
                        << ", column " << locator->getColumnNumber()
                        << ", message: " << temp.get() << logging::eol;
                    return true;

                case DOMError::DOM_SEVERITY_FATAL_ERROR:
                    ++errors;
                    log.errorStream() << "fatal error on line " << locator->getLineNumber()
                        << ", column " << locator->getColumnNumber()
                        << ", message: " << temp.get() << logging::eol;
                    return true;
            }

            ++errors;
            log.errorStream() << "undefined error type on line " << locator->getLineNumber()
                << ", column " << locator->getColumnNumber()
                << ", message: " << temp.get() << logging::eol;
            return false;
        }
    };
}


ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
        : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(Mutex::create()), m_security(new SecurityManager()) {

    int expLimit = 0;
    const char* env = getenv("XMLTOOLING_ENTITY_EXPANSION_LIMIT");
    if (env) {
        expLimit = atoi(env);
    }
    if (expLimit <= 0)
        expLimit = XMLTOOLING_ENTITY_EXPANSION_LIMIT;
    m_security->setEntityExpansionLimit(expLimit);
}

ParserPool::~ParserPool()
{
    while(!m_pool.empty()) {
        m_pool.top()->release();
        m_pool.pop();
    }
}

DOMDocument* ParserPool::newDocument()
{
    return DOMImplementationRegistry::getDOMImplementation(nullptr)->createDocument();
}

#ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS

DOMDocument* ParserPool::parse(DOMLSInput& domsrc)
{
    DOMLSParser* parser=checkoutBuilder();
    XercesJanitor<DOMLSParser> janitor(parser);
    try {
        MyErrorHandler deh;
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, dynamic_cast<DOMErrorHandler*>(&deh));
        DOMDocument* doc=parser->parse(&domsrc);
        if (deh.errors) {
            if (doc)
                doc->release();
            throw XMLParserException("XML error(s) during parsing, check log for specifics");
        }
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        return doc;
    }
    catch (const DOMException& ex) {
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        auto_ptr_char temp(ex.getMessage());
        throw XMLParserException(string("DOM error during parsing: ") + (temp.get() ? temp.get() : "no message"));
    }
    catch (const SAXException& ex) {
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        auto_ptr_char temp(ex.getMessage());
        throw XMLParserException(string("SAX error during parsing: ") + (temp.get() ? temp.get() : "no message"));
    }
    catch (const XMLException& ex) {
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        auto_ptr_char temp(ex.getMessage());
        throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
    }
    catch (const XMLToolingException&) {
        parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        throw;
    }
}

#else

DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
{
    DOMBuilder* parser=checkoutBuilder();
    XercesJanitor<DOMBuilder> janitor(parser);
    try {
        MyErrorHandler deh;
        parser->setErrorHandler(&deh);
        DOMDocument* doc=parser->parse(domsrc);
        if (deh.errors) {
            if (doc)
                doc->release();
            throw XMLParserException("XML error(s) during parsing, check log for specifics");
        }
        parser->setErrorHandler(nullptr);
        parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        return doc;
    }
    catch (XMLException& ex) {
        parser->setErrorHandler(nullptr);
        parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        auto_ptr_char temp(ex.getMessage());
        throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
    }
    catch (XMLToolingException&) {
        parser->setErrorHandler(nullptr);
        parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
        checkinBuilder(janitor.release());
        throw;
    }
}

#endif

DOMDocument* ParserPool::parse(istream& is)
{
    StreamInputSource src(is);
    Wrapper4InputSource domsrc(&src,false);
    return parse(domsrc);
}

// Functor to double its argument separated by a character and append to a buffer
template <class T> class doubleit {
public:
    doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
    void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
    T& temp;
    const typename T::value_type& sep;
};

bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
{
    // Just check the pathname and then directly register the pair into the map.

    auto_ptr_char p(pathname);
#ifdef WIN32
    struct _stat stat_buf;
    if (_stat(p.get(), &stat_buf) != 0)
#else
    struct stat stat_buf;
    if (stat(p.get(), &stat_buf) != 0)
#endif
    {
#if _DEBUG
        xmltooling::NDC ndc("loadSchema");
#endif
        Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".ParserPool");
        auto_ptr_char n(nsURI);
        log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
        return false;
    }

    // Roundtrip to local code page and back to translate path as needed.
    string topath(p.get());
    XMLToolingConfig::getConfig().getPathResolver()->resolve(topath, PathResolver::XMLTOOLING_XML_FILE);
    auto_ptr_XMLCh temp(topath.c_str());

    Lock lock(m_lock);
    m_schemaLocMap[nsURI] = temp.get();
    m_schemaLocations.erase();
    for_each(m_schemaLocMap.begin(), m_schemaLocMap.end(), doubleit<xstring>(m_schemaLocations,chSpace));

    return true;
}

bool ParserPool::loadCatalogs(const char* pathnames)
{
    string temp(pathnames);
    trim(temp);
    vector<string> catpaths;
    split(catpaths, temp, is_any_of(PATH_SEPARATOR_STR), algorithm::token_compress_on);
    static bool (ParserPool::* lc)(const char*) = &ParserPool::loadCatalog;
    for_each(catpaths.begin(), catpaths.end(), boost::bind(lc, this, boost::bind(&string::c_str, _1)));
    return !catpaths.empty();
}

bool ParserPool::loadCatalog(const char* pathname)
{
    string p(pathname);
    XMLToolingConfig::getConfig().getPathResolver()->resolve(p, PathResolver::XMLTOOLING_XML_FILE);
    auto_ptr_XMLCh temp(p.c_str());
    return loadCatalog(temp.get());
}

bool ParserPool::loadCatalog(const XMLCh* pathname)
{
#if _DEBUG
    xmltooling::NDC ndc("loadCatalog");
#endif
    Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".ParserPool");

    // XML constants
    static const XMLCh catalog[] =  UNICODE_LITERAL_7(c,a,t,a,l,o,g);
    static const XMLCh system[] =   UNICODE_LITERAL_6(s,y,s,t,e,m);
    static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
    static const XMLCh uri[] =      UNICODE_LITERAL_3(u,r,i);
    static const XMLCh CATALOG_NS[] = {
        chLatin_u, chLatin_r, chLatin_n, chColon,
        chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
        chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
        chLatin_t, chLatin_c, chColon,
        chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
        chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
        chLatin_x, chLatin_m, chLatin_l, chColon,
        chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
    };

    // Parse the catalog with the internal parser pool.

    if (log.isDebugEnabled()) {
        auto_ptr_char temp(pathname);
        log.debug("loading XML catalog from %s", temp.get());
    }

    LocalFileInputSource fsrc(nullptr,pathname);
    Wrapper4InputSource domsrc(&fsrc,false);
    try {
        DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
        XercesJanitor<DOMDocument> janitor(doc);

        // Check root element.
        const DOMElement* root=doc->getDocumentElement();
        if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
            auto_ptr_char temp(pathname);
            log.error("unknown root element, failed to load XML catalog from %s", temp.get());
            return false;
        }

        // Fetch all the <system> elements.
        DOMNodeList* mappings = root->getElementsByTagNameNS(CATALOG_NS,system);
        Lock lock(m_lock);
        for (XMLSize_t i = 0; i < mappings->getLength(); i++) {
            root = static_cast<DOMElement*>(mappings->item(i));
            const XMLCh* from = root->getAttributeNS(nullptr,systemId);
            const XMLCh* to = root->getAttributeNS(nullptr,uri);

            // Roundtrip to local code page and back to translate path as needed.
            auto_ptr_char temp(to);
            string topath(temp.get());
            XMLToolingConfig::getConfig().getPathResolver()->resolve(topath, PathResolver::XMLTOOLING_XML_FILE);
            auto_ptr_XMLCh temp2(topath.c_str());

            m_schemaLocMap[from] = temp2.get();
        }
        m_schemaLocations.erase();
        for_each(m_schemaLocMap.begin(), m_schemaLocMap.end(), doubleit<xstring>(m_schemaLocations,chSpace));
    }
    catch (std::exception& e) {
        log.error("catalog loader caught exception: %s", e.what());
        return false;
    }

    return true;
}

#ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
DOMLSInput* ParserPool::resolveResource(
            const XMLCh *const resourceType,
            const XMLCh *const namespaceUri,
            const XMLCh *const publicId,
            const XMLCh *const systemId,
            const XMLCh *const baseURI
            )
#else
DOMInputSource* ParserPool::resolveEntity(
    const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI
    )
#endif
{
#if _DEBUG
    xmltooling::NDC ndc("resolveEntity");
#endif
    if (!systemId)
        return nullptr;
    xstring sysId(systemId);

    Category& log=Category::getInstance(XMLTOOLING_LOGCAT ".ParserPool");
    if (log.isDebugEnabled()) {
        auto_ptr_char sysId(systemId);
        auto_ptr_char base(baseURI);
        log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
    }

    // Find well-known schemas in the specified location.
    map<xstring,xstring>::const_iterator i = m_schemaLocMap.find(sysId);
    if (i != m_schemaLocMap.end())
        return new Wrapper4InputSource(new LocalFileInputSource(baseURI, i->second.c_str()));

    // Check for entity as a suffix of a value in the map.
    bool (*p_ends_with)(const xstring&, const xstring&) = ends_with;
    i = find_if(
        m_schemaLocMap.begin(), m_schemaLocMap.end(),
        boost::bind(p_ends_with, boost::bind(&map<xstring,xstring>::value_type::second, _1), boost::ref(sysId))
        );
    if (i != m_schemaLocMap.end())
        return new Wrapper4InputSource(new LocalFileInputSource(baseURI, i->second.c_str()));

    // We'll allow anything without embedded slashes.
    if (XMLString::indexOf(systemId, chForwardSlash) == -1 && XMLString::indexOf(systemId, chBackSlash) == -1)
        return new Wrapper4InputSource(new LocalFileInputSource(baseURI, systemId));

    // Shortcircuit the request.
    auto_ptr_char temp(systemId);
    log.debug("unauthorized entity request (%s), blocking it", temp.get());
    static const XMLByte nullbuf[] = {0};
    return new Wrapper4InputSource(new MemBufInputSource(nullbuf, 0, systemId));
}

#ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS

DOMLSParser* ParserPool::createBuilder()
{
    static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
    DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
    DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,nullptr);
    parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
    if (m_schemaAware) {
        parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
        parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
        parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);

        // We build a "fake" schema location hint that binds each namespace to itself.
        // This ensures the entity resolver will be given the namespace as a systemId it can check.
        parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
    }
    parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
    parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
    parser->getDomConfig()->setParameter(XMLUni::fgDOMResourceResolver, dynamic_cast<DOMLSResourceResolver*>(this));
    parser->getDomConfig()->setParameter(XMLUni::fgXercesSecurityManager, m_security.get());
    parser->getDomConfig()->setParameter(XMLUni::fgDOMDisallowDoctype, true);
    parser->getDomConfig()->setParameter(XMLUni::fgDOMComments, false);
    return parser;
}

DOMLSParser* ParserPool::checkoutBuilder()
{
    Lock lock(m_lock);
    if (m_pool.empty()) {
        DOMLSParser* builder=createBuilder();
        return builder;
    }
    DOMLSParser* p=m_pool.top();
    m_pool.pop();
    if (m_schemaAware)
        p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
    return p;
}

void ParserPool::checkinBuilder(DOMLSParser* builder)
{
    if (builder) {
        Lock lock(m_lock);
        m_pool.push(builder);
    }
}

#else

DOMBuilder* ParserPool::createBuilder()
{
    static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
    DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
    DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
    parser->setFeature(XMLUni::fgDOMNamespaces, m_namespaceAware);
    if (m_schemaAware) {
        parser->setFeature(XMLUni::fgDOMNamespaces, true);
        parser->setFeature(XMLUni::fgXercesSchema, true);
        parser->setFeature(XMLUni::fgDOMValidation, true);
        parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);

        // We build a "fake" schema location hint that binds each namespace to itself.
        // This ensures the entity resolver will be given the namespace as a systemId it can check.
        parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
    }
    parser->setProperty(XMLUni::fgXercesSecurityManager, m_security.get());
    parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
    parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
    parser->setFeature(XMLUni::fgDOMComments, false);
    parser->setEntityResolver(this);
    return parser;
}

DOMBuilder* ParserPool::checkoutBuilder()
{
    Lock lock(m_lock);
    if (m_pool.empty()) {
        DOMBuilder* builder=createBuilder();
        return builder;
    }
    DOMBuilder* p=m_pool.top();
    m_pool.pop();
    if (m_schemaAware)
        p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
    return p;
}

void ParserPool::checkinBuilder(DOMBuilder* builder)
{
    if (builder) {
        Lock lock(m_lock);
        m_pool.push(builder);
    }
}

#endif

StreamInputSource::StreamInputSource(istream& is, const char* systemId) : InputSource(systemId), m_is(is)
{
}

BinInputStream* StreamInputSource::makeStream() const
{
    return new StreamBinInputStream(m_is);
}

StreamInputSource::StreamBinInputStream::StreamBinInputStream(istream& is) : m_is(is), m_pos(0)
{
}

#ifdef XMLTOOLING_XERCESC_64BITSAFE
XMLFilePos
#else
unsigned int
#endif
StreamInputSource::StreamBinInputStream::curPos() const
{
    return m_pos;
}

#ifdef XMLTOOLING_XERCESC_64BITSAFE
const XMLCh* StreamInputSource::StreamBinInputStream::getContentType() const
{
    return nullptr;
}
#endif

xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
{
    XMLByte* target=toFill;
    xsecsize_t bytes_read=0,request=maxToRead;

    // Fulfill the rest by reading from the stream.
    if (request && !m_is.eof() && !m_is.fail()) {
        try {
            m_is.read(reinterpret_cast<char* const>(target),request);
            m_pos+=m_is.gcount();
            bytes_read+=m_is.gcount();
        }
        catch(ios_base::failure& e) {
            Category::getInstance(XMLTOOLING_LOGCAT ".StreamInputSource").critStream()
                << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
                << logging::eol;
            *toFill=0;
            return 0;
        }
    }
    return bytes_read;
}

#ifdef XMLTOOLING_LITE

URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag, std::string backingFile) : InputSource(systemId), m_backingFile(backingFile), m_url(url)
{
}

URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag, std::string backingFile) : InputSource(systemId), m_backingFile(backingFile)
{
    static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
    static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);

    const XMLCh* attr = e->getAttributeNS(nullptr, url);
    if (!attr || !*attr) {
        attr = e->getAttributeNS(nullptr, uri);
        if (!attr || !*attr)
            throw IOException("No URL supplied via DOM to URLInputSource constructor.");
    }

    m_url.setURL(attr);
}

BinInputStream* URLInputSource::makeStream() const
{
    // Ask the URL to create us an appropriate input stream
    return ("" == m_backingFile) ?  m_url.makeNewStream() : new CloneInputStream(m_url.makeNewStream(), m_backingFile);
}

#else

URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag, std::string backingFile)
    : InputSource(systemId), m_backingFile(backingFile), m_cacheTag(cacheTag), m_url(url), m_root(nullptr)
{
}

URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag, std::string backingFile)
    : InputSource(systemId), m_backingFile(backingFile), m_cacheTag(cacheTag), m_root(e)
{
}

BinInputStream* URLInputSource::makeStream() const
{
    BinInputStream*  stream = m_root ? new CurlURLInputStream(m_root, m_cacheTag) : new CurlURLInputStream(m_url.get(), m_cacheTag);
    return (m_backingFile.empty()) ? stream : new CloneInputStream(stream, m_backingFile);
}

#endif

const char URLInputSource::asciiStatusCodeElementName[] = "URLInputSourceStatus";

const XMLCh URLInputSource::utf16StatusCodeElementName[] = UNICODE_LITERAL_20(U,R,L,I,n,p,u,t,S,o,u,r,c,e,S,t,a,t,u,s);