Factor entityID into SessionInitiator subinterface, move WAYF logic out of Shib handler.
[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
31 #include <log4cpp/Category.hh>
32 #include <saml/saml1/core/Protocols.h>
33 #include <saml/saml2/core/Protocols.h>
34 #include <saml/util/SAMLConstants.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/util/StorageService.h>
37 #include <xmltooling/util/URLEncoder.h>
38
39 using namespace shibsp;
40 using namespace samlconstants;
41 using namespace opensaml;
42 using namespace xmltooling;
43 using namespace log4cpp;
44 using namespace xercesc;
45 using namespace std;
46
47 namespace shibsp {
48     SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML1ConsumerFactory;
49     SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML2ConsumerFactory;
50 };
51
52 void SHIBSP_API shibsp::registerHandlers()
53 {
54     SPConfig& conf=SPConfig::getConfig();
55     
56     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
57     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
58     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
59     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
60     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
61 }
62
63 AbstractHandler::AbstractHandler(
64     const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
65     ) : m_log(log) {
66     load(e,log,filter,remapper);
67 }
68
69 void AbstractHandler::checkError(const XMLObject* response) const
70 {
71     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
72     if (r2) {
73         const saml2p::Status* status = r2->getStatus();
74         if (status) {
75             const saml2p::StatusCode* sc = status->getStatusCode();
76             const XMLCh* code = sc ? sc->getValue() : NULL;
77             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
78                 FatalProfileException ex("SAML Response message contained an error.");
79                 auto_ptr_char c1(code);
80                 ex.addProperty("StatusCode", c1.get());
81                 if (sc->getStatusCode()) {
82                     code = sc->getStatusCode()->getValue();
83                     auto_ptr_char c2(code);
84                     ex.addProperty("StatusCode2", c2.get());
85                 }
86                 if (status->getStatusMessage()) {
87                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
88                     ex.addProperty("StatusMessage", msg.get());
89                 }
90             }
91         }
92     }
93
94     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
95     if (r1) {
96         const saml1p::Status* status = r1->getStatus();
97         if (status) {
98             const saml1p::StatusCode* sc = status->getStatusCode();
99             const QName* code = sc ? sc->getValue() : NULL;
100             if (code && *code != saml1p::StatusCode::SUCCESS) {
101                 FatalProfileException ex("SAML Response message contained an error.");
102                 ex.addProperty("StatusCode", code->toString().c_str());
103                 if (sc->getStatusCode()) {
104                     code = sc->getStatusCode()->getValue();
105                     if (code)
106                         ex.addProperty("StatusCode2", code->toString().c_str());
107                 }
108                 if (status->getStatusMessage()) {
109                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
110                     ex.addProperty("StatusMessage", msg.get());
111                 }
112             }
113         }
114     }
115 }
116
117 void AbstractHandler::preserveRelayState(SPRequest& request, string& relayState) const
118 {
119     pair<bool,const char*> mech=getString("relayState");
120     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
121
122     // No setting means just pass it by value.
123     if (!mech.first || !mech.second || !*mech.second) {
124         relayState = urlenc->encode(relayState.c_str());
125     }
126     else if (!strcmp(mech.second, "cookie")) {
127         // Here we store the state in a cookie and send a fixed
128         // value so we can recognize it on the way back.
129         pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibstate_");
130         string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
131         request.setCookie(shib_cookie.first.c_str(),stateval.c_str());
132         relayState = "cookie";
133     }
134     else if (strstr(mech.second,"ss:")==mech.second) {
135         mech.second+=3;
136         if (*mech.second) {
137             DDF out,in = DDF("set::RelayState").structure();
138             in.addmember("id").string(mech.second);
139             in.addmember("value").string(relayState.c_str());
140             DDFJanitor jin(in),jout(out);
141             out = request.getServiceProvider().getListenerService()->send(in);
142             if (!out.isstring())
143                 throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
144             relayState = string(mech.second-3) + ':' + urlenc->encode(out.string());
145         }
146     }
147     else
148         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
149 }
150
151 void AbstractHandler::recoverRelayState(HTTPRequest& httpRequest, string& relayState) const
152 {
153     SPConfig& conf = SPConfig::getConfig();
154
155     // Look for StorageService-backed state of the form "ss:SSID:key".
156     const char* state = relayState.c_str();
157     if (strstr(state,"ss:")==state) {
158         state += 3;
159         const char* key = strchr(state,':');
160         if (key) {
161             string ssid = relayState.substr(3, key - state);
162             key++;
163             if (!ssid.empty() && *key) {
164                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
165                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
166                     if (storage) {
167                         if (storage->readString("RelayState",key,&relayState)>0)
168                             storage->deleteString("RelayState",key);
169                         else
170                             relayState = "default";
171                     }
172                     else {
173                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
174                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
175                             );
176                         relayState = "default";
177                     }
178                 }
179                 else if (conf.isEnabled(SPConfig::InProcess)) {
180                     // In process, we should be able to cast down to a full SPRequest.
181                     SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
182                     DDF out,in = DDF("get::RelayState").structure();
183                     in.addmember("id").string(ssid.c_str());
184                     in.addmember("key").string(key);
185                     DDFJanitor jin(in),jout(out);
186                     out = request.getServiceProvider().getListenerService()->send(in);
187                     if (!out.isstring())
188                         throw IOException("StorageService-backed RelayState mechanism did not return a state value.");
189                     relayState = out.string();
190                 }
191             }
192         }
193     }
194     else if (conf.isEnabled(SPConfig::InProcess)) {
195         // In process, we should be able to cast down to a full SPRequest.
196         SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
197         if (relayState.empty() || relayState == "cookie") {
198             // Pull the value from the "relay state" cookie.
199             pair<string,const char*> relay_cookie = request.getApplication().getCookieNameProps("_shibstate_");
200             const char* state = request.getCookie(relay_cookie.first.c_str());
201             if (state && *state) {
202                 // URL-decode the value.
203                 char* rscopy=strdup(state);
204                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
205                 relayState = rscopy;
206                 free(rscopy);
207                 
208                 // Clear the cookie.
209                 request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
210             }
211             else
212                 relayState = "default"; // fall through...
213         }
214         
215         // Check for "default" value.
216         if (relayState == "default") {
217             pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
218             relayState=homeURL.first ? homeURL.second : "/";
219         }
220     }
221 }