a06e07f9172cc68bd509fdf766887c87bfdd419c
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ParserPool.cpp
1 /*
2  *  Copyright 2001-2007 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(Mutex::create()) {}
47
48 ParserPool::~ParserPool()
49 {
50     while(!m_pool.empty()) {
51         m_pool.top()->release();
52         m_pool.pop();
53     }
54     delete 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     XercesJanitor<DOMBuilder> janitor(parser);
66     try {
67         DOMDocument* doc=parser->parse(domsrc);
68         parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
69         checkinBuilder(janitor.release());
70         return doc;
71     }
72     catch (XMLException&) {
73         checkinBuilder(janitor.release());
74         throw;
75     }
76     catch (XMLToolingException&) {
77         checkinBuilder(janitor.release());
78         throw;
79     }
80 }
81
82 DOMDocument* ParserPool::parse(istream& is)
83 {
84     StreamInputSource src(is);
85     Wrapper4InputSource domsrc(&src,false);
86     return parse(domsrc);
87 }
88
89 // Functor to double its argument separated by a character and append to a buffer
90 template <class T> class doubleit
91 {
92 public:
93     doubleit(T& t, const typename T::value_type& s) : temp(t), sep(s) {}
94     void operator() (const pair<T,T>& s) { temp += s.first + sep + s.first + sep; }
95     T& temp;
96     const typename T::value_type& sep;
97 };
98
99 bool ParserPool::loadSchema(const XMLCh* nsURI, const XMLCh* pathname)
100 {
101     // Just check the pathname and then directly register the pair into the map.
102     
103     auto_ptr_char p(pathname);
104 #ifdef WIN32
105     struct _stat stat_buf;
106     if (_stat(p.get(), &stat_buf) != 0)
107 #else
108     struct stat stat_buf;
109     if (stat(p.get(), &stat_buf) != 0)
110 #endif
111     {
112 #if _DEBUG
113         xmltooling::NDC ndc("loadSchema");
114 #endif
115         Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
116         auto_ptr_char n(nsURI);
117         log.error("failed to load schema for (%s), file not found (%s)",n.get(),p.get());
118         return false;
119     }
120
121     Lock lock(m_lock);
122 #ifdef HAVE_GOOD_STL
123     m_schemaLocMap[nsURI]=pathname;
124     m_schemaLocations.erase();
125     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
126 #else
127     auto_ptr_char n(nsURI);
128     m_schemaLocMap[n.get()]=p.get();
129     m_schemaLocations.erase();
130     for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
131 #endif
132
133     return true;
134 }
135
136 bool ParserPool::loadCatalog(const XMLCh* pathname)
137 {
138 #if _DEBUG
139     xmltooling::NDC ndc("loadCatalog");
140 #endif
141     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
142
143     // XML constants
144     static const XMLCh catalog[] = { chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull };
145     static const XMLCh uri[] = { chLatin_u, chLatin_r, chLatin_i, chNull };
146     static const XMLCh name[] = { chLatin_n, chLatin_a, chLatin_m, chLatin_e, chNull };
147     static const XMLCh CATALOG_NS[] = {
148         chLatin_u, chLatin_r, chLatin_n, chColon,
149         chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
150         chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
151         chLatin_t, chLatin_c, chColon,
152         chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
153         chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
154         chLatin_x, chLatin_m, chLatin_l, chColon,
155         chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
156     };
157
158     // Parse the catalog with the internal parser pool.
159
160     if (log.isDebugEnabled()) {
161         auto_ptr_char temp(pathname);
162         log.debug("loading XML catalog from %s", temp.get());
163     }
164
165     LocalFileInputSource fsrc(NULL,pathname);
166     Wrapper4InputSource domsrc(&fsrc,false);
167     try {
168         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
169         XercesJanitor<DOMDocument> janitor(doc);
170         
171         // Check root element.
172         const DOMElement* root=doc->getDocumentElement();
173         if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
174             auto_ptr_char temp(pathname);
175             log.error("unknown root element, failed to load XML catalog from %s", temp.get());
176             return false;
177         }
178         
179         // Fetch all the <uri> elements.
180         DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,uri);
181         Lock lock(m_lock);
182         for (XMLSize_t i=0; i<mappings->getLength(); i++) {
183             root=static_cast<DOMElement*>(mappings->item(i));
184             const XMLCh* from=root->getAttributeNS(NULL,name);
185             const XMLCh* to=root->getAttributeNS(NULL,uri);
186 #ifdef HAVE_GOOD_STL
187             m_schemaLocMap[from]=to;
188 #else
189             auto_ptr_char f(from);
190             auto_ptr_char t(to);
191             m_schemaLocMap[f.get()]=t.get();
192 #endif
193         }
194         m_schemaLocations.erase();
195 #ifdef HAVE_GOOD_STL
196         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
197 #else
198         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
199 #endif
200     }
201     catch (XMLParserException& e) {
202         log.error("catalog loader caught XMLParserException: %s", e.what());
203         return false;
204     }
205
206     return true;
207 }
208
209 DOMInputSource* ParserPool::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI)
210 {
211 #if _DEBUG
212     xmltooling::NDC ndc("resolveEntity");
213 #endif
214     if (!systemId)
215         return NULL;
216
217     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
218     if (log.isDebugEnabled()) {
219         auto_ptr_char sysId(systemId);
220         auto_ptr_char base(baseURI);
221         log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
222     }
223
224 #ifdef HAVE_GOOD_STL
225     // Find well-known schemas in the specified location.
226     map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
227     if (i!=m_schemaLocMap.end())
228         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
229
230     // Check for entity as a value in the map.
231     for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
232         if (XMLString::endsWith(i->second.c_str(), systemId))
233             return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
234     }
235
236     // We'll allow anything without embedded slashes.
237     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
238         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
239 #else
240     // Find well-known schemas in the specified location.
241     auto_ptr_char temp(systemId);
242     map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
243     if (i!=m_schemaLocMap.end()) {
244         auto_ptr_XMLCh temp2(i->second.c_str());
245         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
246     }
247
248     // Check for entity as a value in the map.
249     for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
250         auto_ptr_XMLCh temp2(i->second.c_str());
251         if (XMLString::endsWith(temp2.get(), systemId))
252             return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
253     }
254
255     // We'll allow anything without embedded slashes.
256     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
257         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
258 #endif    
259
260     // Shortcircuit the request.
261 #ifdef HAVE_GOOD_STL
262     auto_ptr_char temp(systemId);
263 #endif
264     log.debug("unauthorized entity request (%s), blocking it", temp.get());
265     static const XMLByte nullbuf[] = {0};
266     return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
267 }
268
269 bool ParserPool::handleError(const DOMError& e)
270 {
271 #ifdef _DEBUG
272     xmltooling::NDC ndc("handleError");
273 #endif
274     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
275     DOMLocator* locator=e.getLocation();
276     auto_ptr_char temp(e.getMessage());
277
278     switch (e.getSeverity()) {
279         case DOMError::DOM_SEVERITY_WARNING:
280             log.warnStream() << "warning on line " << locator->getLineNumber()
281                 << ", column " << locator->getColumnNumber()
282                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
283             return true;
284
285         case DOMError::DOM_SEVERITY_ERROR:
286             log.errorStream() << "error on line " << locator->getLineNumber()
287                 << ", column " << locator->getColumnNumber()
288                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
289             throw XMLParserException(string("error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
290
291         case DOMError::DOM_SEVERITY_FATAL_ERROR:
292             log.critStream() << "fatal error on line " << locator->getLineNumber()
293                 << ", column " << locator->getColumnNumber()
294                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
295             throw XMLParserException(string("fatal error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
296     }
297     throw XMLParserException(string("unclassified error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
298 }
299
300 DOMBuilder* ParserPool::createBuilder()
301 {
302     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
303     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
304     DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
305     if (m_namespaceAware)
306         parser->setFeature(XMLUni::fgDOMNamespaces,true);
307     if (m_schemaAware) {
308         parser->setFeature(XMLUni::fgXercesSchema,true);
309         parser->setFeature(XMLUni::fgDOMValidation,true);
310         parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse,true);
311         parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal,true);
312         
313         // We build a "fake" schema location hint that binds each namespace to itself.
314         // This ensures the entity resolver will be given the namespace as a systemId it can check. 
315 #ifdef HAVE_GOOD_STL
316         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
317 #else
318         auto_ptr_XMLCh temp(m_schemaLocations.c_str());
319         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
320 #endif
321     }
322     parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
323     parser->setEntityResolver(this);
324     parser->setErrorHandler(this);
325     return parser;
326 }
327
328 DOMBuilder* ParserPool::checkoutBuilder()
329 {
330     Lock lock(m_lock);
331     if (m_pool.empty()) {
332         DOMBuilder* builder=createBuilder();
333         return builder;
334     }
335     DOMBuilder* p=m_pool.top();
336     m_pool.pop();
337     if (m_schemaAware) {
338 #ifdef HAVE_GOOD_STL
339         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
340 #else
341         auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
342         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
343 #endif
344     }
345     return p;
346 }
347
348 void ParserPool::checkinBuilder(DOMBuilder* builder)
349 {
350     if (builder) {
351         Lock lock(m_lock);
352         m_pool.push(builder);
353     }
354 }
355
356 unsigned int StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const unsigned int maxToRead)
357 {
358     XMLByte* target=toFill;
359     unsigned int bytes_read=0,request=maxToRead;
360
361     // Fulfill the rest by reading from the stream.
362     if (request && !m_is.eof() && !m_is.fail()) {
363         try {
364             m_is.read(reinterpret_cast<char* const>(target),request);
365             m_pos+=m_is.gcount();
366             bytes_read+=m_is.gcount();
367         }
368         catch(ios_base::failure& e) {
369             Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
370                 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
371                 << CategoryStream::ENDLINE;
372             *toFill=0;
373             return 0;
374         }
375     }
376     return bytes_read;
377 }