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