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