Fix use of relative redirect.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / LogoutHandler.cpp
1 /*
2  *  Copyright 2001-2009 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  * LogoutHandler.cpp
19  *
20  * Base class for logout-related handlers.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "SPRequest.h"
29 #include "handler/LogoutHandler.h"
30 #include "util/TemplateParameters.h"
31
32 #include <fstream>
33 #include <xmltooling/XMLToolingConfig.h>
34 #include <xmltooling/util/PathResolver.h>
35 #include <xmltooling/util/URLEncoder.h>
36
37 using namespace shibsp;
38 using namespace xmltooling;
39 using namespace std;
40
41 LogoutHandler::LogoutHandler() : m_initiator(true)
42 {
43 }
44
45 LogoutHandler::~LogoutHandler()
46 {
47 }
48
49 pair<bool,long> LogoutHandler::sendLogoutPage(
50     const Application& application, const HTTPRequest& request, HTTPResponse& response, bool local, const char* status
51     ) const
52 {
53     const PropertySet* props = application.getPropertySet("Errors");
54     pair<bool,const char*> prop = props ? props->getString(local ? "localLogout" : "globalLogout") : pair<bool,const char*>(false,NULL);
55     if (prop.first) {
56         response.setContentType("text/html");
57         response.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
58         response.setResponseHeader("Cache-Control","private,no-store,no-cache");
59         string fname(prop.second);
60         ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
61         if (!infile)
62             throw ConfigurationException("Unable to access $1 HTML template.", params(1,local ? "localLogout" : "globalLogout"));
63         TemplateParameters tp;
64         tp.m_request = &request;
65         tp.setPropertySet(props);
66         if (status)
67             tp.m_map["logoutStatus"] = status;
68         stringstream str;
69         XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp);
70         return make_pair(true,response.sendResponse(str));
71     }
72     prop = application.getString("homeURL");
73     if (prop.first)
74         return make_pair(true,response.sendRedirect(prop.second));
75
76     // No homeURL, so compute a URL to the root of the site.
77     int port = request.getPort();
78     const char* scheme = request.getScheme();
79     string dest = string(scheme) + "://" + request.getHostname();
80     if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
81         ostringstream portstr;
82         portstr << port;
83         dest += ":" + portstr.str();
84     }
85     dest += '/';
86     return make_pair(true,response.sendRedirect(dest.c_str()));
87 }
88
89 pair<bool,long> LogoutHandler::run(SPRequest& request, bool isHandler) const
90 {
91     // If we're inside a chain, do nothing.
92     if (getParent())
93         return make_pair(false,0L);
94
95     // If this isn't a LogoutInitiator, we only "continue" a notification loop, rather than starting one.
96     if (!m_initiator && !request.getParameter("notifying"))
97         return make_pair(false,0L);
98
99     // Try another front-channel notification. No extra parameters and the session is implicit.
100     return notifyFrontChannel(request.getApplication(), request, request);
101 }
102
103 void LogoutHandler::receive(DDF& in, ostream& out)
104 {
105     DDF ret(NULL);
106     DDFJanitor jout(ret);
107     if (in["notify"].integer() != 1)
108         throw ListenerException("Unsupported operation.");
109
110     // Find application.
111     const char* aid=in["application_id"].string();
112     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
113     if (!app) {
114         // Something's horribly wrong.
115         Category::getInstance(SHIBSP_LOGCAT".Logout").error("couldn't find application (%s) for logout", aid ? aid : "(missing)");
116         throw ConfigurationException("Unable to locate application for logout, deleted?");
117     }
118
119     vector<string> sessions;
120     DDF s = in["sessions"];
121     DDF temp = s.first();
122     while (temp.isstring()) {
123         sessions.push_back(temp.string());
124         temp = s.next();
125         if (notifyBackChannel(*app, in["url"].string(), sessions, in["local"].integer()==1))
126             ret.integer(1);
127     }
128
129     out << ret;
130 }
131
132 pair<bool,long> LogoutHandler::notifyFrontChannel(
133     const Application& application,
134     const HTTPRequest& request,
135     HTTPResponse& response,
136     const map<string,string>* params
137     ) const
138 {
139     // Index of notification point starts at 0.
140     unsigned int index = 0;
141     const char* param = request.getParameter("index");
142     if (param)
143         index = atoi(param);
144
145     // "return" is a backwards-compatible "eventual destination" to go back to after logout completes.
146     param = request.getParameter("return");
147
148     // Fetch the next front notification URL and bump the index for the next round trip.
149     string loc = application.getNotificationURL(request.getRequestURL(), true, index++);
150     if (loc.empty())
151         return make_pair(false,0L);
152
153     const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
154
155     // Start with an "action" telling the application what this is about.
156     loc = loc + (strchr(loc.c_str(),'?') ? '&' : '?') + "action=logout";
157
158     // Now we create a second URL representing the return location back to us.
159     ostringstream locstr;
160     const char* start = request.getRequestURL();
161     const char* end = strchr(start,'?');
162     string tempstr(start, end ? end-start : strlen(start));
163
164     // Add a signal that we're coming back from notification and the next index.
165     locstr << tempstr << "?notifying=1&index=" << index;
166
167     // Add return if set.
168     if (param)
169         locstr << "&return=" << encoder->encode(param);
170
171     // We preserve anything we're instructed to directly.
172     if (params) {
173         for (map<string,string>::const_iterator p = params->begin(); p!=params->end(); ++p)
174             locstr << '&' << p->first << '=' << encoder->encode(p->second.c_str());
175     }
176     else {
177         for (vector<string>::const_iterator q = m_preserve.begin(); q!=m_preserve.end(); ++q) {
178             param = request.getParameter(q->c_str());
179             if (param)
180                 locstr << '&' << *q << '=' << encoder->encode(param);
181         }
182     }
183
184     // Add the notifier's return parameter to the destination location and redirect.
185     // This is NOT the same as the return parameter that might be embedded inside it ;-)
186     loc = loc + "&return=" + encoder->encode(locstr.str().c_str());
187     return make_pair(true,response.sendRedirect(loc.c_str()));
188 }
189
190 #ifndef SHIBSP_LITE
191 #include "util/SPConstants.h"
192 #include <xmltooling/impl/AnyElement.h>
193 #include <xmltooling/soap/SOAP.h>
194 #include <xmltooling/soap/SOAPClient.h>
195 #include <xmltooling/soap/HTTPSOAPTransport.h>
196 using namespace soap11;
197 namespace {
198     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);
199     static const XMLCh SessionID[] =            UNICODE_LITERAL_9(S,e,s,s,i,o,n,I,D);
200     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
201     static const XMLCh _local[] =               UNICODE_LITERAL_5(l,o,c,a,l);
202     static const XMLCh _global[] =              UNICODE_LITERAL_6(g,l,o,b,a,l);
203
204     class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
205     {
206     public:
207         SOAPNotifier() {}
208         virtual ~SOAPNotifier() {}
209     private:
210         void prepareTransport(SOAPTransport& transport) {
211             transport.setVerifyHost(false);
212             HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
213             if (http) {
214                 http->useChunkedEncoding(false);
215                 http->setRequestHeader("User-Agent", PACKAGE_NAME);
216                 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
217             }
218         }
219     };
220 };
221 #endif
222
223 bool LogoutHandler::notifyBackChannel(
224     const Application& application, const char* requestURL, const vector<string>& sessions, bool local
225     ) const
226 {
227     if (sessions.empty()) {
228         Category::getInstance(SHIBSP_LOGCAT".Logout").error("no sessions supplied to back channel notification method");
229         return false;
230     }
231
232     unsigned int index = 0;
233     string endpoint = application.getNotificationURL(requestURL, false, index++);
234     if (endpoint.empty())
235         return true;
236
237     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
238 #ifndef SHIBSP_LITE
239         auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
240         Body* body = BodyBuilder::buildBody();
241         env->setBody(body);
242         ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, LogoutNotification);
243         body->getUnknownXMLObjects().push_back(msg);
244         msg->setAttribute(xmltooling::QName(NULL, _type), local ? _local : _global);
245         for (vector<string>::const_iterator s = sessions.begin(); s!=sessions.end(); ++s) {
246             auto_ptr_XMLCh temp(s->c_str());
247             ElementProxy* child = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, SessionID);
248             child->setTextContent(temp.get());
249             msg->getUnknownXMLObjects().push_back(child);
250         }
251
252         bool result = true;
253         SOAPNotifier soaper;
254         while (!endpoint.empty()) {
255             try {
256                 soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
257                 delete soaper.receive();
258             }
259             catch (exception& ex) {
260                 Category::getInstance(SHIBSP_LOGCAT".Logout").error("error notifying application of logout event: %s", ex.what());
261                 result = false;
262             }
263             soaper.reset();
264             endpoint = application.getNotificationURL(requestURL, false, index++);
265         }
266         return result;
267 #else
268         return false;
269 #endif
270     }
271
272     // When not out of process, we remote the back channel work.
273     DDF out,in(m_address.c_str());
274     DDFJanitor jin(in), jout(out);
275     in.addmember("notify").integer(1);
276     in.addmember("application_id").string(application.getId());
277     in.addmember("url").string(requestURL);
278     if (local)
279         in.addmember("local").integer(1);
280     DDF s = in.addmember("sessions").list();
281     for (vector<string>::const_iterator i = sessions.begin(); i!=sessions.end(); ++i) {
282         DDF temp = DDF(NULL).string(i->c_str());
283         s.add(temp);
284     }
285     out=application.getServiceProvider().getListenerService()->send(in);
286     return (out.integer() == 1);
287 }