Add cache method to find but not remove sessions by name.
[shibboleth/sp.git] / shibsp / handler / impl / AbstractHandler.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  * AbstractHandler.cpp
19  * 
20  * Base class for handlers based on a DOMPropertySet. 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "remoting/ListenerService.h"
30 #include "util/SPConstants.h"
31
32 #ifndef SHIBSP_LITE
33 # include <saml/SAMLConfig.h>
34 # include <saml/binding/SAMLArtifact.h>
35 # include <saml/saml1/core/Protocols.h>
36 # include <saml/saml2/core/Protocols.h>
37 # include <saml/util/SAMLConstants.h>
38 # include <xmltooling/util/StorageService.h>
39 #else
40 # include "lite/SAMLConstants.h"
41 #endif
42
43 #include <xmltooling/XMLToolingConfig.h>
44 #include <xmltooling/util/URLEncoder.h>
45
46 using namespace shibsp;
47 using namespace samlconstants;
48 using namespace opensaml;
49 using namespace xmltooling;
50 using namespace log4cpp;
51 using namespace xercesc;
52 using namespace std;
53
54 namespace shibsp {
55     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
56     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
57     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
58     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
59 };
60
61 void SHIBSP_API shibsp::registerHandlers()
62 {
63     SPConfig& conf=SPConfig::getConfig();
64     
65     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
66     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
67     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
68     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
69     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
70
71     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
72
73     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
74 }
75
76 AbstractHandler::AbstractHandler(
77     const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
78     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
79     load(e,log,filter,remapper);
80 }
81
82 #ifndef SHIBSP_LITE
83 void AbstractHandler::checkError(const XMLObject* response) const
84 {
85     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
86     if (r2) {
87         const saml2p::Status* status = r2->getStatus();
88         if (status) {
89             const saml2p::StatusCode* sc = status->getStatusCode();
90             const XMLCh* code = sc ? sc->getValue() : NULL;
91             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
92                 FatalProfileException ex("SAML Response message contained an error.");
93                 auto_ptr_char c1(code);
94                 ex.addProperty("StatusCode", c1.get());
95                 if (sc->getStatusCode()) {
96                     code = sc->getStatusCode()->getValue();
97                     auto_ptr_char c2(code);
98                     ex.addProperty("StatusCode2", c2.get());
99                 }
100                 if (status->getStatusMessage()) {
101                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
102                     ex.addProperty("StatusMessage", msg.get());
103                 }
104             }
105         }
106     }
107
108     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
109     if (r1) {
110         const saml1p::Status* status = r1->getStatus();
111         if (status) {
112             const saml1p::StatusCode* sc = status->getStatusCode();
113             const QName* code = sc ? sc->getValue() : NULL;
114             if (code && *code != saml1p::StatusCode::SUCCESS) {
115                 FatalProfileException ex("SAML Response message contained an error.");
116                 ex.addProperty("StatusCode", code->toString().c_str());
117                 if (sc->getStatusCode()) {
118                     code = sc->getStatusCode()->getValue();
119                     if (code)
120                         ex.addProperty("StatusCode2", code->toString().c_str());
121                 }
122                 if (status->getStatusMessage()) {
123                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
124                     ex.addProperty("StatusMessage", msg.get());
125                 }
126             }
127         }
128     }
129 }
130
131 void AbstractHandler::prepareResponse(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
132 {
133     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
134     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
135     status->setStatusCode(scode);
136     scode->setValue(code);
137     if (subcode) {
138         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
139         scode->setStatusCode(ssubcode);
140         ssubcode->setValue(subcode);
141     }
142     if (msg) {
143         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
144         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
145         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
146         status->setStatusMessage(sm);
147         sm->setMessage(widemsg.get());
148     }
149     response.setStatus(status);
150 }
151 #endif
152
153 void AbstractHandler::preserveRelayState(const Application& application, HTTPResponse& response, string& relayState) const
154 {
155     if (relayState.empty())
156         return;
157
158     // No setting means just pass it by value.
159     pair<bool,const char*> mech=getString("relayState");
160     if (!mech.first || !mech.second || !*mech.second)
161         return;
162
163     if (!strcmp(mech.second, "cookie")) {
164         // Here we store the state in a cookie and send a fixed
165         // value so we can recognize it on the way back.
166         if (relayState != "cookie") {
167             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
168             pair<string,const char*> shib_cookie=application.getCookieNameProps("_shibstate_");
169             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
170             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
171             relayState = "cookie";
172         }
173     }
174     else if (strstr(mech.second,"ss:")==mech.second) {
175         if (relayState.find("ss:")!=0) {
176             mech.second+=3;
177             if (*mech.second) {
178                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
179 #ifndef SHIBSP_LITE
180                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
181                     if (storage) {
182                         string rsKey;
183                         SAMLConfig::getConfig().generateRandomBytes(rsKey,10);
184                         rsKey = SAMLArtifact::toHex(rsKey);
185                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
186                             throw IOException("Attempted to insert duplicate storage key.");
187                         relayState = string(mech.second-3) + ':' + rsKey;
188                     }
189                     else {
190                         m_log.error("Storage-backed RelayState with invalid StorageService ID (%s)", mech.second);
191                         relayState.erase();
192                     }
193 #endif
194                 }
195                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
196                     DDF out,in = DDF("set::RelayState").structure();
197                     in.addmember("id").string(mech.second);
198                     in.addmember("value").string(relayState.c_str());
199                     DDFJanitor jin(in),jout(out);
200                     out = application.getServiceProvider().getListenerService()->send(in);
201                     if (!out.isstring())
202                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
203                     relayState = string(mech.second-3) + ':' + out.string();
204                 }
205             }
206         }
207     }
208     else
209         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
210 }
211
212 void AbstractHandler::recoverRelayState(const Application& application, HTTPRequest& httpRequest, string& relayState, bool clear) const
213 {
214     SPConfig& conf = SPConfig::getConfig();
215
216     // Look for StorageService-backed state of the form "ss:SSID:key".
217     const char* state = relayState.c_str();
218     if (strstr(state,"ss:")==state) {
219         state += 3;
220         const char* key = strchr(state,':');
221         if (key) {
222             string ssid = relayState.substr(3, key - state);
223             key++;
224             if (!ssid.empty() && *key) {
225                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
226 #ifndef SHIBSP_LITE
227                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
228                     if (storage) {
229                         ssid = key;
230                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
231                             if (clear)
232                                 storage->deleteString("RelayState",ssid.c_str());
233                             return;
234                         }
235                         else
236                             relayState.erase();
237                     }
238                     else {
239                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
240                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
241                             );
242                         relayState.erase();
243                     }
244 #endif
245                 }
246                 else if (conf.isEnabled(SPConfig::InProcess)) {
247                     DDF out,in = DDF("get::RelayState").structure();
248                     in.addmember("id").string(ssid.c_str());
249                     in.addmember("key").string(key);
250                     in.addmember("clear").integer(clear ? 1 : 0);
251                     DDFJanitor jin(in),jout(out);
252                     out = application.getServiceProvider().getListenerService()->send(in);
253                     if (!out.isstring()) {
254                         m_log.error("StorageService-backed RelayState mechanism did not return a state value.");
255                         relayState.erase();
256                     }
257                     else {
258                         relayState = out.string();
259                         return;
260                     }
261                 }
262             }
263         }
264     }
265     
266     if (conf.isEnabled(SPConfig::InProcess)) {
267         if (relayState == "cookie") {
268             // Pull the value from the "relay state" cookie.
269             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
270             // In process, we should be able to cast down to a full SPRequest.
271             SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
272             const char* state = request.getCookie(relay_cookie.first.c_str());
273             if (state && *state) {
274                 // URL-decode the value.
275                 char* rscopy=strdup(state);
276                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
277                 relayState = rscopy;
278                 free(rscopy);
279                 
280                 if (clear)
281                     request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
282                 return;
283             }
284
285             relayState.erase();
286         }
287
288         // Check for "default" value.
289         if (relayState.empty() || relayState == "default") {
290             pair<bool,const char*> homeURL=application.getString("homeURL");
291             relayState=homeURL.first ? homeURL.second : "/";
292             return;
293         }
294     }
295
296     if (relayState == "default")
297         relayState.empty();
298 }