2 * The Shibboleth License, Version 1.
4 * University Corporation for Advanced Internet Development, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
14 * Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution, if any, must include
17 * the following acknowledgment: "This product includes software developed by
18 * the University Corporation for Advanced Internet Development
19 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20 * may appear in the software itself, if and wherever such third-party
21 * acknowledgments normally appear.
23 * Neither the name of Shibboleth nor the names of its contributors, nor
24 * Internet2, nor the University Corporation for Advanced Internet Development,
25 * Inc., nor UCAID may be used to endorse or promote products derived from this
26 * software without specific prior written permission. For written permission,
27 * please contact shibboleth@shibboleth.org
29 * Products derived from this software may not be called Shibboleth, Internet2,
30 * UCAID, or the University Corporation for Advanced Internet Development, nor
31 * may Shibboleth appear in their name, without prior written permission of the
32 * University Corporation for Advanced Internet Development.
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51 * shib-target.cpp -- The ShibTarget class, a superclass for general
54 * Created by: Derek Atkins <derek@ihtfp.com>
69 #include <shib/shib-threads.h>
70 #include <xercesc/util/Base64.hpp>
72 #ifndef HAVE_STRCASECMP
73 # define strcasecmp stricmp
78 using namespace shibboleth;
79 using namespace shibtarget;
80 using namespace log4cpp;
82 namespace shibtarget {
90 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
91 void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
93 // Handlers do the real Shibboleth work
94 pair<bool,void*> dispatch(
96 const IPropertySet* handler,
98 const char* forceType=NULL
102 friend class ShibTarget;
103 IRequestMapper::Settings m_settings;
104 const IApplication *m_app;
105 mutable string m_handlerURL;
106 mutable map<string,string> m_cookieMap;
108 ISessionCacheEntry* m_cacheEntry;
110 ShibTargetConfig* m_Config;
113 IRequestMapper* m_mapper;
118 /*************************************************************************
119 * Shib Target implementation
122 ShibTarget::ShibTarget(void) : m_priv(NULL)
124 m_priv = new ShibTargetPriv();
127 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
129 m_priv = new ShibTargetPriv();
133 ShibTarget::~ShibTarget(void)
135 if (m_priv) delete m_priv;
138 void ShibTarget::init(
139 const char* protocol,
140 const char* hostname,
143 const char* content_type,
144 const char* remote_addr,
149 saml::NDC ndc("init");
153 throw SAMLException("Request initialization occurred twice!");
155 if (method) m_method = method;
156 if (protocol) m_protocol = protocol;
157 if (hostname) m_hostname = hostname;
158 if (uri) m_uri = uri;
159 if (content_type) m_content_type = content_type;
160 if (remote_addr) m_remote_addr = remote_addr;
162 m_priv->m_Config = &ShibTargetConfig::getConfig();
163 m_priv->get_application(this, protocol, hostname, port, uri);
167 // These functions implement the server-agnostic shibboleth engine
168 // The web server modules implement a subclass and then call into
169 // these methods once they instantiate their request object.
171 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
174 saml::NDC ndc("doCheckAuthN");
177 const char* procState = "Request Processing Error";
178 const char* targetURL = m_url.c_str();
183 throw ConfigurationException("System uninitialized, application did not supply request information.");
185 string hURL = getHandlerURL(targetURL);
186 const char* handlerURL=hURL.c_str();
188 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
190 // If the request URL contains the handler base URL for this application, either dispatch
191 // directly (mainly Apache 2.0) or just pass back control.
192 if (strstr(targetURL,handlerURL)) {
196 return pair<bool,void*>(true, returnOK());
199 // Three settings dictate how to proceed.
200 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
201 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
202 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
204 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
205 // then we ignore this request and consider it unprotected. Apache might lie to us if
206 // ShibBasicHijack is on, but that's up to it.
207 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
208 #ifdef HAVE_STRCASECMP
209 (!authType.first || strcasecmp(authType.second,"shibboleth")))
211 (!authType.first || stricmp(authType.second,"shibboleth")))
213 return pair<bool,void*>(true,returnDecline());
215 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
216 const char* session_id = getCookie(shib_cookie.first);
217 if (!session_id || !*session_id) {
218 // No session. Maybe that's acceptable?
219 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
220 return pair<bool,void*>(true,returnOK());
222 // No cookie, but we require a session. Initiate a new session using the indicated method.
223 procState = "Session Initiator Error";
224 const IPropertySet* initiator=NULL;
225 if (requireSessionWith.first)
226 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
228 initiator=m_priv->m_app->getDefaultSessionInitiator();
230 // Standard handler element, so we dispatch normally.
232 return m_priv->dispatch(this,initiator,false);
234 // Legacy config support maps the Sessions element to the Shib profile.
235 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
236 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
240 procState = "Session Processing Error";
242 // Localized exception throw if the session isn't valid.
243 m_priv->m_conf->getListener()->sessionGet(
246 m_remote_addr.c_str(),
247 &m_priv->m_cacheEntry
250 catch (SAMLException& e) {
251 log(LogLevelError, string("session processing failed: ") + e.what());
253 // If no session is required, bail now.
254 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
255 // Has to be OK because DECLINED will just cause Apache
256 // to fail when it can't locate anything to process the
257 // AuthType. No session plus requireSession false means
258 // do not authenticate the user at this time.
259 return pair<bool,void*>(true, returnOK());
261 // Try and cast down. This should throw an exception if it fails.
262 bool retryable=false;
264 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
270 // Session is invalid but we can retry -- initiate a new session.
271 procState = "Session Initiator Error";
272 const IPropertySet* initiator=NULL;
273 if (requireSessionWith.first)
274 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
276 initiator=m_priv->m_app->getDefaultSessionInitiator();
277 // Standard handler element, so we dispatch normally.
279 return m_priv->dispatch(this,initiator,false);
281 // Legacy config support maps the Sessions element to the Shib profile.
282 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
283 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
286 throw; // send it to the outer handler
289 // We're done. Everything is okay. Nothing to report. Nothing to do..
290 // Let the caller decide how to proceed.
291 log(LogLevelDebug, "doCheckAuthN succeeded");
292 return pair<bool,void*>(false,NULL);
294 catch (SAMLException& e) {
299 mlp.insert("errorText", "Caught an unknown exception.");
303 // If we get here then we've got an error.
304 mlp.insert("errorType", procState);
306 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
308 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
311 pair<bool,void*> ShibTarget::doHandler(void)
314 saml::NDC ndc("doHandler");
317 const char* procState = "Shibboleth Handler Error";
318 const char* targetURL = m_url.c_str();
323 throw ConfigurationException("System uninitialized, application did not supply request information.");
325 string hURL = getHandlerURL(targetURL);
326 const char* handlerURL=hURL.c_str();
328 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
330 // Make sure we only process handler requests.
331 if (!strstr(targetURL,handlerURL))
332 return pair<bool,void*>(true, returnDecline());
334 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
336 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
338 // Process incoming request.
339 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
341 // Make sure this is SSL, if it should be
342 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
343 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
345 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
346 // so the path info is the next character (or null).
347 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
349 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
350 procState = "Session Creation Error";
351 return m_priv->dispatch(this,handler);
353 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
354 procState = "Session Initiator Error";
355 return m_priv->dispatch(this,handler);
357 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
358 procState = "Session Termination Error";
359 return m_priv->dispatch(this,handler);
361 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
362 procState = "Diagnostics Error";
363 return m_priv->dispatch(this,handler);
366 procState = "Extension Service Error";
367 return m_priv->dispatch(this,handler);
371 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
372 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
374 // This is a legacy direct execution of the handler (the old shireURL).
375 // If this is a GET, we see if it's a lazy session request, otherwise
376 // assume it's a SAML 1.x POST profile response and process it.
377 if (!strcasecmp(m_method.c_str(), "GET")) {
378 procState = "Session Initiator Error";
379 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
380 return m_priv->dispatch(this, sessionProps, true, binding.get());
383 procState = "Session Creation Error";
384 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
385 return m_priv->dispatch(this, sessionProps, true, binding.get());
387 catch (MetadataException& e) {
389 // See if a metadata error page is installed.
390 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
392 pair<bool,const char*> p=props->getString("metadata");
394 mlp.insert("errorType", procState);
396 mlp.insert("requestURL", targetURL);
397 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
401 catch (SAMLException& e) {
406 mlp.insert("errorText", "Caught an unknown exception.");
410 // If we get here then we've got an error.
411 mlp.insert("errorType", procState);
414 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
416 return make_pair(true,m_priv->sendError(this,"session", mlp));
419 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
422 saml::NDC ndc("doCheckAuthZ");
426 const char* procState = "Authorization Processing Error";
427 const char* targetURL = m_url.c_str();
431 throw ConfigurationException("System uninitialized, application did not supply request information.");
433 // Three settings dictate how to proceed.
434 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
435 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
436 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
438 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
439 // then we ignore this request and consider it unprotected. Apache might lie to us if
440 // ShibBasicHijack is on, but that's up to it.
441 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
442 #ifdef HAVE_STRCASECMP
443 (!authType.first || strcasecmp(authType.second,"shibboleth")))
445 (!authType.first || stricmp(authType.second,"shibboleth")))
447 return pair<bool,void*>(true,returnDecline());
449 // Do we have an access control plugin?
450 if (m_priv->m_settings.second) {
452 if (!m_priv->m_cacheEntry) {
453 // No data yet, so we may need to try and get the session.
454 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
455 const char *session_id = getCookie(shib_cookie.first);
457 if (session_id && *session_id) {
458 m_priv->m_conf->getListener()->sessionGet(
461 m_remote_addr.c_str(),
462 &m_priv->m_cacheEntry
466 catch (SAMLException&) {
467 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
471 Locker acllock(m_priv->m_settings.second);
472 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
473 // Let the caller decide how to proceed.
474 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
475 return pair<bool,void*>(false,NULL);
478 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
480 mlp.insert("requestURL", targetURL);
481 return make_pair(true,m_priv->sendError(this, "access", mlp));
485 return make_pair(true,returnDecline());
487 catch (SAMLException& e) {
492 mlp.insert("errorText", "Caught an unknown exception.");
496 // If we get here then we've got an error.
497 mlp.insert("errorType", procState);
500 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
502 return make_pair(true,m_priv->sendError(this, "access", mlp));
505 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
508 saml::NDC ndc("doExportAssertions");
512 const char* procState = "Attribute Processing Error";
513 const char* targetURL = m_url.c_str();
517 throw ConfigurationException("System uninitialized, application did not supply request information.");
519 if (!m_priv->m_cacheEntry) {
520 // No data yet, so we need to get the session. This can only happen
521 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
522 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
523 const char *session_id = getCookie(shib_cookie.first);
525 if (session_id && *session_id) {
526 m_priv->m_conf->getListener()->sessionGet(
529 m_remote_addr.c_str(),
530 &m_priv->m_cacheEntry
534 catch (SAMLException&) {
535 log(LogLevelError, "unable to obtain session information to export into request headers");
536 // If we have to have a session, then this is a fatal error.
543 if (!m_priv->m_cacheEntry) {
545 throw InvalidSessionException("Unable to obtain session information for request.");
547 return pair<bool,void*>(false,NULL); // just bail silently
550 // Get the AAP providers, which contain the attribute policy info.
551 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
553 // Clear out the list of mapped attributes
554 while (provs.hasNext()) {
555 IAAP* aap=provs.next();
557 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
558 while (rules.hasNext()) {
559 const char* header=rules.next()->getHeader();
565 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
567 // Maybe export the response.
568 clearHeader("Shib-Attributes");
569 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
570 if (exp.first && exp.second && cr.unfiltered) {
572 os << *cr.unfiltered;
574 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
576 for (pos=serialized, pos2=serialized; *pos2; pos2++)
580 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
581 XMLString::release(&serialized);
584 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
585 clearHeader("Shib-Origin-Site");
586 clearHeader("Shib-Identity-Provider");
587 clearHeader("Shib-Authentication-Method");
588 clearHeader("Shib-NameIdentifier-Format");
589 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
590 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
591 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
592 setHeader("Shib-Authentication-Method", am.get());
596 while (provs.hasNext()) {
597 IAAP* aap=provs.next();
599 const IAttributeRule* rule=aap->lookup(
600 m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat()
602 if (rule && rule->getHeader()) {
603 auto_ptr_char form(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat());
604 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
605 setHeader("Shib-NameIdentifier-Format", form.get());
606 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
607 setRemoteUser(nameid.get());
609 setHeader(rule->getHeader(), nameid.get());
613 clearHeader("Shib-Application-ID");
614 setHeader("Shib-Application-ID", m_priv->m_app->getId());
616 // Export the attributes.
617 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
618 while (a_iter.hasNext()) {
619 SAMLAssertion* assert=a_iter.next();
620 Iterator<SAMLStatement*> statements=assert->getStatements();
621 while (statements.hasNext()) {
622 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
625 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
626 while (attrs.hasNext()) {
627 SAMLAttribute* attr=attrs.next();
629 // Are we supposed to export it?
631 while (provs.hasNext()) {
632 IAAP* aap=provs.next();
634 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
635 if (!rule || !rule->getHeader())
638 Iterator<string> vals=attr->getSingleByteValues();
639 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
640 setRemoteUser(vals.next());
643 string header = getHeader(rule->getHeader());
646 for (; vals.hasNext(); it++) {
647 string value = vals.next();
648 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
650 pos = value.find_first_of(";", pos)) {
651 value.insert(pos, "\\");
658 setHeader(rule->getHeader(), header);
665 return pair<bool,void*>(false,NULL);
667 catch (SAMLException& e) {
672 mlp.insert("errorText", "Caught an unknown exception.");
676 // If we get here then we've got an error.
677 mlp.insert("errorType", procState);
680 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
682 return make_pair(true,m_priv->sendError(this, "rm", mlp));
685 const char* ShibTarget::getCookie(const string& name) const
687 if (m_priv->m_cookieMap.empty()) {
688 string cookies=getCookies();
690 string::size_type pos=0,cname,namelen,val,vallen;
691 while (pos !=string::npos && pos < cookies.length()) {
692 while (isspace(cookies[pos])) pos++;
694 pos=cookies.find_first_of("=",pos);
695 if (pos == string::npos)
699 if (pos==cookies.length())
702 pos=cookies.find_first_of(";",pos);
703 if (pos != string::npos) {
706 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
709 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
712 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
713 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
716 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
718 static const char* defProps="; path=/";
720 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
722 pair<bool,const char*> p=props->getString("cookieProps");
725 pair<bool,const char*> p2=props->getString("cookieName");
727 return make_pair(string(prefix) + p2.second,p.second);
728 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
731 // Shouldn't happen, but just in case..
732 return make_pair(prefix,defProps);
735 string ShibTarget::getHandlerURL(const char* resource) const
737 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
738 return m_priv->m_handlerURL;
741 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
744 const char* handler=NULL;
745 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
747 pair<bool,bool> p=props->getBool("handlerSSL");
750 pair<bool,const char*> p2=props->getString("handlerURL");
755 // Should never happen...
756 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
757 throw ConfigurationException(
758 "Invalid handlerURL property ($1) in Application ($2)",
759 params(2, handler ? handler : "null", m_priv->m_app->getId())
762 // The "handlerURL" property can be in one of three formats:
764 // 1) a full URI: http://host/foo/bar
765 // 2) a hostless URI: http:///foo/bar
766 // 3) a relative path: /foo/bar
768 // # Protocol Host Path
769 // 1 handler handler handler
770 // 2 handler resource handler
771 // 3 resource resource handler
773 // note: if ssl_only is true, make sure the protocol is https
775 const char* path = NULL;
777 // Decide whether to use the handler or the resource for the "protocol"
779 if (*handler != '/') {
787 // break apart the "protocol" string into protocol, host, and "the rest"
788 const char* colon=strchr(prot,':');
790 const char* slash=strchr(colon,'/');
794 // Compute the actual protocol and store in member.
796 m_priv->m_handlerURL.assign("https://");
798 m_priv->m_handlerURL.assign(prot, colon-prot);
800 // create the "host" from either the colon/slash or from the target string
801 // If prot == handler then we're in either #1 or #2, else #3.
802 // If slash == colon then we're in #2.
803 if (prot != handler || slash == colon) {
804 colon = strchr(resource, ':');
805 colon += 3; // Get past the ://
806 slash = strchr(colon, '/');
808 string host(colon, slash-colon);
810 // Build the handler URL
811 m_priv->m_handlerURL+=host + path;
812 return m_priv->m_handlerURL;
815 void ShibTarget::log(ShibLogLevel level, const string& msg)
817 Category::getInstance("shibtarget.ShibTarget").log(
818 (level == LogLevelDebug ? Priority::DEBUG :
819 (level == LogLevelInfo ? Priority::INFO :
820 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
825 const IApplication* ShibTarget::getApplication() const
827 return m_priv->m_app;
830 const IConfig* ShibTarget::getConfig() const
832 return m_priv->m_conf;
835 void* ShibTarget::returnDecline(void)
840 void* ShibTarget::returnOK(void)
846 /*************************************************************************
847 * Shib Target Private implementation
850 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL) {}
852 ShibTargetPriv::~ShibTargetPriv()
855 m_cacheEntry->unlock();
873 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
878 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
879 // TODO: No, should be able to hold the conf but release the mapper.
881 // We lock the configuration system for the duration.
882 m_conf=m_Config->getINI();
885 // Map request to application and content settings.
886 m_mapper=m_conf->getRequestMapper();
889 // Obtain the application settings from the parsed URL
890 m_settings = m_mapper->getSettings(st);
892 // Now find the application from the URL settings
893 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
894 m_app=m_conf->getApplication(application_id.second);
900 throw ConfigurationException("Unable to map request to application settings, check configuration.");
903 // Compute the full target URL
904 st->m_url = protocol + "://" + hostname;
905 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
906 st->m_url += ":" + port;
910 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
912 ShibTarget::header_t hdrs[] = {
913 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
914 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
917 const IPropertySet* props=m_app->getPropertySet("Errors");
919 pair<bool,const char*> p=props->getString(page);
921 ifstream infile(p.second);
922 if (!infile.fail()) {
923 const char* res = mlp.run(infile,props);
925 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
928 else if (!strcmp(page,"access"))
929 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
932 string errstr = string("sendError could not process error template (") + page + ") for application (";
933 errstr += m_app->getId();
935 st->log(ShibTarget::LogLevelError, errstr);
937 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
941 pair<bool,void*> ShibTargetPriv::dispatch(
943 const IPropertySet* config,
945 const char* forceType
948 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
950 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
951 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
953 throw UnsupportedProfileException(
954 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
956 return handler->run(st,config,isHandler);
958 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");