Reworked profile handlers outside of core library.
[shibboleth/sp.git] / shib-target / shib-target.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
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.
22  *
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
28  *
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.
33  *
34  *
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.
48  */
49
50 /*
51  * shib-target.cpp -- The ShibTarget class, a superclass for general
52  *                    target code
53  *
54  * Created by:  Derek Atkins <derek@ihtfp.com>
55  *
56  * $Id$
57  */
58
59 #include "internal.h"
60
61 #ifdef HAVE_UNISTD_H
62 # include <unistd.h>
63 #endif
64
65 #include <sstream>
66 #include <fstream>
67 #include <stdexcept>
68
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>
74
75 #ifndef HAVE_STRCASECMP
76 # define strcasecmp stricmp
77 #endif
78
79 using namespace std;
80 using namespace saml;
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace log4cpp;
84
85 namespace shibtarget {
86   class ShibTargetPriv
87   {
88   public:
89     ShibTargetPriv();
90     ~ShibTargetPriv();
91
92     // Helper functions
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);
95     
96     // Handlers do the real Shibboleth work
97     pair<bool,void*> dispatch(
98         ShibTarget* st,
99         const IPropertySet* handler,
100         bool isHandler=true,
101         const char* forceType=NULL
102         ) const;
103
104   private:
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;
110
111     ISessionCacheEntry* m_cacheEntry;
112
113     ShibTargetConfig* m_Config;
114
115     IConfig* m_conf;
116     IRequestMapper* m_mapper;
117   };
118 }
119
120
121 /*************************************************************************
122  * Shib Target implementation
123  */
124
125 ShibTarget::ShibTarget(void) : m_priv(NULL)
126 {
127   m_priv = new ShibTargetPriv();
128 }
129
130 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
131 {
132   m_priv = new ShibTargetPriv();
133   m_priv->m_app = app;
134 }
135
136 ShibTarget::~ShibTarget(void)
137 {
138   if (m_priv) delete m_priv;
139 }
140
141 void ShibTarget::init(
142     const char* protocol,
143     const char* hostname,
144     int port,
145     const char* uri,
146     const char* content_type,
147     const char* remote_addr,
148     const char* method
149     )
150 {
151 #ifdef _DEBUG
152   saml::NDC ndc("init");
153 #endif
154
155   if (m_priv->m_app)
156     throw SAMLException("Request initialization occurred twice!");
157
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;
164   m_port = port;
165   m_priv->m_Config = &ShibTargetConfig::getConfig();
166   m_priv->get_application(this, protocol, hostname, port, uri);
167 }
168
169
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.
173
174 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
175 {
176 #ifdef _DEBUG
177     saml::NDC ndc("doCheckAuthN");
178 #endif
179
180     const char* procState = "Request Processing Error";
181     const char* targetURL = m_url.c_str();
182     ShibMLP mlp;
183
184     try {
185         if (!m_priv->m_app)
186             throw ConfigurationException("System uninitialized, application did not supply request information.");
187
188         string hURL = getHandlerURL(targetURL);
189         const char* handlerURL=hURL.c_str();
190         if (!handlerURL)
191             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
192
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)) {
196             if (handler)
197                 return doHandler();
198             else
199                 return pair<bool,void*>(true, returnOK());
200         }
201
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");
206
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")))
213 #else
214                 (!authType.first || stricmp(authType.second,"shibboleth")))
215 #endif
216             return pair<bool,void*>(true,returnDecline());
217
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());
224
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);
230             if (!initiator)
231                 initiator=m_priv->m_app->getDefaultSessionInitiator();
232             
233             // Standard handler element, so we dispatch normally.
234             if (initiator)
235                 return m_priv->dispatch(this,initiator,false);
236             else {
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());
240             }
241         }
242
243         procState = "Session Processing Error";
244         try {
245             // Localized exception throw if the session isn't valid.
246             m_priv->m_conf->getListener()->sessionGet(
247                 m_priv->m_app,
248                 session_id,
249                 m_remote_addr.c_str(),
250                 &m_priv->m_cacheEntry
251                 );
252         }
253         catch (SAMLException& e) {
254             log(LogLevelError, string("session processing failed: ") + e.what());
255
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());
263
264             // Try and cast down. This should throw an exception if it fails.
265             bool retryable=false;
266             try {
267                 RetryableProfileException& trycast=dynamic_cast<RetryableProfileException&>(e);
268                 retryable=true;
269             }
270             catch (exception&) {
271             }
272             if (retryable) {
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);
278                 if (!initiator)
279                     initiator=m_priv->m_app->getDefaultSessionInitiator();
280                 // Standard handler element, so we dispatch normally.
281                 if (initiator)
282                     return m_priv->dispatch(this,initiator,false);
283                 else {
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());
287                 }
288             }
289             throw;    // send it to the outer handler
290         }
291
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);
296     }
297     catch (SAMLException& e) {
298         mlp.insert(e);
299     }
300 #ifndef _DEBUG
301     catch (...) {
302         mlp.insert("errorText", "Caught an unknown exception.");
303     }
304 #endif
305
306     // If we get here then we've got an error.
307     mlp.insert("errorType", procState);
308     if (targetURL)
309         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
310
311     return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
312 }
313
314 pair<bool,void*> ShibTarget::doHandler(void)
315 {
316 #ifdef _DEBUG
317     saml::NDC ndc("doHandler");
318 #endif
319
320     const char* procState = "Shibboleth Handler Error";
321     const char* targetURL = m_url.c_str();
322     ShibMLP mlp;
323
324     try {
325         if (!m_priv->m_app)
326             throw ConfigurationException("System uninitialized, application did not supply request information.");
327
328         string hURL = getHandlerURL(targetURL);
329         const char* handlerURL=hURL.c_str();
330         if (!handlerURL)
331             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
332
333         // Make sure we only process handler requests.
334         if (!strstr(targetURL,handlerURL))
335             return pair<bool,void*>(true, returnDecline());
336
337         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
338         if (!sessionProps)
339             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
340
341         // Process incoming request.
342         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
343       
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.");
347
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));
351         if (handler) {
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);
355             }
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);
359             }
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);
363             }
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);
367             }
368             else {
369                 procState = "Extension Service Error";
370                 return m_priv->dispatch(this,handler);
371             }
372         }
373         
374         if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
375             throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
376         
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());
384         }
385         
386         procState = "Session Creation Error";
387         auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
388         return m_priv->dispatch(this, sessionProps, true, binding.get());
389     }
390     catch (MetadataException& e) {
391         mlp.insert(e);
392         // See if a metadata error page is installed.
393         const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
394         if (props) {
395             pair<bool,const char*> p=props->getString("metadata");
396             if (p.first) {
397                 mlp.insert("errorType", procState);
398                 if (targetURL)
399                     mlp.insert("requestURL", targetURL);
400                 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
401             }
402         }
403     }
404     catch (SAMLException& e) {
405         mlp.insert(e);
406     }
407 #ifndef _DEBUG
408     catch (...) {
409         mlp.insert("errorText", "Caught an unknown exception.");
410     }
411 #endif
412
413     // If we get here then we've got an error.
414     mlp.insert("errorType", procState);
415
416     if (targetURL)
417         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
418
419     return make_pair(true,m_priv->sendError(this,"session", mlp));
420 }
421
422 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
423 {
424 #ifdef _DEBUG
425     saml::NDC ndc("doCheckAuthZ");
426 #endif
427
428     ShibMLP mlp;
429     const char* procState = "Authorization Processing Error";
430     const char* targetURL = m_url.c_str();
431
432     try {
433         if (!m_priv->m_app)
434             throw ConfigurationException("System uninitialized, application did not supply request information.");
435
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");
440
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")))
447 #else
448                 (!authType.first || stricmp(authType.second,"shibboleth")))
449 #endif
450             return pair<bool,void*>(true,returnDecline());
451
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);
459             }
460             else {
461                 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
462                 if (targetURL)
463                     mlp.insert("requestURL", targetURL);
464                 return make_pair(true,m_priv->sendError(this, "access", mlp));
465             }
466         }
467         else
468             return make_pair(true,returnDecline());
469     }
470     catch (SAMLException& e) {
471         mlp.insert(e);
472     }
473 #ifndef _DEBUG
474     catch (...) {
475         mlp.insert("errorText", "Caught an unknown exception.");
476     }
477 #endif
478
479     // If we get here then we've got an error.
480     mlp.insert("errorType", procState);
481
482     if (targetURL)
483         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
484
485     return make_pair(true,m_priv->sendError(this, "access", mlp));
486 }
487
488 pair<bool,void*> ShibTarget::doExportAssertions()
489 {
490 #ifdef _DEBUG
491     saml::NDC ndc("doExportAssertions");
492 #endif
493
494     ShibMLP mlp;
495     const char* procState = "Attribute Processing Error";
496     const char* targetURL = m_url.c_str();
497
498     try {
499         if (!m_priv->m_app)
500             throw ConfigurationException("System uninitialized, application did not supply request information.");
501
502         pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
503         const char *session_id = getCookie(shib_cookie.first);
504
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(
509                 m_priv->m_app,
510                 session_id,
511                 m_remote_addr.c_str(),
512                 &m_priv->m_cacheEntry
513                 );
514         }
515
516         // Get the AAP providers, which contain the attribute policy info.
517         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
518
519         // Clear out the list of mapped attributes
520         while (provs.hasNext()) {
521             IAAP* aap=provs.next();
522             Locker locker(aap);
523             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
524             while (rules.hasNext()) {
525                 const char* header=rules.next()->getHeader();
526                 if (header)
527                     clearHeader(header);
528             }
529         }
530         
531         ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
532
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) {
537             ostringstream os;
538             os << *cr.unfiltered;
539             unsigned int outlen;
540             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
541             XMLByte *pos, *pos2;
542             for (pos=serialized, pos2=serialized; *pos2; pos2++)
543                 if (isgraph(*pos2))
544                     *pos++=*pos2;
545             *pos=0;
546             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
547             XMLString::release(&serialized);
548         }
549     
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());
559         
560         // Export NameID?
561         provs.reset();
562         while (provs.hasNext()) {
563             IAAP* aap=provs.next();
564             Locker locker(aap);
565             const IAttributeRule* rule=aap->lookup(
566                 m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat()
567                 );
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());
574                 else
575                     setHeader(rule->getHeader(), nameid.get());
576             }
577         }
578         
579         clearHeader("Shib-Application-ID");
580         setHeader("Shib-Application-ID", m_priv->m_app->getId());
581     
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());
589                 if (!astate)
590                     continue;
591                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
592                 while (attrs.hasNext()) {
593                     SAMLAttribute* attr=attrs.next();
594             
595                     // Are we supposed to export it?
596                     provs.reset();
597                     while (provs.hasNext()) {
598                         IAAP* aap=provs.next();
599                         Locker locker(aap);
600                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
601                         if (!rule || !rule->getHeader())
602                             continue;
603                     
604                         Iterator<string> vals=attr->getSingleByteValues();
605                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
606                             setRemoteUser(vals.next());
607                         else {
608                             int it=0;
609                             string header = getHeader(rule->getHeader());
610                             if (!header.empty())
611                                 it++;
612                             for (; vals.hasNext(); it++) {
613                                 string value = vals.next();
614                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
615                                         pos != string::npos;
616                                         pos = value.find_first_of(";", pos)) {
617                                     value.insert(pos, "\\");
618                                     pos += 2;
619                                 }
620                                 if (it)
621                                     header += ";";
622                                 header += value;
623                             }
624                             setHeader(rule->getHeader(), header);
625                         }
626                     }
627                 }
628             }
629         }
630     
631         return pair<bool,void*>(false,NULL);
632     }
633     catch (SAMLException& e) {
634         mlp.insert(e);
635     }
636 #ifndef _DEBUG
637     catch (...) {
638         mlp.insert("errorText", "Caught an unknown exception.");
639     }
640 #endif
641
642     // If we get here then we've got an error.
643     mlp.insert("errorType", procState);
644
645     if (targetURL)
646         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
647
648     return make_pair(true,m_priv->sendError(this, "rm", mlp));
649 }
650
651 const char* ShibTarget::getCookie(const string& name) const
652 {
653     if (m_priv->m_cookieMap.empty()) {
654         string cookies=getCookies();
655
656         string::size_type pos=0,cname,namelen,val,vallen;
657         while (pos !=string::npos && pos < cookies.length()) {
658             while (isspace(cookies[pos])) pos++;
659             cname=pos;
660             pos=cookies.find_first_of("=",pos);
661             if (pos == string::npos)
662                 break;
663             namelen=pos-cname;
664             pos++;
665             if (pos==cookies.length())
666                 break;
667             val=pos;
668             pos=cookies.find_first_of(";",pos);
669             if (pos != string::npos) {
670                 vallen=pos-val;
671                 pos++;
672                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
673             }
674             else
675                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
676         }
677     }
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();
680 }
681
682 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
683 {
684     static const char* defProps="; path=/";
685     
686     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
687     if (props) {
688         pair<bool,const char*> p=props->getString("cookieProps");
689         if (!p.first)
690             p.second=defProps;
691         pair<bool,const char*> p2=props->getString("cookieName");
692         if (p2.first)
693             return make_pair(string(prefix) + p2.second,p.second);
694         return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
695     }
696     
697     // Shouldn't happen, but just in case..
698     return make_pair(prefix,defProps);
699 }
700
701 string ShibTarget::getHandlerURL(const char* resource) const
702 {
703     if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
704         return m_priv->m_handlerURL;
705         
706     if (!m_priv->m_app)
707         throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
708
709     bool ssl_only=false;
710     const char* handler=NULL;
711     const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
712     if (props) {
713         pair<bool,bool> p=props->getBool("handlerSSL");
714         if (p.first)
715             ssl_only=p.second;
716         pair<bool,const char*> p2=props->getString("handlerURL");
717         if (p2.first)
718             handler=p2.second;
719     }
720     
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())
726             );
727
728     // The "handlerURL" property can be in one of three formats:
729     //
730     // 1) a full URI:       http://host/foo/bar
731     // 2) a hostless URI:   http:///foo/bar
732     // 3) a relative path:  /foo/bar
733     //
734     // #  Protocol  Host        Path
735     // 1  handler   handler     handler
736     // 2  handler   resource    handler
737     // 3  resource  resource    handler
738     //
739     // note: if ssl_only is true, make sure the protocol is https
740
741     const char* path = NULL;
742
743     // Decide whether to use the handler or the resource for the "protocol"
744     const char* prot;
745     if (*handler != '/') {
746         prot = handler;
747     }
748     else {
749         prot = resource;
750         path = handler;
751     }
752
753     // break apart the "protocol" string into protocol, host, and "the rest"
754     const char* colon=strchr(prot,':');
755     colon += 3;
756     const char* slash=strchr(colon,'/');
757     if (!path)
758         path = slash;
759
760     // Compute the actual protocol and store in member.
761     if (ssl_only)
762         m_priv->m_handlerURL.assign("https://");
763     else
764         m_priv->m_handlerURL.assign(prot, colon-prot);
765
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, '/');
773     }
774     string host(colon, slash-colon);
775
776     // Build the handler URL
777     m_priv->m_handlerURL+=host + path;
778     return m_priv->m_handlerURL;
779 }
780
781 void ShibTarget::log(ShibLogLevel level, const string& msg)
782 {
783     Category::getInstance("shibtarget.ShibTarget").log(
784         (level == LogLevelDebug ? Priority::DEBUG :
785         (level == LogLevelInfo ? Priority::INFO :
786         (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
787         msg
788     );
789 }
790
791 const IApplication* ShibTarget::getApplication() const
792 {
793     return m_priv->m_app;
794 }
795
796 const IConfig* ShibTarget::getConfig() const
797 {
798     return m_priv->m_conf;
799 }
800
801 void* ShibTarget::returnDecline(void)
802 {
803     return NULL;
804 }
805
806 void* ShibTarget::returnOK(void)
807 {
808     return NULL;
809 }
810
811
812 /*************************************************************************
813  * Shib Target Private implementation
814  */
815
816 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL) {}
817
818 ShibTargetPriv::~ShibTargetPriv()
819 {
820     if (m_cacheEntry) {
821         m_cacheEntry->unlock();
822         m_cacheEntry = NULL;
823     }
824
825     if (m_mapper) {
826         m_mapper->unlock();
827         m_mapper = NULL;
828     }
829     
830     if (m_conf) {
831         m_conf->unlock();
832         m_conf = NULL;
833     }
834
835     m_app = NULL;
836     m_Config = NULL;
837 }
838
839 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
840 {
841   if (m_app)
842     return;
843
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.
846
847   // We lock the configuration system for the duration.
848   m_conf=m_Config->getINI();
849   m_conf->lock();
850     
851   // Map request to application and content settings.
852   m_mapper=m_conf->getRequestMapper();
853   m_mapper->lock();
854
855   // Obtain the application settings from the parsed URL
856   m_settings = m_mapper->getSettings(st);
857
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);
861   if (!m_app) {
862     m_mapper->unlock();
863     m_mapper = NULL;
864     m_conf->unlock();
865     m_conf = NULL;
866     throw ConfigurationException("Unable to map request to application settings, check configuration.");
867   }
868
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;
873   st->m_url += uri;
874 }
875
876 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
877 {
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")
881         };
882     
883     const IPropertySet* props=m_app->getPropertySet("Errors");
884     if (props) {
885         pair<bool,const char*> p=props->getString(page);
886         if (p.first) {
887             ifstream infile(p.second);
888             if (!infile.fail()) {
889                 const char* res = mlp.run(infile,props);
890                 if (res)
891                     return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
892             }
893         }
894         else if (!strcmp(page,"access"))
895             return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
896     }
897
898     string errstr = string("sendError could not process error template (") + page + ") for application (";
899     errstr += m_app->getId();
900     errstr += ")";
901     st->log(ShibTarget::LogLevelError, errstr);
902     return st->sendPage(
903         "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
904         );
905 }
906
907 pair<bool,void*> ShibTargetPriv::dispatch(
908     ShibTarget* st,
909     const IPropertySet* config,
910     bool isHandler,
911     const char* forceType
912     ) const
913 {
914     pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
915     if (binding.first) {
916         auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
917         IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
918         if (!handler)
919             throw UnsupportedProfileException(
920                 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
921                 );
922         return handler->run(st,config,isHandler);
923     }
924     throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");
925 }