2 * Copyright 2001-2005 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * shib-target.cpp -- The ShibTarget class, a superclass for general
21 * Created by: Derek Atkins <derek@ihtfp.com>
36 #include <shib/shib-threads.h>
37 #include <xercesc/util/Base64.hpp>
39 #ifndef HAVE_STRCASECMP
40 # define strcasecmp stricmp
45 using namespace shibboleth;
46 using namespace shibtarget;
47 using namespace log4cpp;
49 namespace shibtarget {
53 CgiParse(const ShibTarget* st);
56 typedef multimap<string,char*>::const_iterator walker;
57 pair<walker,walker> get_values(const char* name) const;
60 char* fmakeword(char stop, unsigned int *cl, const char** ppch);
61 char* makeword(char *line, char stop);
62 void plustospace(char *str);
64 multimap<string,char*> kvp_map;
74 void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
75 void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
76 void clearHeaders(ShibTarget* st);
79 friend class ShibTarget;
80 IRequestMapper::Settings m_settings;
81 const IApplication *m_app;
82 mutable string m_handlerURL;
83 mutable map<string,string> m_cookieMap;
84 mutable CgiParse* m_cgiParser;
86 ISessionCacheEntry* m_cacheEntry;
88 ShibTargetConfig* m_Config;
91 IRequestMapper* m_mapper;
96 /*************************************************************************
97 * Shib Target implementation
100 ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
102 ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
107 ShibTarget::~ShibTarget(void)
112 void ShibTarget::init(
113 const char* protocol,
114 const char* hostname,
117 const char* content_type,
118 const char* remote_addr,
123 saml::NDC ndc("init");
127 throw SAMLException("Request initialization occurred twice!");
129 if (method) m_method = method;
130 if (protocol) m_protocol = protocol;
131 if (hostname) m_hostname = hostname;
132 if (uri) m_uri = uri;
133 if (content_type) m_content_type = content_type;
134 if (remote_addr) m_remote_addr = remote_addr;
136 m_priv->m_Config = &ShibTargetConfig::getConfig();
137 m_priv->get_application(this, protocol, hostname, port, uri);
141 // These functions implement the server-agnostic shibboleth engine
142 // The web server modules implement a subclass and then call into
143 // these methods once they instantiate their request object.
145 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
148 saml::NDC ndc("doCheckAuthN");
151 const char* procState = "Request Processing Error";
152 const char* targetURL = m_url.c_str();
157 throw ConfigurationException("System uninitialized, application did not supply request information.");
159 // If not SSL, check to see if we should block or redirect it.
160 if (!strcmp("http",getProtocol())) {
161 pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
162 if (redirectToSSL.first) {
163 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
164 // Compute the new target URL
165 string redirectURL = string("https://") + getHostname();
166 if (strcmp(redirectToSSL.second,"443")) {
167 redirectURL = redirectURL + ':' + redirectToSSL.second;
169 redirectURL += getRequestURI();
170 return make_pair(true, sendRedirect(redirectURL));
173 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
174 return make_pair(true,m_priv->sendError(this,"ssl", mlp));
179 string hURL = getHandlerURL(targetURL);
180 const char* handlerURL=hURL.c_str();
182 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
184 // If the request URL contains the handler base URL for this application, either dispatch
185 // directly (mainly Apache 2.0) or just pass back control.
186 if (strstr(targetURL,handlerURL)) {
190 return pair<bool,void*>(true, returnOK());
193 // Three settings dictate how to proceed.
194 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
195 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
196 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
198 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
199 // then we ignore this request and consider it unprotected. Apache might lie to us if
200 // ShibBasicHijack is on, but that's up to it.
201 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
202 #ifdef HAVE_STRCASECMP
203 (!authType.first || strcasecmp(authType.second,"shibboleth")))
205 (!authType.first || _stricmp(authType.second,"shibboleth")))
207 return pair<bool,void*>(true,returnDecline());
209 // Fix for secadv 20050901
210 m_priv->clearHeaders(this);
212 pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
213 const char* session_id = getCookie(shib_cookie.first);
214 if (!session_id || !*session_id) {
215 // No session. Maybe that's acceptable?
216 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
217 return pair<bool,void*>(true,returnOK());
219 // No cookie, but we require a session. Initiate a new session using the indicated method.
220 procState = "Session Initiator Error";
221 const IHandler* initiator=NULL;
222 if (requireSessionWith.first) {
223 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
225 throw ConfigurationException(
226 "No session initiator found with id ($1), check requireSessionWith command.",
227 params(1,requireSessionWith.second)
231 initiator=m_priv->m_app->getDefaultSessionInitiator();
233 throw ConfigurationException("No default session initiator found, check configuration.");
236 return initiator->run(this,false);
239 procState = "Session Processing Error";
241 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
244 m_remote_addr.c_str()
246 // Make a localized exception throw if the session isn't valid.
247 if (!m_priv->m_cacheEntry)
248 throw InvalidSessionException("Session no longer valid.");
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.
262 SAMLException* base = &e;
263 RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
265 // Session is invalid but we can retry -- initiate a new session.
266 procState = "Session Initiator Error";
267 const IHandler* initiator=NULL;
268 if (requireSessionWith.first) {
269 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
271 throw ConfigurationException(
272 "No session initiator found with id ($1), check requireSessionWith command.",
273 params(1,requireSessionWith.second)
277 initiator=m_priv->m_app->getDefaultSessionInitiator();
279 throw ConfigurationException("No default session initiator found, check configuration.");
281 return initiator->run(this,false);
283 throw; // send it to the outer handler
286 // We're done. Everything is okay. Nothing to report. Nothing to do..
287 // Let the caller decide how to proceed.
288 log(LogLevelDebug, "doCheckAuthN succeeded");
289 return pair<bool,void*>(false,NULL);
291 catch (SAMLException& e) {
296 mlp.insert("errorText", "Caught an unknown exception.");
300 // If we get here then we've got an error.
301 mlp.insert("errorType", procState);
303 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
305 return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
308 pair<bool,void*> ShibTarget::doHandler(void)
311 saml::NDC ndc("doHandler");
314 const char* procState = "Shibboleth Handler Error";
315 const char* targetURL = m_url.c_str();
320 throw ConfigurationException("System uninitialized, application did not supply request information.");
322 string hURL = getHandlerURL(targetURL);
323 const char* handlerURL=hURL.c_str();
325 throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
327 // Make sure we only process handler requests.
328 if (!strstr(targetURL,handlerURL))
329 return pair<bool,void*>(true, returnDecline());
331 const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
333 throw ConfigurationException("Unable to map request to application session settings, check configuration.");
335 // Process incoming request.
336 pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
338 // Make sure this is SSL, if it should be
339 if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
340 throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
342 // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
343 // so the path info is the next character (or null).
344 const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
346 throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
348 if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService)))
349 procState = "Session Creation Error";
350 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator)))
351 procState = "Session Initiator Error";
352 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService)))
353 procState = "Session Termination Error";
354 else if (saml::XML::isElementNamed(handler->getProperties()->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService)))
355 procState = "Diagnostics Error";
357 procState = "Extension Service Error";
358 pair<bool,void*> hret=handler->run(this);
360 // Did the handler run successfully?
364 throw SAMLException("Configured Shibboleth handler failed to process the request.");
366 catch (MetadataException& e) {
368 // See if a metadata error page is installed.
369 const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
371 pair<bool,const char*> p=props->getString("metadata");
373 mlp.insert("errorType", procState);
375 mlp.insert("requestURL", targetURL);
376 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
380 catch (SAMLException& e) {
385 mlp.insert("errorText", "Caught an unknown exception.");
389 // If we get here then we've got an error.
390 mlp.insert("errorType", procState);
393 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
395 return make_pair(true,m_priv->sendError(this,"session", mlp));
398 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
401 saml::NDC ndc("doCheckAuthZ");
405 const char* procState = "Authorization Processing Error";
406 const char* targetURL = m_url.c_str();
410 throw ConfigurationException("System uninitialized, application did not supply request information.");
412 // Three settings dictate how to proceed.
413 pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
414 pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
415 pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
417 // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
418 // then we ignore this request and consider it unprotected. Apache might lie to us if
419 // ShibBasicHijack is on, but that's up to it.
420 if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
421 #ifdef HAVE_STRCASECMP
422 (!authType.first || strcasecmp(authType.second,"shibboleth")))
424 (!authType.first || _stricmp(authType.second,"shibboleth")))
426 return pair<bool,void*>(true,returnDecline());
428 // Do we have an access control plugin?
429 if (m_priv->m_settings.second) {
431 if (!m_priv->m_cacheEntry) {
432 // No data yet, so we may need to try and get the session.
433 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
434 const char *session_id = getCookie(shib_cookie.first);
436 if (session_id && *session_id) {
437 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
440 m_remote_addr.c_str()
444 catch (SAMLException&) {
445 log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
449 Locker acllock(m_priv->m_settings.second);
450 if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
451 // Let the caller decide how to proceed.
452 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
453 return pair<bool,void*>(false,NULL);
456 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
458 mlp.insert("requestURL", targetURL);
459 return make_pair(true,m_priv->sendError(this, "access", mlp));
463 return make_pair(true,returnDecline());
465 catch (SAMLException& e) {
470 mlp.insert("errorText", "Caught an unknown exception.");
474 // If we get here then we've got an error.
475 mlp.insert("errorType", procState);
478 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
480 return make_pair(true,m_priv->sendError(this, "access", mlp));
483 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
486 saml::NDC ndc("doExportAssertions");
490 const char* procState = "Attribute Processing Error";
491 const char* targetURL = m_url.c_str();
495 throw ConfigurationException("System uninitialized, application did not supply request information.");
497 if (!m_priv->m_cacheEntry) {
498 // No data yet, so we need to get the session. This can only happen
499 // if the call to doCheckAuthn doesn't happen in the same object lifetime.
500 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
501 const char *session_id = getCookie(shib_cookie.first);
503 if (session_id && *session_id) {
504 m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
507 m_remote_addr.c_str()
511 catch (SAMLException&) {
512 log(LogLevelError, "unable to obtain session information to export into request headers");
513 // If we have to have a session, then this is a fatal error.
520 if (!m_priv->m_cacheEntry) {
522 throw InvalidSessionException("Unable to obtain session information for request.");
524 return pair<bool,void*>(false,NULL); // just bail silently
527 // Extract data from session.
528 pair<const char*,const SAMLSubject*> sub=m_priv->m_cacheEntry->getSubject(false,true);
529 pair<const char*,const SAMLResponse*> unfiltered=m_priv->m_cacheEntry->getTokens(true,false);
530 pair<const char*,const SAMLResponse*> filtered=m_priv->m_cacheEntry->getTokens(false,true);
532 // Maybe export the tokens.
533 pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
534 if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
536 XMLByte* serialized =
537 Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);
539 for (pos=serialized, pos2=serialized; *pos2; pos2++)
543 setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
544 XMLString::release(&serialized);
547 // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
548 setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
549 setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
550 setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
552 // Get the AAP providers, which contain the attribute policy info.
553 Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
556 while (provs.hasNext()) {
557 IAAP* aap=provs.next();
559 const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
560 const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
561 if (rule && rule->getHeader()) {
562 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
563 auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());
564 setHeader("Shib-NameIdentifier-Format", form.get());
565 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
566 setRemoteUser(nameid.get());
568 setHeader(rule->getHeader(), nameid.get());
572 setHeader("Shib-Application-ID", m_priv->m_app->getId());
574 // Export the attributes.
575 Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));
576 while (a_iter.hasNext()) {
577 SAMLAssertion* assert=a_iter.next();
578 Iterator<SAMLStatement*> statements=assert->getStatements();
579 while (statements.hasNext()) {
580 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
583 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
584 while (attrs.hasNext()) {
585 SAMLAttribute* attr=attrs.next();
587 // Are we supposed to export it?
589 while (provs.hasNext()) {
590 IAAP* aap=provs.next();
592 const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
593 if (!rule || !rule->getHeader())
596 Iterator<string> vals=attr->getSingleByteValues();
597 if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
598 setRemoteUser(vals.next());
601 string header = getHeader(rule->getHeader());
604 for (; vals.hasNext(); it++) {
605 string value = vals.next();
606 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
608 pos = value.find_first_of(";", pos)) {
609 value.insert(pos, "\\");
616 setHeader(rule->getHeader(), header);
623 return pair<bool,void*>(false,NULL);
625 catch (SAMLException& e) {
630 mlp.insert("errorText", "Caught an unknown exception.");
634 // If we get here then we've got an error.
635 mlp.insert("errorType", procState);
638 mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
640 return make_pair(true,m_priv->sendError(this, "rm", mlp));
643 const char* ShibTarget::getRequestParameter(const char* param, size_t index) const
645 if (!m_priv->m_cgiParser)
646 m_priv->m_cgiParser=new CgiParse(this);
648 pair<CgiParse::walker,CgiParse::walker> bounds=m_priv->m_cgiParser->get_values(param);
650 // Advance to the right index.
651 while (index && bounds.first!=bounds.second) {
656 return (bounds.first==bounds.second) ? NULL : bounds.first->second;
659 const char* ShibTarget::getCookie(const string& name) const
661 if (m_priv->m_cookieMap.empty()) {
662 string cookies=getCookies();
664 string::size_type pos=0,cname,namelen,val,vallen;
665 while (pos !=string::npos && pos < cookies.length()) {
666 while (isspace(cookies[pos])) pos++;
668 pos=cookies.find_first_of("=",pos);
669 if (pos == string::npos)
673 if (pos==cookies.length())
676 pos=cookies.find_first_of(";",pos);
677 if (pos != string::npos) {
680 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
683 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
686 map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
687 return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
690 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
692 static const char* defProps="; path=/";
694 const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
696 pair<bool,const char*> p=props->getString("cookieProps");
699 pair<bool,const char*> p2=props->getString("cookieName");
701 return make_pair(string(prefix) + p2.second,p.second);
702 return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
705 // Shouldn't happen, but just in case..
706 return pair<string,const char*>(prefix,defProps);
709 string ShibTarget::getHandlerURL(const char* resource) const
711 if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
712 return m_priv->m_handlerURL;
715 throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
718 const char* handler=NULL;
719 const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
721 pair<bool,bool> p=props->getBool("handlerSSL");
724 pair<bool,const char*> p2=props->getString("handlerURL");
729 // Should never happen...
730 if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
731 throw ConfigurationException(
732 "Invalid handlerURL property ($1) in Application ($2)",
733 params(2, handler ? handler : "null", m_priv->m_app->getId())
736 // The "handlerURL" property can be in one of three formats:
738 // 1) a full URI: http://host/foo/bar
739 // 2) a hostless URI: http:///foo/bar
740 // 3) a relative path: /foo/bar
742 // # Protocol Host Path
743 // 1 handler handler handler
744 // 2 handler resource handler
745 // 3 resource resource handler
747 // note: if ssl_only is true, make sure the protocol is https
749 const char* path = NULL;
751 // Decide whether to use the handler or the resource for the "protocol"
753 if (*handler != '/') {
761 // break apart the "protocol" string into protocol, host, and "the rest"
762 const char* colon=strchr(prot,':');
764 const char* slash=strchr(colon,'/');
768 // Compute the actual protocol and store in member.
770 m_priv->m_handlerURL.assign("https://");
772 m_priv->m_handlerURL.assign(prot, colon-prot);
774 // create the "host" from either the colon/slash or from the target string
775 // If prot == handler then we're in either #1 or #2, else #3.
776 // If slash == colon then we're in #2.
777 if (prot != handler || slash == colon) {
778 colon = strchr(resource, ':');
779 colon += 3; // Get past the ://
780 slash = strchr(colon, '/');
782 string host(colon, (slash ? slash-colon : strlen(colon)));
784 // Build the handler URL
785 m_priv->m_handlerURL+=host + path;
786 return m_priv->m_handlerURL;
789 void ShibTarget::log(ShibLogLevel level, const string& msg)
791 Category::getInstance("shibtarget.ShibTarget").log(
792 (level == LogLevelDebug ? Priority::DEBUG :
793 (level == LogLevelInfo ? Priority::INFO :
794 (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
799 const IApplication* ShibTarget::getApplication() const
801 return m_priv->m_app;
804 const IConfig* ShibTarget::getConfig() const
806 return m_priv->m_conf;
809 void* ShibTarget::returnDecline(void)
814 void* ShibTarget::returnOK(void)
819 static char x2c(char *what)
823 digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
825 digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
829 void ShibTarget::url_decode(char* s)
833 for(x=0,y=0;s[y];++x,++y)
835 if((s[x] = s[y]) == '%')
844 static inline char hexchar(unsigned short s)
846 return (s<=9) ? ('0' + s) : ('A' + s - 10);
849 string ShibTarget::url_encode(const char* s)
851 static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
855 if (strchr(badchars,*s) || *s<=0x20 || *s>=0x7F) {
857 ret+=hexchar(*s >> 4);
858 ret+=hexchar(*s & 0x0F);
866 /*************************************************************************
867 * Shib Target Private implementation
870 ShibTargetPriv::ShibTargetPriv()
871 : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL), m_cgiParser(NULL) {}
873 ShibTargetPriv::~ShibTargetPriv()
876 m_cacheEntry->unlock();
895 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
900 // XXX: Do we need to keep conf and mapper locked while we hold m_app?
901 // TODO: No, should be able to hold the conf but release the mapper.
903 // We lock the configuration system for the duration.
904 m_conf=m_Config->getINI();
907 // Map request to application and content settings.
908 m_mapper=m_conf->getRequestMapper();
911 // Obtain the application settings from the parsed URL
912 m_settings = m_mapper->getSettings(st);
914 // Now find the application from the URL settings
915 pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
916 m_app=m_conf->getApplication(application_id.second);
922 throw ConfigurationException("Unable to map request to application settings, check configuration.");
925 // Compute the full target URL
926 st->m_url = protocol + "://" + hostname;
927 if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
928 ostringstream portstr;
930 st->m_url += ":" + portstr.str();
935 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
937 ShibTarget::header_t hdrs[] = {
938 ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
939 ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
942 const IPropertySet* props=m_app->getPropertySet("Errors");
944 pair<bool,const char*> p=props->getString(page);
946 ifstream infile(p.second);
947 if (!infile.fail()) {
948 const char* res = mlp.run(infile,props);
950 return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
953 else if (!strcmp(page,"access"))
954 return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
957 string errstr = string("sendError could not process error template (") + page + ") for application (";
958 errstr += m_app->getId();
960 st->log(ShibTarget::LogLevelError, errstr);
962 "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
966 void ShibTargetPriv::clearHeaders(ShibTarget* st)
968 // Clear invariant stuff.
969 st->clearHeader("Shib-Origin-Site");
970 st->clearHeader("Shib-Identity-Provider");
971 st->clearHeader("Shib-Authentication-Method");
972 st->clearHeader("Shib-NameIdentifier-Format");
973 st->clearHeader("Shib-Attributes");
974 st->clearHeader("Shib-Application-ID");
976 // Clear out the list of mapped attributes
977 Iterator<IAAP*> provs=m_app->getAAPProviders();
978 while (provs.hasNext()) {
979 IAAP* aap=provs.next();
981 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
982 while (rules.hasNext()) {
983 const char* header=rules.next()->getHeader();
985 st->clearHeader(header);
990 /*************************************************************************
991 * CGI Parser implementation
994 CgiParse::CgiParse(const ShibTarget* st)
996 const char* pch=NULL;
997 if (!strcmp(st->getRequestMethod(),"POST"))
998 pch=st->getRequestBody();
1000 pch=st->getQueryString();
1001 size_t cl=pch ? strlen(pch) : 0;
1007 value=fmakeword('&',&cl,&pch);
1009 ShibTarget::url_decode(value);
1010 name=makeword(value,'=');
1011 kvp_map.insert(pair<string,char*>(name,value));
1016 CgiParse::~CgiParse()
1018 for (multimap<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1022 pair<CgiParse::walker,CgiParse::walker> CgiParse::get_values(const char* name) const
1024 return kvp_map.equal_range(name);
1027 /* Parsing routines modified from NCSA source. */
1028 char* CgiParse::makeword(char *line, char stop)
1031 char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1033 for(x=0;((line[x]) && (line[x] != stop));x++)
1042 line[y++] = line[x++];
1047 char* CgiParse::fmakeword(char stop, size_t *cl, const char** ppch)
1055 word = (char *) malloc(sizeof(char) * (wsize + 1));
1059 word[ll] = *((*ppch)++);
1064 word = (char *)realloc(word,sizeof(char)*(wsize+1));
1067 if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1069 if(word[ll] != stop)
1078 void CgiParse::plustospace(char *str)
1083 if(str[x] == '+') str[x] = ' ';