Add shorthand methods for obtaining properties using standard precedence rules.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AbstractHandler.cpp
1 /*
2  *  Copyright 2001-2010 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 "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/LogoutHandler.h"
30 #include "remoting/ListenerService.h"
31 #include "util/CGIParser.h"
32 #include "util/SPConstants.h"
33 #include "util/TemplateParameters.h"
34
35 #include <vector>
36 #include <fstream>
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/URLEncoder.h>
40
41
42 #ifndef SHIBSP_LITE
43 # include <saml/exceptions.h>
44 # include <saml/SAMLConfig.h>
45 # include <saml/binding/SAMLArtifact.h>
46 # include <saml/saml1/core/Protocols.h>
47 # include <saml/saml2/core/Protocols.h>
48 # include <saml/saml2/metadata/Metadata.h>
49 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
50 # include <saml/util/SAMLConstants.h>
51 # include <xmltooling/security/Credential.h>
52 # include <xmltooling/security/CredentialResolver.h>
53 # include <xmltooling/util/StorageService.h>
54 using namespace opensaml::saml2md;
55 using namespace opensaml;
56 #else
57 # include "lite/SAMLConstants.h"
58 #endif
59
60 #include <xmltooling/XMLToolingConfig.h>
61 #include <xmltooling/util/URLEncoder.h>
62
63 using namespace shibsp;
64 using namespace samlconstants;
65 using namespace xmltooling;
66 using namespace xercesc;
67 using namespace std;
68
69 namespace shibsp {
70     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML1ConsumerFactory;
71     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ConsumerFactory;
72     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2ArtifactResolutionFactory;
73     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory ChainingLogoutInitiatorFactory;
74     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory LocalLogoutInitiatorFactory;
75     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutInitiatorFactory;
76     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2LogoutFactory;
77     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SAML2NameIDMgmtFactory;
78     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory AssertionLookupFactory;
79     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory MetadataGeneratorFactory;
80     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory StatusHandlerFactory;
81     SHIBSP_DLLLOCAL PluginManager< Handler,string,pair<const DOMElement*,const char*> >::Factory SessionHandlerFactory;
82
83     void SHIBSP_DLLLOCAL generateRandomHex(std::string& buf, unsigned int len) {
84         static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
85         int r;
86         unsigned char b1,b2;
87         buf.erase();
88         for (unsigned int i=0; i<len; i+=4) {
89             r = rand();
90             b1 = (0x00FF & r);
91             b2 = (0xFF00 & r)  >> 8;
92             buf += (DIGITS[(0xF0 & b1) >> 4 ]);
93             buf += (DIGITS[0x0F & b1]);
94             buf += (DIGITS[(0xF0 & b2) >> 4 ]);
95             buf += (DIGITS[0x0F & b2]);
96         }
97     }
98 };
99
100 void SHIBSP_API shibsp::registerHandlers()
101 {
102     SPConfig& conf=SPConfig::getConfig();
103
104     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
105     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
106     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
107     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
108     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
109     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_PAOS, SAML2ConsumerFactory);
110
111     conf.ArtifactResolutionServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2ArtifactResolutionFactory);
112
113     conf.HandlerManager.registerFactory(SAML20_BINDING_URI, AssertionLookupFactory);
114     conf.HandlerManager.registerFactory(METADATA_GENERATOR_HANDLER, MetadataGeneratorFactory);
115     conf.HandlerManager.registerFactory(STATUS_HANDLER, StatusHandlerFactory);
116     conf.HandlerManager.registerFactory(SESSION_HANDLER, SessionHandlerFactory);
117
118     conf.LogoutInitiatorManager.registerFactory(CHAINING_LOGOUT_INITIATOR, ChainingLogoutInitiatorFactory);
119     conf.LogoutInitiatorManager.registerFactory(LOCAL_LOGOUT_INITIATOR, LocalLogoutInitiatorFactory);
120     conf.LogoutInitiatorManager.registerFactory(SAML2_LOGOUT_INITIATOR, SAML2LogoutInitiatorFactory);
121     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2LogoutFactory);
122     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2LogoutFactory);
123     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2LogoutFactory);
124     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2LogoutFactory);
125     conf.SingleLogoutServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2LogoutFactory);
126
127     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_SOAP, SAML2NameIDMgmtFactory);
128     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_REDIRECT, SAML2NameIDMgmtFactory);
129     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2NameIDMgmtFactory);
130     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2NameIDMgmtFactory);
131     conf.ManageNameIDServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2NameIDMgmtFactory);
132 }
133
134 Handler::Handler()
135 {
136 }
137
138 Handler::~Handler()
139 {
140 }
141
142 void Handler::log(SPRequest::SPLogLevel level, const string& msg) const
143 {
144     Category::getInstance(SHIBSP_LOGCAT".Handler").log(
145         (level == SPRequest::SPDebug ? Priority::DEBUG :
146         (level == SPRequest::SPInfo ? Priority::INFO :
147         (level == SPRequest::SPWarn ? Priority::WARN :
148         (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
149         msg
150         );
151 }
152
153 void Handler::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.find("cookie:") != 0) {
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             // Generate a random key for the cookie name instead of the fixed name.
171             string rsKey;
172             generateRandomHex(rsKey,5);
173             shib_cookie.first = "_shibstate_" + rsKey;
174             response.setCookie(shib_cookie.first.c_str(),stateval.c_str());
175             relayState = "cookie:" + rsKey;
176         }
177     }
178     else if (strstr(mech.second,"ss:")==mech.second) {
179         if (relayState.find("ss:") != 0) {
180             mech.second+=3;
181             if (*mech.second) {
182                 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
183 #ifndef SHIBSP_LITE
184                     StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
185                     if (storage) {
186                         string rsKey;
187                         generateRandomHex(rsKey,5);
188                         if (!storage->createString("RelayState", rsKey.c_str(), relayState.c_str(), time(NULL) + 600))
189                             throw IOException("Attempted to insert duplicate storage key.");
190                         relayState = string(mech.second-3) + ':' + rsKey;
191                     }
192                     else {
193                         string msg("Storage-backed RelayState with invalid StorageService ID (");
194                         msg = msg + mech.second+ ')';
195                         log(SPRequest::SPError, msg);
196                         relayState.erase();
197                     }
198 #endif
199                 }
200                 else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
201                     DDF out,in = DDF("set::RelayState").structure();
202                     in.addmember("id").string(mech.second);
203                     in.addmember("value").unsafe_string(relayState.c_str());
204                     DDFJanitor jin(in),jout(out);
205                     out = application.getServiceProvider().getListenerService()->send(in);
206                     if (!out.isstring())
207                         throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
208                     relayState = string(mech.second-3) + ':' + out.string();
209                 }
210             }
211         }
212     }
213     else
214         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
215 }
216
217 void Handler::recoverRelayState(
218     const Application& application, const HTTPRequest& request, HTTPResponse& response, string& relayState, bool clear
219     ) const
220 {
221     SPConfig& conf = SPConfig::getConfig();
222
223     // Look for StorageService-backed state of the form "ss:SSID:key".
224     const char* state = relayState.c_str();
225     if (strstr(state,"ss:")==state) {
226         state += 3;
227         const char* key = strchr(state,':');
228         if (key) {
229             string ssid = relayState.substr(3, key - state);
230             key++;
231             if (!ssid.empty() && *key) {
232                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
233 #ifndef SHIBSP_LITE
234                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
235                     if (storage) {
236                         ssid = key;
237                         if (storage->readString("RelayState",ssid.c_str(),&relayState)>0) {
238                             if (clear)
239                                 storage->deleteString("RelayState",ssid.c_str());
240                             return;
241                         }
242                         else
243                             relayState.erase();
244                     }
245                     else {
246                         string msg("Storage-backed RelayState with invalid StorageService ID (");
247                         msg += ssid + ')';
248                         log(SPRequest::SPError, msg);
249                         relayState.erase();
250                     }
251 #endif
252                 }
253                 else if (conf.isEnabled(SPConfig::InProcess)) {
254                     DDF out,in = DDF("get::RelayState").structure();
255                     in.addmember("id").string(ssid.c_str());
256                     in.addmember("key").string(key);
257                     in.addmember("clear").integer(clear ? 1 : 0);
258                     DDFJanitor jin(in),jout(out);
259                     out = application.getServiceProvider().getListenerService()->send(in);
260                     if (!out.isstring()) {
261                         log(SPRequest::SPError, "StorageService-backed RelayState mechanism did not return a state value.");
262                         relayState.erase();
263                     }
264                     else {
265                         relayState = out.string();
266                         return;
267                     }
268                 }
269             }
270         }
271     }
272
273     // Look for cookie-backed state of the form "cookie:key".
274     if (strstr(state,"cookie:")==state) {
275         state += 7;
276         if (*state) {
277             // Pull the value from the "relay state" cookie.
278             pair<string,const char*> relay_cookie = application.getCookieNameProps("_shibstate_");
279             relay_cookie.first = string("_shibstate_") + state;
280             state = request.getCookie(relay_cookie.first.c_str());
281             if (state && *state) {
282                 // URL-decode the value.
283                 char* rscopy=strdup(state);
284                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
285                 relayState = rscopy;
286                 free(rscopy);
287
288                 if (clear) {
289                     string exp(relay_cookie.second);
290                     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
291                     response.setCookie(relay_cookie.first.c_str(), exp.c_str());
292                 }
293                 return;
294             }
295         }
296
297         relayState.erase();
298     }
299
300     // Check for "default" value (or the old "cookie" value that might come from stale bookmarks).
301     if (relayState.empty() || relayState == "default" || relayState == "cookie") {
302         pair<bool,const char*> homeURL=application.getString("homeURL");
303         if (homeURL.first)
304             relayState=homeURL.second;
305         else {
306             // Compute a URL to the root of the site.
307             int port = request.getPort();
308             const char* scheme = request.getScheme();
309             relayState = string(scheme) + "://" + request.getHostname();
310             if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
311                 ostringstream portstr;
312                 portstr << port;
313                 relayState += ":" + portstr.str();
314             }
315             relayState += '/';
316         }
317     }
318 }
319
320 AbstractHandler::AbstractHandler(
321     const DOMElement* e, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
322     ) : m_log(log), m_configNS(shibspconstants::SHIB2SPCONFIG_NS) {
323     load(e,NULL,filter,remapper);
324 }
325
326 AbstractHandler::~AbstractHandler()
327 {
328 }
329
330 void AbstractHandler::log(SPRequest::SPLogLevel level, const string& msg) const
331 {
332     m_log.log(
333         (level == SPRequest::SPDebug ? Priority::DEBUG :
334         (level == SPRequest::SPInfo ? Priority::INFO :
335         (level == SPRequest::SPWarn ? Priority::WARN :
336         (level == SPRequest::SPError ? Priority::ERROR : Priority::CRIT)))),
337         msg
338         );
339 }
340
341 #ifndef SHIBSP_LITE
342
343 const char* Handler::getType() const
344 {
345     return getString("type").second;
346 }
347
348 void AbstractHandler::checkError(const XMLObject* response, const saml2md::RoleDescriptor* role) const
349 {
350     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
351     if (r2) {
352         const saml2p::Status* status = r2->getStatus();
353         if (status) {
354             const saml2p::StatusCode* sc = status->getStatusCode();
355             const XMLCh* code = sc ? sc->getValue() : NULL;
356             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
357                 FatalProfileException ex("SAML response contained an error.");
358                 annotateException(&ex, role, status);   // throws it
359             }
360         }
361     }
362
363     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
364     if (r1) {
365         const saml1p::Status* status = r1->getStatus();
366         if (status) {
367             const saml1p::StatusCode* sc = status->getStatusCode();
368             const xmltooling::QName* code = sc ? sc->getValue() : NULL;
369             if (code && *code != saml1p::StatusCode::SUCCESS) {
370                 FatalProfileException ex("SAML response contained an error.");
371                 ex.addProperty("statusCode", code->toString().c_str());
372                 if (sc->getStatusCode()) {
373                     code = sc->getStatusCode()->getValue();
374                     if (code)
375                         ex.addProperty("statusCode2", code->toString().c_str());
376                 }
377                 if (status->getStatusMessage()) {
378                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
379                     if (msg.get() && *msg.get())
380                         ex.addProperty("statusMessage", msg.get());
381                 }
382                 ex.raise();
383             }
384         }
385     }
386 }
387
388 void AbstractHandler::fillStatus(saml2p::StatusResponseType& response, const XMLCh* code, const XMLCh* subcode, const char* msg) const
389 {
390     saml2p::Status* status = saml2p::StatusBuilder::buildStatus();
391     saml2p::StatusCode* scode = saml2p::StatusCodeBuilder::buildStatusCode();
392     status->setStatusCode(scode);
393     scode->setValue(code);
394     if (subcode) {
395         saml2p::StatusCode* ssubcode = saml2p::StatusCodeBuilder::buildStatusCode();
396         scode->setStatusCode(ssubcode);
397         ssubcode->setValue(subcode);
398     }
399     if (msg) {
400         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
401         auto_ptr_XMLCh widemsg((flag.first && flag.second) ? msg : "Error processing request.");
402         saml2p::StatusMessage* sm = saml2p::StatusMessageBuilder::buildStatusMessage();
403         status->setStatusMessage(sm);
404         sm->setMessage(widemsg.get());
405     }
406     response.setStatus(status);
407 }
408
409 long AbstractHandler::sendMessage(
410     const MessageEncoder& encoder,
411     XMLObject* msg,
412     const char* relayState,
413     const char* destination,
414     const saml2md::RoleDescriptor* role,
415     const Application& application,
416     HTTPResponse& httpResponse,
417     bool signIfPossible
418     ) const
419 {
420     const EntityDescriptor* entity = role ? dynamic_cast<const EntityDescriptor*>(role->getParent()) : NULL;
421     const PropertySet* relyingParty = application.getRelyingParty(entity);
422     pair<bool,const char*> flag = signIfPossible ? make_pair(true,(const char*)"true") : relyingParty->getString("signing");
423     if (role && flag.first &&
424         (!strcmp(flag.second, "true") ||
425             (encoder.isUserAgentPresent() && !strcmp(flag.second, "front")) ||
426             (!encoder.isUserAgentPresent() && !strcmp(flag.second, "back")))) {
427         CredentialResolver* credResolver=application.getCredentialResolver();
428         if (credResolver) {
429             Locker credLocker(credResolver);
430             const Credential* cred = NULL;
431             pair<bool,const char*> keyName = relyingParty->getString("keyName");
432             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signingAlg");
433             if (role) {
434                 MetadataCredentialCriteria mcc(*role);
435                 mcc.setUsage(Credential::SIGNING_CREDENTIAL);
436                 if (keyName.first)
437                     mcc.getKeyNames().insert(keyName.second);
438                 if (sigalg.first)
439                     mcc.setXMLAlgorithm(sigalg.second);
440                 cred = credResolver->resolve(&mcc);
441             }
442             else {
443                 CredentialCriteria cc;
444                 cc.setUsage(Credential::SIGNING_CREDENTIAL);
445                 if (keyName.first)
446                     cc.getKeyNames().insert(keyName.second);
447                 if (sigalg.first)
448                     cc.setXMLAlgorithm(sigalg.second);
449                 cred = credResolver->resolve(&cc);
450             }
451             if (cred) {
452                 // Signed request.
453                 return encoder.encode(
454                     httpResponse,
455                     msg,
456                     destination,
457                     entity,
458                     relayState,
459                     &application,
460                     cred,
461                     sigalg.second,
462                     relyingParty->getXMLString("digestAlg").second
463                     );
464             }
465             else {
466                 m_log.warn("no signing credential resolved, leaving message unsigned");
467             }
468         }
469         else {
470             m_log.warn("no credential resolver installed, leaving message unsigned");
471         }
472     }
473
474     // Unsigned request.
475     return encoder.encode(httpResponse, msg, destination, entity, relayState, &application);
476 }
477
478 #endif
479
480 void AbstractHandler::preservePostData(
481     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
482     ) const
483 {
484 #ifdef HAVE_STRCASECMP
485     if (strcasecmp(request.getMethod(), "POST")) return;
486 #else
487     if (stricmp(request.getMethod(), "POST")) return;
488 #endif
489
490     // No specs mean no save.
491     const PropertySet* props=application.getPropertySet("Sessions");
492     pair<bool,const char*> mech = props->getString("postData");
493     if (!mech.first) {
494         m_log.info("postData property not supplied, form data will not be preserved across SSO");
495         return;
496     }
497
498     DDF postData = getPostData(application, request);
499     if (postData.isnull())
500         return;
501
502     if (strstr(mech.second,"ss:") == mech.second) {
503         mech.second+=3;
504         if (!*mech.second) {
505             postData.destroy();
506             throw ConfigurationException("Unsupported postData mechanism ($1).", params(1, mech.second - 3));
507         }
508
509         string postkey;
510         if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
511             DDFJanitor postjan(postData);
512 #ifndef SHIBSP_LITE
513             StorageService* storage = application.getServiceProvider().getStorageService(mech.second);
514             if (storage) {
515                 // Use a random key
516                 string rsKey;
517                 SAMLConfig::getConfig().generateRandomBytes(rsKey,20);
518                 rsKey = SAMLArtifact::toHex(rsKey);
519                 ostringstream out;
520                 out << postData;
521                 if (!storage->createString("PostData", rsKey.c_str(), out.str().c_str(), time(NULL) + 600))
522                     throw IOException("Attempted to insert duplicate storage key.");
523                 postkey = string(mech.second-3) + ':' + rsKey;
524             }
525             else {
526                 m_log.error("storage-backed PostData mechanism with invalid StorageService ID (%s)", mech.second);
527             }
528 #endif
529         }
530         else if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
531             DDF out,in = DDF("set::PostData").structure();
532             DDFJanitor jin(in),jout(out);
533             in.addmember("id").string(mech.second);
534             in.add(postData);
535             out = application.getServiceProvider().getListenerService()->send(in);
536             if (!out.isstring())
537                 throw IOException("StorageService-backed PostData mechanism did not return a state key.");
538             postkey = string(mech.second-3) + ':' + out.string();
539         }
540
541         // Set a cookie with key info.
542         pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
543         postkey += shib_cookie.second;
544         response.setCookie(shib_cookie.first.c_str(), postkey.c_str());
545     }
546     else {
547         postData.destroy();
548         throw ConfigurationException("Unsupported postData mechanism ($1).", params(1,mech.second));
549     }
550 }
551
552 DDF AbstractHandler::recoverPostData(
553     const Application& application, const HTTPRequest& request, HTTPResponse& response, const char* relayState
554     ) const
555 {
556     // First we need the post recovery cookie.
557     pair<string,const char*> shib_cookie = getPostCookieNameProps(application, relayState);
558     const char* cookie = request.getCookie(shib_cookie.first.c_str());
559     if (!cookie || !*cookie)
560         return DDF();
561
562     // Clear the cookie.
563     string exp(shib_cookie.second);
564     exp += "; expires=Mon, 01 Jan 2001 00:00:00 GMT";
565     response.setCookie(shib_cookie.first.c_str(), exp.c_str());
566
567     // Look for StorageService-backed state of the form "ss:SSID:key".
568     const char* state = cookie;
569     if (strstr(state, "ss:") == state) {
570         state += 3;
571         const char* key = strchr(state, ':');
572         if (key) {
573             string ssid = string(cookie).substr(3, key - state);
574             key++;
575             if (!ssid.empty() && *key) {
576                 SPConfig& conf = SPConfig::getConfig();
577                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
578 #ifndef SHIBSP_LITE
579                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
580                     if (storage) {
581                         if (storage->readString("PostData", key, &ssid) > 0) {
582                             storage->deleteString("PostData", key);
583                             istringstream inret(ssid);
584                             DDF ret;
585                             inret >> ret;
586                             return ret;
587                         }
588                         else {
589                             m_log.error("failed to recover form post data using key (%s)", key);
590                         }
591                     }
592                     else {
593                         m_log.error("storage-backed PostData with invalid StorageService ID (%s)", ssid.c_str());
594                     }
595 #endif
596                 }
597                 else if (conf.isEnabled(SPConfig::InProcess)) {
598                     DDF in = DDF("get::PostData").structure();
599                     DDFJanitor jin(in);
600                     in.addmember("id").string(ssid.c_str());
601                     in.addmember("key").string(key);
602                     DDF out = application.getServiceProvider().getListenerService()->send(in);
603                     if (out.islist())
604                         return out;
605                     out.destroy();
606                     m_log.error("storageService-backed PostData mechanism did not return preserved data.");
607                 }
608             }
609         }
610     }
611     return DDF();
612 }
613
614 long AbstractHandler::sendPostResponse(
615     const Application& application, HTTPResponse& httpResponse, const char* url, DDF& postData
616     ) const
617 {
618     HTTPResponse::sanitizeURL(url);
619
620     const PropertySet* props=application.getPropertySet("Sessions");
621     pair<bool,const char*> postTemplate = props->getString("postTemplate");
622     if (!postTemplate.first)
623         throw ConfigurationException("Missing postTemplate property, unable to recreate form post.");
624
625     string fname(postTemplate.second);
626     ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
627     if (!infile)
628         throw ConfigurationException("Unable to access HTML template ($1).", params(1, fname.c_str()));
629     TemplateParameters respParam;
630     respParam.m_map["action"] = url;
631
632     // Load the parameters into objects for the template.
633     multimap<string,string>& collection = respParam.m_collectionMap["PostedData"];
634     DDF param = postData.first();
635     while (!param.isnull()) {
636         collection.insert(pair<const string,string>(param.name(), (param.string() ? param.string() : "")));
637         param = postData.next();
638     }
639
640     stringstream str;
641     XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, respParam);
642
643     pair<bool,bool> postExpire = props->getBool("postExpire");
644
645     httpResponse.setContentType("text/html");
646     if (!postExpire.first || postExpire.second) {
647         httpResponse.setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
648         httpResponse.setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
649         httpResponse.setResponseHeader("Pragma", "no-cache");
650     }
651     return httpResponse.sendResponse(str);
652 }
653
654 pair<string,const char*> AbstractHandler::getPostCookieNameProps(const Application& app, const char* relayState) const
655 {
656     // Decorates the name of the cookie with the relay state key, if any.
657     // Doing so gives a better assurance that the recovered data really
658     // belongs to the relayed request.
659     pair<string,const char*> shib_cookie=app.getCookieNameProps("_shibpost_");
660     if (strstr(relayState, "cookie:") == relayState) {
661         shib_cookie.first = string("_shibpost_") + (relayState + 7);
662     }
663     else if (strstr(relayState, "ss:") == relayState) {
664         const char* pch = strchr(relayState + 3, ':');
665         if (pch)
666             shib_cookie.first = string("_shibpost_") + (pch + 1);
667     }
668     return shib_cookie;
669 }
670
671 DDF AbstractHandler::getPostData(const Application& application, const HTTPRequest& request) const
672 {
673     string contentType = request.getContentType();
674     if (contentType.compare("application/x-www-form-urlencoded") == 0) {
675         const PropertySet* props=application.getPropertySet("Sessions");
676         pair<bool,unsigned int> plimit = props->getUnsignedInt("postLimit");
677         if (!plimit.first)
678             plimit.second = 1024 * 1024;
679         if (plimit.second == 0 || request.getContentLength() <= plimit.second) {
680             CGIParser cgi(request);
681             pair<CGIParser::walker,CGIParser::walker> params = cgi.getParameters(NULL);
682             if (params.first == params.second)
683                 return DDF("parameters").list();
684             DDF child;
685             DDF ret = DDF("parameters").list();
686             for (; params.first != params.second; ++params.first) {
687                 if (!params.first->first.empty()) {
688                     child = DDF(params.first->first.c_str()).unsafe_string(params.first->second);
689                     ret.add(child);
690                 }
691             }
692             return ret;
693         }
694         else {
695             m_log.warn("POST limit exceeded, ignoring %d bytes of posted data", request.getContentLength());
696         }
697     }
698     else {
699         m_log.info("ignoring POST data with non-standard encoding (%s)", contentType.c_str());
700     }
701     return DDF();
702 }
703
704 pair<bool,bool> AbstractHandler::getBool(const char* name, const SPRequest& request, unsigned int type) const
705 {
706     if (type & HANDLER_PROPERTY_REQUEST) {
707         const char* param = request.getParameter(name);
708         if (param && *param)
709             return make_pair(true, (*param=='t' || *param=='1'));
710     }
711     
712     if (type & HANDLER_PROPERTY_MAP) {
713         pair<bool,bool> ret = request.getRequestSettings().first->getBool(name);
714         if (ret.first)
715             return ret;
716     }
717
718     if (type & HANDLER_PROPERTY_FIXED) {
719         return getBool(name);
720     }
721
722     return make_pair(false,false);
723 }
724
725 pair<bool,const char*> AbstractHandler::getString(const char* name, const SPRequest& request, unsigned int type) const
726 {
727     if (type & HANDLER_PROPERTY_REQUEST) {
728         const char* param = request.getParameter(name);
729         if (param && *param)
730             return make_pair(true, param);
731     }
732     
733     if (type & HANDLER_PROPERTY_MAP) {
734         pair<bool,const char*> ret = request.getRequestSettings().first->getString(name);
735         if (ret.first)
736             return ret;
737     }
738
739     if (type & HANDLER_PROPERTY_FIXED) {
740         return getString(name);
741     }
742
743     return pair<bool,const char*>(false,NULL);
744 }
745
746 pair<bool,unsigned int> AbstractHandler::getUnsignedInt(const char* name, const SPRequest& request, unsigned int type) const
747 {
748     if (type & HANDLER_PROPERTY_REQUEST) {
749         const char* param = request.getParameter(name);
750         if (param && *param)
751             return pair<bool,unsigned int>(true, strtol(param,NULL,10));
752     }
753     
754     if (type & HANDLER_PROPERTY_MAP) {
755         pair<bool,unsigned int> ret = request.getRequestSettings().first->getUnsignedInt(name);
756         if (ret.first)
757             return ret;
758     }
759
760     if (type & HANDLER_PROPERTY_FIXED) {
761         return getUnsignedInt(name);
762     }
763
764     return pair<bool,unsigned int>(false,0);
765 }
766
767 pair<bool,int> AbstractHandler::getInt(const char* name, const SPRequest& request, unsigned int type) const
768 {
769     if (type & HANDLER_PROPERTY_REQUEST) {
770         const char* param = request.getParameter(name);
771         if (param && *param)
772             return pair<bool,int>(true, atoi(param));
773     }
774     
775     if (type & HANDLER_PROPERTY_MAP) {
776         pair<bool,int> ret = request.getRequestSettings().first->getInt(name);
777         if (ret.first)
778             return ret;
779     }
780
781     if (type & HANDLER_PROPERTY_FIXED) {
782         return getInt(name);
783     }
784
785     return pair<bool,int>(false,0);
786 }