Merge branch '1.x' of ssh://authdev.it.ohio-state.edu/~scantor/git/cpp-xmltooling...
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ParserPool.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * ParserPool.cpp
23  *
24  * A thread-safe pool of parsers that share characteristics.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "logging.h"
30 #include "util/CurlURLInputStream.h"
31 #include "util/NDC.h"
32 #include "util/ParserPool.h"
33 #include "util/Threads.h"
34 #include "util/XMLHelper.h"
35
36 #include <algorithm>
37 #include <functional>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <xercesc/util/PlatformUtils.hpp>
41 #include <xercesc/util/XMLUniDefs.hpp>
42 #include <xercesc/sax/SAXException.hpp>
43 #include <xercesc/framework/MemBufInputSource.hpp>
44 #include <xercesc/framework/LocalFileInputSource.hpp>
45 #include <xercesc/framework/Wrapper4InputSource.hpp>
46
47 using namespace xmltooling::logging;
48 using namespace xmltooling;
49 using namespace xercesc;
50 using namespace std;
51
52
53 namespace {
54     class MyErrorHandler : public DOMErrorHandler {
55     public:
56         unsigned int errors;
57
58         MyErrorHandler() : errors(0) {}
59
60         bool handleError(const DOMError& e)
61         {
62 #ifdef _DEBUG
63             xmltooling::NDC ndc("handleError");
64 #endif
65             Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
66
67             DOMLocator* locator=e.getLocation();
68             auto_ptr_char temp(e.getMessage());
69
70             switch (e.getSeverity()) {
71                 case DOMError::DOM_SEVERITY_WARNING:
72                     log.warnStream() << "warning on line " << locator->getLineNumber()
73                         << ", column " << locator->getColumnNumber()
74                         << ", message: " << temp.get() << logging::eol;
75                     return true;
76
77                 case DOMError::DOM_SEVERITY_ERROR:
78                     ++errors;
79                     log.errorStream() << "error on line " << locator->getLineNumber()
80                         << ", column " << locator->getColumnNumber()
81                         << ", message: " << temp.get() << logging::eol;
82                     return true;
83
84                 case DOMError::DOM_SEVERITY_FATAL_ERROR:
85                     ++errors;
86                     log.errorStream() << "fatal error on line " << locator->getLineNumber()
87                         << ", column " << locator->getColumnNumber()
88                         << ", message: " << temp.get() << logging::eol;
89                     return true;
90             }
91
92             ++errors;
93             log.errorStream() << "undefined error type on line " << locator->getLineNumber()
94                 << ", column " << locator->getColumnNumber()
95                 << ", message: " << temp.get() << logging::eol;
96             return false;
97         }
98     };
99 }
100
101
102 ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
103     : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(Mutex::create()), m_security(new SecurityManager()) {}
104
105 ParserPool::~ParserPool()
106 {
107     while(!m_pool.empty()) {
108         m_pool.top()->release();
109         m_pool.pop();
110     }
111     delete m_lock;
112     delete m_security;
113 }
114
115 DOMDocument* ParserPool::newDocument()
116 {
117     return DOMImplementationRegistry::getDOMImplementation(nullptr)->createDocument();
118 }
119
120 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
121
122 DOMDocument* ParserPool::parse(DOMLSInput& domsrc)
123 {
124     DOMLSParser* parser=checkoutBuilder();
125     XercesJanitor<DOMLSParser> janitor(parser);
126     try {
127         MyErrorHandler deh;
128         parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, dynamic_cast<DOMErrorHandler*>(&deh));
129         DOMDocument* doc=parser->parse(&domsrc);
130         if (deh.errors) {
131             if (doc)
132                 doc->release();
133             throw XMLParserException("XML error(s) during parsing, check log for specifics");
134         }
135         parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
136         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
137         checkinBuilder(janitor.release());
138         return doc;
139     }
140     catch (XMLException& ex) {
141         parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
142         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
143         checkinBuilder(janitor.release());
144         auto_ptr_char temp(ex.getMessage());
145         throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
146     }
147     catch (XMLToolingException&) {
148         parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, (void*)nullptr);
149         parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
150         checkinBuilder(janitor.release());
151         throw;
152     }
153 }
154
155 #else
156
157 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
158 {
159     DOMBuilder* parser=checkoutBuilder();
160     XercesJanitor<DOMBuilder> janitor(parser);
161     try {
162         MyErrorHandler deh;
163         parser->setErrorHandler(&deh);
164         DOMDocument* doc=parser->parse(domsrc);
165         if (deh.errors) {
166             if (doc)
167                 doc->release();
168             throw XMLParserException("XML error(s) during parsing, check log for specifics");
169         }
170         parser->setErrorHandler(nullptr);
171         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
172         checkinBuilder(janitor.release());
173         return doc;
174     }
175     catch (XMLException& ex) {
176         parser->setErrorHandler(nullptr);
177         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
178         checkinBuilder(janitor.release());
179         auto_ptr_char temp(ex.getMessage());
180         throw XMLParserException(string("Xerces error during parsing: ") + (temp.get() ? temp.get() : "no message"));
181     }
182     catch (XMLToolingException&) {
183         parser->setErrorHandler(nullptr);
184         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
185         checkinBuilder(janitor.release());
186         throw;
187     }
188 }
189
190 #endif
191
192 DOMDocument* ParserPool::parse(istream& is)
193 {
194     StreamInputSource src(is);
195     Wrapper4InputSource domsrc(&src,false);
196     return parse(domsrc);
197 }
198
199 // Functor to double its argument separated by a character and append to a buffer
200 template <class T> class doubleit
201 {
202 public:
203     doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
204     void operator() (const pair<const T,T>& s) { temp += s.first + sep + s.first + sep; }
205     T& temp;
206     const typename T::value_type& sep;
207 };
208
209 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
210 {
211     // Just check the pathname and then directly register the pair into the map.
212
213     auto_ptr_char p(pathname);
214 #ifdef WIN32
215     struct _stat stat_buf;
216     if (_stat(p.get(), &stat_buf) != 0)
217 #else
218     struct stat stat_buf;
219     if (stat(p.get(), &stat_buf) != 0)
220 #endif
221     {
222 #if _DEBUG
223         xmltooling::NDC ndc("loadSchema");
224 #endif
225         Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
226         auto_ptr_char n(nsURI);
227         log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
228         return false;
229     }
230
231     Lock lock(m_lock);
232     m_schemaLocMap[nsURI]=pathname;
233     m_schemaLocations.erase();
234     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
235
236     return true;
237 }
238
239 bool ParserPool::loadCatalog(const XMLCh* pathname)
240 {
241 #if _DEBUG
242     xmltooling::NDC ndc("loadCatalog");
243 #endif
244     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
245
246     // XML constants
247     static const XMLCh catalog[] =  UNICODE_LITERAL_7(c,a,t,a,l,o,g);
248     static const XMLCh system[] =   UNICODE_LITERAL_6(s,y,s,t,e,m);
249     static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
250     static const XMLCh uri[] =      UNICODE_LITERAL_3(u,r,i);
251     static const XMLCh CATALOG_NS[] = {
252         chLatin_u, chLatin_r, chLatin_n, chColon,
253         chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
254         chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
255         chLatin_t, chLatin_c, chColon,
256         chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
257         chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
258         chLatin_x, chLatin_m, chLatin_l, chColon,
259         chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
260     };
261
262     // Parse the catalog with the internal parser pool.
263
264     if (log.isDebugEnabled()) {
265         auto_ptr_char temp(pathname);
266         log.debug("loading XML catalog from %s", temp.get());
267     }
268
269     LocalFileInputSource fsrc(nullptr,pathname);
270     Wrapper4InputSource domsrc(&fsrc,false);
271     try {
272         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
273         XercesJanitor<DOMDocument> janitor(doc);
274
275         // Check root element.
276         const DOMElement* root=doc->getDocumentElement();
277         if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
278             auto_ptr_char temp(pathname);
279             log.error("unknown root element, failed to load XML catalog from %s", temp.get());
280             return false;
281         }
282
283         // Fetch all the <system> elements.
284         DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
285         Lock lock(m_lock);
286         for (XMLSize_t i=0; i<mappings->getLength(); i++) {
287             root=static_cast<DOMElement*>(mappings->item(i));
288             const XMLCh* from=root->getAttributeNS(nullptr,systemId);
289             const XMLCh* to=root->getAttributeNS(nullptr,uri);
290             m_schemaLocMap[from]=to;
291         }
292         m_schemaLocations.erase();
293         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
294     }
295     catch (exception& e) {
296         log.error("catalog loader caught exception: %s", e.what());
297         return false;
298     }
299
300     return true;
301 }
302
303 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
304 DOMLSInput* ParserPool::resolveResource(
305             const XMLCh *const resourceType,
306             const XMLCh *const namespaceUri,
307             const XMLCh *const publicId,
308             const XMLCh *const systemId,
309             const XMLCh *const baseURI
310             )
311 #else
312 DOMInputSource* ParserPool::resolveEntity(
313     const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI
314     )
315 #endif
316 {
317 #if _DEBUG
318     xmltooling::NDC ndc("resolveEntity");
319 #endif
320     if (!systemId)
321         return nullptr;
322
323     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
324     if (log.isDebugEnabled()) {
325         auto_ptr_char sysId(systemId);
326         auto_ptr_char base(baseURI);
327         log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
328     }
329
330     // Find well-known schemas in the specified location.
331     map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
332     if (i!=m_schemaLocMap.end())
333         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
334
335     // Check for entity as a value in the map.
336     for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
337         if (XMLString::endsWith(i->second.c_str(), systemId))
338             return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
339     }
340
341     // We'll allow anything without embedded slashes.
342     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
343         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
344
345     // Shortcircuit the request.
346     auto_ptr_char temp(systemId);
347     log.debug("unauthorized entity request (%s), blocking it", temp.get());
348     static const XMLByte nullbuf[] = {0};
349     return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
350 }
351
352 #ifdef XMLTOOLING_XERCESC_COMPLIANT_DOMLS
353
354 DOMLSParser* ParserPool::createBuilder()
355 {
356     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
357     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
358     DOMLSParser* parser=static_cast<DOMImplementationLS*>(impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS,nullptr);
359     parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, m_namespaceAware);
360     if (m_schemaAware) {
361         parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true);
362         parser->getDomConfig()->setParameter(XMLUni::fgXercesSchema, true);
363         parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true);
364         parser->getDomConfig()->setParameter(XMLUni::fgXercesCacheGrammarFromParse, true);
365
366         // We build a "fake" schema location hint that binds each namespace to itself.
367         // This ensures the entity resolver will be given the namespace as a systemId it can check.
368         parser->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
369     }
370     parser->getDomConfig()->setParameter(XMLUni::fgXercesUserAdoptsDOMDocument, true);
371     parser->getDomConfig()->setParameter(XMLUni::fgXercesDisableDefaultEntityResolution, true);
372     parser->getDomConfig()->setParameter(XMLUni::fgDOMResourceResolver, dynamic_cast<DOMLSResourceResolver*>(this));
373     parser->getDomConfig()->setParameter(XMLUni::fgXercesSecurityManager, m_security);
374     return parser;
375 }
376
377 DOMLSParser* ParserPool::checkoutBuilder()
378 {
379     Lock lock(m_lock);
380     if (m_pool.empty()) {
381         DOMLSParser* builder=createBuilder();
382         return builder;
383     }
384     DOMLSParser* p=m_pool.top();
385     m_pool.pop();
386     if (m_schemaAware)
387         p->getDomConfig()->setParameter(XMLUni::fgXercesSchemaExternalSchemaLocation, const_cast<XMLCh*>(m_schemaLocations.c_str()));
388     return p;
389 }
390
391 void ParserPool::checkinBuilder(DOMLSParser* builder)
392 {
393     if (builder) {
394         Lock lock(m_lock);
395         m_pool.push(builder);
396     }
397 }
398
399 #else
400
401 DOMBuilder* ParserPool::createBuilder()
402 {
403     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
404     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
405     DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
406     parser->setFeature(XMLUni::fgDOMNamespaces, m_namespaceAware);
407     if (m_schemaAware) {
408         parser->setFeature(XMLUni::fgDOMNamespaces, true);
409         parser->setFeature(XMLUni::fgXercesSchema, true);
410         parser->setFeature(XMLUni::fgDOMValidation, true);
411         parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse, true);
412
413         // We build a "fake" schema location hint that binds each namespace to itself.
414         // This ensures the entity resolver will be given the namespace as a systemId it can check.
415         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
416     }
417     parser->setProperty(XMLUni::fgXercesSecurityManager, m_security);
418     parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument, true);
419     parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
420     parser->setEntityResolver(this);
421     return parser;
422 }
423
424 DOMBuilder* ParserPool::checkoutBuilder()
425 {
426     Lock lock(m_lock);
427     if (m_pool.empty()) {
428         DOMBuilder* builder=createBuilder();
429         return builder;
430     }
431     DOMBuilder* p=m_pool.top();
432     m_pool.pop();
433     if (m_schemaAware)
434         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
435     return p;
436 }
437
438 void ParserPool::checkinBuilder(DOMBuilder* builder)
439 {
440     if (builder) {
441         Lock lock(m_lock);
442         m_pool.push(builder);
443     }
444 }
445
446 #endif
447
448 StreamInputSource::StreamInputSource(istream& is, const char* systemId) : InputSource(systemId), m_is(is)
449 {
450 }
451
452 BinInputStream* StreamInputSource::makeStream() const
453 {
454     return new StreamBinInputStream(m_is);
455 }
456
457 StreamInputSource::StreamBinInputStream::StreamBinInputStream(istream& is) : m_is(is), m_pos(0)
458 {
459 }
460
461 #ifdef XMLTOOLING_XERCESC_64BITSAFE
462 XMLFilePos
463 #else
464 unsigned int
465 #endif
466 StreamInputSource::StreamBinInputStream::curPos() const
467 {
468     return m_pos;
469 }
470
471 #ifdef XMLTOOLING_XERCESC_64BITSAFE
472 const XMLCh* StreamInputSource::StreamBinInputStream::getContentType() const
473 {
474     return nullptr;
475 }
476 #endif
477
478 xsecsize_t StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const xsecsize_t maxToRead)
479 {
480     XMLByte* target=toFill;
481     xsecsize_t bytes_read=0,request=maxToRead;
482
483     // Fulfill the rest by reading from the stream.
484     if (request && !m_is.eof() && !m_is.fail()) {
485         try {
486             m_is.read(reinterpret_cast<char* const>(target),request);
487             m_pos+=m_is.gcount();
488             bytes_read+=m_is.gcount();
489         }
490         catch(ios_base::failure& e) {
491             Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
492                 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
493                 << logging::eol;
494             *toFill=0;
495             return 0;
496         }
497     }
498     return bytes_read;
499 }
500
501 #ifdef XMLTOOLING_LITE
502
503 URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag) : InputSource(systemId), m_url(url)
504 {
505 }
506
507 URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag) : InputSource(systemId)
508 {
509     static const XMLCh uri[] = UNICODE_LITERAL_3(u,r,i);
510     static const XMLCh url[] = UNICODE_LITERAL_3(u,r,l);
511
512     const XMLCh* attr = e->getAttributeNS(nullptr, url);
513     if (!attr || !*attr) {
514         attr = e->getAttributeNS(nullptr, uri);
515         if (!attr || !*attr)
516             throw IOException("No URL supplied via DOM to URLInputSource constructor.");
517     }
518
519     m_url.setURL(attr);
520 }
521
522 BinInputStream* URLInputSource::makeStream() const
523 {
524     // Ask the URL to create us an appropriate input stream
525     return m_url.makeNewStream();
526 }
527
528 #else
529
530 URLInputSource::URLInputSource(const XMLCh* url, const char* systemId, string* cacheTag)
531     : InputSource(systemId), m_cacheTag(cacheTag), m_url(url), m_root(nullptr)
532 {
533 }
534
535 URLInputSource::URLInputSource(const DOMElement* e, const char* systemId, string* cacheTag)
536     : InputSource(systemId), m_cacheTag(cacheTag), m_root(e)
537 {
538 }
539
540 BinInputStream* URLInputSource::makeStream() const
541 {
542     return m_root ? new CurlURLInputStream(m_root, m_cacheTag) : new CurlURLInputStream(m_url.get(), m_cacheTag);
543 }
544
545 #endif
546
547 const char URLInputSource::asciiStatusCodeElementName[] = "URLInputSourceStatus";
548
549 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);