Add null checks to helper methods.
[shibboleth/cpp-xmltooling.git] / xmltooling / util / ReloadableXMLFile.cpp
1 /*
2  *  Copyright 2001-2010 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  * @file ReloadableXMLFile.cpp
19  *
20  * Base class for file-based XML configuration.
21  */
22
23 #include "internal.h"
24 #include "io/HTTPResponse.h"
25 #ifndef XMLTOOLING_LITE
26 # include "security/Credential.h"
27 # include "security/CredentialCriteria.h"
28 # include "security/CredentialResolver.h"
29 # include "security/SignatureTrustEngine.h"
30 # include "signature/Signature.h"
31 # include "signature/SignatureValidator.h"
32 #endif
33 #include "util/NDC.h"
34 #include "util/PathResolver.h"
35 #include "util/ReloadableXMLFile.h"
36 #include "util/Threads.h"
37 #include "util/XMLConstants.h"
38 #include "util/XMLHelper.h"
39
40 #if defined(XMLTOOLING_LOG4SHIB)
41 # include <log4shib/NDC.hh>
42 #elif defined(XMLTOOLING_LOG4CPP)
43 # include <log4cpp/NDC.hh>
44 #endif
45
46 #include <memory>
47 #include <fstream>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50
51 #include <xercesc/framework/LocalFileInputSource.hpp>
52 #include <xercesc/framework/Wrapper4InputSource.hpp>
53 #include <xercesc/util/XMLUniDefs.hpp>
54
55 #ifndef XMLTOOLING_LITE
56 # include <xsec/dsig/DSIGReference.hpp>
57 # include <xsec/dsig/DSIGTransformList.hpp>
58 using namespace xmlsignature;
59 #endif
60
61 using namespace xmltooling::logging;
62 using namespace xmltooling;
63 using namespace xercesc;
64 using namespace std;
65
66 #ifndef XMLTOOLING_LITE
67 namespace {
68     class XMLTOOL_DLLLOCAL DummyCredentialResolver : public CredentialResolver
69     {
70     public:
71         DummyCredentialResolver() {}
72         ~DummyCredentialResolver() {}
73
74         Lockable* lock() {return this;}
75         void unlock() {}
76
77         const Credential* resolve(const CredentialCriteria* criteria=nullptr) const {return nullptr;}
78         vector<const Credential*>::size_type resolve(
79             vector<const Credential*>& results, const CredentialCriteria* criteria=nullptr
80             ) const {return 0;}
81     };
82 };
83 #endif
84
85 static const XMLCh id[] =               UNICODE_LITERAL_2(i,d);
86 static const XMLCh uri[] =              UNICODE_LITERAL_3(u,r,i);
87 static const XMLCh url[] =              UNICODE_LITERAL_3(u,r,l);
88 static const XMLCh path[] =             UNICODE_LITERAL_4(p,a,t,h);
89 static const XMLCh pathname[] =         UNICODE_LITERAL_8(p,a,t,h,n,a,m,e);
90 static const XMLCh file[] =             UNICODE_LITERAL_4(f,i,l,e);
91 static const XMLCh filename[] =         UNICODE_LITERAL_8(f,i,l,e,n,a,m,e);
92 static const XMLCh validate[] =         UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
93 static const XMLCh reloadChanges[] =    UNICODE_LITERAL_13(r,e,l,o,a,d,C,h,a,n,g,e,s);
94 static const XMLCh reloadInterval[] =   UNICODE_LITERAL_14(r,e,l,o,a,d,I,n,t,e,r,v,a,l);
95 static const XMLCh maxRefreshDelay[] =  UNICODE_LITERAL_15(m,a,x,R,e,f,r,e,s,h,D,e,l,a,y);
96 static const XMLCh backingFilePath[] =  UNICODE_LITERAL_15(b,a,c,k,i,n,g,F,i,l,e,P,a,t,h);
97 static const XMLCh type[] =             UNICODE_LITERAL_4(t,y,p,e);
98 static const XMLCh certificate[] =      UNICODE_LITERAL_11(c,e,r,t,i,f,i,c,a,t,e);
99 static const XMLCh signerName[] =       UNICODE_LITERAL_10(s,i,g,n,e,r,N,a,m,e);
100 static const XMLCh _TrustEngine[] =     UNICODE_LITERAL_11(T,r,u,s,t,E,n,g,i,n,e);
101 static const XMLCh _CredentialResolver[] = UNICODE_LITERAL_18(C,r,e,d,e,n,t,i,a,l,R,e,s,o,l,v,e,r);
102
103
104 ReloadableXMLFile::ReloadableXMLFile(const DOMElement* e, Category& log, bool startReloadThread)
105     : m_root(e), m_local(true), m_validate(false), m_filestamp(0), m_reloadInterval(0),
106       m_lock(nullptr), m_loaded(false), m_log(log),
107 #ifndef XMLTOOLING_LITE
108       m_credResolver(nullptr), m_trust(nullptr),
109 #endif
110       m_shutdown(false), m_reload_wait(nullptr), m_reload_thread(nullptr)
111 {
112 #ifdef _DEBUG
113     NDC ndc("ReloadableXMLFile");
114 #endif
115
116     // Establish source of data...
117     const XMLCh* source=e->getAttributeNS(nullptr,uri);
118     if (!source || !*source) {
119         source=e->getAttributeNS(nullptr,url);
120         if (!source || !*source) {
121             source=e->getAttributeNS(nullptr,path);
122             if (!source || !*source) {
123                 source=e->getAttributeNS(nullptr,pathname);
124                 if (!source || !*source) {
125                     source=e->getAttributeNS(nullptr,file);
126                     if (!source || !*source) {
127                         source=e->getAttributeNS(nullptr,filename);
128                     }
129                 }
130             }
131         }
132         else {
133             m_local=false;
134         }
135     }
136     else {
137         m_local=false;
138     }
139
140     if (source && *source) {
141         m_validate = XMLHelper::getAttrBool(e, false, validate);
142
143         auto_ptr_char temp(source);
144         m_source = temp.get();
145
146         if (!m_local && !strstr(m_source.c_str(),"://")) {
147             log.warn("deprecated usage of uri/url attribute for a local resource, use path instead");
148             m_local = true;
149         }
150
151 #ifndef XMLTOOLING_LITE
152         // Check for signature bits.
153         if (e->hasAttributeNS(nullptr, certificate)) {
154             // Use a file-based credential resolver rooted here.
155             m_credResolver = XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(FILESYSTEM_CREDENTIAL_RESOLVER, e);
156         }
157         else {
158             const DOMElement* sub = XMLHelper::getFirstChildElement(e, _CredentialResolver);
159             string t(XMLHelper::getAttrString(sub, nullptr, type));
160             if (!t.empty()) {
161                 m_credResolver = XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(t.c_str(), sub);
162             }
163             else {
164                 sub = XMLHelper::getFirstChildElement(e, _TrustEngine);
165                 t = XMLHelper::getAttrString(sub, nullptr, type);
166                 if (!t.empty()) {
167                     TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), sub);
168                     if (!(m_trust = dynamic_cast<SignatureTrustEngine*>(trust))) {
169                         delete trust;
170                         throw XMLToolingException("TrustEngine-based ReloadableXMLFile requires a SignatureTrustEngine plugin.");
171                     }
172
173                     m_signerName = XMLHelper::getAttrString(e, nullptr, signerName);
174                 }
175             }
176         }
177 #endif
178
179         if (m_local) {
180             XMLToolingConfig::getConfig().getPathResolver()->resolve(m_source, PathResolver::XMLTOOLING_CFG_FILE);
181
182             bool flag = XMLHelper::getAttrBool(e, true, reloadChanges);
183             if (flag) {
184 #ifdef WIN32
185                 struct _stat stat_buf;
186                 if (_stat(m_source.c_str(), &stat_buf) == 0)
187 #else
188                 struct stat stat_buf;
189                 if (stat(m_source.c_str(), &stat_buf) == 0)
190 #endif
191                     m_filestamp = stat_buf.st_mtime;
192                 else
193                     throw IOException("Unable to access local file ($1)", params(1,m_source.c_str()));
194                 m_lock = RWLock::create();
195             }
196             log.debug("using local resource (%s), will %smonitor for changes", m_source.c_str(), m_lock ? "" : "not ");
197         }
198         else {
199             log.debug("using remote resource (%s)", m_source.c_str());
200             m_backing = XMLHelper::getAttrString(e, nullptr, backingFilePath);
201             if (!m_backing.empty()) {
202                 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_backing, PathResolver::XMLTOOLING_RUN_FILE);
203                 log.debug("backup remote resource to (%s)", m_backing.c_str());
204                 try {
205                     ifstream backer(m_backing + ".tag");
206                     if (backer) {
207                         char cachebuf[256];
208                         if (backer.getline(cachebuf, 255)) {
209                             m_cacheTag = cachebuf;
210                             log.debug("loaded initial cache tag (%s)", m_cacheTag.c_str());
211                         }
212                     }
213                 }
214                 catch (exception&) {
215                 }
216             }
217             m_reloadInterval = XMLHelper::getAttrInt(e, 0, reloadInterval);
218             if (m_reloadInterval == 0)
219                 m_reloadInterval = XMLHelper::getAttrInt(e, 0, maxRefreshDelay);
220             if (m_reloadInterval > 0) {
221                 m_log.debug("will reload remote resource at most every %d seconds", m_reloadInterval);
222                 m_lock = RWLock::create();
223             }
224             m_filestamp = time(nullptr);   // assume it gets loaded initially
225         }
226
227         if (startReloadThread)
228             startup();
229     }
230     else {
231         log.debug("no resource uri/path/name supplied, will load inline configuration");
232     }
233
234     m_id = XMLHelper::getAttrString(e, nullptr, id);
235 }
236
237 ReloadableXMLFile::~ReloadableXMLFile()
238 {
239     shutdown();
240     delete m_lock;
241 }
242
243 void ReloadableXMLFile::startup()
244 {
245     if (m_lock && !m_reload_thread) {
246         m_reload_wait = CondWait::create();
247         m_reload_thread = Thread::create(&reload_fn, this);
248     }
249 }
250
251 void ReloadableXMLFile::shutdown()
252 {
253     if (m_reload_thread) {
254         // Shut down the reload thread and let it know.
255         m_shutdown = true;
256         m_reload_wait->signal();
257         m_reload_thread->join(nullptr);
258         delete m_reload_thread;
259         delete m_reload_wait;
260         m_reload_thread = nullptr;
261         m_reload_wait = nullptr;
262     }
263 }
264
265 void* ReloadableXMLFile::reload_fn(void* pv)
266 {
267     ReloadableXMLFile* r = reinterpret_cast<ReloadableXMLFile*>(pv);
268
269 #ifndef WIN32
270     // First, let's block all signals
271     Thread::mask_all_signals();
272 #endif
273
274     if (!r->m_id.empty()) {
275         string threadid("[");
276         threadid += r->m_id + ']';
277         logging::NDC::push(threadid);
278     }
279
280 #ifdef _DEBUG
281     NDC ndc("reload");
282 #endif
283
284     auto_ptr<Mutex> mutex(Mutex::create());
285     mutex->lock();
286
287     if (r->m_local)
288         r->m_log.info("reload thread started...running when signaled");
289     else
290         r->m_log.info("reload thread started...running every %d seconds", r->m_reloadInterval);
291
292     while (!r->m_shutdown) {
293         if (r->m_local)
294             r->m_reload_wait->wait(mutex.get());
295         else
296             r->m_reload_wait->timedwait(mutex.get(), r->m_reloadInterval);
297         if (r->m_shutdown)
298             break;
299
300         try {
301             r->m_log.info("reloading %s resource...", r->m_local ? "local" : "remote");
302             pair<bool,DOMElement*> ret = r->background_load();
303             if (ret.first)
304                 ret.second->getOwnerDocument()->release();
305         }
306         catch (long& ex) {
307             if (ex == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED) {
308                 r->m_log.info("remote resource (%s) unchanged from cached version", r->m_source.c_str());
309             }
310             else {
311                 // Shouldn't happen, we should only get codes intended to be gracefully handled.
312                 r->m_log.crit("maintaining existing configuration, remote resource fetch returned atypical status code (%d)", ex);
313             }
314         }
315         catch (exception& ex) {
316             r->m_log.crit("maintaining existing configuration, error reloading resource (%s): %s", r->m_source.c_str(), ex.what());
317         }
318     }
319
320     r->m_log.info("reload thread finished");
321
322     mutex->unlock();
323
324     if (!r->m_id.empty()) {
325         logging::NDC::pop();
326     }
327
328     return nullptr;
329 }
330
331 Lockable* ReloadableXMLFile::lock()
332 {
333     if (!m_lock)
334         return this;
335
336     m_lock->rdlock();
337
338     if (m_local) {
339     // Check if we need to refresh.
340 #ifdef WIN32
341         struct _stat stat_buf;
342         if (_stat(m_source.c_str(), &stat_buf) != 0)
343             return this;
344 #else
345         struct stat stat_buf;
346         if (stat(m_source.c_str(), &stat_buf) != 0)
347             return this;
348 #endif
349         if (m_filestamp >= stat_buf.st_mtime)
350             return this;
351
352         // Elevate lock and recheck.
353         m_log.debug("timestamp of local resource changed, elevating to a write lock");
354         m_lock->unlock();
355         m_lock->wrlock();
356         if (m_filestamp >= stat_buf.st_mtime) {
357             // Somebody else handled it, just downgrade.
358             m_log.debug("update of local resource handled by another thread, downgrading lock");
359             m_lock->unlock();
360             m_lock->rdlock();
361             return this;
362         }
363
364         // Update the timestamp regardless.
365         m_filestamp = stat_buf.st_mtime;
366         m_log.info("change detected, signaling reload thread...");
367         m_reload_wait->signal();
368     }
369
370     return this;
371 }
372
373 void ReloadableXMLFile::unlock()
374 {
375     if (m_lock)
376         m_lock->unlock();
377 }
378
379 pair<bool,DOMElement*> ReloadableXMLFile::load(bool backup)
380 {
381 #ifdef _DEBUG
382     NDC ndc("load");
383 #endif
384
385     try {
386         if (m_source.empty()) {
387             // Data comes from the DOM we were handed.
388             m_log.debug("loading inline configuration...");
389             return make_pair(false, XMLHelper::getFirstChildElement(m_root));
390         }
391         else {
392             // Data comes from a file we have to parse.
393             if (backup)
394                 m_log.warn("using local backup of remote resource");
395             else
396                 m_log.debug("loading configuration from external resource...");
397
398             DOMDocument* doc=nullptr;
399             if (m_local || backup) {
400                 auto_ptr_XMLCh widenit(backup ? m_backing.c_str() : m_source.c_str());
401                 // Use library-wide lock for now, nothing else is using it anyway.
402                 Locker locker(backup ? getBackupLock() : nullptr);
403                 LocalFileInputSource src(widenit.get());
404                 Wrapper4InputSource dsrc(&src, false);
405                 if (m_validate)
406                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
407                 else
408                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
409             }
410             else {
411                 URLInputSource src(m_root, nullptr, &m_cacheTag);
412                 Wrapper4InputSource dsrc(&src, false);
413                 if (m_validate)
414                     doc=XMLToolingConfig::getConfig().getValidatingParser().parse(dsrc);
415                 else
416                     doc=XMLToolingConfig::getConfig().getParser().parse(dsrc);
417
418                 // Check for a response code signal.
419                 if (XMLHelper::isNodeNamed(doc->getDocumentElement(), xmlconstants::XMLTOOLING_NS, URLInputSource::utf16StatusCodeElementName)) {
420                     int responseCode = XMLString::parseInt(doc->getDocumentElement()->getFirstChild()->getNodeValue());
421                     doc->release();
422                     if (responseCode == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED)
423                         throw (long)responseCode; // toss out as a "known" case to handle gracefully
424                     else {
425                         m_log.warn("remote resource fetch returned atypical status code (%d)", responseCode);
426                         throw IOException("remote resource fetch failed, check log for status code of response");
427                     }
428                 }
429             }
430
431             m_log.infoStream() << "loaded XML resource (" << (backup ? m_backing : m_source) << ")" << logging::eol;
432 #ifndef XMLTOOLING_LITE
433             if (m_credResolver || m_trust) {
434                 m_log.debug("checking signature on XML resource");
435                 try {
436                     DOMElement* sigel = XMLHelper::getFirstChildElement(doc->getDocumentElement(), xmlconstants::XMLSIG_NS, Signature::LOCAL_NAME);
437                     if (!sigel)
438                         throw XMLSecurityException("Signature validation required, but no signature found.");
439
440                     // Wrap and unmarshall the signature for the duration of the check.
441                     auto_ptr<Signature> sigobj(dynamic_cast<Signature*>(SignatureBuilder::buildOneFromElement(sigel)));    // don't bind to document
442                     validateSignature(*sigobj.get());
443                 }
444                 catch (exception&) {
445                     doc->release();
446                     throw;
447                 }
448
449             }
450 #endif
451             return make_pair(true, doc->getDocumentElement());
452         }
453     }
454     catch (XMLException& e) {
455         auto_ptr_char msg(e.getMessage());
456         m_log.errorStream() << "Xerces error while loading resource (" << (backup ? m_backing : m_source) << "): "
457             << msg.get() << logging::eol;
458         throw XMLParserException(msg.get());
459     }
460     catch (exception& e) {
461         m_log.errorStream() << "error while loading resource ("
462             << (m_source.empty() ? "inline" : (backup ? m_backing : m_source)) << "): " << e.what() << logging::eol;
463         throw;
464     }
465 }
466
467 pair<bool,DOMElement*> ReloadableXMLFile::load()
468 {
469     // If this method is used, we're responsible for managing failover to a
470     // backup of a remote resource (if available), and for backing up remote
471     // resources.
472     try {
473         pair<bool,DOMElement*> ret = load(false);
474         if (!m_backing.empty()) {
475             m_log.debug("backing up remote resource to (%s)", m_backing.c_str());
476             try {
477                 Locker locker(getBackupLock());
478                 ofstream backer(m_backing);
479                 backer << *(ret.second->getOwnerDocument());
480                 preserveCacheTag();
481             }
482             catch (exception& ex) {
483                 m_log.crit("exception while backing up resource: %s", ex.what());
484             }
485         }
486         return ret;
487     }
488     catch (long& responseCode) {
489         // If there's an HTTP error or the document hasn't changed,
490         // use the backup iff we have no "valid" resource in place.
491         // That prevents reload of the backup copy any time the document
492         // hasn't changed.
493         if (responseCode == HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED)
494             m_log.info("remote resource (%s) unchanged from cached version", m_source.c_str());
495         if (!m_loaded && !m_backing.empty())
496             return load(true);
497         throw;
498     }
499     catch (exception&) {
500         // Same as above, but for general load/parse errors.
501         if (!m_loaded && !m_backing.empty())
502             return load(true);
503         throw;
504     }
505 }
506
507 pair<bool,DOMElement*> ReloadableXMLFile::background_load()
508 {
509     // If this method isn't overridden, we acquire a write lock
510     // and just call the old override.
511     if (m_lock)
512         m_lock->wrlock();
513     SharedLock locker(m_lock, false);
514     return load();
515 }
516
517 Lockable* ReloadableXMLFile::getBackupLock()
518 {
519     return &XMLToolingConfig::getConfig();
520 }
521
522 void ReloadableXMLFile::preserveCacheTag()
523 {
524     if (!m_cacheTag.empty() && !m_backing.empty()) {
525         try {
526             ofstream backer(m_backing + ".tag");
527             backer << m_cacheTag;
528         }
529         catch (exception&) {
530         }
531     }
532 }
533
534 #ifndef XMLTOOLING_LITE
535
536 void ReloadableXMLFile::validateSignature(Signature& sigObj) const
537 {
538     DSIGSignature* sig=sigObj.getXMLSignature();
539     if (!sig)
540         throw XMLSecurityException("Signature does not exist yet.");
541
542     // Make sure the whole document was signed.
543     bool valid=false;
544     DSIGReferenceList* refs=sig->getReferenceList();
545     if (refs && refs->getSize()==1) {
546         DSIGReference* ref=refs->item(0);
547         if (ref) {
548             const XMLCh* URI=ref->getURI();
549             if (URI==nullptr || *URI==0) {
550                 DSIGTransformList* tlist=ref->getTransforms();
551                 if (tlist->getSize() <= 2) { 
552                     for (unsigned int i=0; tlist && i<tlist->getSize(); i++) {
553                         if (tlist->item(i)->getTransformType()==TRANSFORM_ENVELOPED_SIGNATURE)
554                             valid=true;
555                         else if (tlist->item(i)->getTransformType()!=TRANSFORM_EXC_C14N &&
556                                  tlist->item(i)->getTransformType()!=TRANSFORM_C14N &&
557                                  tlist->item(i)->getTransformType()!=TRANSFORM_C14N11) {
558                             valid=false;
559                             break;
560                         }
561                     }
562                 }
563             }
564         }
565     }
566     
567     if (!valid)
568         throw XMLSecurityException("Invalid signature profile for signed configuration resource.");
569
570     // Set up criteria.
571     CredentialCriteria cc;
572     cc.setUsage(Credential::SIGNING_CREDENTIAL);
573     cc.setSignature(sigObj, CredentialCriteria::KEYINFO_EXTRACTION_KEY);
574     if (!m_signerName.empty())
575         cc.setPeerName(m_signerName.c_str());
576
577     if (m_credResolver) {
578         Locker locker(m_credResolver);
579         vector<const Credential*> creds;
580         if (m_credResolver->resolve(creds, &cc)) {
581             SignatureValidator sigValidator;
582             for (vector<const Credential*>::const_iterator i = creds.begin(); i != creds.end(); ++i) {
583                 try {
584                     sigValidator.setCredential(*i);
585                     sigValidator.validate(&sigObj);
586                     return; // success!
587                 }
588                 catch (exception&) {
589                 }
590             }
591             throw XMLSecurityException("Unable to verify signature with supplied key(s).");
592         }
593         else {
594             throw XMLSecurityException("CredentialResolver did not supply any candidate keys.");
595         }
596     }
597     else if (m_trust) {
598         DummyCredentialResolver dummy;
599         if (m_trust->validate(sigObj, dummy, &cc))
600             return;
601         throw XMLSecurityException("TrustEngine unable to verify signature.");
602     }
603
604     throw XMLSecurityException("Unable to verify signature.");
605 }
606
607 #endif