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