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