Consolidated exception and status handling into a single class.
[shibboleth/sp.git] / shib-target / shib-target.cpp
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /*
51  * shib-target.cpp -- The ShibTarget class, a superclass for general
52  *                    target code
53  *
54  * Created by:  Derek Atkins <derek@ihtfp.com>
55  *
56  * $Id$
57  */
58
59 #include "internal.h"
60
61 #ifdef HAVE_UNISTD_H
62 # include <unistd.h>
63 #endif
64
65 #include <sstream>
66 #include <fstream>
67 #include <stdexcept>
68
69 #include <shib/shib-threads.h>
70 #include <log4cpp/Category.hh>
71 #include <log4cpp/PropertyConfigurator.hh>
72 #include <xercesc/util/Base64.hpp>
73 #include <xercesc/util/regx/RegularExpression.hpp>
74
75 #ifndef HAVE_STRCASECMP
76 # define strcasecmp stricmp
77 #endif
78
79 using namespace std;
80 using namespace saml;
81 using namespace shibboleth;
82 using namespace shibtarget;
83 using namespace log4cpp;
84
85 namespace shibtarget {
86   class CgiParse
87   {
88   public:
89     CgiParse(const char* data, unsigned int len);
90     ~CgiParse();
91     const char* get_value(const char* name) const;
92     
93     static char x2c(char *what);
94     static void url_decode(char *url);
95   private:
96     char * fmakeword(char stop, unsigned int *cl, const char** ppch);
97     char * makeword(char *line, char stop);
98     void plustospace(char *str);
99
100     map<string,char*> kvp_map;
101   };
102
103   class ShibTargetPriv
104   {
105   public:
106     ShibTargetPriv();
107     ~ShibTargetPriv();
108
109     string url_encode(const char* s);
110     void get_application(const string& protocol, const string& hostname, int port, const string& uri);
111     void* sendError(ShibTarget* st, string page, ShibMLP &mlp);
112     const char* getSessionId(ShibTarget* st);
113     const char* getRelayState(ShibTarget* st);
114
115   private:
116     friend class ShibTarget;
117     IRequestMapper::Settings m_settings;
118     const IApplication *m_app;
119     string m_shireURL;
120
121     string m_cookies;
122     const char* session_id;
123     const char* relay_state;
124
125     ShibProfile m_sso_profile;
126     string m_provider_id;
127     SAMLAuthenticationStatement* m_sso_statement;
128     SAMLResponse* m_pre_response;
129     SAMLResponse* m_post_response;
130     
131     // These are the actual request parameters set via the init method.
132     string m_url;
133     string m_method;
134     string m_protocol;
135     string m_content_type;
136     string m_remote_addr;
137
138     ShibTargetConfig* m_Config;
139
140     IConfig* m_conf;
141     IRequestMapper* m_mapper;
142   };
143 }
144
145
146 /*************************************************************************
147  * Shib Target implementation
148  */
149
150 ShibTarget::ShibTarget(void) : m_priv(NULL)
151 {
152   m_priv = new ShibTargetPriv();
153 }
154
155 ShibTarget::ShibTarget(const IApplication *app) : m_priv(NULL)
156 {
157   m_priv = new ShibTargetPriv();
158   m_priv->m_app = app;
159 }
160
161 ShibTarget::~ShibTarget(void)
162 {
163   if (m_priv) delete m_priv;
164 }
165
166 void ShibTarget::init(
167     ShibTargetConfig *config,
168     string protocol,
169     string hostname,
170     int port,
171     string uri,
172     string content_type,
173     string remote_host,
174     string method
175     )
176 {
177 #ifdef _DEBUG
178   saml::NDC ndc("ShibTarget::init");
179 #endif
180
181   if (m_priv->m_app)
182     throw runtime_error("ShibTarget Already Initialized");
183   if (!config)
184     throw runtime_error("config is NULL.  Oops.");
185
186   m_priv->m_protocol = protocol;
187   m_priv->m_content_type = content_type;
188   m_priv->m_remote_addr = remote_host;
189   m_priv->m_Config = config;
190   m_priv->m_method = method;
191   m_priv->get_application(protocol, hostname, port, uri);
192 }
193
194
195 // These functions implement the server-agnostic shibboleth engine
196 // The web server modules implement a subclass and then call into 
197 // these methods once they instantiate their request object.
198 pair<bool,void*>
199 ShibTarget::doCheckAuthN(bool requireSessionFlag, bool handleProfile)
200 {
201 #ifdef _DEBUG
202     saml::NDC ndc("ShibTarget::doCheckAuthN");
203 #endif
204
205     const char *targetURL = NULL;
206     const char *procState = "Request Setup Error";
207     ShibMLP mlp;
208
209     try {
210         if (!m_priv->m_app)
211             throw SAMLException("System uninitialized, application did not supply request information.");
212
213         targetURL = m_priv->m_url.c_str();
214         const char *shireURL = getShireURL(targetURL);
215         if (!shireURL)
216             throw SAMLException("Cannot determine assertion consumer service from resource URL, check configuration.");
217
218         if (strstr(targetURL,shireURL)) {
219             if (handleProfile)
220                 return doHandleProfile();
221             else
222                 return pair<bool,void*>(true, returnOK());
223         }
224
225         string auth_type = getAuthType();
226         if (strcasecmp(auth_type.c_str(),"shibboleth"))
227             return pair<bool,void*>(true,returnDecline());
228
229         pair<bool,bool> requireSession = m_priv->m_settings.first->getBool("requireSession");
230         if (!requireSession.first || !requireSession.second) {
231             // Web server might override.
232             if (requireSessionFlag)
233                 requireSession.second=true;
234         }
235
236         const char* session_id = m_priv->getSessionId(this);
237         if (!session_id || !*session_id) {
238             // No session.  Maybe that's acceptable?
239             if (!requireSession.second)
240                 return pair<bool,void*>(true,returnOK());
241
242             // No cookie, but we require a session.  Generate an AuthnRequest.
243             return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
244         }
245
246         procState = "Session Processing Error";
247         try {
248             // Localized exception throw if the session isn't valid.
249             sessionGet(
250                 session_id,
251                 m_priv->m_remote_addr.c_str(),
252                 m_priv->m_sso_profile,
253                 m_priv->m_provider_id,
254                 &m_priv->m_sso_statement,
255                 &m_priv->m_pre_response,
256                 &m_priv->m_post_response
257                 );
258         }
259         catch (SAMLException& e) {
260             // If no session is required, bail now.
261             if (!requireSession.second)
262                 // Has to be OK because DECLINED will just cause Apache
263                 // to fail when it can't locate anything to process the
264                 // AuthType.  No session plus requireSession false means
265                 // do not authenticate the user at this time.
266                 return pair<bool,void*>(true, returnOK());
267             
268             // TODO: need to test this...may need an actual reference cast
269             if (typeid(e)==typeid(RetryableProfileException)) {
270                 // Session is invalid but we can retry -- generate an AuthnRequest
271                 return pair<bool,void*>(true,sendRedirect(getAuthnRequest(targetURL)));
272             }
273             throw;    // send it to the outer handler
274         }
275
276         // We're done.  Everything is okay.  Nothing to report.  Nothing to do..
277         // Let the caller decide how to proceed.
278         log(LogLevelInfo, "doCheckAuthN succeeded");
279         return pair<bool,void*>(false,NULL);
280     }
281     catch (SAMLException& e) {
282         mlp.insert(e);
283     }
284 #ifndef _DEBUG
285     catch (...) {
286         mlp.insert("errorText", "Caught an unknown exception.");
287     }
288 #endif
289
290     // If we get here then we've got an error.
291     mlp.insert("errorType", procState);
292     if (targetURL)
293         mlp.insert("requestURL", targetURL);
294
295     return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
296 }
297
298 pair<bool,void*>
299 ShibTarget::doHandleProfile(void)
300 {
301 #ifdef _DEBUG
302     saml::NDC ndc("ShibTarget::doHandleProfile");
303 #endif
304
305     const char *targetURL = NULL;
306     const char *procState = "Session Creation Service Error";
307     ShibMLP mlp;
308
309     try {
310         if (!m_priv->m_app)
311             throw SAMLException("System uninitialized, application did not supply request information.");
312
313         targetURL = m_priv->m_url.c_str();
314         const char* shireURL = getShireURL(targetURL);
315
316         if (!shireURL)
317             throw SAMLException("Cannot determine assertion consumer service, check configuration.");
318
319         // Make sure we only process the SHIRE requests.
320         if (!strstr(targetURL, shireURL))
321             return pair<bool,void*>(true, returnDecline());
322
323         const IPropertySet* sessionProps=m_priv->m_app->getPropertySet("Sessions");
324         if (!sessionProps)
325             throw SAMLException("Unable to map request to application session settings, check configuration.");
326
327         // Process incoming request.
328         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
329       
330         // Make sure this is SSL, if it should be
331         if ((!shireSSL.first || shireSSL.second) && m_priv->m_protocol != "https")
332             throw FatalProfileException("Blocked non-SSL access to session creation service.");
333
334         // If this is a GET, we see if it's a lazy session request, otherwise
335         // assume it's a profile response and process it.
336         string cgistr;
337         if (!strcasecmp(m_priv->m_method.c_str(), "GET")) {
338             cgistr = getArgs();
339             string areq;
340             if (!cgistr.empty())
341                 areq=getLazyAuthnRequest(cgistr.c_str());
342             if (!areq.empty())
343                 return pair<bool,void*>(true, sendRedirect(areq));
344         }
345         else if (!strcasecmp(m_priv->m_method.c_str(), "POST")) {
346             if (m_priv->m_content_type.empty() || strcasecmp(m_priv->m_content_type.c_str(),"application/x-www-form-urlencoded")) {
347                 throw FatalProfileException(
348                     "Blocked invalid POST content-type ($1) to session creation service.",
349                     params(1,m_priv->m_content_type)
350                     );
351             }
352             // Read the POST Data
353             cgistr = getPostData();
354         }
355         
356         // Process the submission
357         string cookie,target;
358         try {
359             sessionNew(
360                 SAML11_POST | SAML11_ARTIFACT,
361                 cgistr.c_str(),
362                 m_priv->m_remote_addr.c_str(),
363                 cookie,
364                 target
365                 );
366         }
367         catch (SAMLException& e) {
368             log(LogLevelError, string("profile processing failed: ") + e.what());
369     
370             // TODO: need to test this...may need an actual reference cast
371             if (typeid(e)==typeid(RetryableProfileException)) {
372                 return pair<bool,void*>(true, sendRedirect(getAuthnRequest(target.c_str())));
373             }
374             throw;    // send it to the outer handler
375         }
376
377         log(LogLevelDebug, string("profile processing succeeded, new session created (") + cookie + ")");
378
379         if (target=="default") {
380             pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
381             target=homeURL.first ? homeURL.second : "/";
382         }
383         else if (target=="cookie") {
384             // Pull the target value from the "relay state" cookie.
385             const char* relay_state = m_priv->getRelayState(this);
386             if (!relay_state || !*relay_state) {
387                 // No apparent relay state value to use, so fall back on the default.
388                 pair<bool,const char*> homeURL=m_priv->m_app->getString("homeURL");
389                 target=homeURL.first ? homeURL.second : "/";
390             }
391             else {
392                 CgiParse::url_decode((char*)relay_state);
393                 target=relay_state;
394             }
395         }
396     
397         // We've got a good session, set the cookie...
398         pair<string,const char*> shib_cookie=getCookieNameProps("_shibsession_");
399         cookie += shib_cookie.second;
400         setCookie(shib_cookie.first, cookie);
401     
402         // ... and redirect to the target
403         return pair<bool,void*>(true, sendRedirect(target));
404     }
405     catch (SAMLException& e) {
406         mlp.insert(e);
407     }
408 #ifndef _DEBUG
409     catch (...) {
410         mlp.insert("errorText", "Caught an unknown exception.");
411     }
412 #endif
413
414     // If we get here then we've got an error.
415     mlp.insert("errorType", procState);
416
417     if (targetURL)
418         mlp.insert("requestURL", targetURL);
419
420     return pair<bool,void*>(true,m_priv->sendError(this, "session", mlp));
421 }
422
423 pair<bool,void*>
424 ShibTarget::doCheckAuthZ(void)
425 {
426 #ifdef _DEBUG
427     saml::NDC ndc("ShibTarget::doCheckAuthZ");
428 #endif
429
430     ShibMLP mlp;
431     const char *procState = "Authorization Processing Error";
432     const char *targetURL = NULL;
433     HTAccessInfo *ht = NULL;
434     HTGroupTable* grpstatus = NULL;
435
436     try {
437         if (!m_priv->m_app)
438             throw SAMLException("System uninitialized, application did not supply request information.");
439
440         targetURL = m_priv->m_url.c_str();
441         const char *session_id = m_priv->getSessionId(this);
442
443         // Do we have an access control plugin?
444         if (m_priv->m_settings.second) {
445             Locker acllock(m_priv->m_settings.second);
446             if (!m_priv->m_settings.second->authorized(*m_priv->m_sso_statement,
447                 m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*))) {
448                 log(LogLevelError, "doCheckAuthZ() access control provider denied access");
449                 if (targetURL)
450                     mlp.insert("requestURL", targetURL);
451                 // TODO: check setting and return 403
452                 return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
453             }
454         }
455
456         // Perform HTAccess Checks
457         ht = getAccessInfo();
458
459         // No Info means OK.  Just return
460         if (!ht)
461             return pair<bool,void*>(false, NULL);
462
463         vector<bool> auth_OK(ht->elements.size(), false);
464         bool method_restricted=false;
465         string remote_user = getRemoteUser();
466
467     #define CHECK_OK do { \
468       if (ht->requireAll) { \
469         delete ht; \
470         if (grpstatus) delete grpstatus; \
471         return pair<bool,void*>(false, NULL); \
472       } \
473       auth_OK[x] = true; \
474       continue; \
475     } while (0)
476
477         for (int x = 0; x < ht->elements.size(); x++) {
478             auth_OK[x] = false;
479             HTAccessInfo::RequireLine *line = ht->elements[x];
480             if (! line->use_line)
481                 continue;
482             method_restricted = true;
483
484             const char *w = line->tokens[0].c_str();
485
486             if (!strcasecmp(w,"Shibboleth")) {
487                 // This is a dummy rule needed because Apache conflates authn and authz.
488                 // Without some require rule, AuthType is ignored and no check_user hooks run.
489                 CHECK_OK;
490             }
491             else if (!strcmp(w,"valid-user")) {
492                 log(LogLevelDebug, "doCheckAuthZ accepting valid-user");
493                 CHECK_OK;
494             }
495             else if (!strcmp(w,"user") && !remote_user.empty()) {
496                 bool regexp=false;
497                 for (int i = 1; i < line->tokens.size(); i++) {
498                     w = line->tokens[i].c_str();
499                     if (*w == '~') {
500                         regexp = true;
501                         continue;
502                     }
503                 
504                     if (regexp) {
505                         try {
506                             // To do regex matching, we have to convert from UTF-8.
507                             auto_ptr<XMLCh> trans(fromUTF8(w));
508                             RegularExpression re(trans.get());
509                             auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
510                             if (re.matches(trans2.get())) {
511                                 log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
512                                 CHECK_OK;
513                             }
514                         }
515                         catch (XMLException& ex) {
516                             auto_ptr_char tmp(ex.getMessage());
517                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
518                                + w + "): " + tmp.get());
519                         }
520                     }
521                     else if (!strcmp(remote_user.c_str(), w)) {
522                         log(LogLevelDebug, string("doCheckAuthZ accepting user: ") + w);
523                         CHECK_OK;
524                     }
525                 }
526             }
527             else if (!strcmp(w,"group")) {
528                 grpstatus = getGroupTable(remote_user);
529                 if (!grpstatus) {
530                     delete ht;
531                     return pair<bool,void*>(true, returnDecline());
532                 }
533     
534                 for (int i = 1; i < line->tokens.size(); i++) {
535                     w = line->tokens[i].c_str();
536                     if (grpstatus->lookup(w)) {
537                         log(LogLevelDebug, string("doCheckAuthZ accepting group: ") + w);
538                         CHECK_OK;
539                     }
540                 }
541                 delete grpstatus;
542                 grpstatus = NULL;
543             }
544             else {
545                 Iterator<IAAP*> provs = m_priv->m_app->getAAPProviders();
546                 AAP wrapper(provs, w);
547                 if (wrapper.fail()) {
548                     log(LogLevelWarn, string("doCheckAuthZ didn't recognize require rule: ") + w);
549                     continue;
550                 }
551
552                 bool regexp = false;
553                 string vals = getHeader(wrapper->getHeader());
554                 for (int i = 1; i < line->tokens.size() && !vals.empty(); i++) {
555                     w = line->tokens[i].c_str();
556                     if (*w == '~') {
557                         regexp = true;
558                         continue;
559                     }
560
561                     try {
562                         auto_ptr<RegularExpression> re;
563                         if (regexp) {
564                             delete re.release();
565                             auto_ptr<XMLCh> trans(fromUTF8(w));
566                             auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
567                             re=temp;
568                         }
569                     
570                         string vals_str(vals);
571                         int j = 0;
572                         for (int i = 0;  i < vals_str.length();  i++) {
573                             if (vals_str.at(i) == ';') {
574                                 if (i == 0) {
575                                     log(LogLevelError, string("doCheckAuthZ invalid header encoding") +
576                                         vals + ": starts with a semicolon");
577                                     throw SAMLException("Invalid information supplied to authorization module.");
578                                 }
579
580                                 if (vals_str.at(i-1) == '\\') {
581                                     vals_str.erase(i-1, 1);
582                                     i--;
583                                     continue;
584                                 }
585
586                                 string val = vals_str.substr(j, i-j);
587                                 j = i+1;
588                                 if (regexp) {
589                                     auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
590                                     if (re->matches(trans.get())) {
591                                         log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
592                                            ", got " + val + ": authorization granted");
593                                         CHECK_OK;
594                                     }
595                                 }
596                                 else if ((wrapper->getCaseSensitive() && val==w) ||
597                                         (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
598                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
599                                         ", got " + val + ": authorization granted.");
600                                     CHECK_OK;
601                                 }
602                                 else {
603                                     log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
604                                         ", got " + val + ": authoritzation not granted.");
605                                 }
606                             }
607                         }
608     
609                         string val = vals_str.substr(j, vals_str.length()-j);
610                         if (regexp) {
611                             auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
612                             if (re->matches(trans.get())) {
613                                 log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
614                                     ", got " + val + ": authorization granted.");
615                                 CHECK_OK;
616                             }
617                         }
618                         else if ((wrapper->getCaseSensitive() && val==w) ||
619                                 (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
620                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
621                                 ", got " + val + ": authorization granted");
622                             CHECK_OK;
623                         }
624                         else {
625                             log(LogLevelDebug, string("doCheckAuthZ expecting ") + w +
626                                 ", got " + val + ": authorization not granted");
627                         }
628                     }
629                     catch (XMLException& ex) {
630                         auto_ptr_char tmp(ex.getMessage());
631                             log(LogLevelError, string("doCheckAuthZ caught exception while parsing regular expression (")
632                                 + w + "): " + tmp.get());
633                     }
634                 }
635             }
636         } // for x
637
638
639         // check if all require directives are true
640         bool auth_all_OK = true;
641         for (int i = 0; i < ht->elements.size(); i++) {
642             auth_all_OK &= auth_OK[i];
643         }
644
645         delete ht;
646         if (grpstatus) delete grpstatus;
647         if (auth_all_OK || !method_restricted)
648             return pair<bool,void*>(false, NULL);
649
650         // If we get here there's an access error, so just fall through
651     }
652     catch (SAMLException& e) {
653         mlp.insert(e);
654     }
655 #ifndef _DEBUG
656     catch (...) {
657         mlp.insert("errorText", "Caught an unknown exception.");
658     }
659 #endif
660
661     // If we get here then we've got an error.
662     mlp.insert("errorType", procState);
663
664     if (targetURL)
665         mlp.insert("requestURL", targetURL);
666
667     delete ht;
668
669     return pair<bool,void*>(true,m_priv->sendError(this, "access", mlp));
670 }
671
672 pair<bool,void*>
673 ShibTarget::doExportAssertions(bool exportAssertion)
674 {
675 #ifdef _DEBUG
676     saml::NDC ndc("ShibTarget::doExportAssertions");
677 #endif
678
679     ShibMLP mlp;
680     const char *procState = "Attribute Processing Error";
681     const char *targetURL = NULL;
682     char *page = "rm";
683
684     try {
685         if (!m_priv->m_app)
686             throw SAMLException("System uninitialized, application did not supply request information.");
687
688         targetURL = m_priv->m_url.c_str();
689         const char *session_id = m_priv->getSessionId(this);
690
691         if (!m_priv->m_sso_statement) {
692             // No data yet, so we need to get the session. This can only happen
693             // if the call to doCheckAuthn doesn't happen in the same object lifetime.
694             sessionGet(
695                 session_id,
696                 m_priv->m_remote_addr.c_str(),
697                 m_priv->m_sso_profile,
698                 m_priv->m_provider_id,
699                 &m_priv->m_sso_statement,
700                 &m_priv->m_pre_response,
701                 &m_priv->m_post_response
702                 );
703         }
704
705         // Get the AAP providers, which contain the attribute policy info.
706         Iterator<IAAP*> provs=m_priv->m_app->getAAPProviders();
707
708         // Clear out the list of mapped attributes
709         while (provs.hasNext()) {
710             IAAP* aap=provs.next();
711             Locker locker(aap);
712             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
713             while (rules.hasNext()) {
714                 const char* header=rules.next()->getHeader();
715                 if (header)
716                     clearHeader(header);
717             }
718         }
719         
720         // Maybe export the first assertion.
721         clearHeader("Shib-Attributes");
722         pair<bool,bool> exp=m_priv->m_settings.first->getBool("exportAssertion");
723         if (!exp.first || !exp.second)
724             if (exportAssertion)
725                 exp.second=true;
726         if (exp.second && m_priv->m_pre_response) {
727             ostringstream os;
728             os << *(m_priv->m_pre_response);
729             unsigned int outlen;
730             char* resp = (char*)os.str().c_str();
731             XMLByte* serialized = Base64::encode(reinterpret_cast<XMLByte*>(resp), os.str().length(), &outlen);
732             // TODO: strip linefeeds
733             setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
734             XMLString::release(&serialized);
735         }
736     
737         // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
738         clearHeader("Shib-Origin-Site");
739         clearHeader("Shib-Identity-Provider");
740         clearHeader("Shib-Authentication-Method");
741         clearHeader("Shib-NameIdentifier-Format");
742         setHeader("Shib-Origin-Site", m_priv->m_provider_id.c_str());
743         setHeader("Shib-Identity-Provider", m_priv->m_provider_id.c_str());
744         auto_ptr_char am(m_priv->m_sso_statement->getAuthMethod());
745         setHeader("Shib-Authentication-Method", am.get());
746         
747         // Export NameID?
748         provs.reset();
749         while (provs.hasNext()) {
750             IAAP* aap=provs.next();
751             Locker locker(aap);
752             const IAttributeRule* rule=aap->lookup(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
753             if (rule && rule->getHeader()) {
754                 auto_ptr_char form(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getFormat());
755                 auto_ptr_char nameid(m_priv->m_sso_statement->getSubject()->getNameIdentifier()->getName());
756                 setHeader("Shib-NameIdentifier-Format", form.get());
757                 if (!strcmp(rule->getHeader(),"REMOTE_USER"))
758                     setRemoteUser(nameid.get());
759                 else
760                     setHeader(rule->getHeader(), nameid.get());
761             }
762         }
763         
764         clearHeader("Shib-Application-ID");
765         setHeader("Shib-Application-ID", m_priv->m_app->getId());
766     
767         // Export the attributes.
768         Iterator<SAMLAssertion*> a_iter(m_priv->m_post_response ? m_priv->m_post_response->getAssertions() : EMPTY(SAMLAssertion*));
769         while (a_iter.hasNext()) {
770             SAMLAssertion* assert=a_iter.next();
771             Iterator<SAMLStatement*> statements=assert->getStatements();
772             while (statements.hasNext()) {
773                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
774                 if (!astate)
775                     continue;
776                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
777                 while (attrs.hasNext()) {
778                     SAMLAttribute* attr=attrs.next();
779             
780                     // Are we supposed to export it?
781                     provs.reset();
782                     while (provs.hasNext()) {
783                         IAAP* aap=provs.next();
784                         Locker locker(aap);
785                         const IAttributeRule* rule=aap->lookup(attr->getName(),attr->getNamespace());
786                         if (!rule || !rule->getHeader())
787                             continue;
788                     
789                         Iterator<string> vals=attr->getSingleByteValues();
790                         if (!strcmp(rule->getHeader(),"REMOTE_USER") && vals.hasNext())
791                             setRemoteUser(vals.next());
792                         else {
793                             int it=0;
794                             string header = getHeader(rule->getHeader());
795                             if (!header.empty())
796                                 it++;
797                             for (; vals.hasNext(); it++) {
798                                 string value = vals.next();
799                                 for (string::size_type pos = value.find_first_of(";", string::size_type(0));
800                                         pos != string::npos;
801                                         pos = value.find_first_of(";", pos)) {
802                                     value.insert(pos, "\\");
803                                     pos += 2;
804                                 }
805                                 if (it)
806                                     header += ";";
807                                 header += value;
808                             }
809                             setHeader(rule->getHeader(), header);
810                         }
811                     }
812                 }
813             }
814         }
815     
816         return pair<bool,void*>(false,NULL);
817     }
818     catch (SAMLException& e) {
819         mlp.insert(e);
820     }
821 #ifndef _DEBUG
822     catch (...) {
823         mlp.insert("errorText", "Caught an unknown exception.");
824     }
825 #endif
826
827     // If we get here then we've got an error.
828     mlp.insert("errorType", procState);
829
830     if (targetURL)
831         mlp.insert("requestURL", targetURL);
832
833     return pair<bool,void*>(true,m_priv->sendError(this, page, mlp));
834 }
835
836
837 // Low level APIs
838
839 // Get the session cookie name and properties for the application
840 pair<string,const char*> ShibTarget::getCookieNameProps(const char* prefix) const
841 {
842     static const char* defProps="; path=/";
843     
844     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
845     if (props) {
846         pair<bool,const char*> p=props->getString("cookieProps");
847         if (!p.first)
848             p.second=defProps;
849         pair<bool,const char*> p2=props->getString("cookieName");
850         if (p2.first)
851             return make_pair(string(prefix) + p2.second,p.second);
852         return make_pair(string(prefix) + m_priv->m_app->getHash(),p.second);
853     }
854     
855     // Shouldn't happen, but just in case..
856     return make_pair(prefix,defProps);
857 }
858         
859 // Find the default assertion consumer service for the resource
860 const char*
861 ShibTarget::getShireURL(const char* resource) const
862 {
863     if (!m_priv->m_shireURL.empty())
864         return m_priv->m_shireURL.c_str();
865
866     // XXX: what to do is m_app is NULL?
867
868     bool shire_ssl_only=false;
869     const char* shire=NULL;
870     const IPropertySet* props=m_priv->m_app->getPropertySet("Sessions");
871     if (props) {
872         pair<bool,bool> p=props->getBool("shireSSL");
873         if (p.first)
874             shire_ssl_only=p.second;
875         pair<bool,const char*> p2=props->getString("shireURL");
876         if (p2.first)
877             shire=p2.second;
878     }
879     
880     // Should never happen...
881     if (!shire || (*shire!='/' && strncmp(shire,"http:",5) && strncmp(shire,"https:",6)))
882         return NULL;
883
884     // The "shireURL" property can be in one of three formats:
885     //
886     // 1) a full URI:       http://host/foo/bar
887     // 2) a hostless URI:   http:///foo/bar
888     // 3) a relative path:  /foo/bar
889     //
890     // #  Protocol  Host        Path
891     // 1  shire     shire       shire
892     // 2  shire     resource    shire
893     // 3  resource  resource    shire
894     //
895     // note: if shire_ssl_only is true, make sure the protocol is https
896
897     const char* path = NULL;
898
899     // Decide whether to use the shire or the resource for the "protocol"
900     const char* prot;
901     if (*shire != '/') {
902         prot = shire;
903     }
904     else {
905         prot = resource;
906         path = shire;
907     }
908
909     // break apart the "protocol" string into protocol, host, and "the rest"
910     const char* colon=strchr(prot,':');
911     colon += 3;
912     const char* slash=strchr(colon,'/');
913     if (!path)
914         path = slash;
915
916     // Compute the actual protocol and store in member.
917     if (shire_ssl_only)
918         m_priv->m_shireURL.assign("https://");
919     else
920         m_priv->m_shireURL.assign(prot, colon-prot);
921
922     // create the "host" from either the colon/slash or from the target string
923     // If prot == shire then we're in either #1 or #2, else #3.
924     // If slash == colon then we're in #2.
925     if (prot != shire || slash == colon) {
926         colon = strchr(resource, ':');
927         colon += 3;      // Get past the ://
928         slash = strchr(colon, '/');
929     }
930     string host(colon, slash-colon);
931
932     // Build the shire URL
933     m_priv->m_shireURL+=host + path;
934     return m_priv->m_shireURL.c_str();
935 }
936         
937 // Generate a Shib 1.x AuthnRequest redirect URL for the resource,
938 // using whatever relay state mechanism is specified for the app.
939 string ShibTarget::getAuthnRequest(const char* resource)
940 {
941     // XXX: what to do if m_app is NULL?
942
943     string req;
944     char timebuf[16];
945     sprintf(timebuf,"%u",time(NULL));
946     
947     const IPropertySet* props=m_priv->m_app ? m_priv->m_app->getPropertySet("Sessions") : NULL;
948     if (props) {
949         pair<bool,const char*> wayf=props->getString("wayfURL");
950         if (wayf.first) {
951             req=req + wayf.second + "?shire=" + m_priv->url_encode(getShireURL(resource)) + "&time=" + timebuf;
952             
953             // How should the target value be preserved?
954             pair<bool,bool> localRelayState=m_priv->m_conf->getPropertySet("Local")->getBool("localRelayState");
955             if (!localRelayState.first || !localRelayState.second) {
956                 // The old way, just send it along.
957                 req = req + "&target=" + m_priv->url_encode(resource);
958             }
959             else {
960                 // Here we store the state in a cookie and send a fixed
961                 // value to the IdP so we can recognize it on the way back.
962                 pair<string,const char*> shib_cookie=getCookieNameProps("_shibstate_");
963                 setCookie(shib_cookie.first,m_priv->url_encode(resource) + shib_cookie.second);
964                 req += "&target=cookie";
965             }
966             
967             pair<bool,bool> old=m_priv->m_app->getBool("oldAuthnRequest");
968             if (!old.first || !old.second) {
969                 wayf=m_priv->m_app->getString("providerId");
970                 if (wayf.first)
971                     req=req + "&providerId=" + m_priv->url_encode(wayf.second);
972             }
973         }
974     }
975     return req;
976 }
977         
978 // Process a lazy session setup request and turn it into an AuthnRequest
979 string ShibTarget::getLazyAuthnRequest(const char* query_string)
980 {
981     CgiParse parser(query_string,strlen(query_string));
982     const char* target=parser.get_value("target");
983     if (!target || !*target)
984         return "";
985     return getAuthnRequest(target);
986 }
987
988 void ShibTarget::sessionNew(
989     int supported_profiles,
990     const char* packet,
991     const char* ip,
992     string& cookie,
993     string& target
994     ) const
995 {
996 #ifdef _DEBUG
997     saml::NDC ndc("sessionNew");
998 #endif
999     Category& log = Category::getInstance("shibtarget.ShibTarget");
1000
1001     if (!packet || !*packet) {
1002         log.error("missing profile response");
1003         throw FatalProfileException("Profile response missing.");
1004     }
1005
1006     if (!ip || !*ip) {
1007         log.error("missing client address");
1008         throw FatalProfileException("Invalid client address.");
1009     }
1010   
1011     if (supported_profiles <= 0) {
1012         log.error("no profile support indicated");
1013         throw FatalProfileException("No profile support indicated.");
1014     }
1015   
1016     shibrpc_new_session_args_2 arg;
1017     arg.recipient = (char*) m_priv->m_shireURL.c_str();
1018     arg.application_id = (char*) m_priv->m_app->getId();
1019     arg.packet = (char*)packet;
1020     arg.client_addr = (char*)ip;
1021     arg.supported_profiles = supported_profiles;
1022
1023     log.info("create session for user at (%s) for application (%s)", ip, arg.application_id);
1024
1025     shibrpc_new_session_ret_2 ret;
1026     memset(&ret, 0, sizeof(ret));
1027
1028     // Loop on the RPC in case we lost contact the first time through
1029     int retry = 1;
1030     CLIENT* clnt;
1031     RPC rpc;
1032     do {
1033         clnt = rpc->connect();
1034         clnt_stat status = shibrpc_new_session_2 (&arg, &ret, clnt);
1035         if (status != RPC_SUCCESS) {
1036             // FAILED.  Release, disconnect, and retry
1037             log.error("RPC Failure: %p (%p) (%d): %s", this, clnt, status, clnt_spcreateerror("shibrpc_new_session_2"));
1038             rpc->disconnect();
1039             if (retry)
1040                 retry--;
1041             else
1042                 throw ListenerException("Failure passing session setup information to listener.");
1043         }
1044         else {
1045             // SUCCESS.  Pool and continue
1046             retry = -1;
1047         }
1048     } while (retry>=0);
1049
1050     if (ret.status && *ret.status)
1051         log.debug("RPC completed with exception: %s", ret.status);
1052     else
1053         log.debug("RPC completed successfully");
1054
1055     SAMLException* except=NULL;
1056     if (ret.status && *ret.status) {
1057         // Reconstitute exception object.
1058         try { 
1059             istringstream estr(ret.status);
1060             except=SAMLException::getInstance(estr);
1061         }
1062         catch (SAMLException& e) {
1063             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1064             log.error("XML was: %s", ret.status);
1065             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1066             rpc.pool();
1067             throw FatalProfileException("An unrecoverable error occurred while creating your session.");
1068         }
1069 #ifndef _DEBUG
1070         catch (...) {
1071             log.error("caught unknown exception building SAMLException");
1072             log.error("XML was: %s", ret.status);
1073             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1074             rpc.pool();
1075             throw;
1076         }
1077 #endif
1078     }
1079     else {
1080         log.debug("new session cookie: %s", ret.cookie);
1081         cookie = ret.cookie;
1082         if (ret.target)
1083             target = ret.target;
1084     }
1085
1086     clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_new_session_ret_2, (caddr_t)&ret);
1087     rpc.pool();
1088     if (except) {
1089         auto_ptr<SAMLException> wrapper(except);
1090         throw *wrapper;
1091     }
1092 }
1093
1094 void ShibTarget::sessionGet(
1095     const char* cookie,
1096     const char* ip,
1097     ShibProfile& profile,
1098     string& provider_id,
1099     SAMLAuthenticationStatement** auth_statement,
1100     SAMLResponse** attr_response_pre,
1101     SAMLResponse** attr_response_post
1102     ) const
1103 {
1104 #ifdef _DEBUG
1105     saml::NDC ndc("sessionGet");
1106 #endif
1107     Category& log = Category::getInstance("shibtarget.ShibTarget");
1108
1109     if (!cookie || !*cookie) {
1110         log.error("no session key provided");
1111         throw InvalidSessionException("No session key was provided.");
1112     }
1113     else if (strchr(cookie,'=')) {
1114         log.error("cookie value not extracted successfully, probably overlapping cookies across domains");
1115         throw InvalidSessionException("The session key wasn't extracted successfully from the browser cookie.");
1116     }
1117
1118     if (!ip || !*ip) {
1119         log.error("invalid client Address");
1120         throw FatalProfileException("Invalid client address.");
1121     }
1122
1123     log.info("getting session for client at (%s)", ip);
1124     log.debug("session cookie (%s)", cookie);
1125
1126     shibrpc_get_session_args_2 arg;
1127     arg.cookie = (char*)cookie;
1128     arg.client_addr = (char*)ip;
1129     arg.application_id = (char*)m_priv->m_app->getId();
1130
1131     shibrpc_get_session_ret_2 ret;
1132     memset (&ret, 0, sizeof(ret));
1133
1134     // Loop on the RPC in case we lost contact the first time through
1135     int retry = 1;
1136     CLIENT *clnt;
1137     RPC rpc;
1138     do {
1139         clnt = rpc->connect();
1140         clnt_stat status = shibrpc_get_session_2(&arg, &ret, clnt);
1141         if (status != RPC_SUCCESS) {
1142             // FAILED.  Release, disconnect, and try again...
1143             log.error("RPC Failure: %p (%p) (%d) %s", this, clnt, status, clnt_spcreateerror("shibrpc_get_session_2"));
1144             rpc->disconnect();
1145             if (retry)
1146                 retry--;
1147             else
1148                 throw ListenerException("Failure requesting session information from listener.");
1149         }
1150         else {
1151             // SUCCESS
1152             retry = -1;
1153         }
1154     } while (retry>=0);
1155
1156     if (ret.status && *ret.status)
1157         log.debug("RPC completed with exception: %s", ret.status);
1158     else
1159         log.debug("RPC completed successfully");
1160
1161     SAMLException* except=NULL;
1162     if (ret.status && *ret.status) {
1163         // Reconstitute exception object.
1164         try { 
1165             istringstream estr(ret.status);
1166             except=SAMLException::getInstance(estr);
1167         }
1168         catch (SAMLException& e) {
1169             log.error("caught SAML Exception while building the SAMLException: %s", e.what());
1170             log.error("XML was: %s", ret.status);
1171             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1172             rpc.pool();
1173             throw FatalProfileException("An unrecoverable error occurred while accessing your session.");
1174         }
1175         catch (...) {
1176             log.error("caught unknown exception building SAMLException");
1177             log.error("XML was: %s", ret.status);
1178             clnt_freeres(clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1179             rpc.pool();
1180             throw;
1181         }
1182     }
1183     else {
1184         try {
1185             profile = ret.profile;
1186             provider_id = ret.provider_id;
1187         
1188             // return the Authentication Statement
1189             if (auth_statement) {
1190                 istringstream authstream(ret.auth_statement);
1191                 log.debugStream() << "trying to decode authentication statement: "
1192                     << ret.auth_statement << CategoryStream::ENDLINE;
1193                 *auth_statement = new SAMLAuthenticationStatement(authstream);
1194             }
1195     
1196             // return the unfiltered Response
1197             if (attr_response_pre) {
1198                 istringstream prestream(ret.attr_response_pre);
1199                 log.debugStream() << "trying to decode unfiltered attribute response: "
1200                     << ret.attr_response_pre << CategoryStream::ENDLINE;
1201                 *attr_response_pre = new SAMLResponse(prestream);
1202             }
1203     
1204             // return the filtered Response
1205             if (attr_response_post) {
1206                 istringstream poststream(ret.attr_response_post);
1207                 log.debugStream() << "trying to decode filtered attribute response: "
1208                     << ret.attr_response_post << CategoryStream::ENDLINE;
1209                 *attr_response_post = new SAMLResponse(poststream);
1210             }
1211         }
1212         catch (SAMLException& e) {
1213             log.error("caught SAML exception while reconstituting session objects: %s", e.what());
1214             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1215             rpc.pool();
1216             throw;
1217         }
1218 #ifndef _DEBUG
1219         catch (...) {
1220             log.error("caught unknown exception while reconstituting session objects");
1221             clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1222             rpc.pool();
1223             throw;
1224         }
1225 #endif
1226     }
1227
1228     clnt_freeres (clnt, (xdrproc_t)xdr_shibrpc_get_session_ret_2, (caddr_t)&ret);
1229     rpc.pool();
1230     if (except) {
1231         auto_ptr<SAMLException> wrapper(except);
1232         throw *wrapper;
1233     }
1234 }
1235
1236 /*************************************************************************
1237  * Shib Target Private implementation
1238  */
1239
1240 ShibTargetPriv::ShibTargetPriv() : m_app(NULL), m_mapper(NULL), m_conf(NULL), m_Config(NULL), session_id(NULL), relay_state(NULL),
1241     m_sso_profile(PROFILE_UNSPECIFIED), m_sso_statement(NULL), m_pre_response(NULL), m_post_response(NULL) {}
1242
1243 ShibTargetPriv::~ShibTargetPriv()
1244 {
1245   delete m_sso_statement;
1246   m_sso_statement = NULL;
1247
1248   delete m_pre_response;
1249   m_pre_response = NULL;
1250   
1251   delete m_post_response;
1252   m_post_response = NULL;
1253
1254   if (m_mapper) {
1255     m_mapper->unlock();
1256     m_mapper = NULL;
1257   }
1258   if (m_conf) {
1259     m_conf->unlock();
1260     m_conf = NULL;
1261   }
1262   m_app = NULL;
1263   m_Config = NULL;
1264 }
1265
1266 static inline char hexchar(unsigned short s)
1267 {
1268     return (s<=9) ? ('0' + s) : ('A' + s - 10);
1269 }
1270
1271 string
1272 ShibTargetPriv::url_encode(const char* s)
1273 {
1274     static char badchars[]="\"\\+<>#%{}|^~[]`;/?:@=&";
1275
1276     string ret;
1277     for (; *s; s++) {
1278         if (strchr(badchars,*s) || *s<=0x1F || *s>=0x7F) {
1279             ret+='%';
1280         ret+=hexchar(*s >> 4);
1281         ret+=hexchar(*s & 0x0F);
1282         }
1283         else
1284             ret+=*s;
1285     }
1286     return ret;
1287 }
1288
1289 void
1290 ShibTargetPriv::get_application(const string& protocol, const string& hostname, int port, const string& uri)
1291 {
1292   if (m_app)
1293     return;
1294
1295   // XXX: Do we need to keep conf and mapper locked while we hold m_app?
1296   // TODO: No, should be able to hold the conf but release the mapper.
1297
1298   // We lock the configuration system for the duration.
1299   m_conf=m_Config->getINI();
1300   m_conf->lock();
1301     
1302   // Map request to application and content settings.
1303   m_mapper=m_conf->getRequestMapper();
1304   m_mapper->lock();
1305
1306   // Obtain the application settings from the parsed URL
1307   m_settings = m_mapper->getSettingsFromParsedURL(protocol.c_str(),
1308                                                   hostname.c_str(),
1309                                                   port, uri.c_str());
1310
1311   // Now find the application from the URL settings
1312   pair<bool,const char*> application_id=m_settings.first->getString("applicationId");
1313   const IApplication* application=m_conf->getApplication(application_id.second);
1314   if (!application) {
1315     m_mapper->unlock();
1316     m_mapper = NULL;
1317     m_conf->unlock();
1318     m_conf = NULL;
1319     throw SAMLException("Unable to map request to application settings, check configuration.");
1320   }
1321
1322   // Store the application for later use
1323   m_app = application;
1324
1325   // Compute the target URL
1326   m_url = protocol + "://" + hostname;
1327   if ((protocol == "http" && port != 80) || (protocol == "https" && port != 443))
1328     m_url += ":" + port;
1329   m_url += uri;
1330 }
1331
1332
1333 void*
1334 ShibTargetPriv::sendError(ShibTarget* st, string page, ShibMLP &mlp)
1335 {
1336     const IPropertySet* props=m_app->getPropertySet("Errors");
1337     if (props) {
1338         pair<bool,const char*> p=props->getString(page.c_str());
1339         if (p.first) {
1340             ifstream infile(p.second);
1341             if (!infile.fail()) {
1342                 const char* res = mlp.run(infile,props);
1343                 if (res)
1344                     return st->sendPage(res);
1345             }
1346         }
1347     }
1348
1349     string errstr = "sendError could not process the error template for application (";
1350     errstr += m_app->getId();
1351     errstr += ")";
1352     st->log(ShibTarget::LogLevelError, errstr);
1353     return st->sendPage("Internal Server Error. Please contact the site administrator.");
1354 }
1355
1356 const char* ShibTargetPriv::getSessionId(ShibTarget* st)
1357 {
1358   if (session_id) {
1359     //string m = string("getSessionId returning precreated session_id: ") + session_id;
1360     //st->log(ShibTarget::LogLevelDebug, m);
1361     return session_id;
1362   }
1363
1364   char *sid;
1365   pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibsession_");
1366   if (m_cookies.empty())
1367       m_cookies = st->getCookies();
1368   if (!m_cookies.empty()) {
1369     if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1370       // We found a cookie.  pull it out (our session_id)
1371       sid += shib_cookie.first.length() + 1; // skip over the '='
1372       char *cookieend = strchr(sid, ';');
1373       if (cookieend)
1374         *cookieend = '\0';
1375       session_id = sid;
1376     }
1377   }
1378
1379   //string m = string("getSessionId returning new session_id: ") + session_id;
1380   //st->log(ShibTarget::LogLevelDebug, m);
1381   return session_id;
1382 }
1383
1384 const char* ShibTargetPriv::getRelayState(ShibTarget* st)
1385 {
1386   if (relay_state)
1387     return relay_state;
1388
1389   char *sid;
1390   pair<string,const char*> shib_cookie = st->getCookieNameProps("_shibstate_");
1391   if (m_cookies.empty())
1392       m_cookies = st->getCookies();
1393   if (!m_cookies.empty()) {
1394     if (sid = strstr(m_cookies.c_str(), shib_cookie.first.c_str())) {
1395       // We found a cookie.  pull it out
1396       sid += shib_cookie.first.length() + 1; // skip over the '='
1397       char *cookieend = strchr(sid, ';');
1398       if (cookieend)
1399         *cookieend = '\0';
1400       relay_state = sid;
1401     }
1402   }
1403
1404   return relay_state;
1405 }
1406
1407 /*************************************************************************
1408  * CGI Parser implementation
1409  */
1410
1411 CgiParse::CgiParse(const char* data, unsigned int len)
1412 {
1413     const char* pch = data;
1414     unsigned int cl = len;
1415         
1416     while (cl && pch) {
1417         char *name;
1418         char *value;
1419         value=fmakeword('&',&cl,&pch);
1420         plustospace(value);
1421         url_decode(value);
1422         name=makeword(value,'=');
1423         kvp_map[name]=value;
1424         free(name);
1425     }
1426 }
1427
1428 CgiParse::~CgiParse()
1429 {
1430     for (map<string,char*>::iterator i=kvp_map.begin(); i!=kvp_map.end(); i++)
1431         free(i->second);
1432 }
1433
1434 const char*
1435 CgiParse::get_value(const char* name) const
1436 {
1437     map<string,char*>::const_iterator i=kvp_map.find(name);
1438     if (i==kvp_map.end())
1439         return NULL;
1440     return i->second;
1441 }
1442
1443 /* Parsing routines modified from NCSA source. */
1444 char *
1445 CgiParse::makeword(char *line, char stop)
1446 {
1447     int x = 0,y;
1448     char *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));
1449
1450     for(x=0;((line[x]) && (line[x] != stop));x++)
1451         word[x] = line[x];
1452
1453     word[x] = '\0';
1454     if(line[x])
1455         ++x;
1456     y=0;
1457
1458     while(line[x])
1459       line[y++] = line[x++];
1460     line[y] = '\0';
1461     return word;
1462 }
1463
1464 char *
1465 CgiParse::fmakeword(char stop, unsigned int *cl, const char** ppch)
1466 {
1467     int wsize;
1468     char *word;
1469     int ll;
1470
1471     wsize = 1024;
1472     ll=0;
1473     word = (char *) malloc(sizeof(char) * (wsize + 1));
1474
1475     while(1)
1476     {
1477         word[ll] = *((*ppch)++);
1478         if(ll==wsize-1)
1479         {
1480             word[ll+1] = '\0';
1481             wsize+=1024;
1482             word = (char *)realloc(word,sizeof(char)*(wsize+1));
1483         }
1484         --(*cl);
1485         if((word[ll] == stop) || word[ll] == EOF || (!(*cl)))
1486         {
1487             if(word[ll] != stop)
1488                 ll++;
1489             word[ll] = '\0';
1490             return word;
1491         }
1492         ++ll;
1493     }
1494 }
1495
1496 void
1497 CgiParse::plustospace(char *str)
1498 {
1499     register int x;
1500
1501     for(x=0;str[x];x++)
1502         if(str[x] == '+') str[x] = ' ';
1503 }
1504
1505 char
1506 CgiParse::x2c(char *what)
1507 {
1508     register char digit;
1509
1510     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
1511     digit *= 16;
1512     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
1513     return(digit);
1514 }
1515
1516 void
1517 CgiParse::url_decode(char *url)
1518 {
1519     register int x,y;
1520
1521     for(x=0,y=0;url[y];++x,++y)
1522     {
1523         if((url[x] = url[y]) == '%')
1524         {
1525             url[x] = x2c(&url[y+1]);
1526             y+=2;
1527         }
1528     }
1529     url[x] = '\0';
1530 }
1531
1532 // Subclasses may not need to override these particular virtual methods.
1533 string ShibTarget::getAuthType(void)
1534 {
1535   return string("shibboleth");
1536 }
1537 void* ShibTarget::returnDecline(void)
1538 {
1539   return NULL;
1540 }
1541 void* ShibTarget::returnOK(void)
1542 {
1543   return NULL;
1544 }
1545 HTAccessInfo* ShibTarget::getAccessInfo(void)
1546 {
1547   return NULL;
1548 }
1549 HTGroupTable* ShibTarget::getGroupTable(string &user)
1550 {
1551   return NULL;
1552 }