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