2 * Copyright 2001-2007 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * Base class for logout-related handlers.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "handler/LogoutHandler.h"
29 #include "util/TemplateParameters.h"
32 #include <xmltooling/XMLToolingConfig.h>
33 #include <xmltooling/util/PathResolver.h>
34 #include <xmltooling/util/URLEncoder.h>
36 using namespace shibsp;
37 using namespace xmltooling;
40 pair<bool,long> LogoutHandler::sendLogoutPage(
41 const Application& application, const HTTPRequest& request, HTTPResponse& response, bool local, const char* status
44 const PropertySet* props = application.getPropertySet("Errors");
45 pair<bool,const char*> prop = props ? props->getString(local ? "localLogout" : "globalLogout") : pair<bool,const char*>(false,NULL);
47 response.setContentType("text/html");
48 response.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
49 response.setResponseHeader("Cache-Control","private,no-store,no-cache");
50 string fname(prop.second);
51 ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
53 throw ConfigurationException("Unable to access $1 HTML template.", params(1,local ? "localLogout" : "globalLogout"));
54 TemplateParameters tp;
55 tp.m_request = &request;
56 tp.setPropertySet(props);
58 tp.m_map["logoutStatus"] = status;
60 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp);
61 return make_pair(true,response.sendResponse(str));
63 prop = application.getString("homeURL");
66 return make_pair(true,response.sendRedirect(prop.second));
69 pair<bool,long> LogoutHandler::run(SPRequest& request, bool isHandler) const
71 // If we're inside a chain, do nothing.
73 return make_pair(false,0L);
75 // If this isn't a LogoutInitiator, we only "continue" a notification loop, rather than starting one.
76 if (!m_initiator && !request.getParameter("notifying"))
77 return make_pair(false,0L);
79 // Try another front-channel notification. No extra parameters and the session is implicit.
80 return notifyFrontChannel(request.getApplication(), request, request);
83 void LogoutHandler::receive(DDF& in, ostream& out)
87 if (in["notify"].integer() != 1)
88 throw ListenerException("Unsupported operation.");
91 const char* aid=in["application_id"].string();
92 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
94 // Something's horribly wrong.
95 Category::getInstance(SHIBSP_LOGCAT".Logout").error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
96 throw ConfigurationException("Unable to locate application for logout, deleted?");
99 vector<string> sessions;
100 DDF s = in["sessions"];
101 DDF temp = s.first();
102 while (temp.isstring()) {
103 sessions.push_back(temp.string());
105 if (notifyBackChannel(*app, in["url"].string(), sessions, in["local"].integer()==1))
112 pair<bool,long> LogoutHandler::notifyFrontChannel(
113 const Application& application,
114 const HTTPRequest& request,
115 HTTPResponse& response,
116 const map<string,string>* params
119 // Index of notification point starts at 0.
120 unsigned int index = 0;
121 const char* param = request.getParameter("index");
125 // "return" is a backwards-compatible "eventual destination" to go back to after logout completes.
126 param = request.getParameter("return");
128 // Fetch the next front notification URL and bump the index for the next round trip.
129 string loc = application.getNotificationURL(request.getRequestURL(), true, index++);
131 return make_pair(false,0L);
133 const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
135 // Start with an "action" telling the application what this is about.
136 loc = loc + (strchr(loc.c_str(),'?') ? '&' : '?') + "action=logout";
138 // Now we create a second URL representing the return location back to us.
139 ostringstream locstr;
140 const char* start = request.getRequestURL();
141 const char* end = strchr(start,'?');
142 string tempstr(start, end ? end-start : strlen(start));
144 // Add a signal that we're coming back from notification and the next index.
145 locstr << tempstr << "?notifying=1&index=" << index;
147 // Add return if set.
149 locstr << "&return=" << encoder->encode(param);
151 // We preserve anything we're instructed to directly.
153 for (map<string,string>::const_iterator p = params->begin(); p!=params->end(); ++p)
154 locstr << '&' << p->first << '=' << encoder->encode(p->second.c_str());
157 for (vector<string>::const_iterator q = m_preserve.begin(); q!=m_preserve.end(); ++q) {
158 param = request.getParameter(q->c_str());
160 locstr << '&' << *q << '=' << encoder->encode(param);
164 // Add the notifier's return parameter to the destination location and redirect.
165 // This is NOT the same as the return parameter that might be embedded inside it ;-)
166 loc = loc + "&return=" + encoder->encode(locstr.str().c_str());
167 return make_pair(true,response.sendRedirect(loc.c_str()));
171 #include "util/SPConstants.h"
172 #include <xmltooling/impl/AnyElement.h>
173 #include <xmltooling/soap/SOAP.h>
174 #include <xmltooling/soap/SOAPClient.h>
175 #include <xmltooling/soap/HTTPSOAPTransport.h>
176 using namespace soap11;
178 static const XMLCh LogoutNotification[] = UNICODE_LITERAL_18(L,o,g,o,u,t,N,o,t,i,f,i,c,a,t,i,o,n);
179 static const XMLCh SessionID[] = UNICODE_LITERAL_9(S,e,s,s,i,o,n,I,D);
180 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
181 static const XMLCh _local[] = UNICODE_LITERAL_5(l,o,c,a,l);
182 static const XMLCh _global[] = UNICODE_LITERAL_6(g,l,o,b,a,l);
184 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
188 virtual ~SOAPNotifier() {}
190 void prepareTransport(SOAPTransport& transport) {
191 transport.setVerifyHost(false);
192 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
194 http->useChunkedEncoding(false);
195 http->setRequestHeader("User-Agent", PACKAGE_NAME);
196 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
203 bool LogoutHandler::notifyBackChannel(
204 const Application& application, const char* requestURL, const vector<string>& sessions, bool local
207 if (sessions.empty()) {
208 Category::getInstance(SHIBSP_LOGCAT".Logout").error("no sessions supplied to back channel notification method");
212 unsigned int index = 0;
213 string endpoint = application.getNotificationURL(requestURL, false, index++);
214 if (endpoint.empty())
217 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
219 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
220 Body* body = BodyBuilder::buildBody();
222 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, LogoutNotification);
223 body->getUnknownXMLObjects().push_back(msg);
224 msg->setAttribute(xmltooling::QName(NULL, _type), local ? _local : _global);
225 for (vector<string>::const_iterator s = sessions.begin(); s!=sessions.end(); ++s) {
226 auto_ptr_XMLCh temp(s->c_str());
227 ElementProxy* child = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, SessionID);
228 child->setTextContent(temp.get());
229 msg->getUnknownXMLObjects().push_back(child);
234 while (!endpoint.empty()) {
236 soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
237 delete soaper.receive();
239 catch (exception& ex) {
240 Category::getInstance(SHIBSP_LOGCAT".Logout").error("error notifying application of logout event: %s", ex.what());
244 endpoint = application.getNotificationURL(requestURL, false, index++);
252 // When not out of process, we remote the back channel work.
253 DDF out,in(m_address.c_str());
254 DDFJanitor jin(in), jout(out);
255 in.addmember("notify").integer(1);
256 in.addmember("application_id").string(application.getId());
257 in.addmember("url").string(requestURL);
259 in.addmember("local").integer(1);
260 DDF s = in.addmember("sessions").list();
261 for (vector<string>::const_iterator i = sessions.begin(); i!=sessions.end(); ++i) {
262 DDF temp = DDF(NULL).string(i->c_str());
265 out=application.getServiceProvider().getListenerService()->send(in);
266 return (out.integer() == 1);