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 <log4cpp/Category.hh>
71 #include <log4cpp/PropertyConfigurator.hh>
72 #include <xercesc/util/Base64.hpp>
73 #include <xercesc/util/regx/RegularExpression.hpp>
75 #ifndef HAVE_STRCASECMP
76 # define strcasecmp stricmp
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace log4cpp;
85 namespace shibtarget {
93 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
94 void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
96 // Handlers do the real Shibboleth work
97 pair<bool,void*> dispatch(
99 const IPropertySet* handler,
101 const char* forceType=NULL
105 friend class ShibTarget;
106 IRequestMapper::Settings m_settings;
107 const IApplication *m_app;
108 mutable string m_handlerURL;
109 mutable map<string,string> m_cookieMap;
111 ISessionCacheEntry* m_cacheEntry;
113 ShibTargetConfig* m_Config;
116 IRequestMapper* m_mapper;
121 /*************************************************************************
122 * Shib Target implementation
125 ShibTarget::ShibTarget(void) : m_priv(NULL)
127 m_priv = new ShibTargetPriv();
130 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
132 m_priv = new ShibTargetPriv();
136 ShibTarget::~ShibTarget(void)
138 if (m_priv) delete m_priv;
141 void ShibTarget::init(
142 const char* protocol,
143 const char* hostname,
146 const char* content_type,
147 const char* remote_addr,
152 saml::NDC ndc("init");
156 throw SAMLException("Request initialization occurred twice!");
158 if (method) m_method = method;
159 if (protocol) m_protocol = protocol;
160 if (hostname) m_hostname = hostname;
161 if (uri) m_uri = uri;
162 if (content_type) m_content_type = content_type;
163 if (remote_addr) m_remote_addr = remote_addr;
165 m_priv->m_Config = &ShibTargetConfig::getConfig();
166 m_priv->get_application(this, protocol, hostname, port, uri);
170 // These functions implement the server-agnostic shibboleth engine
171 // The web server modules implement a subclass and then call into
172 // these methods once they instantiate their request object.
174 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
177 saml::NDC ndc("doCheckAuthN");
180 const char* procState = "Request Processing Error";
181 const char* targetURL = m_url.c_str();
186 throw ConfigurationException("System uninitialized, application did not supply request information.");
188 string hURL = getHandlerURL(targetURL);
189 const char* handlerURL=hURL.c_str();
191 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
193 // If the request URL contains the handler base URL for this application, either dispatch
194 // directly (mainly Apache 2.0) or just pass back control.
195 if (strstr(targetURL,handlerURL)) {
199 return pair<bool,void*>(true, returnOK());
202 // Three settings dictate how to proceed.
203 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
204 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
205 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
207 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
208 // then we ignore this request and consider it unprotected. Apache might lie to us if
209 // ShibBasicHijack is on, but that's up to it.
210 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
211 #ifdef HAVE_STRCASECMP
212 (!authType.first || strcasecmp(authType.second,"shibboleth")))
214 (!authType.first || stricmp(authType.second,"shibboleth")))
216 return pair<bool,void*>(true,returnDecline());
218 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
219 const char* session_id = getCookie(shib_cookie.first);
220 if (!session_id || !*session_id) {
221 // No session. Maybe that's acceptable?
222 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
223 return pair<bool,void*>(true,returnOK());
225 // No cookie, but we require a session. Initiate a new session using the indicated method.
226 procState = "Session Initiator Error";
227 const IPropertySet* initiator=NULL;
228 if (requireSessionWith.first)
229 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
231 initiator=m_priv->m_app->getDefaultSessionInitiator();
233 // Standard handler element, so we dispatch normally.
235 return m_priv->dispatch(this,initiator,false);
237 // Legacy config support maps the Sessions element to the Shib profile.
238 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
239 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
243 procState = "Session Processing Error";
245 // Localized exception throw if the session isn't valid.
246 m_priv->m_conf->getListener()->sessionGet(
249 m_remote_addr.c_str(),
250 &m_priv->m_cacheEntry
253 catch (SAMLException& e) {
254 log(LogLevelError, string("session processing failed: ") + e.what());
256 // If no session is required, bail now.
257 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
258 // Has to be OK because DECLINED will just cause Apache
259 // to fail when it can't locate anything to process the
260 // AuthType. No session plus requireSession false means
261 // do not authenticate the user at this time.
262 return pair<bool,void*>(true, returnOK());
264 // Try and cast down. This should throw an exception if it fails.
265 bool retryable=false;
267 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
273 // Session is invalid but we can retry -- initiate a new session.
274 procState = "Session Initiator Error";
275 const IPropertySet* initiator=NULL;
276 if (requireSessionWith.first)
277 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
279 initiator=m_priv->m_app->getDefaultSessionInitiator();
280 // Standard handler element, so we dispatch normally.
282 return m_priv->dispatch(this,initiator,false);
284 // Legacy config support maps the Sessions element to the Shib profile.
285 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
286 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
289 throw; // send it to the outer handler
292 // We're done. Everything is okay. Nothing to report. Nothing to do..
293 // Let the caller decide how to proceed.
294 log(LogLevelDebug, "doCheckAuthN succeeded");
295 return pair<bool,void*>(false,NULL);
297 catch (SAMLException& e) {
302 mlp.insert("errorText", "Caught an unknown exception.");
306 // If we get here then we've got an error.
307 mlp.insert("errorType", procState);
309 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
311 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
314 pair<bool,void*> ShibTarget::doHandler(void)
317 saml::NDC ndc("doHandler");
320 const char* procState = "Shibboleth Handler Error";
321 const char* targetURL = m_url.c_str();
326 throw ConfigurationException("System uninitialized, application did not supply request information.");
328 string hURL = getHandlerURL(targetURL);
329 const char* handlerURL=hURL.c_str();
331 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
333 // Make sure we only process handler requests.
334 if (!strstr(targetURL,handlerURL))
335 return pair<bool,void*>(true, returnDecline());
337 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
339 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
341 // Process incoming request.
342 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
344 // Make sure this is SSL, if it should be
345 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
346 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
348 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
349 // so the path info is the next character (or null).
350 const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
352 if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
353 procState = "Session Creation Error";
354 return m_priv->dispatch(this,handler);
356 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
357 procState = "Session Initiator Error";
358 return m_priv->dispatch(this,handler);
360 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
361 procState = "Session Termination Error";
362 return m_priv->dispatch(this,handler);
364 else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
365 procState = "Diagnostics Error";
366 return m_priv->dispatch(this,handler);
369 procState = "Extension Service Error";
370 return m_priv->dispatch(this,handler);
374 if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
375 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
377 // This is a legacy direct execution of the handler (the old shireURL).
378 // If this is a GET, we see if it's a lazy session request, otherwise
379 // assume it's a SAML 1.x POST profile response and process it.
380 if (!strcasecmp(m_method.c_str(), "GET")) {
381 procState = "Session Initiator Error";
382 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
383 return m_priv->dispatch(this, sessionProps, true, binding.get());
386 procState = "Session Creation Error";
387 auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
388 return m_priv->dispatch(this, sessionProps, true, binding.get());
390 catch (MetadataException& e) {
392 // See if a metadata error page is installed.
393 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
395 pair<bool,const char*> p=props->getString("metadata");
397 mlp.insert("errorType", procState);
399 mlp.insert("requestURL", targetURL);
400 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
404 catch (SAMLException& e) {
409 mlp.insert("errorText", "Caught an unknown exception.");
413 // If we get here then we've got an error.
414 mlp.insert("errorType", procState);
417 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
419 return make_pair(true,m_priv->sendError(this,"session", mlp));
422 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
425 saml::NDC ndc("doCheckAuthZ");
429 const char* procState = "Authorization Processing Error";
430 const char* targetURL = m_url.c_str();
434 throw ConfigurationException("System uninitialized, application did not supply request information.");
436 // Three settings dictate how to proceed.
437 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
438 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
439 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
441 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
442 // then we ignore this request and consider it unprotected. Apache might lie to us if
443 // ShibBasicHijack is on, but that's up to it.
444 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
445 #ifdef HAVE_STRCASECMP
446 (!authType.first || strcasecmp(authType.second,"shibboleth")))
448 (!authType.first || stricmp(authType.second,"shibboleth")))
450 return pair<bool,void*>(true,returnDecline());
452 // Do we have an access control plugin?
453 if (m_priv->m_settings.second) {
454 Locker acllock(m_priv->m_settings.second);
455 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
456 // Let the caller decide how to proceed.
457 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
458 return pair<bool,void*>(false,NULL);
461 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
463 mlp.insert("requestURL", targetURL);
464 return make_pair(true,m_priv->sendError(this, "access", mlp));
468 return make_pair(true,returnDecline());
470 catch (SAMLException& e) {
475 mlp.insert("errorText", "Caught an unknown exception.");
479 // If we get here then we've got an error.
480 mlp.insert("errorType", procState);
483 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
485 return make_pair(true,m_priv->sendError(this, "access", mlp));
488 pair<bool,void*> ShibTarget::doExportAssertions()
491 saml::NDC ndc("doExportAssertions");
495 const char* procState = "Attribute Processing Error";
496 const char* targetURL = m_url.c_str();
500 throw ConfigurationException("System uninitialized, application did not supply request information.");
502 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
503 const char *session_id = getCookie(shib_cookie.first);
505 if (!m_priv->m_cacheEntry) {
506 // No data yet, so we need to get the session. This can only happen
507 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
508 m_priv->m_conf->getListener()->sessionGet(
511 m_remote_addr.c_str(),
512 &m_priv->m_cacheEntry
516 // Get the AAP providers, which contain the attribute policy info.
517 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
519 // Clear out the list of mapped attributes
520 while (provs.hasNext()) {
521 IAAP* aap=provs.next();
523 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
524 while (rules.hasNext()) {
525 const char* header=rules.next()->getHeader();
531 ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
533 // Maybe export the response.
534 clearHeader("Shib-Attributes");
535 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
536 if (exp.first && exp.second && cr.unfiltered) {
538 os << *cr.unfiltered;
540 XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
542 for (pos=serialized, pos2=serialized; *pos2; pos2++)
546 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
547 XMLString::release(&serialized);
550 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
551 clearHeader("Shib-Origin-Site");
552 clearHeader("Shib-Identity-Provider");
553 clearHeader("Shib-Authentication-Method");
554 clearHeader("Shib-NameIdentifier-Format");
555 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
556 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
557 auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
558 setHeader("Shib-Authentication-Method", am.get());
562 while (provs.hasNext()) {
563 IAAP* aap=provs.next();
565 const IAttributeRule* rule=aap->lookup(
566 m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat()
568 if (rule && rule->getHeader()) {
569 auto_ptr_char form(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat());
570 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
571 setHeader("Shib-NameIdentifier-Format", form.get());
572 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
573 setRemoteUser(nameid.get());
575 setHeader(rule->getHeader(), nameid.get());
579 clearHeader("Shib-Application-ID");
580 setHeader("Shib-Application-ID", m_priv->m_app->getId());
582 // Export the attributes.
583 Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
584 while (a_iter.hasNext()) {
585 SAMLAssertion* assert=a_iter.next();
586 Iterator<SAMLStatement*> statements=assert->getStatements();
587 while (statements.hasNext()) {
588 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
591 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
592 while (attrs.hasNext()) {
593 SAMLAttribute* attr=attrs.next();
595 // Are we supposed to export it?
597 while (provs.hasNext()) {
598 IAAP* aap=provs.next();
600 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
601 if (!rule || !rule->getHeader())
604 Iterator<string> vals=attr->getSingleByteValues();
605 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
606 setRemoteUser(vals.next());
609 string header = getHeader(rule->getHeader());
612 for (; vals.hasNext(); it++) {
613 string value = vals.next();
614 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
616 pos = value.find_first_of(";", pos)) {
617 value.insert(pos, "\\");
624 setHeader(rule->getHeader(), header);
631 return pair<bool,void*>(false,NULL);
633 catch (SAMLException& e) {
638 mlp.insert("errorText", "Caught an unknown exception.");
642 // If we get here then we've got an error.
643 mlp.insert("errorType", procState);
646 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
648 return make_pair(true,m_priv->sendError(this, "rm", mlp));
651 const char* ShibTarget::getCookie(const string& name) const
653 if (m_priv->m_cookieMap.empty()) {
654 string cookies=getCookies();
656 string::size_type pos=0,cname,namelen,val,vallen;
657 while (pos !=string::npos && pos < cookies.length()) {
658 while (isspace(cookies[pos])) pos++;
660 pos=cookies.find_first_of("=",pos);
661 if (pos == string::npos)
665 if (pos==cookies.length())
668 pos=cookies.find_first_of(";",pos);
669 if (pos != string::npos) {
672 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
675 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
678 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
679 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
682 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
684 static const char* defProps="; path=/";
686 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
688 pair<bool,const char*> p=props->getString("cookieProps");
691 pair<bool,const char*> p2=props->getString("cookieName");
693 return make_pair(string(prefix) + p2.second,p.second);
694 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
697 // Shouldn't happen, but just in case..
698 return make_pair(prefix,defProps);
701 string ShibTarget::getHandlerURL(const char* resource) const
703 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
704 return m_priv->m_handlerURL;
707 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
710 const char* handler=NULL;
711 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
713 pair<bool,bool> p=props->getBool("handlerSSL");
716 pair<bool,const char*> p2=props->getString("handlerURL");
721 // Should never happen...
722 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
723 throw ConfigurationException(
724 "Invalid handlerURL property ($1) in Application ($2)",
725 params(2, handler ? handler : "null", m_priv->m_app->getId())
728 // The "handlerURL" property can be in one of three formats:
730 // 1) a full URI: http://host/foo/bar
731 // 2) a hostless URI: http:///foo/bar
732 // 3) a relative path: /foo/bar
734 // # Protocol Host Path
735 // 1 handler handler handler
736 // 2 handler resource handler
737 // 3 resource resource handler
739 // note: if ssl_only is true, make sure the protocol is https
741 const char* path = NULL;
743 // Decide whether to use the handler or the resource for the "protocol"
745 if (*handler != '/') {
753 // break apart the "protocol" string into protocol, host, and "the rest"
754 const char* colon=strchr(prot,':');
756 const char* slash=strchr(colon,'/');
760 // Compute the actual protocol and store in member.
762 m_priv->m_handlerURL.assign("https://");
764 m_priv->m_handlerURL.assign(prot, colon-prot);
766 // create the "host" from either the colon/slash or from the target string
767 // If prot == handler then we're in either #1 or #2, else #3.
768 // If slash == colon then we're in #2.
769 if (prot != handler || slash == colon) {
770 colon = strchr(resource, ':');
771 colon += 3; // Get past the ://
772 slash = strchr(colon, '/');
774 string host(colon, slash-colon);
776 // Build the handler URL
777 m_priv->m_handlerURL+=host + path;
778 return m_priv->m_handlerURL;
781 void ShibTarget::log(ShibLogLevel level, const string& msg)
783 Category::getInstance("shibtarget.ShibTarget").log(
784 (level == LogLevelDebug ? Priority::DEBUG :
785 (level == LogLevelInfo ? Priority::INFO :
786 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
791 const IApplication* ShibTarget::getApplication() const
793 return m_priv->m_app;
796 const IConfig* ShibTarget::getConfig() const
798 return m_priv->m_conf;
801 void* ShibTarget::returnDecline(void)
806 void* ShibTarget::returnOK(void)
812 /*************************************************************************
813 * Shib Target Private implementation
816 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL) {}
818 ShibTargetPriv::~ShibTargetPriv()
821 m_cacheEntry->unlock();
839 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
844 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
845 // TODO: No, should be able to hold the conf but release the mapper.
847 // We lock the configuration system for the duration.
848 m_conf=m_Config->getINI();
851 // Map request to application and content settings.
852 m_mapper=m_conf->getRequestMapper();
855 // Obtain the application settings from the parsed URL
856 m_settings = m_mapper->getSettings(st);
858 // Now find the application from the URL settings
859 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
860 m_app=m_conf->getApplication(application_id.second);
866 throw ConfigurationException("Unable to map request to application settings, check configuration.");
869 // Compute the full target URL
870 st->m_url = protocol + "://" + hostname;
871 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
872 st->m_url += ":" + port;
876 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
878 ShibTarget::header_t hdrs[] = {
879 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
880 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
883 const IPropertySet* props=m_app->getPropertySet("Errors");
885 pair<bool,const char*> p=props->getString(page);
887 ifstream infile(p.second);
888 if (!infile.fail()) {
889 const char* res = mlp.run(infile,props);
891 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
894 else if (!strcmp(page,"access"))
895 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
898 string errstr = string("sendError could not process error template (") + page + ") for application (";
899 errstr += m_app->getId();
901 st->log(ShibTarget::LogLevelError, errstr);
903 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
907 pair<bool,void*> ShibTargetPriv::dispatch(
909 const IPropertySet* config,
911 const char* forceType
914 pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
916 auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
917 IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
919 throw UnsupportedProfileException(
920 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
922 return handler->run(st,config,isHandler);
924 throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");