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