Treat . and .. as absolute path signals.
[shibboleth/xmltooling.git] / xmltooling / util / ReloadableXMLFile.cpp
1 /*\r
2  *  Copyright 2001-2007 Internet2\r
3  * \r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *     http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 /**\r
18  * @file ReloadableXMLFile.cpp\r
19  * \r
20  * Base class for file-based XML configuration.\r
21  */\r
22 \r
23 #include "internal.h"\r
24 #include "util/NDC.h"\r
25 #include "util/PathResolver.h"\r
26 #include "util/ReloadableXMLFile.h"\r
27 #include "util/XMLConstants.h"\r
28 #include "util/XMLHelper.h"\r
29 \r
30 #include <fstream>\r
31 #include <sys/types.h>\r
32 #include <sys/stat.h>\r
33 \r
34 #include <xercesc/framework/LocalFileInputSource.hpp>\r
35 #include <xercesc/framework/Wrapper4InputSource.hpp>\r
36 #include <xercesc/framework/URLInputSource.hpp>\r
37 #include <xercesc/util/XMLUniDefs.hpp>\r
38 \r
39 using namespace xmltooling::logging;\r
40 using namespace xmltooling;\r
41 using namespace std;\r
42 \r
43 static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);\r
44 static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);\r
45 static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);\r
46 static const XMLCh pathname[] =         UNICODE_LITERAL_8(p,a,t,h,n,a,m,e);\r
47 static const XMLCh file[] =             UNICODE_LITERAL_4(f,i,l,e);\r
48 static const XMLCh filename[] =         UNICODE_LITERAL_8(f,i,l,e,n,a,m,e);\r
49 static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);\r
50 static const XMLCh reloadChanges[] =    UNICODE_LITERAL_13(r,e,l,o,a,d,C,h,a,n,g,e,s);\r
51 static const XMLCh reloadInterval[] =   UNICODE_LITERAL_14(r,e,l,o,a,d,I,n,t,e,r,v,a,l);\r
52 static const XMLCh backingFilePath[] =  UNICODE_LITERAL_15(b,a,c,k,i,n,g,F,i,l,e,P,a,t,h);\r
53 \r
54 ReloadableXMLFile::ReloadableXMLFile(const DOMElement* e, Category& log)\r
55     : m_root(e), m_local(true), m_validate(false), m_filestamp(0), m_reloadInterval(0), m_lock(NULL), m_log(log)\r
56 {\r
57 #ifdef _DEBUG\r
58     NDC ndc("ReloadableXMLFile");\r
59 #endif\r
60 \r
61     // Establish source of data...\r
62     const XMLCh* source=e->getAttributeNS(NULL,uri);\r
63     if (!source || !*source) {\r
64         source=e->getAttributeNS(NULL,url);\r
65         if (!source || !*source) {\r
66             source=e->getAttributeNS(NULL,path);\r
67             if (!source || !*source) {\r
68                 source=e->getAttributeNS(NULL,pathname);\r
69                 if (!source || !*source) {\r
70                     source=e->getAttributeNS(NULL,file);\r
71                     if (!source || !*source) {\r
72                         source=e->getAttributeNS(NULL,filename);\r
73                     }\r
74                 }\r
75             }\r
76         }\r
77         else\r
78             m_local=false;\r
79     }\r
80     else\r
81         m_local=false;\r
82     \r
83     if (source && *source) {\r
84         const XMLCh* flag=e->getAttributeNS(NULL,validate);\r
85         m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));\r
86 \r
87         auto_ptr_char temp(source);\r
88         m_source=temp.get();\r
89         \r
90         if (!m_local && !strstr(m_source.c_str(),"://")) {\r
91             log.warn("deprecated usage of uri/url attribute for a local resource, use path instead");\r
92             m_local=true;\r
93         }\r
94 \r
95         if (m_local) {\r
96             XMLToolingConfig::getConfig().getPathResolver()->resolve(m_source, PathResolver::XMLTOOLING_CFG_FILE);\r
97 \r
98             flag=e->getAttributeNS(NULL,reloadChanges);\r
99             if (!XMLString::equals(flag,xmlconstants::XML_FALSE) && !XMLString::equals(flag,xmlconstants::XML_ZERO)) {\r
100 #ifdef WIN32\r
101                 struct _stat stat_buf;\r
102                 if (_stat(m_source.c_str(), &stat_buf) == 0)\r
103 #else\r
104                 struct stat stat_buf;\r
105                 if (stat(m_source.c_str(), &stat_buf) == 0)\r
106 #endif\r
107                     m_filestamp=stat_buf.st_mtime;\r
108                 else\r
109                     throw IOException("Unable to access local file ($1)", params(1,m_source.c_str()));\r
110                 m_lock=RWLock::create();\r
111             }\r
112             log.debug("using local resource (%s), will %smonitor for changes", m_source.c_str(), m_lock ? "" : "not ");\r
113         }\r
114         else {\r
115             log.debug("using remote resource (%s)", m_source.c_str());\r
116             source = e->getAttributeNS(NULL,backingFilePath);\r
117             if (source && *source) {\r
118                 auto_ptr_char temp2(source);\r
119                 m_backing=temp2.get();\r
120                 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_backing, PathResolver::XMLTOOLING_RUN_FILE);\r
121                 log.debug("backup remote resource with (%s)", m_backing.c_str());\r
122             }\r
123             source = e->getAttributeNS(NULL,reloadInterval);\r
124             if (source && *source) {\r
125                 m_reloadInterval = XMLString::parseInt(source);\r
126                 if (m_reloadInterval > 0) {\r
127                     m_log.debug("will reload remote resource at most every %d seconds", m_reloadInterval);\r
128                     m_lock=RWLock::create();\r
129                 }\r
130             }\r
131             m_filestamp = time(NULL);   // assume it gets loaded initially\r
132         }\r
133     }\r
134     else {\r
135         log.debug("no resource uri/path/name supplied, will load inline configuration");\r
136     }\r
137 }\r
138 \r
139 pair<bool,DOMElement*> ReloadableXMLFile::load(bool backup)\r
140 {\r
141 #ifdef _DEBUG\r
142     NDC ndc("init");\r
143 #endif\r
144 \r
145     try {\r
146         if (m_source.empty()) {\r
147             // Data comes from the DOM we were handed.\r
148             m_log.debug("loading inline configuration...");\r
149             return make_pair(false,XMLHelper::getFirstChildElement(m_root));\r
150         }\r
151         else {\r
152             // Data comes from a file we have to parse.\r
153             if (backup)\r
154                 m_log.warn("using local backup of remote resource");\r
155             else\r
156                 m_log.debug("loading configuration from external resource...");\r
157 \r
158             DOMDocument* doc=NULL;\r
159             auto_ptr_XMLCh widenit(backup ? m_backing.c_str() : m_source.c_str());\r
160             if (m_local || backup) {\r
161                 LocalFileInputSource src(widenit.get());\r
162                 Wrapper4InputSource dsrc(&src,false);\r
163                 if (m_validate)\r
164                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
165                 else\r
166                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
167             }\r
168             else {\r
169                 URLInputSource src(widenit.get());\r
170                 Wrapper4InputSource dsrc(&src,false);\r
171                 if (m_validate)\r
172                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
173                 else\r
174                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
175             }\r
176 \r
177             m_log.infoStream() << "loaded XML resource (" << (backup ? m_backing : m_source) << ")" << logging::eol;\r
178 \r
179             if (!backup && !m_backing.empty()) {\r
180                 m_log.debug("backing up remote resource to (%s)", m_backing.c_str());\r
181                 try {\r
182                     ofstream backer(m_backing.c_str());\r
183                     backer << *(doc->getDocumentElement());\r
184                 }\r
185                 catch (exception& ex) {\r
186                     m_log.crit("exception while backing up resource: %s", ex.what());\r
187                 }\r
188             }\r
189 \r
190             return make_pair(true,doc->getDocumentElement());\r
191         }\r
192     }\r
193     catch (XMLException& e) {\r
194         auto_ptr_char msg(e.getMessage());\r
195         m_log.errorStream() << "Xerces error while loading resource (" << (backup ? m_backing : m_source) << "): "\r
196             << msg.get() << logging::eol;\r
197         if (!backup && !m_backing.empty())\r
198             return load(true);\r
199         throw XMLParserException(msg.get());\r
200     }\r
201     catch (exception& e) {\r
202         m_log.errorStream() << "error while loading configuration from ("\r
203             << (m_source.empty() ? "inline" : (backup ? m_backing : m_source)) << "): " << e.what() << logging::eol;\r
204         if (!backup && !m_backing.empty())\r
205             return load(true);\r
206         throw;\r
207     }\r
208 }\r
209 \r
210 Lockable* ReloadableXMLFile::lock()\r
211 {\r
212     if (!m_lock)\r
213         return this;\r
214         \r
215     m_lock->rdlock();\r
216 \r
217     // Check if we need to refresh.\r
218     if (m_local) {\r
219 #ifdef WIN32\r
220         struct _stat stat_buf;\r
221         if (_stat(m_source.c_str(), &stat_buf) != 0)\r
222             return this;\r
223 #else\r
224         struct stat stat_buf;\r
225         if (stat(m_source.c_str(), &stat_buf) != 0)\r
226             return this;\r
227 #endif\r
228         if (m_filestamp>=stat_buf.st_mtime)\r
229             return this;\r
230         \r
231         // Elevate lock and recheck.\r
232         m_log.debug("timestamp of local resource changed, elevating to a write lock");\r
233         m_lock->unlock();\r
234         m_lock->wrlock();\r
235         if (m_filestamp>=stat_buf.st_mtime) {\r
236             // Somebody else handled it, just downgrade.\r
237             m_log.debug("update of local resource handled by another thread, downgrading lock");\r
238             m_lock->unlock();\r
239             m_lock->rdlock();\r
240             return this;\r
241         }\r
242 \r
243         // Update the timestamp regardless. No point in repeatedly trying.\r
244         m_filestamp=stat_buf.st_mtime;\r
245         m_log.info("change detected, reloading local resource...");\r
246     }\r
247     else {\r
248         time_t now = time(NULL);\r
249 \r
250         // Time to reload? If we have no data, filestamp is zero\r
251         // and there's no way current time is less than the interval.\r
252         if (now - m_filestamp < m_reloadInterval)\r
253             return this;\r
254 \r
255         // Elevate lock and recheck.\r
256         m_log.debug("reload interval for remote resource elapsed, elevating to a write lock");\r
257         m_lock->unlock();\r
258         m_lock->wrlock();\r
259         if (now - m_filestamp < m_reloadInterval) {\r
260             // Somebody else handled it, just downgrade.\r
261             m_log.debug("update of remote resource handled by another thread, downgrading lock");\r
262             m_lock->unlock();\r
263             m_lock->rdlock();\r
264             return this;\r
265         }\r
266 \r
267         m_filestamp = now;\r
268         m_log.info("reloading remote resource...");\r
269     }\r
270     \r
271     // Do this once...\r
272     try {\r
273         // At this point we're holding the write lock, so make sure we pop it.\r
274         SharedLock lockwrap(m_lock,false);\r
275         pair<bool,DOMElement*> ret=load();\r
276         if (ret.first)\r
277             ret.second->getOwnerDocument()->release();\r
278     } catch (exception& ex) {\r
279         m_log.crit("maintaining existing configuration, error reloading resource (%s): %s", m_source.c_str(), ex.what());\r
280     }\r
281     \r
282     // If we made it here, the swap may or may not have worked, but we need to relock.\r
283     m_log.debug("attempt to update resource complete, relocking");\r
284     m_lock->rdlock();\r
285     return this;\r
286 }\r