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