Fix for SSPCPP-84.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2SessionInitiator.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  * SAML2SessionInitiator.cpp
19  * 
20  * SAML 2.0 AuthnRequest support.
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/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
32
33 #ifndef SHIBSP_LITE
34 # include <saml/SAMLConfig.h>
35 # include <saml/saml2/core/Protocols.h>
36 # include <saml/saml2/metadata/EndpointManager.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39 using namespace opensaml::saml2;
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 #else
43 #include <xercesc/util/XMLUniDefs.hpp>
44 #endif
45
46 using namespace shibsp;
47 using namespace opensaml;
48 using namespace xmltooling;
49 using namespace std;
50
51 namespace shibsp {
52
53 #if defined (_MSC_VER)
54     #pragma warning( push )
55     #pragma warning( disable : 4250 )
56 #endif
57
58     class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
59     {
60     public:
61         SAML2SessionInitiator(const DOMElement* e, const char* appId);
62         virtual ~SAML2SessionInitiator() {
63 #ifndef SHIBSP_LITE
64             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
65                 XMLString::release(&m_outgoing);
66                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
67                 delete m_requestTemplate;
68             }
69 #endif
70         }
71         
72         void setParent(const PropertySet* parent);
73         void receive(DDF& in, ostream& out);
74         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
75
76     private:
77         pair<bool,long> doRequest(
78             const Application& application,
79             HTTPResponse& httpResponse,
80             const char* entityID,
81             const XMLCh* acsIndex,
82             const char* acsLocation,
83             const XMLCh* acsBinding,
84             bool isPassive,
85             bool forceAuthn,
86             const char* authnContextClassRef,
87             const char* authnContextComparison,
88             string& relayState
89             ) const;
90
91         string m_appId;
92         auto_ptr_char m_paosNS,m_ecpNS;
93         auto_ptr_XMLCh m_paosBinding;
94 #ifndef SHIBSP_LITE
95         XMLCh* m_outgoing;
96         vector<const XMLCh*> m_bindings;
97         map<const XMLCh*,MessageEncoder*> m_encoders;
98         MessageEncoder* m_ecp;
99         AuthnRequest* m_requestTemplate;
100 #else
101         bool m_ecp;
102 #endif
103     };
104
105 #if defined (_MSC_VER)
106     #pragma warning( pop )
107 #endif
108
109     SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
110     {
111         return new SAML2SessionInitiator(p.first, p.second);
112     }
113
114 };
115
116 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
117     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId),
118         m_paosNS(samlconstants::PAOS_NS), m_ecpNS(samlconstants::SAML20ECP_NS), m_paosBinding(samlconstants::SAML20_BINDING_PAOS)
119 {
120     static const XMLCh ECP[] = UNICODE_LITERAL_3(E,C,P);
121     const XMLCh* flag = e ? e->getAttributeNS(NULL,ECP) : NULL;
122 #ifdef SHIBSP_LITE
123     m_ecp = (flag && (*flag == chLatin_t || *flag == chDigit_1));
124 #else
125     m_outgoing=NULL;
126     m_ecp = NULL;
127     m_requestTemplate=NULL;
128
129     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
130         // Check for a template AuthnRequest to build from.
131         DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
132         if (child)
133             m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
134
135         // If directed, build an ECP encoder.
136         if (flag && (*flag == chLatin_t || *flag == chDigit_1)) {
137             try {
138                 m_ecp = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
139                     samlconstants::SAML20_BINDING_PAOS, pair<const DOMElement*,const XMLCh*>(e,NULL)
140                     );
141             }
142             catch (exception& ex) {
143                 m_log.error("error building PAOS/ECP MessageEncoder: %s", ex.what());
144             }
145         }
146
147         // Handle outgoing binding setup.
148         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
149         if (outgoing.first) {
150             m_outgoing = XMLString::replicate(outgoing.second);
151             XMLString::trim(m_outgoing);
152         }
153         else {
154             // No override, so we'll install a default binding precedence.
155             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
156                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
157             m_outgoing = XMLString::transcode(prec.c_str());
158         }
159
160         int pos;
161         XMLCh* start = m_outgoing;
162         while (start && *start) {
163             pos = XMLString::indexOf(start,chSpace);
164             if (pos != -1)
165                 *(start + pos)=chNull;
166             m_bindings.push_back(start);
167             try {
168                 auto_ptr_char b(start);
169                 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
170                     b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
171                     );
172                 m_encoders[start] = encoder;
173                 m_log.debug("supporting outgoing binding (%s)", b.get());
174             }
175             catch (exception& ex) {
176                 m_log.error("error building MessageEncoder: %s", ex.what());
177             }
178             if (pos != -1)
179                 start = start + pos + 1;
180             else
181                 break;
182         }
183     }
184 #endif
185
186     // If Location isn't set, defer address registration until the setParent call.
187     pair<bool,const char*> loc = getString("Location");
188     if (loc.first) {
189         string address = m_appId + loc.second + "::run::SAML2SI";
190         setAddress(address.c_str());
191     }
192 }
193
194 void SAML2SessionInitiator::setParent(const PropertySet* parent)
195 {
196     DOMPropertySet::setParent(parent);
197     pair<bool,const char*> loc = getString("Location");
198     if (loc.first) {
199         string address = m_appId + loc.second + "::run::SAML2SI";
200         setAddress(address.c_str());
201     }
202     else {
203         m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
204     }
205 }
206
207 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
208 {
209     // First check for ECP support, since that doesn't require an IdP to be known.
210     bool ECP = false;
211     if (m_ecp && request.getHeader("Accept").find("application/vnd.paos+xml") != string::npos) {
212         string PAOS = request.getHeader("PAOS");
213         if (PAOS.find(m_paosNS.get()) != string::npos && PAOS.find(m_ecpNS.get()) != string::npos)
214             ECP = true;
215     }
216
217     // We have to know the IdP to function unless this is ECP.
218     if (!ECP && (entityID.empty()))
219         return make_pair(false,0L);
220
221     string target;
222     const Handler* ACS=NULL;
223     const char* option;
224     pair<bool,const char*> acClass;
225     pair<bool,const char*> acComp;
226     bool isPassive=false,forceAuthn=false;
227     const Application& app=request.getApplication();
228
229     // ECP means the ACS will be by value no matter what.
230     pair<bool,bool> acsByIndex = ECP ? make_pair(true,false) : getBool("acsByIndex");
231
232     if (isHandler) {
233         option=request.getParameter("acsIndex");
234         if (option) {
235             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
236             if (!ACS)
237                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
238             else if (ECP && !XMLString::equals(ACS->getString("Binding").second, samlconstants::SAML20_BINDING_PAOS)) {
239                 request.log(SPRequest::SPWarn, "acsIndex in request referenced a non-PAOS ACS, using default ACS location");
240                 ACS = NULL;
241             }
242         }
243
244         option = request.getParameter("target");
245         if (option) {
246             target = option;
247             // Always need to recover target URL to compute handler below.
248             recoverRelayState(request.getApplication(), request, request, target, false);
249         }
250
251         pair<bool,bool> flag;
252         option = request.getParameter("isPassive");
253         if (option) {
254             isPassive = (*option=='1' || *option=='t');
255         }
256         else {
257             flag = getBool("isPassive");
258             isPassive = (flag.first && flag.second);
259         }
260         if (!isPassive) {
261             option = request.getParameter("forceAuthn");
262             if (option) {
263                 forceAuthn = (*option=='1' || *option=='t');
264             }
265             else {
266                 flag = getBool("forceAuthn");
267                 forceAuthn = (flag.first && flag.second);
268             }
269         }
270
271         if (acClass.second = request.getParameter("authnContextClassRef"))
272             acClass.first = true;
273         else
274             acClass = getString("authnContextClassRef");
275
276         if (acComp.second = request.getParameter("authnContextComparison"))
277             acComp.first = true;
278         else
279             acComp = getString("authnContextComparison");
280     }
281     else {
282         // We're running as a "virtual handler" from within the filter.
283         // The target resource is the current one and everything else is defaulted.
284         target=request.getRequestURL();
285         const PropertySet* settings = request.getRequestSettings().first;
286
287         pair<bool,bool> flag = settings->getBool("isPassive");
288         if (!flag.first)
289             flag = getBool("isPassive");
290         isPassive = flag.first && flag.second;
291         if (!isPassive) {
292             flag = settings->getBool("forceAuthn");
293             if (!flag.first)
294                 flag = getBool("forceAuthn");
295             forceAuthn = flag.first && flag.second;
296         }
297
298         acClass = settings->getString("authnContextClassRef");
299         if (!acClass.first)
300             acClass = getString("authnContextClassRef");
301         acComp = settings->getString("authnContextComparison");
302         if (!acComp.first)
303             acComp = getString("authnContextComparison");
304     }
305
306     if (ECP)
307         m_log.debug("attempting to initiate session using SAML 2.0 Enhanced Client Profile");
308     else
309         m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID.c_str());
310
311     if (!ACS) {
312         if (ECP) {
313             const vector<const Handler*>& handlers = app.getAssertionConsumerServicesByBinding(m_paosBinding.get());
314             if (handlers.empty())
315                 throw ConfigurationException("Unable to locate PAOS response endpoint.");
316             ACS = handlers.front();
317         }
318         else {
319             pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
320             if (index.first) {
321                 ACS = app.getAssertionConsumerServiceByIndex(index.second);
322                 if (!ACS)
323                     request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
324             }
325             if (!ACS)
326                 ACS = app.getDefaultAssertionConsumerService();
327         }
328     }
329
330     // To invoke the request builder, the key requirement is to figure out how
331     // to express the ACS, by index or value, and if by value, where.
332     // We have to compute the handlerURL no matter what, because we may need to
333     // flip the index to an SSL-version.
334     string ACSloc=request.getHandlerURL(target.c_str());
335     
336     SPConfig& conf = SPConfig::getConfig();
337     if (conf.isEnabled(SPConfig::OutOfProcess)) {
338         if (!acsByIndex.first || acsByIndex.second) {
339             // Pass by Index.
340             if (isHandler) {
341                 // We may already have RelayState set if we looped back here,
342                 // but just in case target is a resource, we reset it back.
343                 target.erase();
344                 option = request.getParameter("target");
345                 if (option)
346                     target = option;
347             }
348             
349             // Determine index to use.
350             pair<bool,const XMLCh*> ix = pair<bool,const XMLCh*>(false,NULL);
351             if (ACS) {
352                 if (!strncmp(ACSloc.c_str(), "https", 5)) {
353                         ix = ACS->getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
354                         if (!ix.first)
355                                 ix = ACS->getXMLString("index");
356                 }
357                 else {
358                         ix = ACS->getXMLString("index");
359                 }
360             }
361             
362             return doRequest(
363                 app, request, entityID.c_str(),
364                 ix.second, NULL, NULL,
365                 isPassive, forceAuthn,
366                 acClass.first ? acClass.second : NULL,
367                 acComp.first ? acComp.second : NULL,
368                 target
369                 );
370         }
371
372         // Since we're not passing by index, we need to fully compute the return URL and binding.
373         // Compute the ACS URL. We add the ACS location to the base handlerURL.
374         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
375         if (loc.first) ACSloc+=loc.second;
376
377         if (isHandler) {
378             // We may already have RelayState set if we looped back here,
379             // but just in case target is a resource, we reset it back.
380             target.erase();
381             option = request.getParameter("target");
382             if (option)
383                 target = option;
384         }
385
386         return doRequest(
387             app, request, entityID.c_str(),
388             NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
389             isPassive, forceAuthn,
390             acClass.first ? acClass.second : NULL,
391             acComp.first ? acComp.second : NULL,
392             target
393             );
394     }
395
396     // Remote the call.
397     DDF out,in = DDF(m_address.c_str()).structure();
398     DDFJanitor jin(in), jout(out);
399     in.addmember("application_id").string(app.getId());
400     if (!entityID.empty())
401         in.addmember("entity_id").string(entityID.c_str());
402     if (isPassive)
403         in.addmember("isPassive").integer(1);
404     else if (forceAuthn)
405         in.addmember("forceAuthn").integer(1);
406     if (acClass.first)
407         in.addmember("authnContextClassRef").string(acClass.second);
408     if (acComp.first)
409         in.addmember("authnContextComparison").string(acComp.second);
410     if (!acsByIndex.first || acsByIndex.second) {
411         if (ACS) {
412             // Determine index to use.
413             pair<bool,const char*> ix = pair<bool,const char*>(false,NULL);
414                 if (!strncmp(ACSloc.c_str(), "https", 5)) {
415                         ix = ACS->getString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
416                         if (!ix.first)
417                                 ix = ACS->getString("index");
418                 }
419                 else {
420                         ix = ACS->getString("index");
421                 }
422             in.addmember("acsIndex").string(ix.second);
423         }
424     }
425     else {
426         // Since we're not passing by index, we need to fully compute the return URL and binding.
427         // Compute the ACS URL. We add the ACS location to the base handlerURL.
428         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
429         if (loc.first) ACSloc+=loc.second;
430         in.addmember("acsLocation").string(ACSloc.c_str());
431         if (ACS)
432             in.addmember("acsBinding").string(ACS->getString("Binding").second);
433     }
434
435     if (isHandler) {
436         // We may already have RelayState set if we looped back here,
437         // but just in case target is a resource, we reset it back.
438         target.erase();
439         option = request.getParameter("target");
440         if (option)
441             target = option;
442     }
443     if (!target.empty())
444         in.addmember("RelayState").string(target.c_str());
445
446     // Remote the processing.
447     out = request.getServiceProvider().getListenerService()->send(in);
448     return unwrap(request, out);
449 }
450
451 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
452 {
453     // Find application.
454     const char* aid=in["application_id"].string();
455     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
456     if (!app) {
457         // Something's horribly wrong.
458         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
459         throw ConfigurationException("Unable to locate application for new session, deleted?");
460     }
461
462     DDF ret(NULL);
463     DDFJanitor jout(ret);
464
465     // Wrap the outgoing object with a Response facade.
466     auto_ptr<HTTPResponse> http(getResponse(ret));
467
468     auto_ptr_XMLCh index(in["acsIndex"].string());
469     auto_ptr_XMLCh bind(in["acsBinding"].string());
470
471     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
472
473     // Since we're remoted, the result should either be a throw, which we pass on,
474     // a false/0 return, which we just return as an empty structure, or a response/redirect,
475     // which we capture in the facade and send back.
476     doRequest(
477         *app, *http.get(), in["entity_id"].string(),
478         index.get(), in["acsLocation"].string(), bind.get(),
479         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
480         in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
481         relayState
482         );
483     out << ret;
484 }
485
486 #ifndef SHIBSP_LITE
487 namespace {
488     class _sameIdP : public binary_function<const IDPEntry*, const XMLCh*, bool>
489     {
490     public:
491         bool operator()(const IDPEntry* entry, const XMLCh* entityID) const {
492             return entry ? XMLString::equals(entry->getProviderID(), entityID) : false;
493         }
494     };
495 };
496 #endif
497
498 pair<bool,long> SAML2SessionInitiator::doRequest(
499     const Application& app,
500     HTTPResponse& httpResponse,
501     const char* entityID,
502     const XMLCh* acsIndex,
503     const char* acsLocation,
504     const XMLCh* acsBinding,
505     bool isPassive,
506     bool forceAuthn,
507     const char* authnContextClassRef,
508     const char* authnContextComparison,
509     string& relayState
510     ) const
511 {
512 #ifndef SHIBSP_LITE
513     bool ECP = XMLString::equals(acsBinding, m_paosBinding.get());
514
515     pair<const EntityDescriptor*,const RoleDescriptor*> entity = pair<const EntityDescriptor*,const RoleDescriptor*>(NULL,NULL);
516     const IDPSSODescriptor* role = NULL;
517     const EndpointType* ep = NULL;
518     const MessageEncoder* encoder = NULL;
519
520     // We won't need this for ECP, but safety dictates we get the lock here.
521     MetadataProvider* m=app.getMetadataProvider();
522     Locker locker(m);
523     
524     if (ECP) {
525         encoder = m_ecp;
526         if (!encoder) {
527             m_log.error("MessageEncoder for PAOS binding not available");
528             return make_pair(false,0L);
529         }
530     }
531     else {
532         // Use metadata to locate the IdP's SSO service.
533         MetadataProvider::Criteria mc(entityID, &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
534         entity=m->getEntityDescriptor(mc);
535         if (!entity.first) {
536             m_log.warn("unable to locate metadata for provider (%s)", entityID);
537             throw MetadataException("Unable to locate metadata for identity provider ($entityID)", namedparams(1, "entityID", entityID));
538         }
539         else if (!entity.second) {
540             m_log.warn("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
541             if (getParent())
542                 return make_pair(false,0L);
543             throw MetadataException("Unable to locate SAML 2.0 identity provider role for provider ($entityID)", namedparams(1, "entityID", entityID));
544         }
545
546         // Loop over the supportable outgoing bindings.
547         role = dynamic_cast<const IDPSSODescriptor*>(entity.second);
548         vector<const XMLCh*>::const_iterator b;
549         for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
550             if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
551                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
552                 if (enc!=m_encoders.end())
553                     encoder = enc->second;
554                 break;
555             }
556         }
557         if (!ep || !encoder) {
558             m_log.warn("unable to locate compatible SSO service for provider (%s)", entityID);
559             if (getParent())
560                 return make_pair(false,0L);
561             throw MetadataException("Unable to locate compatible SSO service for provider ($entityID)", namedparams(1, "entityID", entityID));
562         }
563     }
564
565     preserveRelayState(app, httpResponse, relayState);
566
567     auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
568     if (m_requestTemplate) {
569         // Freshen TS and ID.
570         req->setID(NULL);
571         req->setIssueInstant(time(NULL));
572     }
573
574     if (ep)
575         req->setDestination(ep->getLocation());
576     if (acsIndex && *acsIndex)
577         req->setAssertionConsumerServiceIndex(acsIndex);
578     if (acsLocation) {
579         auto_ptr_XMLCh wideloc(acsLocation);
580         req->setAssertionConsumerServiceURL(wideloc.get());
581     }
582     if (acsBinding && *acsBinding)
583         req->setProtocolBinding(acsBinding);
584     if (isPassive)
585         req->IsPassive(isPassive);
586     else if (forceAuthn)
587         req->ForceAuthn(forceAuthn);
588     if (!req->getIssuer()) {
589         Issuer* issuer = IssuerBuilder::buildIssuer();
590         req->setIssuer(issuer);
591         issuer->setName(app.getRelyingParty(entity.first)->getXMLString("entityID").second);
592     }
593     if (!req->getNameIDPolicy()) {
594         NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
595         req->setNameIDPolicy(namepol);
596         namepol->AllowCreate(true);
597     }
598     if (authnContextClassRef || authnContextComparison) {
599         RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
600         if (!reqContext) {
601             reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
602             req->setRequestedAuthnContext(reqContext);
603         }
604         if (authnContextClassRef) {
605             reqContext->getAuthnContextDeclRefs().clear();
606             auto_ptr_XMLCh wideclass(authnContextClassRef);
607             AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
608             cref->setReference(wideclass.get());
609             reqContext->getAuthnContextClassRefs().push_back(cref);
610         }
611         if (authnContextComparison &&
612                 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
613             auto_ptr_XMLCh widecomp(authnContextComparison);
614             reqContext->setComparison(widecomp.get());
615         }
616     }
617
618     if (ECP && entityID) {
619         auto_ptr_XMLCh wideid(entityID);
620         Scoping* scoping = req->getScoping();
621         if (!scoping) {
622             scoping = ScopingBuilder::buildScoping();
623             req->setScoping(scoping);
624         }
625         IDPList* idplist = scoping->getIDPList();
626         if (!idplist) {
627             idplist = IDPListBuilder::buildIDPList();
628             scoping->setIDPList(idplist);
629         }
630         VectorOf(IDPEntry) entries = idplist->getIDPEntrys();
631         if (find_if(entries, bind2nd(_sameIdP(), wideid.get())) == NULL) {
632             IDPEntry* entry = IDPEntryBuilder::buildIDPEntry();
633             entry->setProviderID(wideid.get());
634             entries.push_back(entry);
635         }
636     }
637
638     auto_ptr_char dest(ep ? ep->getLocation() : NULL);
639
640     long ret = sendMessage(
641         *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role ? role->WantAuthnRequestsSigned() : false
642         );
643     req.release();  // freed by encoder
644     return make_pair(true,ret);
645 #else
646     return make_pair(false,0L);
647 #endif
648 }