Multi-line svn commit, see body.
[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 "logging.h"
26 #include "util/NDC.h"
27 #include "util/ParserPool.h"
28 #include "util/XMLHelper.h"
29
30 #include <algorithm>
31 #include <functional>
32 #include <sys/types.h>
33 #include <sys/stat.h>
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::logging;
42 using namespace xmltooling;
43 using namespace std;
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<const 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[] =  UNICODE_LITERAL_7(c,a,t,a,l,o,g);
145     static const XMLCh system[] =   UNICODE_LITERAL_6(s,y,s,t,e,m);
146     static const XMLCh systemId[] = UNICODE_LITERAL_8(s,y,s,t,e,m,I,d);
147     static const XMLCh uri[] =      UNICODE_LITERAL_3(u,r,i);
148     static const XMLCh CATALOG_NS[] = {
149         chLatin_u, chLatin_r, chLatin_n, chColon,
150         chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
151         chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon,
152         chLatin_t, chLatin_c, chColon,
153         chLatin_e, chLatin_n, chLatin_t, chLatin_i, chLatin_t, chLatin_y, chColon,
154         chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon,
155         chLatin_x, chLatin_m, chLatin_l, chColon,
156         chLatin_c, chLatin_a, chLatin_t, chLatin_a, chLatin_l, chLatin_o, chLatin_g, chNull
157     };
158
159     // Parse the catalog with the internal parser pool.
160
161     if (log.isDebugEnabled()) {
162         auto_ptr_char temp(pathname);
163         log.debug("loading XML catalog from %s", temp.get());
164     }
165
166     LocalFileInputSource fsrc(NULL,pathname);
167     Wrapper4InputSource domsrc(&fsrc,false);
168     try {
169         DOMDocument* doc=XMLToolingConfig::getConfig().getParser().parse(domsrc);
170         XercesJanitor<DOMDocument> janitor(doc);
171         
172         // Check root element.
173         const DOMElement* root=doc->getDocumentElement();
174         if (!XMLHelper::isNodeNamed(root,CATALOG_NS,catalog)) {
175             auto_ptr_char temp(pathname);
176             log.error("unknown root element, failed to load XML catalog from %s", temp.get());
177             return false;
178         }
179         
180         // Fetch all the <system> elements.
181         DOMNodeList* mappings=root->getElementsByTagNameNS(CATALOG_NS,system);
182         Lock lock(m_lock);
183         for (XMLSize_t i=0; i<mappings->getLength(); i++) {
184             root=static_cast<DOMElement*>(mappings->item(i));
185             const XMLCh* from=root->getAttributeNS(NULL,systemId);
186             const XMLCh* to=root->getAttributeNS(NULL,uri);
187 #ifdef HAVE_GOOD_STL
188             m_schemaLocMap[from]=to;
189 #else
190             auto_ptr_char f(from);
191             auto_ptr_char t(to);
192             m_schemaLocMap[f.get()]=t.get();
193 #endif
194         }
195         m_schemaLocations.erase();
196 #ifdef HAVE_GOOD_STL
197         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<xstring>(m_schemaLocations,chSpace));
198 #else
199         for_each(m_schemaLocMap.begin(),m_schemaLocMap.end(),doubleit<string>(m_schemaLocations,' '));
200 #endif
201     }
202     catch (exception& e) {
203         log.error("catalog loader caught exception: %s", e.what());
204         return false;
205     }
206
207     return true;
208 }
209
210 DOMInputSource* ParserPool::resolveEntity(const XMLCh* const publicId, const XMLCh* const systemId, const XMLCh* const baseURI)
211 {
212 #if _DEBUG
213     xmltooling::NDC ndc("resolveEntity");
214 #endif
215     if (!systemId)
216         return NULL;
217
218     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
219     if (log.isDebugEnabled()) {
220         auto_ptr_char sysId(systemId);
221         auto_ptr_char base(baseURI);
222         log.debug("asked to resolve %s with baseURI %s",sysId.get(),base.get() ? base.get() : "(null)");
223     }
224
225 #ifdef HAVE_GOOD_STL
226     // Find well-known schemas in the specified location.
227     map<xstring,xstring>::const_iterator i=m_schemaLocMap.find(systemId);
228     if (i!=m_schemaLocMap.end())
229         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
230
231     // Check for entity as a value in the map.
232     for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
233         if (XMLString::endsWith(i->second.c_str(), systemId))
234             return new Wrapper4InputSource(new LocalFileInputSource(baseURI,i->second.c_str()));
235     }
236
237     // We'll allow anything without embedded slashes.
238     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
239         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
240 #else
241     // Find well-known schemas in the specified location.
242     auto_ptr_char temp(systemId);
243     map<string,string>::const_iterator i=m_schemaLocMap.find(temp.get());
244     if (i!=m_schemaLocMap.end()) {
245         auto_ptr_XMLCh temp2(i->second.c_str());
246         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
247     }
248
249     // Check for entity as a value in the map.
250     for (i=m_schemaLocMap.begin(); i!=m_schemaLocMap.end(); ++i) {
251         auto_ptr_XMLCh temp2(i->second.c_str());
252         if (XMLString::endsWith(temp2.get(), systemId))
253             return new Wrapper4InputSource(new LocalFileInputSource(baseURI,temp2.get()));
254     }
255
256     // We'll allow anything without embedded slashes.
257     if (XMLString::indexOf(systemId, chForwardSlash)==-1)
258         return new Wrapper4InputSource(new LocalFileInputSource(baseURI,systemId));
259 #endif    
260
261     // Shortcircuit the request.
262 #ifdef HAVE_GOOD_STL
263     auto_ptr_char temp(systemId);
264 #endif
265     log.debug("unauthorized entity request (%s), blocking it", temp.get());
266     static const XMLByte nullbuf[] = {0};
267     return new Wrapper4InputSource(new MemBufInputSource(nullbuf,0,systemId));
268 }
269
270 bool ParserPool::handleError(const DOMError& e)
271 {
272 #ifdef _DEBUG
273     xmltooling::NDC ndc("handleError");
274 #endif
275     Category& log=Category::getInstance(XMLTOOLING_LOGCAT".ParserPool");
276     DOMLocator* locator=e.getLocation();
277     auto_ptr_char temp(e.getMessage());
278
279     switch (e.getSeverity()) {
280         case DOMError::DOM_SEVERITY_WARNING:
281             log.warnStream() << "warning on line " << locator->getLineNumber()
282                 << ", column " << locator->getColumnNumber()
283                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
284             return true;
285
286         case DOMError::DOM_SEVERITY_ERROR:
287             log.errorStream() << "error on line " << locator->getLineNumber()
288                 << ", column " << locator->getColumnNumber()
289                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
290             throw XMLParserException(string("error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
291
292         case DOMError::DOM_SEVERITY_FATAL_ERROR:
293             log.critStream() << "fatal error on line " << locator->getLineNumber()
294                 << ", column " << locator->getColumnNumber()
295                 << ", message: " << temp.get() << CategoryStream::ENDLINE;
296             throw XMLParserException(string("fatal error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
297     }
298     throw XMLParserException(string("unclassified error during XML parsing: ") + (temp.get() ? temp.get() : "no message"));
299 }
300
301 DOMBuilder* ParserPool::createBuilder()
302 {
303     static const XMLCh impltype[] = { chLatin_L, chLatin_S, chNull };
304     DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(impltype);
305     DOMBuilder* parser=static_cast<DOMImplementationLS*>(impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS,0);
306     if (m_namespaceAware)
307         parser->setFeature(XMLUni::fgDOMNamespaces,true);
308     if (m_schemaAware) {
309         parser->setFeature(XMLUni::fgXercesSchema,true);
310         parser->setFeature(XMLUni::fgDOMValidation,true);
311         parser->setFeature(XMLUni::fgXercesCacheGrammarFromParse,true);
312         parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal,true);
313         
314         // We build a "fake" schema location hint that binds each namespace to itself.
315         // This ensures the entity resolver will be given the namespace as a systemId it can check. 
316 #ifdef HAVE_GOOD_STL
317         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
318 #else
319         auto_ptr_XMLCh temp(m_schemaLocations.c_str());
320         parser->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp.get()));
321 #endif
322     }
323     parser->setFeature(XMLUni::fgXercesUserAdoptsDOMDocument,true);
324     parser->setEntityResolver(this);
325     parser->setErrorHandler(this);
326     return parser;
327 }
328
329 DOMBuilder* ParserPool::checkoutBuilder()
330 {
331     Lock lock(m_lock);
332     if (m_pool.empty()) {
333         DOMBuilder* builder=createBuilder();
334         return builder;
335     }
336     DOMBuilder* p=m_pool.top();
337     m_pool.pop();
338     if (m_schemaAware) {
339 #ifdef HAVE_GOOD_STL
340         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(m_schemaLocations.c_str()));
341 #else
342         auto_ptr_XMLCh temp2(m_schemaLocations.c_str());
343         p->setProperty(XMLUni::fgXercesSchemaExternalSchemaLocation,const_cast<XMLCh*>(temp2.get()));
344 #endif
345     }
346     return p;
347 }
348
349 void ParserPool::checkinBuilder(DOMBuilder* builder)
350 {
351     if (builder) {
352         Lock lock(m_lock);
353         m_pool.push(builder);
354     }
355 }
356
357 unsigned int StreamInputSource::StreamBinInputStream::readBytes(XMLByte* const toFill, const unsigned int maxToRead)
358 {
359     XMLByte* target=toFill;
360     unsigned int bytes_read=0,request=maxToRead;
361
362     // Fulfill the rest by reading from the stream.
363     if (request && !m_is.eof() && !m_is.fail()) {
364         try {
365             m_is.read(reinterpret_cast<char* const>(target),request);
366             m_pos+=m_is.gcount();
367             bytes_read+=m_is.gcount();
368         }
369         catch(ios_base::failure& e) {
370             Category::getInstance(XMLTOOLING_LOGCAT".StreamInputSource").critStream()
371                 << "XML::StreamInputSource::StreamBinInputStream::readBytes caught an exception: " << e.what()
372                 << CategoryStream::ENDLINE;
373             *toFill=0;
374             return 0;
375         }
376     }
377     return bytes_read;
378 }