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