Removed ShibTarget members.
[shibboleth/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 <fstream>
33
34 #include <saml/SAMLConfig.h>
35 #include <xercesc/util/Base64.hpp>
36 #include <shibsp/AccessControl.h>
37 #include <shibsp/RequestMapper.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/TemplateEngine.h>
40 #include <xmltooling/util/XMLHelper.h>
41
42 #ifndef HAVE_STRCASECMP
43 # define strcasecmp stricmp
44 #endif
45
46 using namespace shibsp;
47 using namespace shibtarget;
48 using namespace shibboleth;
49 using namespace saml;
50 using namespace opensaml::saml2md;
51 using namespace log4cpp;
52 using namespace std;
53
54 using xmltooling::TemplateEngine;
55 using xmltooling::XMLToolingException;
56 using xmltooling::XMLToolingConfig;
57 using xmltooling::XMLHelper;
58
59 namespace shibtarget {
60
61     class ExtTemplateParameters : public TemplateEngine::TemplateParameters
62     {
63         const PropertySet* m_props;
64     public:
65         ExtTemplateParameters() : m_props(NULL) {}
66         ~ExtTemplateParameters() {}
67
68         void setPropertySet(const PropertySet* props) {
69             m_props = props;
70
71             // Create a timestamp.
72             time_t now = time(NULL);
73 #ifdef HAVE_CTIME_R
74             char timebuf[32];
75             m_map["now"] = ctime_r(&now,timebuf);
76 #else
77             m_map["now"] = ctime(&now);
78 #endif
79         }
80
81         const char* getParameter(const char* name) const {
82             const char* pch = TemplateParameters::getParameter(name);
83             if (pch || !m_props)
84                 return pch;
85             pair<bool,const char*> p = m_props->getString(name);
86             return p.first ? p.second : NULL;
87         }
88     };
89
90     class ShibTargetPriv
91     {
92     public:
93         ShibTargetPriv();
94         ~ShibTargetPriv();
95
96         // Helper functions
97         void get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri);
98         long sendError(ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex=NULL);
99         void clearHeaders(ShibTarget* st);
100     
101     private:
102         friend class ShibTarget;
103         RequestMapper::Settings m_settings;
104         const IApplication *m_app;
105
106         ISessionCacheEntry* m_cacheEntry;
107
108         ShibTargetConfig* m_Config;
109
110         IConfig* m_conf;
111         RequestMapper* m_mapper;
112     };
113
114     static const XMLCh SessionInitiator[] =     UNICODE_LITERAL_16(S,e,s,s,i,o,n,I,n,i,t,i,a,t,o,r);
115     static const XMLCh DiagnosticService[] =    UNICODE_LITERAL_17(D,i,a,g,n,o,s,t,i,c,S,e,r,v,i,c,e);
116 }
117
118
119 /*************************************************************************
120  * Shib Target implementation
121  */
122
123 ShibTarget::ShibTarget() : m_priv(new ShibTargetPriv()) {}
124
125 ShibTarget::ShibTarget(const IApplication *app) : m_priv(new ShibTargetPriv())
126 {
127     m_priv->m_app = app;
128 }
129
130 ShibTarget::~ShibTarget(void)
131 {
132     delete m_priv;
133 }
134
135 void ShibTarget::init(
136     const char* scheme,
137     const char* hostname,
138     int port,
139     const char* uri
140     )
141 {
142     if (m_priv->m_app)
143         throw XMLToolingException("Request initialization occurred twice!");
144
145     m_priv->m_Config = &ShibTargetConfig::getConfig();
146     m_priv->get_application(this, scheme, hostname, port, uri);
147     AbstractSPRequest::m_app = m_priv->m_app;
148 }
149
150
151 // These functions implement the server-agnostic shibboleth engine
152 // The web server modules implement a subclass and then call into 
153 // these methods once they instantiate their request object.
154
155 pair<bool,long> ShibTarget::doCheckAuthN(bool handler)
156 {
157 #ifdef _DEBUG
158     xmltooling::NDC ndc("doCheckAuthN");
159 #endif
160
161     const char* procState = "Request Processing Error";
162     const char* targetURL = m_url.c_str();
163     ExtTemplateParameters tp;
164
165     try {
166         if (!m_priv->m_app)
167             throw ConfigurationException("System uninitialized, application did not supply request information.");
168
169         // If not SSL, check to see if we should block or redirect it.
170         if (!strcmp("http",getScheme())) {
171             pair<bool,const char*> redirectToSSL = m_priv->m_settings.first->getString("redirectToSSL");
172             if (redirectToSSL.first) {
173                 if (!strcasecmp("GET",getMethod()) || !strcasecmp("HEAD",getMethod())) {
174                     // Compute the new target URL
175                     string redirectURL = string("https://") + getHostname();
176                     if (strcmp(redirectToSSL.second,"443")) {
177                         redirectURL = redirectURL + ':' + redirectToSSL.second;
178                     }
179                     redirectURL += getRequestURI();
180                     return make_pair(true, sendRedirect(redirectURL.c_str()));
181                 }
182                 else {
183                     tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
184                     return make_pair(true,m_priv->sendError(this,"ssl", tp));
185                 }
186             }
187         }
188         
189         string hURL = getHandlerURL(targetURL);
190         const char* handlerURL=hURL.c_str();
191         if (!handlerURL)
192             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
193
194         // If the request URL contains the handler base URL for this application, either dispatch
195         // directly (mainly Apache 2.0) or just pass back control.
196         if (strstr(targetURL,handlerURL)) {
197             if (handler)
198                 return doHandler();
199             else
200                 return make_pair(true, returnOK());
201         }
202
203         // Three settings dictate how to proceed.
204         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
205         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
206         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
207
208         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
209         // then we ignore this request and consider it unprotected. Apache might lie to us if
210         // ShibBasicHijack is on, but that's up to it.
211         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
212 #ifdef HAVE_STRCASECMP
213                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
214 #else
215                 (!authType.first || _stricmp(authType.second,"shibboleth")))
216 #endif
217             return make_pair(true,returnDecline());
218
219         // Fix for secadv 20050901
220         m_priv->clearHeaders(this);
221
222         pair<string,const char*> shib_cookie = m_priv->m_app->getCookieNameProps("_shibsession_");
223         const char* session_id = getCookie(shib_cookie.first.c_str());
224         if (!session_id || !*session_id) {
225             // No session.  Maybe that's acceptable?
226             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
227                 return make_pair(true,returnOK());
228
229             // No cookie, but we require a session. Initiate a new session using the indicated method.
230             procState = "Session Initiator Error";
231             const IHandler* initiator=NULL;
232             if (requireSessionWith.first) {
233                 initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
234                 if (!initiator)
235                     throw ConfigurationException(
236                         "No session initiator found with id ($1), check requireSessionWith command.",
237                         xmltooling::params(1,requireSessionWith.second)
238                         );
239             }
240             else {
241                 initiator=m_priv->m_app->getDefaultSessionInitiator();
242                 if (!initiator)
243                     throw ConfigurationException("No default session initiator found, check configuration.");
244             }
245
246             return initiator->run(this,false);
247         }
248
249         procState = "Session Processing Error";
250         try {
251             m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
252                 session_id,
253                 m_priv->m_app,
254                 getRemoteAddr().c_str()
255                 );
256             // Make a localized exception throw if the session isn't valid.
257             if (!m_priv->m_cacheEntry)
258                 throw RetryableProfileException("Session no longer valid.");
259         }
260         catch (exception& e) {
261             log(SPError, string("session processing failed: ") + e.what());
262
263             // If no session is required, bail now.
264             if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first)
265                 // Has to be OK because DECLINED will just cause Apache
266                 // to fail when it can't locate anything to process the
267                 // AuthType.  No session plus requireSession false means
268                 // do not authenticate the user at this time.
269                 return make_pair(true, returnOK());
270
271             // Try and cast down.
272             exception* base = &e;
273             RetryableProfileException* trycast=dynamic_cast<RetryableProfileException*>(base);
274             if (trycast) {
275                 // Session is invalid but we can retry -- initiate a new session.
276                 procState = "Session Initiator Error";
277                 const IHandler* initiator=NULL;
278                 if (requireSessionWith.first) {
279                     initiator=m_priv->m_app->getSessionInitiatorById(requireSessionWith.second);
280                     if (!initiator)
281                         throw ConfigurationException(
282                             "No session initiator found with id ($1), check requireSessionWith command.",
283                             xmltooling::params(1,requireSessionWith.second)
284                             );
285                 }
286                 else {
287                     initiator=m_priv->m_app->getDefaultSessionInitiator();
288                     if (!initiator)
289                         throw ConfigurationException("No default session initiator found, check configuration.");
290                 }
291                 return initiator->run(this,false);
292             }
293             throw;    // send it to the outer handler
294         }
295
296         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
297         // Let the caller decide how to proceed.
298         log(SPDebug, "doCheckAuthN succeeded");
299         return make_pair(false,0);
300     }
301     catch (XMLToolingException& e) {
302         tp.m_map["errorType"] = procState;
303         tp.m_map["errorText"] = e.what();
304         if (targetURL)
305             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
306         return make_pair(true,m_priv->sendError(this, "session", tp, &e));
307     }
308 #ifndef _DEBUG
309     catch (...) {
310         tp.m_map["errorType"] = procState;
311         tp.m_map["errorText"] = "Caught an unknown exception.";
312         if (targetURL)
313             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
314         return make_pair(true,m_priv->sendError(this, "session", tp));
315     }
316 #endif
317 }
318
319 pair<bool,long> ShibTarget::doHandler(void)
320 {
321 #ifdef _DEBUG
322     xmltooling::NDC ndc("doHandler");
323 #endif
324
325     ExtTemplateParameters tp;
326     const char* procState = "Shibboleth Handler Error";
327     const char* targetURL = m_url.c_str();
328
329     try {
330         if (!m_priv->m_app)
331             throw ConfigurationException("System uninitialized, application did not supply request information.");
332
333         string hURL = getHandlerURL(targetURL);
334         const char* handlerURL=hURL.c_str();
335         if (!handlerURL)
336             throw ConfigurationException("Cannot determine handler from resource URL, check configuration.");
337
338         // Make sure we only process handler requests.
339         if (!strstr(targetURL,handlerURL))
340             return make_pair(true, returnDecline());
341
342         const PropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
343         if (!sessionProps)
344             throw ConfigurationException("Unable to map request to application session settings, check configuration.");
345
346         // Process incoming request.
347         pair<bool,bool> handlerSSL=sessionProps->getBool("handlerSSL");
348       
349         // Make sure this is SSL, if it should be
350         if ((!handlerSSL.first || handlerSSL.second) && strcmp(getScheme(),"https"))
351             throw FatalProfileException("Blocked non-SSL access to Shibboleth handler.");
352
353         // We dispatch based on our path info. We know the request URL begins with or equals the handler URL,
354         // so the path info is the next character (or null).
355         const IHandler* handler=m_priv->m_app->getHandler(targetURL + strlen(handlerURL));
356         if (!handler)
357             throw opensaml::BindingException("Shibboleth handler invoked at an unconfigured location.");
358
359         if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,AssertionConsumerService::LOCAL_NAME))
360             procState = "Session Creation Error";
361         else if (XMLString::equals(handler->getProperties()->getElement()->getLocalName(),SessionInitiator))
362             procState = "Session Initiator Error";
363         else if (XMLHelper::isNodeNamed(handler->getProperties()->getElement(),samlconstants::SAML20MD_NS,SingleLogoutService::LOCAL_NAME))
364             procState = "Session Termination Error";
365         else if (XMLString::equals(handler->getProperties()->getElement()->getLocalName(),DiagnosticService))
366             procState = "Diagnostics Error";
367         else
368             procState = "Extension Service Error";
369         pair<bool,long> hret=handler->run(this);
370
371         // Did the handler run successfully?
372         if (hret.first)
373             return hret;
374        
375         throw opensaml::BindingException("Configured Shibboleth handler failed to process the request.");
376     }
377     catch (MetadataException& e) {
378         tp.m_map["errorText"] = e.what();
379         // See if a metadata error page is installed.
380         const PropertySet* props=m_priv->m_app->getPropertySet("Errors");
381         if (props) {
382             pair<bool,const char*> p=props->getString("metadata");
383             if (p.first) {
384                 tp.m_map["errorType"] = procState;
385                 if (targetURL)
386                     tp.m_map["requestURL"] = targetURL;
387                 return make_pair(true,m_priv->sendError(this, "metadata", tp));
388             }
389         }
390         throw;
391     }
392     catch (XMLToolingException& e) {
393         tp.m_map["errorType"] = procState;
394         tp.m_map["errorText"] = e.what();
395         if (targetURL)
396             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
397         return make_pair(true,m_priv->sendError(this, "session", tp, &e));
398     }
399 #ifndef _DEBUG
400     catch (...) {
401         tp.m_map["errorType"] = procState;
402         tp.m_map["errorText"] = "Caught an unknown exception.";
403         if (targetURL)
404             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
405         return make_pair(true,m_priv->sendError(this, "session", tp));
406     }
407 #endif
408 }
409
410 pair<bool,long> ShibTarget::doCheckAuthZ(void)
411 {
412 #ifdef _DEBUG
413     xmltooling::NDC ndc("doCheckAuthZ");
414 #endif
415
416     ExtTemplateParameters tp;
417     const char* procState = "Authorization Processing Error";
418     const char* targetURL = m_url.c_str();
419
420     try {
421         if (!m_priv->m_app)
422             throw ConfigurationException("System uninitialized, application did not supply request information.");
423
424         // Three settings dictate how to proceed.
425         pair<bool,const char*> authType = m_priv->m_settings.first->getString("authType");
426         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
427         pair<bool,const char*> requireSessionWith = m_priv->m_settings.first->getString("requireSessionWith");
428
429         // If no session is required AND the AuthType (an Apache-derived concept) isn't shibboleth,
430         // then we ignore this request and consider it unprotected. Apache might lie to us if
431         // ShibBasicHijack is on, but that's up to it.
432         if ((!requireSession.first || !requireSession.second) && !requireSessionWith.first &&
433 #ifdef HAVE_STRCASECMP
434                 (!authType.first || strcasecmp(authType.second,"shibboleth")))
435 #else
436                 (!authType.first || _stricmp(authType.second,"shibboleth")))
437 #endif
438             return make_pair(true,returnDecline());
439
440         // Do we have an access control plugin?
441         if (m_priv->m_settings.second) {
442                 
443                 if (!m_priv->m_cacheEntry) {
444                     // No data yet, so we may need to try and get the session.
445                         pair<string,const char*> shib_cookie=m_priv->m_app->getCookieNameProps("_shibsession_");
446                 const char *session_id = getCookie(shib_cookie.first.c_str());
447                     try {
448                                 if (session_id && *session_id) {
449                         m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
450                             session_id,
451                             m_priv->m_app,
452                             getRemoteAddr().c_str()
453                             );
454                                 }
455                     }
456                     catch (exception&) {
457                         log(SPError, "doCheckAuthZ: unable to obtain session information to pass to access control provider");
458                     }
459                 }
460         
461             xmltooling::Locker acllock(m_priv->m_settings.second);
462             /* TODO: port
463             if (m_priv->m_settings.second->authorized(this,m_priv->m_cacheEntry)) {
464                 // Let the caller decide how to proceed.
465                 log(LogLevelDebug, "doCheckAuthZ: access control provider granted access");
466                 return make_pair(false,0);
467             }
468             else {
469                 log(LogLevelWarn, "doCheckAuthZ: access control provider denied access");
470                 if (targetURL)
471                     tp.m_map["requestURL"] = targetURL;
472                 return make_pair(true,m_priv->sendError(this, "access", tp));
473             }
474             */
475             return make_pair(false,0);
476         }
477         else
478             return make_pair(true,returnDecline());
479     }
480     catch (exception& e) {
481         tp.m_map["errorType"] = procState;
482         tp.m_map["errorText"] = e.what();
483         if (targetURL)
484             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
485         return make_pair(true,m_priv->sendError(this, "access", tp));
486     }
487 #ifndef _DEBUG
488     catch (...) {
489         tp.m_map["errorType"] = procState;
490         tp.m_map["errorText"] = "Caught an unknown exception.";
491         if (targetURL)
492             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
493         return make_pair(true,m_priv->sendError(this, "access", tp));
494     }
495 #endif
496 }
497
498 pair<bool,long> ShibTarget::doExportAssertions(bool requireSession)
499 {
500 #ifdef _DEBUG
501     xmltooling::NDC ndc("doExportAssertions");
502 #endif
503
504     ExtTemplateParameters tp;
505     const char* procState = "Attribute Processing Error";
506     const char* targetURL = m_url.c_str();
507
508     try {
509         if (!m_priv->m_app)
510             throw ConfigurationException("System uninitialized, application did not supply request information.");
511
512         if (!m_priv->m_cacheEntry) {
513             // No data yet, so we need to get the session. This can only happen
514             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
515                 pair<string,const char*> shib_cookie=m_priv->m_app->getCookieNameProps("_shibsession_");
516             const char *session_id = getCookie(shib_cookie.first.c_str());
517             try {
518                         if (session_id && *session_id) {
519                     m_priv->m_cacheEntry=m_priv->m_conf->getSessionCache()->find(
520                         session_id,
521                         m_priv->m_app,
522                         getRemoteAddr().c_str()
523                         );
524                         }
525             }
526             catch (exception&) {
527                 log(SPError, "unable to obtain session information to export into request headers");
528                 // If we have to have a session, then this is a fatal error.
529                 if (requireSession)
530                         throw;
531             }
532         }
533
534                 // Still no data?
535         if (!m_priv->m_cacheEntry) {
536                 if (requireSession)
537                         throw RetryableProfileException("Unable to obtain session information for request.");
538                 else
539                         return make_pair(false,0);      // just bail silently
540         }
541         
542         // Extract data from session.
543         pair<const char*,const SAMLSubject*> sub=m_priv->m_cacheEntry->getSubject(false,true);
544         pair<const char*,const SAMLResponse*> unfiltered=m_priv->m_cacheEntry->getTokens(true,false);
545         pair<const char*,const SAMLResponse*> filtered=m_priv->m_cacheEntry->getTokens(false,true);
546
547         // Maybe export the tokens.
548         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
549         if (exp.first && exp.second && unfiltered.first && *unfiltered.first) {
550             unsigned int outlen;
551             XMLByte* serialized =
552                 Base64::encode(reinterpret_cast<XMLByte*>((char*)unfiltered.first), XMLString::stringLen(unfiltered.first), &outlen);
553             XMLByte *pos, *pos2;
554             for (pos=serialized, pos2=serialized; *pos2; pos2++)
555                 if (isgraph(*pos2))
556                     *pos++=*pos2;
557             *pos=0;
558             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
559             XMLString::release(&serialized);
560         }
561
562         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
563         setHeader("Shib-Origin-Site", m_priv->m_cacheEntry->getProviderId());
564         setHeader("Shib-Identity-Provider", m_priv->m_cacheEntry->getProviderId());
565         setHeader("Shib-Authentication-Method", m_priv->m_cacheEntry->getAuthnContext());
566         
567         // Get the AAP providers, which contain the attribute policy info.
568         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
569
570         // Export NameID?
571         while (provs.hasNext()) {
572             IAAP* aap=provs.next();
573             xmltooling::Locker locker(aap);
574             const XMLCh* format = sub.second->getNameIdentifier()->getFormat();
575             const IAttributeRule* rule=aap->lookup(format ? format : SAMLNameIdentifier::UNSPECIFIED);
576             if (rule && rule->getHeader()) {
577                 auto_ptr_char form(format ? format : SAMLNameIdentifier::UNSPECIFIED);
578                 auto_ptr_char nameid(sub.second->getNameIdentifier()->getName());
579                 setHeader("Shib-NameIdentifier-Format", form.get());
580                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
581                     setRemoteUser(nameid.get());
582                 else
583                     setHeader(rule->getHeader(), nameid.get());
584             }
585         }
586         
587         setHeader("Shib-Application-ID", m_priv->m_app->getId());
588     
589         // Export the attributes.
590         Iterator<SAMLAssertion*> a_iter(filtered.second ? filtered.second->getAssertions() : EMPTY(SAMLAssertion*));
591         while (a_iter.hasNext()) {
592             SAMLAssertion* assert=a_iter.next();
593             Iterator<SAMLStatement*> statements=assert->getStatements();
594             while (statements.hasNext()) {
595                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
596                 if (!astate)
597                     continue;
598                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
599                 while (attrs.hasNext()) {
600                     SAMLAttribute* attr=attrs.next();
601             
602                     // Are we supposed to export it?
603                     provs.reset();
604                     while (provs.hasNext()) {
605                         IAAP* aap=provs.next();
606                         xmltooling::Locker locker(aap);
607                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
608                         if (!rule || !rule->getHeader())
609                             continue;
610                     
611                         Iterator<string> vals=attr->getSingleByteValues();
612                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
613                             setRemoteUser(vals.next().c_str());
614                         else {
615                             int it=0;
616                             string header = getSecureHeader(rule->getHeader());
617                             if (!header.empty())
618                                 it++;
619                             for (; vals.hasNext(); it++) {
620                                 string value = vals.next();
621                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
622                                         pos != string::npos;
623                                         pos = value.find_first_of(";", pos)) {
624                                     value.insert(pos, "\\");
625                                     pos += 2;
626                                 }
627                                 if (it)
628                                     header += ";";
629                                 header += value;
630                             }
631                             setHeader(rule->getHeader(), header.c_str());
632                         }
633                     }
634                 }
635             }
636         }
637     
638         return make_pair(false,0);
639     }
640     catch (XMLToolingException& e) {
641         tp.m_map["errorType"] = procState;
642         tp.m_map["errorText"] = e.what();
643         if (targetURL)
644             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
645         return make_pair(true,m_priv->sendError(this, "rm", tp, &e));
646     }
647 #ifndef _DEBUG
648     catch (...) {
649         tp.m_map["errorType"] = procState;
650         tp.m_map["errorText"] = "Caught an unknown exception.";
651         if (targetURL)
652             tp.m_map["requestURL"] = m_url.substr(0,m_url.find('?'));
653         return make_pair(true,m_priv->sendError(this, "rm", tp));
654     }
655 #endif
656 }
657
658 const IApplication* ShibTarget::getApplication() const
659 {
660     return m_priv->m_app;
661 }
662
663 const IConfig* ShibTarget::getConfig() const
664 {
665     return m_priv->m_conf;
666 }
667
668 long ShibTarget::returnDecline(void)
669 {
670     return NULL;
671 }
672
673 long ShibTarget::returnOK(void)
674 {
675     return NULL;
676 }
677
678 /*************************************************************************
679  * Shib Target Private implementation
680  */
681
682 ShibTargetPriv::ShibTargetPriv()
683     : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), m_cacheEntry(NULL) {}
684
685 ShibTargetPriv::~ShibTargetPriv()
686 {
687     if (m_cacheEntry) {
688         m_cacheEntry->unlock();
689         m_cacheEntry = NULL;
690     }
691
692     if (m_mapper) {
693         m_mapper->unlock();
694         m_mapper = NULL;
695     }
696     
697     if (m_conf) {
698         m_conf->unlock();
699         m_conf = NULL;
700     }
701
702     m_app = NULL;
703     m_Config = NULL;
704 }
705
706 void ShibTargetPriv::get_application(ShibTarget* st, const string& protocol, const string& hostname, int port, const string& uri)
707 {
708   if (m_app)
709     return;
710
711   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
712   // TODO: No, should be able to hold the conf but release the mapper.
713
714   // We lock the configuration system for the duration.
715   m_conf=m_Config->getINI();
716   m_conf->lock();
717     
718   // Map request to application and content settings.
719   m_mapper=m_conf->getRequestMapper();
720   m_mapper->lock();
721
722   // Obtain the application settings from the parsed URL
723   m_settings = m_mapper->getSettings(*st);
724
725   // Now find the application from the URL settings
726   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
727   m_app=dynamic_cast<const IApplication*>(m_conf->getApplication(application_id.second));
728   if (!m_app) {
729     m_mapper->unlock();
730     m_mapper = NULL;
731     m_conf->unlock();
732     m_conf = NULL;
733     throw ConfigurationException("Unable to map request to application settings, check configuration.");
734   }
735
736   // Compute the full target URL
737   st->m_url = protocol + "://" + hostname;
738   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443)) {
739         ostringstream portstr;
740         portstr << port;
741     st->m_url += ":" + portstr.str();
742   }
743   st->m_url += uri;
744 }
745
746 long ShibTargetPriv::sendError(
747     ShibTarget* st, const char* page, ExtTemplateParameters& tp, const XMLToolingException* ex
748     )
749 {
750     st->setContentType("text/html");
751     st->setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
752     st->setResponseHeader("Cache-Control","private,no-store,no-cache");
753
754     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
755     const PropertySet* props=m_app->getPropertySet("Errors");
756     if (props) {
757         pair<bool,const char*> p=props->getString(page);
758         if (p.first) {
759             ifstream infile(p.second);
760             if (infile) {
761                 tp.setPropertySet(props);
762                 stringstream str;
763                 engine->run(infile, str, tp, ex);
764                 return st->sendResponse(str);
765             }
766         }
767         else if (!strcmp(page,"access")) {
768             istringstream msg("Access Denied");
769             return static_cast<opensaml::GenericResponse*>(st)->sendResponse(msg, opensaml::HTTPResponse::SAML_HTTP_STATUS_FORBIDDEN);
770         }
771     }
772
773     string errstr = string("sendError could not process error template (") + page + ") for application (";
774     errstr += m_app->getId();
775     errstr += ")";
776     st->log(SPRequest::SPError, errstr);
777     istringstream msg("Internal Server Error. Please contact the site administrator.");
778     return st->sendError(msg);
779 }
780
781 void ShibTargetPriv::clearHeaders(ShibTarget* st)
782 {
783     // Clear invariant stuff.
784     st->clearHeader("Shib-Origin-Site");
785     st->clearHeader("Shib-Identity-Provider");
786     st->clearHeader("Shib-Authentication-Method");
787     st->clearHeader("Shib-NameIdentifier-Format");
788     st->clearHeader("Shib-Attributes");
789     st->clearHeader("Shib-Application-ID");
790
791     // Clear out the list of mapped attributes
792     Iterator<IAAP*> provs=m_app->getAAPProviders();
793     while (provs.hasNext()) {
794         IAAP* aap=provs.next();
795         xmltooling::Locker locker(aap);
796         Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
797         while (rules.hasNext()) {
798             const char* header=rules.next()->getHeader();
799             if (header)
800                 st->clearHeader(header);
801         }
802     }
803 }