82264fe2bfbe7b8f71ba071a99a836bb72e19349
[shibboleth/cpp-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/ReloadableXMLFile.h"\r
26 #include "util/XMLConstants.h"\r
27 #include "util/XMLHelper.h"\r
28 \r
29 #include <sys/types.h>\r
30 #include <sys/stat.h>\r
31 \r
32 #include <xercesc/framework/LocalFileInputSource.hpp>\r
33 #include <xercesc/framework/Wrapper4InputSource.hpp>\r
34 #include <xercesc/framework/URLInputSource.hpp>\r
35 #include <xercesc/util/XMLUniDefs.hpp>\r
36 \r
37 using namespace xmltooling;\r
38 using namespace log4cpp;\r
39 using namespace std;\r
40 \r
41 static const XMLCh uri[] =          UNICODE_LITERAL_3(u,r,i);\r
42 static const XMLCh url[] =          UNICODE_LITERAL_3(u,r,l);\r
43 static const XMLCh path[] =         UNICODE_LITERAL_4(p,a,t,h);\r
44 static const XMLCh pathname[] =     UNICODE_LITERAL_8(p,a,t,h,n,a,m,e);\r
45 static const XMLCh file[] =         UNICODE_LITERAL_4(f,i,l,e);\r
46 static const XMLCh filename[] =     UNICODE_LITERAL_8(f,i,l,e,n,a,m,e);\r
47 static const XMLCh validate[] =     UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);\r
48 static const XMLCh reloadChanges[] =UNICODE_LITERAL_13(r,e,l,o,a,d,C,h,a,n,g,e,s);\r
49 \r
50 ReloadableXMLFile::ReloadableXMLFile(const DOMElement* e, Category& log)\r
51     : m_root(e), m_local(true), m_validate(false), m_filestamp(0), m_lock(NULL), m_log(log)\r
52 {\r
53 #ifdef _DEBUG\r
54     NDC ndc("ReloadableXMLFile");\r
55 #endif\r
56 \r
57     // Establish source of data...\r
58     const XMLCh* source=e->getAttributeNS(NULL,uri);\r
59     if (!source || !*source) {\r
60         source=e->getAttributeNS(NULL,url);\r
61         if (!source || !*source) {\r
62             source=e->getAttributeNS(NULL,path);\r
63             if (!source || !*source) {\r
64                 source=e->getAttributeNS(NULL,pathname);\r
65                 if (!source || !*source) {\r
66                     source=e->getAttributeNS(NULL,file);\r
67                     if (!source || !*source) {\r
68                         source=e->getAttributeNS(NULL,filename);\r
69                     }\r
70                 }\r
71             }\r
72         }\r
73         else\r
74             m_local=false;\r
75     }\r
76     else\r
77         m_local=false;\r
78     \r
79     if (source && *source) {\r
80         const XMLCh* flag=e->getAttributeNS(NULL,validate);\r
81         m_validate=(XMLString::equals(flag,xmlconstants::XML_TRUE) || XMLString::equals(flag,xmlconstants::XML_ONE));\r
82 \r
83         auto_ptr_char temp(source);\r
84         m_source=temp.get();\r
85         \r
86         if (!m_local && !strstr(m_source.c_str(),"://")) {\r
87             log.warn("deprecated usage of uri/url attribute for a local resource, use path instead");\r
88             m_local=true;\r
89         }\r
90 \r
91         flag=e->getAttributeNS(NULL,reloadChanges);\r
92         if (!XMLString::equals(flag,xmlconstants::XML_FALSE) && !XMLString::equals(flag,xmlconstants::XML_ZERO)) {\r
93             if (m_local) {\r
94 #ifdef WIN32\r
95                 struct _stat stat_buf;\r
96                 if (_stat(m_source.c_str(), &stat_buf) == 0)\r
97                     m_filestamp=stat_buf.st_mtime;\r
98                 else\r
99                     m_local=false;\r
100 #else\r
101                 struct stat stat_buf;\r
102                 if (stat(m_source.c_str(), &stat_buf) == 0)\r
103                     m_filestamp=stat_buf.st_mtime;\r
104                 else\r
105                     m_local=false;\r
106 #endif\r
107             }\r
108             m_lock=RWLock::create();\r
109         }\r
110 \r
111         log.debug("using external resource (%s), will %smonitor for changes", m_source.c_str(), m_lock ? "" : "not ");\r
112     }\r
113     else\r
114         log.debug("no resource uri/path/name supplied, will load inline configuration");\r
115 }\r
116 \r
117 pair<bool,DOMElement*> ReloadableXMLFile::load()\r
118 {\r
119 #ifdef _DEBUG\r
120     NDC ndc("init");\r
121 #endif\r
122 \r
123     try {\r
124         if (m_source.empty()) {\r
125             // Data comes from the DOM we were handed.\r
126             m_log.debug("loading inline configuration...");\r
127             return make_pair(false,XMLHelper::getFirstChildElement(m_root));\r
128         }\r
129         else {\r
130             // Data comes from a file we have to parse.\r
131             m_log.debug("loading configuration from external resource...");\r
132 \r
133             DOMDocument* doc=NULL;\r
134             auto_ptr_XMLCh widenit(m_source.c_str());\r
135             if (m_local) {\r
136                 LocalFileInputSource src(widenit.get());\r
137                 Wrapper4InputSource dsrc(&src,false);\r
138                 if (m_validate)\r
139                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
140                 else\r
141                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
142             }\r
143             else {\r
144                 URLInputSource src(widenit.get());\r
145                 Wrapper4InputSource dsrc(&src,false);\r
146                 if (m_validate)\r
147                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);\r
148                 else\r
149                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);\r
150             }\r
151 \r
152             m_log.infoStream() << "loaded XML resource (" << m_source << ")" << CategoryStream::ENDLINE;\r
153             return make_pair(true,doc->getDocumentElement());\r
154         }\r
155     }\r
156     catch (XMLException& e) {\r
157         auto_ptr_char msg(e.getMessage());\r
158         m_log.critStream() << "Xerces error while loading resource (" << m_source << "): "\r
159             << msg.get() << CategoryStream::ENDLINE;\r
160         throw XMLParserException(msg.get());\r
161     }\r
162     catch (exception& e) {\r
163         m_log.critStream() << "error while loading configuration from ("\r
164             << (m_source.empty() ? "inline" : m_source) << "): " << e.what() << CategoryStream::ENDLINE;\r
165         throw;\r
166     }\r
167 }\r
168 \r
169 Lockable* ReloadableXMLFile::lock()\r
170 {\r
171     if (!m_lock)\r
172         return this;\r
173         \r
174     m_lock->rdlock();\r
175 \r
176     // Check if we need to refresh.\r
177     if (m_local) {\r
178 #ifdef WIN32\r
179         struct _stat stat_buf;\r
180         if (_stat(m_source.c_str(), &stat_buf) != 0)\r
181             return this;\r
182 #else\r
183         struct stat stat_buf;\r
184         if (stat(m_source.c_str(), &stat_buf) != 0)\r
185             return this;\r
186 #endif\r
187         if (m_filestamp>=stat_buf.st_mtime)\r
188             return this;\r
189         \r
190         // Elevate lock and recheck.\r
191         m_lock->unlock();\r
192         m_lock->wrlock();\r
193         if (m_filestamp>=stat_buf.st_mtime) {\r
194             // Somebody else handled it, just downgrade.\r
195             m_lock->unlock();\r
196             m_lock->rdlock();\r
197             return this;\r
198         }\r
199 \r
200         // Update the timestamp regardless. No point in repeatedly trying.\r
201         m_filestamp=stat_buf.st_mtime;\r
202         m_log.info("change detected, reloading local resource...");\r
203     }\r
204     else {\r
205         if (isValid())\r
206             return this;\r
207 \r
208         // Elevate lock and recheck.\r
209         m_lock->unlock();\r
210         m_lock->wrlock();\r
211         if (isValid()) {\r
212             // Somebody else handled it, just downgrade.\r
213             m_lock->unlock();\r
214             m_lock->rdlock();\r
215             return this;\r
216         }\r
217         m_log.info("local copy invalid, reloading remote resource...");\r
218     }\r
219     \r
220     // Do this once...\r
221     try {\r
222         // At this point we're holding the write lock, so make sure we pop it.\r
223         SharedLock lockwrap(m_lock,false);\r
224         pair<bool,DOMElement*> ret=load();\r
225         if (ret.first)\r
226             ret.second->getOwnerDocument()->release();\r
227     } catch (exception& ex) {\r
228         m_log.crit("maintaining existing configuration, error reloading resource (%s): %s", m_source.c_str(), ex.what());\r
229     }\r
230     \r
231     // If we made it here, the swap may or may not have worked, but we need to relock.\r
232     m_lock->rdlock();\r
233     return this;\r
234 }\r