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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 * Handler for generating a JSON discovery feed based on metadata.
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"
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/Threads.h>
39 #include <xmltooling/util/PathResolver.h>
43 # include <boost/scoped_ptr.hpp>
44 # include <saml/exceptions.h>
45 # include <saml/SAMLConfig.h>
46 # include <saml/saml2/metadata/DiscoverableMetadataProvider.h>
49 using namespace shibsp;
51 using namespace opensaml::saml2md;
52 using namespace opensaml;
53 using namespace boost;
55 using namespace xmltooling;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
68 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
73 acceptNode(const DOMNode* node) const {
78 static SHIBSP_DLLLOCAL Blocker g_Blocker;
80 class SHIBSP_API DiscoveryFeed : public AbstractHandler, public RemotedHandler
83 DiscoveryFeed(const DOMElement* e, const char* appId);
84 virtual ~DiscoveryFeed();
86 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
87 void receive(DDF& in, ostream& out);
90 void feedToFile(const Application& application, string& cacheTag) const;
91 void feedToStream(const Application& application, string& cacheTag, ostream& os) const;
96 // A queue of feed files, linked to the last time of "access".
97 // Each filename is also a cache tag.
98 mutable queue< pair<string,time_t> > m_feedQueue;
99 scoped_ptr<Mutex> m_feedLock;
103 #if defined (_MSC_VER)
104 #pragma warning( pop )
107 Handler* SHIBSP_DLLLOCAL DiscoveryFeedFactory(const pair<const DOMElement*,const char*>& p)
109 return new DiscoveryFeed(p.first, p.second);
114 DiscoveryFeed::DiscoveryFeed(const DOMElement* e, const char* appId)
115 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".DiscoveryFeed"), &g_Blocker), m_cacheToClient(false)
117 pair<bool,const char*> prop = getString("Location");
119 throw ConfigurationException("DiscoveryFeed handler requires Location property.");
120 string address(appId);
121 address += prop.second;
122 setAddress(address.c_str());
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");
131 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_dir, PathResolver::XMLTOOLING_RUN_FILE);
132 m_log.info("feed files will be cached in %s", m_dir.c_str());
134 m_feedLock.reset(Mutex::create());
139 DiscoveryFeed::~DiscoveryFeed()
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 while (!m_feedQueue.empty() && now - m_feedQueue.front().second > 120) {
147 string fname = m_dir + '/' + m_feedQueue.front().first;
148 remove(fname.c_str());
155 pair<bool,long> DiscoveryFeed::run(SPRequest& request, bool isHandler) const
158 SPConfig& conf = SPConfig::getConfig();
162 s = request.getHeader("If-None-Match");
164 if (conf.isEnabled(SPConfig::OutOfProcess)) {
165 // When out of process, we run natively and directly process the message.
167 // The feed is directly returned.
169 feedToStream(request.getApplication(), s, buf);
171 if (m_cacheToClient) {
172 string etag = '"' + s + '"';
173 request.setResponseHeader("ETag", etag.c_str());
175 request.setContentType("application/json");
176 return make_pair(true, request.sendResponse(buf));
180 // Indirect the feed through a file.
181 feedToFile(request.getApplication(), s);
185 // When not out of process, we remote all the message processing.
186 DDF out,in = DDF(m_address.c_str());
187 in.addmember("application_id").string(request.getApplication().getId());
189 in.addmember("cache_tag").string(s.c_str());
190 DDFJanitor jin(in), jout(out);
191 out = request.getServiceProvider().getListenerService()->send(in);
194 // The cache tag and feed are in the response struct.
195 if (m_cacheToClient && out["cache_tag"].string()) {
196 string etag = string("\"") + out["cache_tag"].string() + '"';
197 request.setResponseHeader("ETag", etag.c_str());
199 if (out["feed"].string()) {
200 istringstream buf(out["feed"].string());
201 request.setContentType("application/json");
202 return make_pair(true, request.sendResponse(buf));
204 throw ConfigurationException("Discovery feed was empty.");
207 // The response object is a string containing the cache tag.
208 if (out.isstring() && out.string())
214 m_log.debug("client's cache tag matches our feed");
215 istringstream msg("Not Modified");
216 return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_NOTMODIFIED));
219 string fname = m_dir + '/' + s + ".json";
220 ifstream feed(fname.c_str());
222 throw ConfigurationException("Unable to access cached feed in ($1).", params(1,fname.c_str()));
223 if (m_cacheToClient) {
224 string etag = '"' + s + '"';
225 request.setResponseHeader("ETag", etag.c_str());
227 request.setContentType("application/json");
228 return make_pair(true, request.sendResponse(feed));
230 catch (std::exception& ex) {
231 request.log(SPRequest::SPError, string("error while processing request:") + ex.what());
232 istringstream msg("Discovery Request Failed");
233 return make_pair(true, request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
237 void DiscoveryFeed::receive(DDF& in, ostream& out)
240 const char* aid = in["application_id"].string();
241 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
243 // Something's horribly wrong.
244 m_log.error("couldn't find application (%s) for discovery feed request", aid ? aid : "(missing)");
245 throw ConfigurationException("Unable to locate application for discovery feed request, deleted?");
249 if (in["cache_tag"].string())
250 cacheTag = in["cache_tag"].string();
253 DDFJanitor jout(ret);
255 if (!m_dir.empty()) {
256 // We're relaying the feed through a file.
257 feedToFile(*app, cacheTag);
258 if (!cacheTag.empty())
259 ret.string(cacheTag.c_str());
262 // We're relaying the feed directly.
264 feedToStream(*app, cacheTag, os);
265 if (!cacheTag.empty())
266 ret.addmember("cache_tag").string(cacheTag.c_str());
267 string feed = os.str();
269 ret.addmember("feed").string(feed.c_str());
274 void DiscoveryFeed::feedToFile(const Application& application, string& cacheTag) const
277 m_log.debug("processing discovery feed request");
279 DiscoverableMetadataProvider* m = dynamic_cast<DiscoverableMetadataProvider*>(application.getMetadataProvider(false));
281 m_log.warn("MetadataProvider missing or does not support discovery feed");
283 string feedTag = m ? m->getCacheTag() : "empty";
284 if (cacheTag == ('"' + feedTag + '"')) {
285 // The client already has the same feed we do.
286 m_log.debug("client's cache tag matches our feed (%s)", feedTag.c_str());
287 cacheTag.erase(); // clear the tag to signal no change
293 // The client is out of date or not caching, so we need to see if our copy is good.
294 Lock lock(m_feedLock);
295 time_t now = time(nullptr);
297 // Clean up any old files.
298 while (m_feedQueue.size() > 1 && (now - m_feedQueue.front().second > 120)) {
299 string fname = m_dir + '/' + m_feedQueue.front().first;
300 remove(fname.c_str());
304 if (m_feedQueue.empty() || m_feedQueue.back().first != feedTag) {
305 // We're out of date.
306 string fname = m_dir + '/' + feedTag + ".json";
307 ofstream ofile(fname.c_str());
309 throw ConfigurationException("Unable to create feed in ($1).", params(1,fname.c_str()));
312 m->outputFeed(ofile, first);
316 m_feedQueue.push(make_pair(feedTag, now));
319 // Update the back of the queue.
320 m_feedQueue.back().second = now;
323 throw ConfigurationException("Build does not support discovery feed.");
327 void DiscoveryFeed::feedToStream(const Application& application, string& cacheTag, ostream& os) const
330 m_log.debug("processing discovery feed request");
332 DiscoverableMetadataProvider* m = dynamic_cast<DiscoverableMetadataProvider*>(application.getMetadataProvider(false));
334 m_log.warn("MetadataProvider missing or does not support discovery feed");
336 string feedTag = m ? m->getCacheTag() : "empty";
337 if (cacheTag == ('"' + feedTag + '"')) {
338 // The client already has the same feed we do.
339 m_log.debug("client's cache tag matches our feed (%s)", feedTag.c_str());
340 cacheTag.erase(); // clear the tag to signal no change
347 m->outputFeed(os, first);
351 throw ConfigurationException("Build does not support discovery feed.");