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