Better error handling when session initiator abstains
[shibboleth/sp.git] / shibsp / ServiceProvider.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * ServiceProvider.cpp
23  *
24  * Interface to a Shibboleth ServiceProvider instance.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "AccessControl.h"
30 #include "Application.h"
31 #include "ServiceProvider.h"
32 #include "SessionCache.h"
33 #include "SPRequest.h"
34 #include "attribute/Attribute.h"
35 #include "handler/SessionInitiator.h"
36 #include "util/TemplateParameters.h"
37
38 #include <fstream>
39 #include <sstream>
40 #include <boost/algorithm/string.hpp>
41 #ifndef SHIBSP_LITE
42 # include <saml/exceptions.h>
43 # include <saml/saml2/metadata/MetadataProvider.h>
44 #endif
45 #include <xmltooling/XMLToolingConfig.h>
46 #include <xmltooling/util/NDC.h>
47 #include <xmltooling/util/PathResolver.h>
48 #include <xmltooling/util/URLEncoder.h>
49 #include <xmltooling/util/XMLHelper.h>
50
51 using namespace shibsp;
52 using namespace xmltooling::logging;
53 using namespace xmltooling;
54 using namespace std;
55
56 namespace shibsp {
57     SHIBSP_DLLLOCAL PluginManager<ServiceProvider,string,const DOMElement*>::Factory XMLServiceProviderFactory;
58
59     long SHIBSP_DLLLOCAL sendError(
60         Category& log, SPRequest& request, const Application* app, const char* page, TemplateParameters& tp, bool mayRedirect=true
61         )
62     {
63         // The properties we need can be set in the RequestMap, or the Errors element.
64         bool mderror = dynamic_cast<const opensaml::saml2md::MetadataException*>(tp.getRichException())!=nullptr;
65         bool accesserror = (strcmp(page, "access")==0);
66         pair<bool,const char*> redirectErrors = pair<bool,const char*>(false,nullptr);
67         pair<bool,const char*> pathname = pair<bool,const char*>(false,nullptr);
68
69         // Strictly for error handling, detect a nullptr application and point at the default.
70         if (!app)
71             app = request.getServiceProvider().getApplication(nullptr);
72
73         const PropertySet* props=app->getPropertySet("Errors");
74
75         // First look for settings in the request map of the form pageError.
76         try {
77             RequestMapper::Settings settings = request.getRequestSettings();
78             if (mderror)
79                 pathname = settings.first->getString("metadataError");
80             if (!pathname.first) {
81                 string pagename(page);
82                 pagename += "Error";
83                 pathname = settings.first->getString(pagename.c_str());
84             }
85             if (mayRedirect)
86                 redirectErrors = settings.first->getString("redirectErrors");
87         }
88         catch (exception& ex) {
89             log.error(ex.what());
90         }
91
92         // Check for redirection on errors instead of template.
93         if (mayRedirect) {
94             if (!redirectErrors.first && props)
95                 redirectErrors = props->getString("redirectErrors");
96             if (redirectErrors.first) {
97                 string loc(redirectErrors.second);
98                 request.absolutize(loc);
99                 loc = loc + '?' + tp.toQueryString();
100                 return request.sendRedirect(loc.c_str());
101             }
102         }
103
104         request.setContentType("text/html");
105         request.setResponseHeader("Expires","Wed, 01 Jan 1997 12:00:00 GMT");
106         request.setResponseHeader("Cache-Control","private,no-store,no-cache,max-age=0");
107
108         // Nothing in the request map, so check for a property named "page" in the Errors property set.
109         if (!pathname.first && props) {
110             if (mderror)
111                 pathname=props->getString("metadata");
112             if (!pathname.first)
113                 pathname=props->getString(page);
114         }
115
116         // If there's still no template to use, just use pageError.html unless it's an access issue.
117         string fname;
118         if (!pathname.first) {
119             if (!accesserror) {
120                 fname = string(page) + "Error.html";
121                 pathname.second = fname.c_str();
122             }
123         }
124         else {
125             fname = pathname.second;
126         }
127
128         // If we have a template to use, use it.
129         if (!fname.empty()) {
130             ifstream infile(XMLToolingConfig::getConfig().getPathResolver()->resolve(fname, PathResolver::XMLTOOLING_CFG_FILE).c_str());
131             if (infile) {
132                 tp.setPropertySet(props);
133                 stringstream str;
134                 XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
135                 return request.sendError(str);
136             }
137         }
138
139         // If we got here, then either it's an access error or a template failed.
140         if (accesserror) {
141             istringstream msg("Access Denied");
142             return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
143         }
144
145         log.error("sendError could not process error template (%s)", pathname.second);
146         istringstream msg("Internal Server Error. Please contact the site administrator.");
147         return request.sendError(msg);
148     }
149
150     void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
151         const Application& app = request.getApplication();
152         app.clearHeader(request, "Shib-Cookie-Name", "HTTP_SHIB_COOKIE_NAME");
153         app.clearHeader(request, "Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
154         app.clearHeader(request, "Shib-Session-Index", "HTTP_SHIB_SESSION_INDEX");
155         app.clearHeader(request, "Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
156         app.clearHeader(request, "Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
157         app.clearHeader(request, "Shib-Authentication-Instant", "HTTP_SHIB_AUTHENTICATION_INSTANT");
158         app.clearHeader(request, "Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
159         app.clearHeader(request, "Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
160         app.clearHeader(request, "Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
161         app.clearAttributeHeaders(request);
162         request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
163     }
164 };
165
166 void SHIBSP_API shibsp::registerServiceProviders()
167 {
168     SPConfig::getConfig().ServiceProviderManager.registerFactory(XML_SERVICE_PROVIDER, XMLServiceProviderFactory);
169 }
170
171 ServiceProvider::ServiceProvider()
172 {
173     m_authTypes.insert("shibboleth");
174 }
175
176 ServiceProvider::~ServiceProvider()
177 {
178 }
179
180 #ifndef SHIBSP_LITE
181 SecurityPolicyProvider* ServiceProvider::getSecurityPolicyProvider(bool required) const
182 {
183     if (required)
184         throw ConfigurationException("No SecurityPolicyProvider available.");
185     return nullptr;
186 }
187 #endif
188
189 Remoted* ServiceProvider::regListener(const char* address, Remoted* listener)
190 {
191     Remoted* ret = nullptr;
192     map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
193     if (i != m_listenerMap.end())
194         ret = i->second;
195     m_listenerMap[address] = listener;
196     Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("registered remoted message endpoint (%s)",address);
197     return ret;
198 }
199
200 bool ServiceProvider::unregListener(const char* address, Remoted* current, Remoted* restore)
201 {
202     map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
203     if (i != m_listenerMap.end() && i->second == current) {
204         if (restore)
205             m_listenerMap[address] = restore;
206         else
207             m_listenerMap.erase(address);
208         Category::getInstance(SHIBSP_LOGCAT".ServiceProvider").info("unregistered remoted message endpoint (%s)",address);
209         return true;
210     }
211     return false;
212 }
213
214 Remoted* ServiceProvider::lookupListener(const char *address) const
215 {
216     map<string,Remoted*>::const_iterator i = m_listenerMap.find(address);
217     return (i == m_listenerMap.end()) ? nullptr : i->second;
218 }
219
220 pair<bool,long> ServiceProvider::doAuthentication(SPRequest& request, bool handler) const
221 {
222 #ifdef _DEBUG
223     xmltooling::NDC ndc("doAuthentication");
224 #endif
225     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
226
227     const Application* app = nullptr;
228     string targetURL = request.getRequestURL();
229
230     try {
231         RequestMapper::Settings settings = request.getRequestSettings();
232         app = &(request.getApplication());
233
234         // If not SSL, check to see if we should block or redirect it.
235         if (!request.isSecure()) {
236             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
237             if (redirectToSSL.first) {
238 #ifdef HAVE_STRCASECMP
239                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
240 #else
241                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
242 #endif
243                     // Compute the new target URL
244                     string redirectURL = string("https://") + request.getHostname();
245                     if (strcmp(redirectToSSL.second,"443")) {
246                         redirectURL = redirectURL + ':' + redirectToSSL.second;
247                     }
248                     redirectURL += request.getRequestURI();
249                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
250                 }
251                 else {
252                     TemplateParameters tp;
253                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
254                     return make_pair(true, sendError(log, request, app, "ssl", tp, false));
255                 }
256             }
257         }
258
259         const char* handlerURL=request.getHandlerURL(targetURL.c_str());
260         if (!handlerURL)
261             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
262
263         // If the request URL contains the handler base URL for this application, either dispatch
264         // directly (mainly Apache 2.0) or just pass back control.
265         if (boost::contains(targetURL, handlerURL)) {
266             if (handler)
267                 return doHandler(request);
268             else
269                 return make_pair(true, request.returnOK());
270         }
271
272         // These settings dictate how to proceed.
273         pair<bool,const char*> authType = settings.first->getString("authType");
274         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
275         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
276         pair<bool,const char*> requireLogoutWith = settings.first->getString("requireLogoutWith");
277
278         // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
279         // then we ignore this request and consider it unprotected. Apache might lie to us if
280         // ShibBasicHijack is on, but that's up to it.
281         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
282                 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
283             return make_pair(true, request.returnDecline());
284
285         // Fix for secadv 20050901
286         clearHeaders(request);
287
288         Session* session = nullptr;
289         try {
290             session = request.getSession();
291         }
292         catch (exception& e) {
293             log.warn("error during session lookup: %s", e.what());
294             // If it's not a retryable session failure, we throw to the outer handler for reporting.
295             if (dynamic_cast<opensaml::RetryableProfileException*>(&e) == nullptr)
296                 throw;
297         }
298
299         if (session) {
300             // Check for logout interception.
301             if (requireLogoutWith.first) {
302                 // Check for a completion parameter on the query string.
303                 const char* qstr = request.getQueryString();
304                 if (!qstr || !strstr(qstr, "shiblogoutdone=1")) {
305                     // First leg of circuit, so we redirect to the logout endpoint specified with this URL as a return location.
306                     string selfurl = request.getRequestURL();
307                     if (!qstr)
308                         selfurl += '?';
309                     selfurl += "shiblogoutdone=1";
310                     string loc = requireLogoutWith.second;
311                     request.absolutize(loc);
312                     if (loc.find('?') != string::npos)
313                         loc += '&';
314                     else
315                         loc += '?';
316                     loc += "return=" + XMLToolingConfig::getConfig().getURLEncoder()->encode(selfurl.c_str());
317                     return make_pair(true, request.sendRedirect(loc.c_str()));
318                 }
319             }
320         }
321         else {
322             // No session.  Maybe that's acceptable?
323             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
324                 return make_pair(true, request.returnOK());
325
326             // No session, but we require one. Initiate a new session using the indicated method.
327             const SessionInitiator* initiator=nullptr;
328             if (requireSessionWith.first) {
329                 initiator=app->getSessionInitiatorById(requireSessionWith.second);
330                 if (!initiator) {
331                     throw ConfigurationException(
332                         "No session initiator found with id ($1), check requireSessionWith command.", params(1, requireSessionWith.second)
333                         );
334                 }
335             }
336             else {
337                 initiator=app->getDefaultSessionInitiator();
338                 if (!initiator)
339                     throw ConfigurationException("No default session initiator found, check configuration.");
340             }
341
342             // Dispatch to SessionInitiator. This MUST handle the request, or we want to fail here.
343             // Used to fall through into doExport, but this is a cleaner exit path.
344             pair<bool,long> ret = initiator->run(request, false);
345             if (ret.first)
346                 return ret;
347             throw ConfigurationException("Session initiator did not handle request for a new session, check configuration.");
348         }
349
350         request.setAuthType(authType.second);
351
352         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
353         // Let the caller decide how to proceed.
354         log.debug("doAuthentication succeeded");
355         return make_pair(false,0L);
356     }
357     catch (exception& e) {
358         request.log(SPRequest::SPError, e.what());
359         TemplateParameters tp(&e);
360         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
361         return make_pair(true, sendError(log, request, app, "session", tp));
362     }
363 }
364
365 pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
366 {
367 #ifdef _DEBUG
368     xmltooling::NDC ndc("doAuthorization");
369 #endif
370     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
371
372     const Application* app = nullptr;
373     const Session* session = nullptr;
374     string targetURL = request.getRequestURL();
375
376     try {
377         RequestMapper::Settings settings = request.getRequestSettings();
378         app = &(request.getApplication());
379
380         // Three settings dictate how to proceed.
381         pair<bool,const char*> authType = settings.first->getString("authType");
382         pair<bool,bool> requireSession = settings.first->getBool("requireSession");
383         pair<bool,const char*> requireSessionWith = settings.first->getString("requireSessionWith");
384
385         // If no session is required AND the AuthType (an Apache-derived concept) isn't recognized,
386         // then we ignore this request and consider it unprotected. Apache might lie to us if
387         // ShibBasicHijack is on, but that's up to it.
388         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
389                 (!authType.first || m_authTypes.find(boost::to_lower_copy(string(authType.second))) == m_authTypes.end()))
390             return make_pair(true, request.returnDecline());
391
392         // Do we have an access control plugin?
393         if (settings.second) {
394             try {
395                 session = request.getSession(false);
396             }
397             catch (exception& e) {
398                 log.warn("unable to obtain session to pass to access control provider: %s", e.what());
399             }
400
401             Locker acllock(settings.second);
402             switch (settings.second->authorized(request, session)) {
403                 case AccessControl::shib_acl_true:
404                     log.debug("access control provider granted access");
405                     return make_pair(true, request.returnOK());
406
407                 case AccessControl::shib_acl_false:
408                 {
409                     log.warn("access control provider denied access");
410                     TemplateParameters tp(nullptr, nullptr, session);
411                     tp.m_map["requestURL"] = targetURL;
412                     return make_pair(true, sendError(log, request, app, "access", tp, false));
413                 }
414
415                 default:
416                     // Use the "DECLINE" interface to signal we don't know what to do.
417                     return make_pair(true, request.returnDecline());
418             }
419         }
420         else {
421             return make_pair(true, request.returnDecline());
422         }
423     }
424     catch (exception& e) {
425         request.log(SPRequest::SPError, e.what());
426         TemplateParameters tp(&e, nullptr, session);
427         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
428         return make_pair(true, sendError(log, request, app, "access", tp));
429     }
430 }
431
432 pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSession) const
433 {
434 #ifdef _DEBUG
435     xmltooling::NDC ndc("doExport");
436 #endif
437     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
438
439     const Application* app = nullptr;
440     const Session* session = nullptr;
441     string targetURL = request.getRequestURL();
442
443     try {
444         RequestMapper::Settings settings = request.getRequestSettings();
445         app = &(request.getApplication());
446
447         try {
448             session = request.getSession(false);
449         }
450         catch (exception& e) {
451             log.warn("unable to obtain session to export to request: %s", e.what());
452                 // If we have to have a session, then this is a fatal error.
453                 if (requireSession)
454                         throw;
455         }
456
457                 // Still no data?
458         if (!session) {
459                 if (requireSession)
460                 throw opensaml::RetryableProfileException("Unable to obtain session to export to request.");
461                 else
462                         return make_pair(false, 0L);    // just bail silently
463         }
464
465                 pair<bool,const char*> enc = settings.first->getString("encoding");
466                 if (enc.first && strcmp(enc.second, "URL"))
467                         throw ConfigurationException("Unsupported value for 'encoding' content setting ($1).", params(1,enc.second));
468
469         const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
470
471         app->setHeader(request, "Shib-Application-ID", app->getId());
472         app->setHeader(request, "Shib-Session-ID", session->getID());
473
474         // Check for export of "standard" variables.
475         // A 3.0 release would switch this default to false and rely solely on the
476         // Assertion extractor plugin and ship out of the box with the same defaults.
477         pair<bool,bool> stdvars = settings.first->getBool("exportStdVars");
478         if (!stdvars.first || stdvars.second) {
479             const char* hval = session->getEntityID();
480             if (hval)
481                 app->setHeader(request, "Shib-Identity-Provider", hval);
482             hval = session->getAuthnInstant();
483             if (hval)
484                 app->setHeader(request, "Shib-Authentication-Instant", hval);
485             hval = session->getAuthnContextClassRef();
486             if (hval) {
487                 app->setHeader(request, "Shib-Authentication-Method", hval);
488                 app->setHeader(request, "Shib-AuthnContext-Class", hval);
489             }
490             hval = session->getAuthnContextDeclRef();
491             if (hval)
492                 app->setHeader(request, "Shib-AuthnContext-Decl", hval);
493             hval = session->getSessionIndex();
494             if (hval)
495                 app->setHeader(request, "Shib-Session-Index", hval);
496         }
497
498         // Check for export of algorithmically-derived portion of cookie names.
499         stdvars = settings.first->getBool("exportCookie");
500         if (stdvars.first && stdvars.second) {
501             pair<string,const char*> cookieprops = app->getCookieNameProps(nullptr);
502             app->setHeader(request, "Shib-Cookie-Name", cookieprops.first.c_str());
503         }
504
505         // Maybe export the assertion keys.
506         pair<bool,bool> exp = settings.first->getBool("exportAssertion");
507         if (exp.first && exp.second) {
508             const PropertySet* sessions = app->getPropertySet("Sessions");
509             pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,nullptr);
510             if (!exportLocation.first)
511                 log.warn("can't export assertions without an exportLocation Sessions property");
512             else {
513                 string exportName = "Shib-Assertion-00";
514                 string baseURL;
515                 if (!strncmp(exportLocation.second, "http", 4))
516                     baseURL = exportLocation.second;
517                 else
518                     baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
519                 baseURL = baseURL + "?key=" + session->getID() + "&ID=";
520                 const vector<const char*>& tokens = session->getAssertionIDs();
521                 vector<const char*>::size_type count = 0;
522                 for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
523                     count++;
524                     *(exportName.rbegin()) = '0' + (count%10);
525                     *(++exportName.rbegin()) = '0' + (count/10);
526                     string fullURL = baseURL + encoder->encode(*tokenids);
527                     app->setHeader(request, exportName.c_str(), fullURL.c_str());
528                 }
529                 app->setHeader(request, "Shib-Assertion-Count", exportName.c_str() + 15);
530             }
531         }
532
533         // Export the attributes.
534         const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
535         for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a != attributes.end(); ++a) {
536             if (a->second->isInternal())
537                 continue;
538             string header(app->getSecureHeader(request, a->first.c_str()));
539             const vector<string>& vals = a->second->getSerializedValues();
540             for (vector<string>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
541                 if (!header.empty())
542                     header += ";";
543                                 if (enc.first) {
544                                         // If URL-encoding, any semicolons will get escaped anyway.
545                                         header += encoder->encode(v->c_str());
546                                 }
547                                 else {
548                                         string::size_type pos = v->find_first_of(';', string::size_type(0));
549                                         if (pos != string::npos) {
550                                                 string value(*v);
551                                                 for (; pos != string::npos; pos = value.find_first_of(';', pos)) {
552                                                         value.insert(pos, "\\");
553                                                         pos += 2;
554                                                 }
555                                                 header += value;
556                                         }
557                                         else {
558                                                 header += (*v);
559                                         }
560                                 }
561             }
562             app->setHeader(request, a->first.c_str(), header.c_str());
563         }
564
565         // Check for REMOTE_USER.
566         bool remoteUserSet = false;
567         const vector<string>& rmids = app->getRemoteUserAttributeIds();
568         for (vector<string>::const_iterator rmid = rmids.begin(); !remoteUserSet && rmid != rmids.end(); ++rmid) {
569             pair<multimap<string,const Attribute*>::const_iterator,multimap<string,const Attribute*>::const_iterator> matches =
570                 attributes.equal_range(*rmid);
571             for (; matches.first != matches.second; ++matches.first) {
572                 const vector<string>& vals = matches.first->second->getSerializedValues();
573                 if (!vals.empty()) {
574                                         if (enc.first)
575                                                 request.setRemoteUser(encoder->encode(vals.front().c_str()).c_str());
576                                         else
577                                                 request.setRemoteUser(vals.front().c_str());
578                     remoteUserSet = true;
579                     break;
580                 }
581             }
582         }
583
584         return make_pair(false,0L);
585     }
586     catch (exception& e) {
587         request.log(SPRequest::SPError, e.what());
588         TemplateParameters tp(&e, nullptr, session);
589         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
590         return make_pair(true, sendError(log, request, app, "session", tp));
591     }
592 }
593
594 pair<bool,long> ServiceProvider::doHandler(SPRequest& request) const
595 {
596 #ifdef _DEBUG
597     xmltooling::NDC ndc("doHandler");
598 #endif
599     Category& log = Category::getInstance(SHIBSP_LOGCAT".ServiceProvider");
600
601     const Application* app = nullptr;
602     string targetURL = request.getRequestURL();
603
604     try {
605         RequestMapper::Settings settings = request.getRequestSettings();
606         app = &(request.getApplication());
607
608         // If not SSL, check to see if we should block or redirect it.
609         if (!request.isSecure()) {
610             pair<bool,const char*> redirectToSSL = settings.first->getString("redirectToSSL");
611             if (redirectToSSL.first) {
612 #ifdef HAVE_STRCASECMP
613                 if (!strcasecmp("GET",request.getMethod()) || !strcasecmp("HEAD",request.getMethod())) {
614 #else
615                 if (!stricmp("GET",request.getMethod()) || !stricmp("HEAD",request.getMethod())) {
616 #endif
617                     // Compute the new target URL
618                     string redirectURL = string("https://") + request.getHostname();
619                     if (strcmp(redirectToSSL.second,"443")) {
620                         redirectURL = redirectURL + ':' + redirectToSSL.second;
621                     }
622                     redirectURL += request.getRequestURI();
623                     return make_pair(true, request.sendRedirect(redirectURL.c_str()));
624                 }
625                 else {
626                     TemplateParameters tp;
627                     tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
628                     return make_pair(true,sendError(log, request, app, "ssl", tp, false));
629                 }
630             }
631         }
632
633         const char* handlerURL = request.getHandlerURL(targetURL.c_str());
634         if (!handlerURL)
635             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
636
637         // Make sure we only process handler requests.
638         if (!boost::contains(targetURL, handlerURL))
639             return make_pair(true, request.returnDecline());
640
641         const PropertySet* sessionProps = app->getPropertySet("Sessions");
642         if (!sessionProps)
643             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
644
645         // Process incoming request.
646         pair<bool,bool> handlerSSL = sessionProps->getBool("handlerSSL");
647
648         // Make sure this is SSL, if it should be
649         if ((!handlerSSL.first || handlerSSL.second) && !request.isSecure())
650             throw opensaml::FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
651
652         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
653         // so the path info is the next character (or null).
654         const Handler* handler = app->getHandler(targetURL.c_str() + strlen(handlerURL));
655         if (!handler)
656             throw ConfigurationException("Shibboleth handler invoked at an unconfigured location.");
657
658         pair<bool,long> hret = handler->run(request);
659
660         // Did the handler run successfully?
661         if (hret.first)
662             return hret;
663
664         throw ConfigurationException("Configured Shibboleth handler failed to process the request.");
665     }
666     catch (exception& e) {
667         request.log(SPRequest::SPError, e.what());
668         const Session* session = nullptr;
669         try {
670             session = request.getSession(false, true);
671         }
672         catch (exception&) {
673         }
674         TemplateParameters tp(&e, nullptr, session);
675         tp.m_map["requestURL"] = targetURL.substr(0, targetURL.find('?'));
676         tp.m_request = &request;
677         return make_pair(true, sendError(log, request, app, "session", tp));
678     }
679 }