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