Convert logging to log4shib via compile time switch.
[shibboleth/cpp-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(const Application& application, HTTPResponse& response, bool local, const char* status) const
40 {
41     pair<bool,const char*> prop = application.getString(local ? "localLogout" : "globalLogout");
42     if (prop.first) {
43         response.setContentType("text/html");
44         response.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
45         response.setResponseHeader("Cache-Control","private,no-store,no-cache");
46         ifstream infile(prop.second);
47         if (!infile)
48             throw ConfigurationException("Unable to access $1 HTML template.", params(1,local ? "localLogout" : "globalLogout"));
49         TemplateParameters tp;
50         tp.setPropertySet(application.getPropertySet("Errors"));
51         if (status)
52             tp.m_map["logoutStatus"] = status;
53         stringstream str;
54         XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp);
55         return make_pair(true,response.sendResponse(str));
56     }
57     prop = application.getString("homeURL");
58     if (!prop.first)
59         prop.second = "/";
60     return make_pair(true,response.sendRedirect(prop.second));
61 }
62
63 pair<bool,long> LogoutHandler::run(SPRequest& request, bool isHandler) const
64 {
65     // If we're inside a chain, so do nothing.
66     if (getParent())
67         return make_pair(false,0);
68     
69     // If this isn't a LogoutInitiator, we only "continue" a notification loop, rather than starting one.
70     if (!m_initiator && !request.getParameter("notifying"))
71         return make_pair(false,0);
72
73     // Try another front-channel notification. No extra parameters and the session is implicit.
74     pair<bool,long> ret = notifyFrontChannel(request.getApplication(), request, request);
75     if (ret.first)
76         return ret;
77
78     return make_pair(false,0);
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     // Fetch the next front notification URL and bump the index for the next round trip.
124     string loc = application.getNotificationURL(request.getRequestURL(), true, index++);
125     if (loc.empty())
126         return make_pair(false,0);
127
128     const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
129
130     // Start with an "action" telling the application what this is about.
131     loc = loc + (strchr(loc.c_str(),'?') ? '&' : '?') + "action=logout";
132
133     // Now we create a second URL representing the return location back to us.
134     const char* start = request.getRequestURL();
135     const char* end = strchr(start,'?');
136     string tempstr(start, end ? end-start : strlen(start));
137     ostringstream locstr(tempstr);
138
139     // Add a signal that we're coming back from notification and the next index.
140     locstr << "?notifying=1&index=" << index;
141
142     // We preserve anything we're instructed to directly.
143     if (params) {
144         for (map<string,string>::const_iterator p = params->begin(); p!=params->end(); ++p)
145             locstr << '&' << p->first << '=' << encoder->encode(p->second.c_str());
146     }
147     else {
148         for (vector<string>::const_iterator q = m_preserve.begin(); q!=m_preserve.end(); ++q) {
149             param = request.getParameter(q->c_str());
150             if (param)
151                 locstr << '&' << *q << '=' << encoder->encode(param);
152         }
153     }
154
155     // Add the return parameter to the destination location and redirect.
156     loc = loc + "&return=" + encoder->encode(locstr.str().c_str());
157     return make_pair(true,response.sendRedirect(loc.c_str()));
158 }
159
160 #ifndef SHIBSP_LITE
161 #include "util/SPConstants.h"
162 #include <xmltooling/impl/AnyElement.h>
163 #include <xmltooling/soap/SOAP.h>
164 #include <xmltooling/soap/SOAPClient.h>
165 using namespace soap11;
166 namespace {
167     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);
168     static const XMLCh SessionID[] =            UNICODE_LITERAL_9(S,e,s,s,i,o,n,I,D);
169     static const XMLCh _type[] =                UNICODE_LITERAL_4(t,y,p,e);
170     static const XMLCh _local[] =               UNICODE_LITERAL_5(l,o,c,a,l);
171     static const XMLCh _global[] =              UNICODE_LITERAL_6(g,l,o,b,a,l);
172
173     class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
174     {
175     public:
176         SOAPNotifier() {}
177         virtual ~SOAPNotifier() {}
178     private:
179         void prepareTransport(SOAPTransport& transport) {
180             transport.setVerifyHost(false);
181         }
182     };
183 };
184 #endif
185
186 bool LogoutHandler::notifyBackChannel(
187     const Application& application, const char* requestURL, const vector<string>& sessions, bool local
188     ) const
189 {
190     unsigned int index = 0;
191     string endpoint = application.getNotificationURL(requestURL, false, index++);
192     if (endpoint.empty())
193         return true;
194
195     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
196 #ifndef SHIBSP_LITE
197         auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
198         Body* body = BodyBuilder::buildBody();
199         env->setBody(body);
200         ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, LogoutNotification);
201         body->getUnknownXMLObjects().push_back(msg);
202         msg->setAttribute(QName(NULL, _type), local ? _local : _global);
203         for (vector<string>::const_iterator s = sessions.begin(); s!=sessions.end(); ++s) {
204             auto_ptr_XMLCh temp(s->c_str());
205             ElementProxy* child = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, SessionID);
206             child->setTextContent(temp.get());
207             msg->getUnknownXMLObjects().push_back(child);
208         }
209
210         bool result = true;
211         SOAPNotifier soaper;
212         while (!endpoint.empty()) {
213             try {
214                 soaper.send(*env.get(), application.getId(), endpoint.c_str());
215                 delete soaper.receive();
216             }
217             catch (exception& ex) {
218                 Category::getInstance(SHIBSP_LOGCAT".Logout").error("error notifying application of logout event: %s", ex.what());
219                 result = false;
220             }
221             soaper.reset();
222             endpoint = application.getNotificationURL(requestURL, false, index++);
223         }
224         return result;
225 #else
226         return false;
227 #endif
228     }
229
230     // When not out of process, we remote the back channel work.
231     DDF out,in(m_address.c_str());
232     DDFJanitor jin(in), jout(out);
233     in.addmember("notify").integer(1);
234     in.addmember("application_id").string(application.getId());
235     in.addmember("url").string(requestURL);
236     if (local)
237         in.addmember("local").integer(1);
238     DDF s = in.addmember("sessions").list();
239     for (vector<string>::const_iterator i = sessions.begin(); i!=sessions.end(); ++i) {
240         DDF temp = DDF(NULL).string(i->c_str());
241         s.add(temp);
242     }
243     out=application.getServiceProvider().getListenerService()->send(in);
244     return (out.integer() == 1);
245 }