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