Fix for jsessionid bug.
[shibboleth/cpp-sp.git] / shib-target / shib-target.cpp
1 /*
2  *  Copyright 2001-2005 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /*
18  * shib-target.cpp -- The ShibTarget class, a superclass for general
19  *                    target code
20  *
21  * Created by:  Derek Atkins <derek@ihtfp.com>
22  *
23  * $Id$
24  */
25
26 #include "internal.h"
27
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31
32 #include <sstream>
33 #include <fstream>
34 #include <stdexcept>
35
36 #include <shib/shib-threads.h>
37 #include <xercesc/util/Base64.hpp>
38
39 #ifndef HAVE_STRCASECMP
40 # define strcasecmp stricmp
41 #endif
42
43 using namespace shibtarget::logging;
44 using namespace shibtarget;
45 using namespace shibboleth;
46 using namespace saml;
47 using namespace std;
48
49 namespace shibtarget {
50   class ShibTargetPriv
51   {
52   public:
53     ShibTargetPriv();
54     ~ShibTargetPriv();
55
56     // Helper functions
57     void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
58     void* sendError(ShibTarget* st, const char* page, ShibMLP &mlp);
59     void clearHeaders(ShibTarget* st);
60     
61     // Handlers do the real Shibboleth work
62     pair<bool,void*> dispatch(
63         ShibTarget* st,
64         const IPropertySet* handler,
65         bool isHandler=true,
66         const char* forceType=NULL
67         ) const;
68
69   private:
70     friend class ShibTarget;
71     IRequestMapper::Settings m_settings;
72     const IApplication *m_app;
73     mutable string m_handlerURL;
74     mutable map<string,string> m_cookieMap;
75
76     ISessionCacheEntry* m_cacheEntry;
77
78     ShibTargetConfig* m_Config;
79
80     IConfig* m_conf;
81     IRequestMapper* m_mapper;
82   };
83 }
84
85
86 /*************************************************************************
87  * Shib Target implementation
88  */
89
90 static char _x2c(const char *what)
91 {
92     register char digit;
93
94     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
95     digit *= 16;
96     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
97     return(digit);
98 }
99
100 ShibTarget::ShibTarget(void) : m_priv(NULL)
101 {
102   m_priv = new ShibTargetPriv();
103 }
104
105 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
106 {
107   m_priv = new ShibTargetPriv();
108   m_priv->m_app = app;
109 }
110
111 ShibTarget::~ShibTarget(void)
112 {
113   if (m_priv) delete m_priv;
114 }
115
116 void ShibTarget::init(
117     const char* protocol,
118     const char* hostname,
119     int port,
120     const char* uri,
121     const char* content_type,
122     const char* remote_addr,
123     const char* method
124     )
125 {
126 #ifdef _DEBUG
127     saml::NDC ndc("init");
128 #endif
129
130     if (m_priv->m_app)
131         throw SAMLException("Request initialization occurred twice!");
132
133     if (method) m_method = method;
134     if (protocol) m_protocol = protocol;
135     if (hostname) m_hostname = hostname;
136     if (content_type) m_content_type = content_type;
137     if (remote_addr) m_remote_addr = remote_addr;
138     m_port = port;
139   
140     // Fix for bug 574, secadv 20061002
141     // Unescape URI up to query string delimiter by looking for %XX escapes.
142     // Adapted from Apache's util.c, ap_unescape_url function.
143     if (uri) {
144         while (*uri) {
145             if (*uri == '?') {
146                 m_uri += uri;
147                 break;
148             }
149             else if (*uri == ';') {
150                 // If this is Java being stupid, skip everything up to the query string, if any.
151                 if (!strncmp(uri, ";jsessionid=", 12)) {
152                     if (uri = strchr(uri, '?'))
153                         m_uri += uri;
154                     break;
155                 }
156                 else {
157                     m_uri += *uri;
158                 }
159             }
160             else if (*uri != '%') {
161                 m_uri += *uri;
162             }
163             else {
164                 ++uri;
165                 if (!isxdigit(*uri) || !isxdigit(*(uri+1)))
166                     throw SAMLException("Bad request, contained unsupported encoded characters.");
167                 m_uri += _x2c(uri);
168                 ++uri;
169             }
170             ++uri;
171         }
172     }
173
174     m_priv->m_Config = &ShibTargetConfig::getConfig();
175     m_priv->get_application(this, protocol, hostname, port, m_uri);
176 }
177
178
179 // These functions implement the server-agnostic shibboleth engine
180 // The web server modules implement a subclass and then call into 
181 // these methods once they instantiate their request object.
182
183 pair<bool,void*> ShibTarget::doCheckAuthN(bool handler)
184 {
185 #ifdef _DEBUG
186     saml::NDC ndc("doCheckAuthN");
187 #endif
188
189     const char* procState = "Request Processing Error";
190     const char* targetURL = m_url.c_str();
191     ShibMLP mlp;
192
193     try {
194         if (!m_priv->m_app)
195             throw ConfigurationException("System uninitialized, application did not supply request information.");
196
197         // If not SSL, check to see if we should block or redirect it.
198         if (!strcmp("http",getProtocol())) {
199             pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
200             if (redirectToSSL.first) {
201                 if (!strcasecmp("GET",getRequestMethod()) || !strcasecmp("HEAD",getRequestMethod())) {
202                     // Compute the new target URL
203                     string redirectURL = string("https://") + getHostname();
204                     if (strcmp(redirectToSSL.second,"443")) {
205                         redirectURL = redirectURL + ':' + redirectToSSL.second;
206                     }
207                     redirectURL += getRequestURI();
208                     return make_pair(true, sendRedirect(redirectURL));
209                 }
210                 else {
211                     mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
212                     return make_pair(true,m_priv->sendError(this,"ssl", mlp));
213                 }
214             }
215         }
216         
217         string hURL = getHandlerURL(targetURL);
218         const char* handlerURL=hURL.c_str();
219         if (!handlerURL)
220             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
221
222         // If the request URL contains the handler base URL for this application, either dispatch
223         // directly (mainly Apache 2.0) or just pass back control.
224         if (strstr(targetURL,handlerURL)) {
225             if (handler)
226                 return doHandler();
227             else
228                 return pair<bool,void*>(true, returnOK());
229         }
230
231         // Three settings dictate how to proceed.
232         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
233         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
234         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
235
236         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
237         // then we ignore this request and consider it unprotected. Apache might lie to us if
238         // ShibBasicHijack is on, but that's up to it.
239         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
240 #ifdef HAVE_STRCASECMP
241                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
242 #else
243                 (!authType.first || stricmp(authType.second,"shibboleth")))
244 #endif
245             return pair<bool,void*>(true,returnDecline());
246
247         // Fix for secadv 20050901
248         m_priv->clearHeaders(this);
249
250         pair<string,const char*> shib_cookie = getCookieNameProps("_shibsession_");
251         const char* session_id = getCookie(shib_cookie.first);
252         if (!session_id || !*session_id) {
253             // No session.  Maybe that's acceptable?
254             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
255                 return pair<bool,void*>(true,returnOK());
256
257             // No cookie, but we require a session. Initiate a new session using the indicated method.
258             procState = "Session Initiator Error";
259             const IPropertySet* initiator=NULL;
260             if (requireSessionWith.first)
261                 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
262             if (!initiator)
263                 initiator=m_priv->m_app->getDefaultSessionInitiator();
264             
265             // Standard handler element, so we dispatch normally.
266             if (initiator)
267                 return m_priv->dispatch(this,initiator,false);
268             else {
269                 // Legacy config support maps the Sessions element to the Shib profile.
270                 auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
271                 return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
272             }
273         }
274
275         procState = "Session Processing Error";
276         try {
277             // Localized exception throw if the session isn't valid.
278             m_priv->m_conf->getListener()->sessionGet(
279                 m_priv->m_app,
280                 session_id,
281                 m_remote_addr.c_str(),
282                 &m_priv->m_cacheEntry
283                 );
284         }
285         catch (SAMLException& e) {
286             log(LogLevelError, string("session processing failed: ") + e.what());
287
288             // If no session is required, bail now.
289             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
290                 // Has to be OK because DECLINED will just cause Apache
291                 // to fail when it can't locate anything to process the
292                 // AuthType.  No session plus requireSession false means
293                 // do not authenticate the user at this time.
294                 return pair<bool,void*>(true, returnOK());
295
296             // Try and cast down.
297             SAMLException* base = &e;
298             RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
299             if (trycast) {
300                 // Session is invalid but we can retry -- initiate a new session.
301                 procState = "Session Initiator Error";
302                 const IPropertySet* initiator=NULL;
303                 if (requireSessionWith.first)
304                     initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
305                 if (!initiator)
306                     initiator=m_priv->m_app->getDefaultSessionInitiator();
307                 // Standard handler element, so we dispatch normally.
308                 if (initiator)
309                     return m_priv->dispatch(this,initiator,false);
310                 else {
311                     // Legacy config support maps the Sessions element to the Shib profile.
312                     auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
313                     return m_priv->dispatch(this, m_priv->m_app->getPropertySet("Sessions"), false, binding.get());
314                 }
315             }
316             throw;    // send it to the outer handler
317         }
318
319         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
320         // Let the caller decide how to proceed.
321         log(LogLevelDebug, "doCheckAuthN succeeded");
322         return pair<bool,void*>(false,NULL);
323     }
324     catch (SAMLException& e) {
325         log(LogLevelError, e.what());
326         mlp.insert(e);
327     }
328     catch (exception& e) {
329         log(LogLevelError, e.what());
330         mlp.insert("errorText", e.what());
331     }
332
333     // If we get here then we've got an error.
334     mlp.insert("errorType", procState);
335     if (targetURL)
336         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
337
338     return pair<bool,void*>(true,m_priv->sendError(this,"session", mlp));
339 }
340
341 pair<bool,void*> ShibTarget::doHandler(void)
342 {
343 #ifdef _DEBUG
344     saml::NDC ndc("doHandler");
345 #endif
346
347     const char* procState = "Shibboleth Handler Error";
348     const char* targetURL = m_url.c_str();
349     ShibMLP mlp;
350
351     try {
352         if (!m_priv->m_app)
353             throw ConfigurationException("System uninitialized, application did not supply request information.");
354
355         string hURL = getHandlerURL(targetURL);
356         const char* handlerURL=hURL.c_str();
357         if (!handlerURL)
358             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
359
360         // Make sure we only process handler requests.
361         if (!strstr(targetURL,handlerURL))
362             return pair<bool,void*>(true, returnDecline());
363
364         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
365         if (!sessionProps)
366             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
367
368         // Process incoming request.
369         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
370       
371         // Make sure this is SSL, if it should be
372         if ((!handlerSSL.first || handlerSSL.second) && m_protocol != "https")
373             throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
374
375         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
376         // so the path info is the next character (or null).
377         const IPropertySet* handler=m_priv->m_app->getHandlerConfig(targetURL + strlen(handlerURL));
378         if (handler) {
379             if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(AssertionConsumerService))) {
380                 procState = "Session Creation Error";
381                 return m_priv->dispatch(this,handler);
382             }
383             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(SessionInitiator))) {
384                 procState = "Session Initiator Error";
385                 return m_priv->dispatch(this,handler);
386             }
387             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SAML2META_NS,SHIBT_L(SingleLogoutService))) {
388                 procState = "Session Termination Error";
389                 return m_priv->dispatch(this,handler);
390             }
391             else if (saml::XML::isElementNamed(handler->getElement(),shibtarget::XML::SHIBTARGET_NS,SHIBT_L(DiagnosticService))) {
392                 procState = "Diagnostics Error";
393                 return m_priv->dispatch(this,handler);
394             }
395             else {
396                 procState = "Extension Service Error";
397                 return m_priv->dispatch(this,handler);
398             }
399         }
400         
401         if (strlen(targetURL)>strlen(handlerURL) && targetURL[strlen(handlerURL)]!='?')
402             throw SAMLException("Shibboleth handler invoked at an unconfigured location.");
403         
404         // This is a legacy direct execution of the handler (the old shireURL).
405         // If this is a GET, we see if it's a lazy session request, otherwise
406         // assume it's a SAML 1.x POST profile response and process it.
407         if (!strcasecmp(m_method.c_str(), "GET")) {
408             procState = "Session Initiator Error";
409             auto_ptr_char binding(Constants::SHIB_SESSIONINIT_PROFILE_URI);
410             return m_priv->dispatch(this, sessionProps, true, binding.get());
411         }
412         
413         procState = "Session Creation Error";
414         auto_ptr_char binding(SAMLBrowserProfile::BROWSER_POST);
415         return m_priv->dispatch(this, sessionProps, true, binding.get());
416     }
417     catch (MetadataException& e) {
418         log(LogLevelError, e.what());
419         mlp.insert(e);
420         // See if a metadata error page is installed.
421         const IPropertySet* props=m_priv->m_app->getPropertySet("Errors");
422         if (props) {
423             pair<bool,const char*> p=props->getString("metadata");
424             if (p.first) {
425                 mlp.insert("errorType", procState);
426                 if (targetURL)
427                     mlp.insert("requestURL", targetURL);
428                 return make_pair(true,m_priv->sendError(this,"metadata", mlp));
429             }
430         }
431     }
432     catch (SAMLException& e) {
433         log(LogLevelError, e.what());
434         mlp.insert(e);
435     }
436     catch (exception& e) {
437         log(LogLevelError, e.what());
438         mlp.insert("errorText", e.what());
439     }
440
441     // If we get here then we've got an error.
442     mlp.insert("errorType", procState);
443
444     if (targetURL)
445         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
446
447     return make_pair(true,m_priv->sendError(this,"session", mlp));
448 }
449
450 pair<bool,void*> ShibTarget::doCheckAuthZ(void)
451 {
452 #ifdef _DEBUG
453     saml::NDC ndc("doCheckAuthZ");
454 #endif
455
456     ShibMLP mlp;
457     const char* procState = "Authorization Processing Error";
458     const char* targetURL = m_url.c_str();
459
460     try {
461         if (!m_priv->m_app)
462             throw ConfigurationException("System uninitialized, application did not supply request information.");
463
464         // Three settings dictate how to proceed.
465         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
466         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
467         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
468
469         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
470         // then we ignore this request and consider it unprotected. Apache might lie to us if
471         // ShibBasicHijack is on, but that's up to it.
472         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
473 #ifdef HAVE_STRCASECMP
474                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
475 #else
476                 (!authType.first || stricmp(authType.second,"shibboleth")))
477 #endif
478             return pair<bool,void*>(true,returnDecline());
479
480         // Do we have an access control plugin?
481         if (m_priv->m_settings.second) {
482                 
483                 if (!m_priv->m_cacheEntry) {
484                     // No data yet, so we may need to try and get the session.
485                         pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
486                         const char *session_id = getCookie(shib_cookie.first);
487                     try {
488                                 if (session_id && *session_id) {
489                                     m_priv->m_conf->getListener()->sessionGet(
490                                         m_priv->m_app,
491                                         session_id,
492                                         m_remote_addr.c_str(),
493                                         &m_priv->m_cacheEntry
494                                         );
495                                 }
496                     }
497                     catch (SAMLException&) {
498                         log(LogLevelError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
499                     }
500                 }
501         
502             Locker acllock(m_priv->m_settings.second);
503             if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
504                 // Let the caller decide how to proceed.
505                 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
506                 return pair<bool,void*>(false,NULL);
507             }
508             else {
509                 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
510                 if (targetURL)
511                     mlp.insert("requestURL", targetURL);
512                 return make_pair(true,m_priv->sendError(this, "access", mlp));
513             }
514         }
515         else
516             return make_pair(true,returnDecline());
517     }
518     catch (SAMLException& e) {
519         log(LogLevelError, e.what());
520         mlp.insert(e);
521     }
522     catch (exception& e) {
523         log(LogLevelError, e.what());
524         mlp.insert("errorText", e.what());
525     }
526
527     // If we get here then we've got an error.
528     mlp.insert("errorType", procState);
529
530     if (targetURL)
531         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
532
533     return make_pair(true,m_priv->sendError(this, "access", mlp));
534 }
535
536 pair<bool,void*> ShibTarget::doExportAssertions(bool requireSession)
537 {
538 #ifdef _DEBUG
539     saml::NDC ndc("doExportAssertions");
540 #endif
541
542     ShibMLP mlp;
543     const char* procState = "Attribute Processing Error";
544     const char* targetURL = m_url.c_str();
545
546     try {
547         if (!m_priv->m_app)
548             throw ConfigurationException("System uninitialized, application did not supply request information.");
549
550         if (!m_priv->m_cacheEntry) {
551             // No data yet, so we need to get the session. This can only happen
552             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
553                 pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
554                 const char *session_id = getCookie(shib_cookie.first);
555             try {
556                         if (session_id && *session_id) {
557                             m_priv->m_conf->getListener()->sessionGet(
558                                 m_priv->m_app,
559                                 session_id,
560                                 m_remote_addr.c_str(),
561                                 &m_priv->m_cacheEntry
562                                 );
563                         }
564             }
565             catch (SAMLException&) {
566                 log(LogLevelError, "unable to obtain session information to export into request headers");
567                 // If we have to have a session, then this is a fatal error.
568                 if (requireSession)
569                         throw;
570             }
571         }
572
573                 // Still no data?
574         if (!m_priv->m_cacheEntry) {
575                 if (requireSession)
576                         throw InvalidSessionException("Unable to obtain session information for request.");
577                 else
578                         return pair<bool,void*>(false,NULL);    // just bail silently
579         }
580
581         ISessionCacheEntry::CachedResponse cr=m_priv->m_cacheEntry->getResponse();
582
583         // Maybe export the response.
584         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
585         if (exp.first && exp.second && cr.unfiltered) {
586             ostringstream os;
587             os << *cr.unfiltered;
588             unsigned int outlen;
589             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>((char*)os.str().c_str()), os.str().length(), &outlen);
590             XMLByte *pos, *pos2;
591             for (pos=serialized, pos2=serialized; *pos2; pos2++)
592                 if (isgraph(*pos2))
593                     *pos++=*pos2;
594             *pos=0;
595             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
596             XMLString::release(&serialized);
597         }
598     
599         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
600         setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
601         setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
602         auto_ptr_char am(m_priv->m_cacheEntry->getAuthnStatement()->getAuthMethod());
603         setHeader("Shib-Authentication-Method", am.get());
604         
605         // Get the AAP providers, which contain the attribute policy info.
606         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
607
608         // Export NameID?
609         while (provs.hasNext()) {
610             IAAP* aap=provs.next();
611             Locker locker(aap);
612             const XMLCh* format = m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getFormat();
613             const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
614             if (rule && rule->getHeader()) {
615                 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
616                 auto_ptr_char nameid(m_priv->m_cacheEntry->getAuthnStatement()->getSubject()->getNameIdentifier()->getName());
617                 setHeader("Shib-NameIdentifier-Format", form.get());
618                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
619                     setRemoteUser(nameid.get());
620                 else
621                     setHeader(rule->getHeader(), nameid.get());
622             }
623         }
624         
625         setHeader("Shib-Application-ID", m_priv->m_app->getId());
626     
627         string strUnsetValue;
628         const IPropertySet* localProps=m_priv->m_Config->getINI()->getPropertySet("Local");
629         if (localProps) {
630             pair<bool,const char*> unsetValue=localProps->getString("unsetHeaderValue");
631             if (unsetValue.first)
632                 strUnsetValue = unsetValue.second;
633         }
634
635         // Export the attributes.
636         Iterator<SAMLAssertion*> a_iter(cr.filtered ? cr.filtered->getAssertions() : EMPTY(SAMLAssertion*));
637         while (a_iter.hasNext()) {
638             SAMLAssertion* assert=a_iter.next();
639             Iterator<SAMLStatement*> statements=assert->getStatements();
640             while (statements.hasNext()) {
641                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
642                 if (!astate)
643                     continue;
644                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
645                 while (attrs.hasNext()) {
646                     SAMLAttribute* attr=attrs.next();
647             
648                     // Are we supposed to export it?
649                     provs.reset();
650                     while (provs.hasNext()) {
651                         IAAP* aap=provs.next();
652                         Locker locker(aap);
653                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
654                         if (!rule || !rule->getHeader())
655                             continue;
656                     
657                         Iterator<string> vals=attr->getSingleByteValues();
658                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
659                             setRemoteUser(vals.next());
660                         else {
661                             int it=0;
662                             string header = getHeader(rule->getHeader());
663                             if (header == strUnsetValue)
664                                 header.erase();
665                             else
666                                 it++;
667                             for (; vals.hasNext(); it++) {
668                                 string value = vals.next();
669                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
670                                         pos != string::npos;
671                                         pos = value.find_first_of(";", pos)) {
672                                     value.insert(pos, "\\");
673                                     pos += 2;
674                                 }
675                                 if (it)
676                                     header += ";";
677                                 header += value;
678                             }
679                             setHeader(rule->getHeader(), header);
680                         }
681                     }
682                 }
683             }
684         }
685     
686         return pair<bool,void*>(false,NULL);
687     }
688     catch (SAMLException& e) {
689         log(LogLevelError, e.what());
690         mlp.insert(e);
691     }
692     catch (exception& e) {
693         log(LogLevelError, e.what());
694         mlp.insert("errorText", e.what());
695     }
696
697     // If we get here then we've got an error.
698     mlp.insert("errorType", procState);
699
700     if (targetURL)
701         mlp.insert("requestURL", m_url.substr(0,m_url.find('?')));
702
703     return make_pair(true,m_priv->sendError(this, "rm", mlp));
704 }
705
706 const char* ShibTarget::getCookie(const string& name) const
707 {
708     if (m_priv->m_cookieMap.empty()) {
709         string cookies=getCookies();
710
711         string::size_type pos=0,cname,namelen,val,vallen;
712         while (pos !=string::npos && pos < cookies.length()) {
713             while (isspace(cookies[pos])) pos++;
714             cname=pos;
715             pos=cookies.find_first_of("=",pos);
716             if (pos == string::npos)
717                 break;
718             namelen=pos-cname;
719             pos++;
720             if (pos==cookies.length())
721                 break;
722             val=pos;
723             pos=cookies.find_first_of(";",pos);
724             if (pos != string::npos) {
725                 vallen=pos-val;
726                 pos++;
727                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val,vallen)));
728             }
729             else
730                 m_priv->m_cookieMap.insert(make_pair(cookies.substr(cname,namelen),cookies.substr(val)));
731         }
732     }
733     map<string,string>::const_iterator lookup=m_priv->m_cookieMap.find(name);
734     return (lookup==m_priv->m_cookieMap.end()) ? NULL : lookup->second.c_str();
735 }
736
737 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
738 {
739     static const char* defProps="; path=/";
740     
741     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
742     if (props) {
743         pair<bool,const char*> p=props->getString("cookieProps");
744         if (!p.first)
745             p.second=defProps;
746         pair<bool,const char*> p2=props->getString("cookieName");
747         if (p2.first)
748             return make_pair(string(prefix) + p2.second,p.second);
749         return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
750     }
751     
752     // Shouldn't happen, but just in case..
753     return pair<string,const char*>(prefix,defProps);
754 }
755
756 string ShibTarget::getHandlerURL(const char* resource) const
757 {
758     if (!m_priv->m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
759         return m_priv->m_handlerURL;
760         
761     if (!m_priv->m_app)
762         throw ConfigurationException("Internal error in ShibTargetPriv::getHandlerURL, missing application pointer.");
763
764 #ifdef HAVE_STRCASECMP
765     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
766 #else
767     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
768 #endif
769         throw SAMLException("Target resource was not an absolute URL.");
770         
771
772
773     bool ssl_only=false;
774     const char* handler=NULL;
775     const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
776     if (props) {
777         pair<bool,bool> p=props->getBool("handlerSSL");
778         if (p.first)
779             ssl_only=p.second;
780         pair<bool,const char*> p2=props->getString("handlerURL");
781         if (p2.first)
782             handler=p2.second;
783     }
784     
785     // Should never happen...
786     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
787         throw ConfigurationException(
788             "Invalid handlerURL property ($1) in Application ($2)",
789             params(2, handler ? handler : "null", m_priv->m_app->getId())
790             );
791
792     // The "handlerURL" property can be in one of three formats:
793     //
794     // 1) a full URI:       http://host/foo/bar
795     // 2) a hostless URI:   http:///foo/bar
796     // 3) a relative path:  /foo/bar
797     //
798     // #  Protocol  Host        Path
799     // 1  handler   handler     handler
800     // 2  handler   resource    handler
801     // 3  resource  resource    handler
802     //
803     // note: if ssl_only is true, make sure the protocol is https
804
805     const char* path = NULL;
806
807     // Decide whether to use the handler or the resource for the "protocol"
808     const char* prot;
809     if (*handler != '/') {
810         prot = handler;
811     }
812     else {
813         prot = resource;
814         path = handler;
815     }
816
817     // break apart the "protocol" string into protocol, host, and "the rest"
818     const char* colon=strchr(prot,':');
819     colon += 3;
820     const char* slash=strchr(colon,'/');
821     if (!path)
822         path = slash;
823
824     // Compute the actual protocol and store in member.
825     if (ssl_only)
826         m_priv->m_handlerURL.assign("https://");
827     else
828         m_priv->m_handlerURL.assign(prot, colon-prot);
829
830     // create the "host" from either the colon/slash or from the target string
831     // If prot == handler then we're in either #1 or #2, else #3.
832     // If slash == colon then we're in #2.
833     if (prot != handler || slash == colon) {
834         colon = strchr(resource, ':');
835         colon += 3;      // Get past the ://
836         slash = strchr(colon, '/');
837     }
838     string host(colon, (slash ? slash-colon : strlen(colon)));
839
840     // Build the handler URL
841     m_priv->m_handlerURL+=host + path;
842     return m_priv->m_handlerURL;
843 }
844
845 void ShibTarget::log(ShibLogLevel level, const string& msg)
846 {
847     Category::getInstance("shibtarget.ShibTarget").log(
848         (level == LogLevelDebug ? Priority::DEBUG :
849         (level == LogLevelInfo ? Priority::INFO :
850         (level == LogLevelWarn ? Priority::WARN : Priority::ERROR))),
851         msg
852     );
853 }
854
855 const IApplication* ShibTarget::getApplication() const
856 {
857     return m_priv->m_app;
858 }
859
860 const IConfig* ShibTarget::getConfig() const
861 {
862     return m_priv->m_conf;
863 }
864
865 void* ShibTarget::returnDecline(void)
866 {
867     return NULL;
868 }
869
870 void* ShibTarget::returnOK(void)
871 {
872     return NULL;
873 }
874
875
876 /*************************************************************************
877  * Shib Target Private implementation
878  */
879
880 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_cacheEntry(NULL), m_Config(NULL), m_conf(NULL), m_mapper(NULL) {}
881
882 ShibTargetPriv::~ShibTargetPriv()
883 {
884     if (m_cacheEntry) {
885         m_cacheEntry->unlock();
886         m_cacheEntry = NULL;
887     }
888
889     if (m_mapper) {
890         m_mapper->unlock();
891         m_mapper = NULL;
892     }
893     
894     if (m_conf) {
895         m_conf->unlock();
896         m_conf = NULL;
897     }
898
899     m_app = NULL;
900     m_Config = NULL;
901 }
902
903 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
904 {
905   if (m_app)
906     return;
907
908   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
909   // TODO: No, should be able to hold the conf but release the mapper.
910
911   // We lock the configuration system for the duration.
912   m_conf=m_Config->getINI();
913   m_conf->lock();
914     
915   // Map request to application and content settings.
916   m_mapper=m_conf->getRequestMapper();
917   m_mapper->lock();
918
919   // Obtain the application settings from the parsed URL
920   m_settings = m_mapper->getSettings(st);
921
922   // Now find the application from the URL settings
923   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
924   m_app=m_conf->getApplication(application_id.second);
925   if (!m_app) {
926     m_mapper->unlock();
927     m_mapper = NULL;
928     m_conf->unlock();
929     m_conf = NULL;
930     throw ConfigurationException("Unable to map request to application settings, check configuration.");
931   }
932
933   // Compute the full target URL
934   st->m_url = protocol + "://" + hostname;
935   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
936         ostringstream portstr;
937         portstr << port;
938     st->m_url += ":" + portstr.str();
939   }
940   st->m_url += uri;
941 }
942
943 void* ShibTargetPriv::sendError(ShibTarget* st, const char* page, ShibMLP &mlp)
944 {
945     ShibTarget::header_t hdrs[] = {
946         ShibTarget::header_t("Expires","01-Jan-1997 12:00:00 GMT"),
947         ShibTarget::header_t("Cache-Control","private,no-store,no-cache")
948         };
949     
950     const IPropertySet* props=m_app->getPropertySet("Errors");
951     if (props) {
952         pair<bool,const char*> p=props->getString(page);
953         if (p.first) {
954             ifstream infile(p.second);
955             if (!infile.fail()) {
956                 const char* res = mlp.run(infile,props);
957                 if (res)
958                     return st->sendPage(res, 200, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
959             }
960         }
961         else if (!strcmp(page,"access"))
962             return st->sendPage("Access Denied", 403, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2));
963     }
964
965     string errstr = string("sendError could not process error template (") + page + ") for application (";
966     errstr += m_app->getId();
967     errstr += ")";
968     st->log(ShibTarget::LogLevelError, errstr);
969     return st->sendPage(
970         "Internal Server Error. Please contact the site administrator.", 500, "text/html", ArrayIterator<ShibTarget::header_t>(hdrs,2)
971         );
972 }
973
974 void ShibTargetPriv::clearHeaders(ShibTarget* st)
975 {
976     // Clear invariant stuff.
977     st->clearHeader("Shib-Origin-Site");
978     st->clearHeader("Shib-Identity-Provider");
979     st->clearHeader("Shib-Authentication-Method");
980     st->clearHeader("Shib-NameIdentifier-Format");
981     st->clearHeader("Shib-Attributes");
982     st->clearHeader("Shib-Application-ID");
983
984     // Clear out the list of mapped attributes
985     Iterator<IAAP*> provs=m_app->getAAPProviders();
986     while (provs.hasNext()) {
987         IAAP* aap=provs.next();
988         Locker locker(aap);
989         Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
990         while (rules.hasNext()) {
991             const char* header=rules.next()->getHeader();
992             if (header)
993                 st->clearHeader(header);
994         }
995     }
996 }
997
998 pair<bool,void*> ShibTargetPriv::dispatch(
999     ShibTarget* st,
1000     const IPropertySet* config,
1001     bool isHandler,
1002     const char* forceType
1003     ) const
1004 {
1005     pair<bool,const char*> binding=forceType ? make_pair(true,forceType) : config->getString("Binding");
1006     if (binding.first) {
1007         auto_ptr<IPlugIn> plugin(SAMLConfig::getConfig().getPlugMgr().newPlugin(binding.second,config->getElement()));
1008         IHandler* handler=dynamic_cast<IHandler*>(plugin.get());
1009         if (!handler)
1010             throw UnsupportedProfileException(
1011                 "Plugin for binding ($1) does not implement IHandler interface.",params(1,binding.second)
1012                 );
1013         return handler->run(st,config,isHandler);
1014     }
1015     throw UnsupportedProfileException("Handler element is missing Binding attribute to determine what handler to run.");
1016 }