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