1ce146e9b44e63a7e074be7f2686a690412d9eac
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ParserPool.cpp
1 /*
2  *  Copyright 2001-2006 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * ParserPool.cpp
19  * 
20  * XML parsing
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "util/NDC.h"
26 #include "util/ParserPool.h"
27 #include "util/XMLHelper.h"
28
29 #include <algorithm>
30 #include <functional>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <log4cpp/Category.hh>
34 #include <xercesc/util/PlatformUtils.hpp>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xercesc/sax/SAXException.hpp>
37 #include <xercesc/framework/MemBufInputSource.hpp>
38 #include <xercesc/framework/LocalFileInputSource.hpp>
39 #include <xercesc/framework/Wrapper4InputSource.hpp>
40
41 using namespace xmltooling;
42 using namespace std;
43 using namespace log4cpp;
44
45 ParserPool::ParserPool(bool namespaceAware, bool schemaAware)
46     : m_namespaceAware(namespaceAware), m_schemaAware(schemaAware), m_lock(XMLPlatformUtils::makeMutex()) {}
47
48 ParserPool::~ParserPool()
49 {
50     while(!m_pool.empty()) {
51         m_pool.top()->release();
52         m_pool.pop();
53     }
54     XMLPlatformUtils::closeMutex(m_lock);
55 }
56
57 DOMDocument* ParserPool::newDocument()
58 {
59     return DOMImplementationRegistry::getDOMImplementation(NULL)->createDocument();
60 }
61
62 DOMDocument* ParserPool::parse(DOMInputSource& domsrc)
63 {
64     DOMBuilder* parser=checkoutBuilder();
65     try {
66         DOMDocument* doc=parser->parse(domsrc);
67         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
68         checkinBuilder(parser);
69         return doc;
70     }
71     catch (...) {
72         checkinBuilder(parser);
73         throw;
74     }
75 }
76
77 DOMDocument* ParserPool::parse(istream& is)
78 {
79     StreamInputSource src(is);
80     Wrapper4InputSource domsrc(&src,false);
81     return parse(domsrc);
82 }
83
84 // Functor to double its argument separated by a character and append to a buffer
85 template <class T> class doubleit
86 {
87 public:
88     doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
89     void operator() (const pair<T,T>& s) { temp += s.first + sep + s.first + sep; }
90     T& temp;
91     const typename T::value_type& sep;
92 };
93
94 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
95 {
96     // Just check the pathname and then directly register the pair into the map.
97     
98     auto_ptr_char p(pathname);
99 #ifdef WIN32
100     struct _stat stat_buf;
101     if (_stat(p.get(), &stat_buf) != 0)
102 #else
103     struct stat stat_buf;
104     if (stat(p.get(), &stat_buf) != 0)
105 #endif
106     {
107 #if _DEBUG
108         xmltooling::NDC ndc("loadSchema");
109 #endif
110         Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
111         auto_ptr_char n(nsURI);
112         log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
113         return false;
114     }
115
116     XMLPlatformUtils::lockMutex(m_lock);
117 #ifdef HAVE_GOOD_STL
118     m_schemaLocMap[nsURI]=pathname;
119     m_schemaLocations.erase();
120     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
121 #else
122     auto_ptr_char n(nsURI);
123     m_schemaLocMap[n.get()]=p.get();
124     m_schemaLocations.erase();
125     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
126 #endif
127     XMLPlatformUtils::unlockMutex(m_lock);
128
129     return true;
130 }
131
132 bool ParserPool::loadCatalog(const XMLCh* pathname)
133 {
134 #if _DEBUG
135     xmltooling::NDC ndc("loadCatalog");
136 #endif
137     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
138
139     // XML constants
140     static const XMLCh catalog[] = { chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull };
141     static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
142     static const XMLCh name[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chNull };
143     static const XMLCh CATALOG_NS[] = {
144         chLatin_u, chLatin_r, chLatin_n, chColon,
145         chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
146         chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
147         chLatin_t, chLatin_c, chColon,
148         chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
149         chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
150         chLatin_x, chLatin_m, chLatin_l, chColon,
151         chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
152     };
153
154     // Parse the catalog with the internal parser pool.
155
156     if (log.isDebugEnabled()) {
157         auto_ptr_char temp(pathname);
158         log.debug("loading XML catalog from %s", temp.get());
159     }
160
161     LocalFileInputSource fsrc(NULL,pathname);
162     Wrapper4InputSource domsrc(&fsrc,false);
163     try {
164         DOMDocument* doc=XMLToolingInternalConfig::getInternalConfig().m_parserPool->parse(domsrc);
165         
166         // Check root element.
167         const DOMElement* root=doc->getDocumentElement();
168         if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
169             auto_ptr_char temp(pathname);
170             log.error("unknown root element, failed to load XML catalog from %s", temp.get());
171             doc->release();
172             return false;
173         }
174         
175         // Fetch all the <uri> elements.
176         DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,uri);
177         XMLPlatformUtils::lockMutex(m_lock);
178         for (XMLSize_t i=0; i<mappings->getLength(); i++) {
179             root=static_cast<DOMElement*>(mappings->item(i));
180             const XMLCh* from=root->getAttributeNS(NULL,name);
181             const XMLCh* to=root->getAttributeNS(NULL,uri);
182 #ifdef HAVE_GOOD_STL
183             m_schemaLocMap[from]=to;
184 #else
185             auto_ptr_char f(from);
186             auto_ptr_char t(to);
187             m_schemaLocMap[f.get()]=t.get();
188 #endif
189         }
190         m_schemaLocations.erase();
191 #ifdef HAVE_GOOD_STL
192         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
193 #else
194         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
195 #endif
196         XMLPlatformUtils::unlockMutex(m_lock);
197         doc->release();
198     }
199     catch (XMLParserException& e) {
200         log.error("catalog loader caught XMLParserException: %s", e.what());
201         return false;
202     }
203
204     return true;
205 }
206
207 DOMInputSource* ParserPool::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI)
208 {
209 #if _DEBUG
210     xmltooling::NDC ndc("resolveEntity");
211 #endif
212     if (!systemId)
213         return NULL;
214
215     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
216     if (log.isDebugEnabled()) {
217         auto_ptr_char sysId(systemId);
218         auto_ptr_char base(baseURI);
219         log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
220     }
221
222     // Find well-known schemas in the specified location.
223 #ifdef HAVE_GOOD_STL
224     map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
225     if (i!=m_schemaLocMap.end())
226         return new Wrapper4InputSource(new LocalFileInputSource(NULL,i->second.c_str()));
227 #else
228     auto_ptr_char temp(systemId);
229     map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
230     auto_ptr_XMLCh temp2(i->second.c_str());
231     if (i!=m_schemaLocMap.end())
232         return new Wrapper4InputSource(new LocalFileInputSource(NULL,temp2.get()));
233 #endif    
234
235     // Shortcircuit the request.
236     auto_ptr_char sysId(systemId);
237     log.warn("unauthorized entity request (%s), blocking it", sysId.get() ? sysId.get() : "no systemId");
238     static const XMLByte nullbuf[] = {0};
239     return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
240 }
241
242 bool ParserPool::handleError(const DOMError& e)
243 {
244 #ifdef _DEBUG
245     xmltooling::NDC ndc("handleError");
246 #endif
247     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
248     DOMLocator* locator=e.getLocation();
249     auto_ptr_char temp(e.getMessage());
250
251     switch (e.getSeverity()) {
252         case DOMError::DOM_SEVERITY_WARNING:
253             log.warnStream() << "warning on line " << locator->getLineNumber()
254                 << ", column " << locator->getColumnNumber()
255                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
256             return true;
257
258         case DOMError::DOM_SEVERITY_ERROR:
259             log.errorStream() << "error on line " << locator->getLineNumber()
260                 << ", column " << locator->getColumnNumber()
261                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
262             throw XMLParserException(string("error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
263
264         case DOMError::DOM_SEVERITY_FATAL_ERROR:
265             log.critStream() << "fatal error on line " << locator->getLineNumber()
266                 << ", column " << locator->getColumnNumber()
267                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
268             throw XMLParserException(string("fatal error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
269     }
270     throw XMLParserException(string("unclassified error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
271 }
272
273 DOMBuilder* ParserPool::createBuilder()
274 {
275     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
276     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
277     DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
278     if (m_namespaceAware)
279         parser->setFeature(XMLUni::fgDOMNamespaces,true);
280     if (m_schemaAware) {
281         parser->setFeature(XMLUni::fgXercesSchema,true);
282         parser->setFeature(XMLUni::fgDOMValidation,true);
283         parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse,true);
284         parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal,true);
285         
286         // We build a "fake" schema location hint that binds each namespace to itself.
287         // This ensures the entity resolver will be given the namespace as a systemId it can check. 
288 #ifdef HAVE_GOOD_STL
289         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
290 #else
291         auto_ptr_XMLCh temp(m_schemaLocations.c_str());
292         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
293 #endif
294     }
295     parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
296     parser->setEntityResolver(this);
297     parser->setErrorHandler(this);
298     return parser;
299 }
300
301 DOMBuilder* ParserPool::checkoutBuilder()
302 {
303     XMLPlatformUtils::lockMutex(m_lock);
304     try {
305         if (m_pool.empty()) {
306             DOMBuilder* builder=createBuilder();
307             XMLPlatformUtils::unlockMutex(m_lock);
308             return builder;
309         }
310         DOMBuilder* p=m_pool.top();
311         m_pool.pop();
312         if (m_schemaAware) {
313 #ifdef HAVE_GOOD_STL
314             p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
315 #else
316             auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
317             p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
318 #endif
319         }
320         XMLPlatformUtils::unlockMutex(m_lock);
321         return p;
322     }
323     catch(...) {
324         XMLPlatformUtils::unlockMutex(m_lock);
325         throw;
326     }
327 }
328
329 void ParserPool::checkinBuilder(DOMBuilder* builder)
330 {
331     if (builder) {
332         XMLPlatformUtils::lockMutex(m_lock);
333         m_pool.push(builder);
334         XMLPlatformUtils::unlockMutex(m_lock);
335     }
336 }
337
338 unsigned int StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const unsigned int maxToRead)
339 {
340     XMLByte* target=toFill;
341     unsigned int bytes_read=0,request=maxToRead;
342
343     // Fulfill the rest by reading from the stream.
344     if (request && !m_is.eof()) {
345         try {
346             m_is.read(reinterpret_cast<char* const>(target),request);
347             m_pos+=m_is.gcount();
348             bytes_read+=m_is.gcount();
349         }
350         catch(...) {
351             Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream() <<
352                 "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception" << CategoryStream::ENDLINE;
353             *toFill=0;
354             return 0;
355         }
356     }
357     return bytes_read;
358 }