SSPCPP-669 - cached samlds.json files prematurely removed w/ multiple
[shibboleth/cpp-sp.git] / shibsp / handler / impl / DiscoveryFeed.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * DiscoveryFeed.cpp
23  *
24  * Handler for generating a JSON discovery feed based on metadata.
25  */
26
27 #include "internal.h"
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34
35 #include <ctime>
36 #include <fstream>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/Threads.h>
39 #include <xmltooling/util/PathResolver.h>
40
41 #ifndef SHIBSP_LITE
42 # include <queue>
43 # include <saml/exceptions.h>
44 # include <saml/SAMLConfig.h>
45 # include <saml/saml2/metadata/DiscoverableMetadataProvider.h>
46 #endif
47
48 using namespace shibsp;
49 #ifndef SHIBSP_LITE
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 using namespace boost;
53 #endif
54 using namespace xmltooling;
55 using namespace std;
56
57 namespace shibsp {
58
59 #if defined (_MSC_VER)
60     #pragma warning( push )
61     #pragma warning( disable : 4250 )
62 #endif
63
64     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
65     {
66     public:
67 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
68         short
69 #else
70         FilterAction
71 #endif
72         acceptNode(const DOMNode* node) const {
73             return FILTER_REJECT;
74         }
75     };
76
77     static SHIBSP_DLLLOCAL Blocker g_Blocker;
78
79     class SHIBSP_API DiscoveryFeed : public AbstractHandler, public RemotedHandler
80     {
81     public:
82         DiscoveryFeed(const DOMElement* e, const char* appId);
83         virtual ~DiscoveryFeed();
84
85         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
86         void receive(DDF& in, ostream& out);
87
88     private:
89         void feedToFile(const Application& application, string& cacheTag) const;
90         void feedToStream(const Application& application, string& cacheTag, ostream& os) const;
91
92         string m_dir;
93         bool m_cacheToClient;
94 #ifndef SHIBSP_LITE
95         // Application-specific queues of feed files, linked to the last time of "access".
96         // Each filename is also a cache tag.
97         typedef queue< pair<string, time_t> > feedqueue_t;
98         mutable map<string,feedqueue_t> m_feedQueues;
99         scoped_ptr<Mutex> m_feedLock;
100 #endif
101     };
102
103 #if defined (_MSC_VER)
104     #pragma warning( pop )
105 #endif
106
107     Handler* SHIBSP_DLLLOCAL DiscoveryFeedFactory(const pair<const DOMElement*,const char*>& p)
108     {
109         return new DiscoveryFeed(p.first, p.second);
110     }
111
112 };
113
114 DiscoveryFeed::DiscoveryFeed(const DOMElement* e, const char* appId)
115     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT ".DiscoveryFeed"), &g_Blocker), m_cacheToClient(false)
116 {
117     pair<bool,const char*> prop = getString("Location");
118     if (!prop.first)
119         throw ConfigurationException("DiscoveryFeed handler requires Location property.");
120     string address(appId);
121     address += prop.second;
122     setAddress(address.c_str());
123
124     pair<bool,bool> flag = getBool("cacheToClient");
125     m_cacheToClient = flag.first && flag.second;
126     flag = getBool("cacheToDisk");
127     if (!flag.first || flag.second) {
128         prop = getString("dir");
129         if (prop.first)
130             m_dir = prop.second;
131         XMLToolingConfig::getConfig().getPathResolver()->resolve(m_dir, PathResolver::XMLTOOLING_CACHE_FILE);
132         m_log.info("feed files will be cached in %s", m_dir.c_str());
133 #ifndef SHIBSP_LITE
134         m_feedLock.reset(Mutex::create());
135 #endif
136     }
137 }
138
139 DiscoveryFeed::~DiscoveryFeed()
140 {
141 #ifndef SHIBSP_LITE
142     if (m_feedLock) {
143         // Remove any files unused for more than a couple of minutes.
144         // Anything left will be orphaned, but that shouldn't happen too often.
145         time_t now = time(nullptr);
146         for (map<string, feedqueue_t>::iterator i = m_feedQueues.begin(); i != m_feedQueues.end(); ++i) {
147             while (!i->second.empty() && now - i->second.front().second > 120) {
148                 string fname = m_dir + '/' + i->second.front().first + ".json";
149                 remove(fname.c_str());
150                 i->second.pop();
151             }
152         }
153     }
154 #endif
155 }
156
157 pair<bool,long> DiscoveryFeed::run(SPRequest& request, bool isHandler) const
158 {
159     try {
160         SPConfig& conf = SPConfig::getConfig();
161
162         string s;
163         if (m_cacheToClient) {
164             s = request.getHeader("If-None-Match");
165         }
166
167         if (conf.isEnabled(SPConfig::OutOfProcess)) {
168             // When out of process, we run natively and directly process the message.
169             if (m_dir.empty()) {
170                 // The feed is directly returned.
171                 stringstream buf;
172                 feedToStream(request.getApplication(), s, buf);
173                 if (!s.empty()) {
174                     if (m_cacheToClient) {
175                         string etag = '"' + s + '"';
176                         request.setResponseHeader("ETag", etag.c_str());
177                     }
178                     request.setContentType("application/json; charset=UTF-8");
179                     return make_pair(true, request.sendResponse(buf));
180                 }
181             }
182             else {
183                 // Indirect the feed through a file.
184                 feedToFile(request.getApplication(), s);
185             }
186         }
187         else {
188             // When not out of process, we remote all the message processing.
189             DDF out,in = DDF(m_address.c_str());
190             in.addmember("application_id").string(request.getApplication().getId());
191             if (!s.empty())
192                 in.addmember("cache_tag").string(s.c_str());
193             DDFJanitor jin(in), jout(out);
194             out = request.getServiceProvider().getListenerService()->send(in);
195             s.erase();
196             if (m_dir.empty()) {
197                 // The cache tag and feed are in the response struct.
198                 if (m_cacheToClient && out["cache_tag"].string()) {
199                     string etag = string("\"") + out["cache_tag"].string() + '"';
200                     request.setResponseHeader("ETag", etag.c_str());
201                 }
202                 if (out["feed"].string()) {
203                     istringstream buf(out["feed"].string());
204                     request.setContentType("application/json; charset=UTF-8");
205                     return make_pair(true, request.sendResponse(buf));
206                 }
207                 throw ConfigurationException("Discovery feed was empty.");
208             }
209             else {
210                 // The response object is a string containing the cache tag.
211                 if (out.isstring() && out.string())
212                     s = out.string();
213             }
214         }
215
216         if (s.empty()) {
217             m_log.debug("client's cache tag matches our feed");
218             istringstream msg("Not Modified");
219             return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED));
220         }
221
222         string fname = m_dir + '/' + request.getApplication().getHash() + '_' + s + ".json";
223         ifstream feed(fname.c_str());
224         if (!feed)
225             throw ConfigurationException("Unable to access cached feed in ($1).", params(1,fname.c_str()));
226         if (m_cacheToClient) {
227             string etag = '"' + s + '"';
228             request.setResponseHeader("ETag", etag.c_str());
229         }
230         request.setContentType("application/json; charset=UTF-8");
231         return make_pair(true, request.sendResponse(feed));
232     }
233     catch (std::exception& ex) {
234         request.log(SPRequest::SPError, string("error while processing request:") + ex.what());
235         istringstream msg("Discovery Request Failed");
236         return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
237     }
238 }
239
240 void DiscoveryFeed::receive(DDF& in, ostream& out)
241 {
242     // Find application.
243     const char* aid = in["application_id"].string();
244     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
245     if (!app) {
246         // Something's horribly wrong.
247         m_log.error("couldn't find application (%s) for discovery feed request", aid ? aid : "(missing)");
248         throw ConfigurationException("Unable to locate application for discovery feed request, deleted?");
249     }
250
251     string cacheTag;
252     if (in["cache_tag"].string())
253         cacheTag = in["cache_tag"].string();
254
255     DDF ret(nullptr);
256     DDFJanitor jout(ret);
257
258     if (!m_dir.empty()) {
259         // We're relaying the feed through a file.
260         feedToFile(*app, cacheTag);
261         if (!cacheTag.empty())
262             ret.string(cacheTag.c_str());
263     }
264     else {
265         // We're relaying the feed directly.
266         ostringstream os;
267         feedToStream(*app, cacheTag, os);
268         if (!cacheTag.empty())
269             ret.addmember("cache_tag").string(cacheTag.c_str());
270         string feed = os.str();
271         if (!feed.empty())
272             ret.addmember("feed").string(feed.c_str());
273     }
274     out << ret;
275 }
276
277 void DiscoveryFeed::feedToFile(const Application& application, string& cacheTag) const
278 {
279 #ifndef SHIBSP_LITE
280     m_log.debug("processing discovery feed request");
281
282     DiscoverableMetadataProvider* m = dynamic_cast<DiscoverableMetadataProvider*>(application.getMetadataProvider(false));
283     if (!m)
284         m_log.warn("MetadataProvider missing or does not support discovery feed");
285     Locker locker(m);
286     string feedTag = m ? m->getCacheTag() : "empty";
287     if (cacheTag == ('"' + feedTag + '"')) {
288         // The client already has the same feed we do.
289         m_log.debug("client's cache tag matches our feed (%s)", feedTag.c_str());
290         cacheTag.erase();   // clear the tag to signal no change
291         return;
292     }
293
294     cacheTag = feedTag;
295
296     // The client is out of date or not caching, so we need to see if our copy is good.
297     Lock lock(m_feedLock);
298     time_t now = time(nullptr);
299
300     // Clean up any old files.
301     feedqueue_t q = m_feedQueues[application.getId()];
302     while (q.size() > 1 && (now - q.front().second > 120)) {
303         string fname = m_dir + '/' + application.getHash() + '_' + q.front().first + ".json";
304         remove(fname.c_str());
305         q.pop();
306     }
307
308     if (q.empty() || q.back().first != feedTag) {
309         // We're out of date.
310         string fname = m_dir + '/' + application.getHash() + '_' + feedTag + ".json";
311         ofstream ofile(fname.c_str());
312         if (!ofile)
313             throw ConfigurationException("Unable to create feed in ($1).", params(1,fname.c_str()));
314         bool first = true;
315         if (m)
316             m->outputFeed(ofile, first);
317         else
318             ofile << "[\n]";
319         ofile.close();
320         q.push(make_pair(feedTag, now));
321     }
322     else {
323         // Update the back of the queue.
324         q.back().second = now;
325     }
326 #else
327     throw ConfigurationException("Build does not support discovery feed.");
328 #endif
329 }
330
331 void DiscoveryFeed::feedToStream(const Application& application, string& cacheTag, ostream& os) const
332 {
333 #ifndef SHIBSP_LITE
334     m_log.debug("processing discovery feed request");
335
336     DiscoverableMetadataProvider* m = dynamic_cast<DiscoverableMetadataProvider*>(application.getMetadataProvider(false));
337     if (!m)
338         m_log.warn("MetadataProvider missing or does not support discovery feed");
339     Locker locker(m);
340     string feedTag = m ? m->getCacheTag() : "empty";
341     if (cacheTag == ('"' + feedTag + '"')) {
342         // The client already has the same feed we do.
343         m_log.debug("client's cache tag matches our feed (%s)", feedTag.c_str());
344         cacheTag.erase();   // clear the tag to signal no change
345         return;
346     }
347
348     cacheTag = feedTag;
349     bool first = true;
350     if (m)
351         m->outputFeed(os, first);
352     else
353         os << "[\n]";
354 #else
355     throw ConfigurationException("Build does not support discovery feed.");
356 #endif
357 }