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