Added native command mapper.
[shibboleth/sp.git] / nsapi_shib / nsapi_shib.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 /* nsapi_shib.cpp - Shibboleth NSAPI filter
51
52    Scott Cantor
53    12/13/04
54 */
55
56 #include "config_win32.h"
57
58 // SAML Runtime
59 #include <saml/saml.h>
60 #include <shib/shib.h>
61 #include <shib/shib-threads.h>
62 #include <shib-target/shib-target.h>
63
64 #include <ctime>
65 #include <fstream>
66 #include <sstream>
67 #include <stdexcept>
68
69 #ifdef WIN32
70 # define XP_WIN32
71 #else
72 # define XP_UNIX
73 #endif
74
75 #define MCC_HTTPD
76 #define NET_SSL
77
78 extern "C"
79 {
80 #include <nsapi.h>
81 }
82
83 using namespace std;
84 using namespace saml;
85 using namespace shibboleth;
86 using namespace shibtarget;
87
88 // macros to output text to client
89 #define NET_WRITE(str) \
90     if (IO_ERROR==net_write(sn->csd,str,strlen(str))) return REQ_EXIT
91
92 namespace {
93     ShibTargetConfig* g_Config=NULL;
94     string g_ServerName;
95     string g_ServerScheme;
96 }
97
98 PlugManager::Factory SunRequestMapFactory;
99
100 extern "C" NSAPI_PUBLIC void nsapi_shib_exit(void*)
101 {
102     if (g_Config)
103         g_Config->shutdown();
104     g_Config = NULL;
105 }
106
107 extern "C" NSAPI_PUBLIC int nsapi_shib_init(pblock* pb, Session* sn, Request* rq)
108 {
109     // Save off a default hostname for this virtual server.
110     char* name=pblock_findval("server-name",pb);
111     if (name)
112         g_ServerName=name;
113     else {
114         name=server_hostname;
115         if (name)
116             g_ServerName=name;
117         else {
118             name=util_hostname();
119             if (name) {
120                 g_ServerName=name;
121                 FREE(name);
122             }
123             else {
124                 pblock_nvinsert("error","unable to determine web server hostname",pb);
125                 return REQ_ABORTED;
126             }
127         }
128     }
129     name=pblock_findval("server-scheme",pb);
130     if (name)
131         g_ServerScheme=name;
132
133     log_error(LOG_INFORM,"nsapi_shib_init",sn,rq,"nsapi_shib loaded for host (%s)",g_ServerName.c_str());
134
135 #ifndef _DEBUG
136     try {
137 #endif
138         const char* schemadir=pblock_findval("shib-schemas",pb);
139         if (!schemadir)
140             schemadir=getenv("SHIBSCHEMAS");
141         if (!schemadir)
142             schemadir=SHIB_SCHEMAS;
143         const char* config=pblock_findval("shib-config",pb);
144         if (!config)
145             config=getenv("SHIBCONFIG");
146         if (!config)
147             config=SHIB_CONFIG;
148         g_Config=&ShibTargetConfig::getConfig();
149         g_Config->setFeatures(
150             ShibTargetConfig::Listener |
151             ShibTargetConfig::Metadata |
152             ShibTargetConfig::AAP |
153             ShibTargetConfig::RequestMapper |
154             ShibTargetConfig::LocalExtensions |
155             ShibTargetConfig::Logging
156             );
157         if (!g_Config->init(schemadir)) {
158             g_Config=NULL;
159             pblock_nvinsert("error","unable to initialize Shibboleth libraries",pb);
160             return REQ_ABORTED;
161         }
162
163         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::NativeRequestMapType,&SunRequestMapFactory);
164         // We hijack the legacy type so that 1.2 config files will load this plugin
165         SAMLConfig::getConfig().getPlugMgr().regFactory(shibtarget::XML::LegacyRequestMapType,&SunRequestMapFactory);
166
167         if (!g_Config->load(config)) {
168             g_Config=NULL;
169             pblock_nvinsert("error","unable to initialize load Shibboleth configuration",pb);
170             return REQ_ABORTED;
171         }
172
173         daemon_atrestart(nsapi_shib_exit,NULL);
174 #ifndef _DEBUG
175     }
176     catch (...) {
177         g_Config=NULL;
178         pblock_nvinsert("error","caught exception, unable to initialize Shibboleth libraries",pb);
179         return REQ_ABORTED;
180     }
181 #endif
182     return REQ_PROCEED;
183 }
184
185 /********************************************************************************/
186 // NSAPI Shib Target Subclass
187
188 class ShibTargetNSAPI : public ShibTarget
189 {
190 public:
191   ShibTargetNSAPI(pblock* pb, Session* sn, Request* rq) {
192     // Get everything but hostname...
193     const char* uri=pblock_findval("uri", rq->reqpb);
194     const char* qstr=pblock_findval("query", rq->reqpb);
195     int port=server_portnum;
196     const char* scheme=security_active ? "https" : "http";
197     const char* host=NULL;
198
199     string url;
200     if (uri)
201         url=uri;
202     if (qstr)
203         url=url + '?' + qstr;
204     
205 #ifdef vs_is_default_vs
206     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
207     if (!vs_is_default_vs)
208         // The beauty here is, a non-default vhost can *only* be accessed if the client
209         // specified the exact name in the Host header. So we can trust the Host header.
210         host=pblock_findval("host", rq->headers);
211     else
212 #endif
213     // In other cases, we're going to rely on the initialization process...
214     host=g_ServerName.c_str();
215
216     char* content_type = "";
217     request_header("content-type", &content_type, sn, rq);
218       
219     const char *remote_ip = pblock_findval("ip", sn->client);
220     const char *method = pblock_findval("method", rq->reqpb);
221
222     init(scheme, host, port, url.c_str(), content_type, remote_ip, method);
223
224     m_pb = pb;
225     m_sn = sn;
226     m_rq = rq;
227   }
228   ~ShibTargetNSAPI() {}
229
230   virtual void log(ShibLogLevel level, const string &msg) {
231     ShibTarget::log(level,msg);
232     if (level==LogLevelError)
233         log_error(LOG_FAILURE, "nsapi_shib", m_sn, m_rq, const_cast<char*>(msg.c_str()));
234   }
235   virtual string getCookies(void) const {
236     char *cookies = NULL;
237     if (request_header("cookie", &cookies, m_sn, m_rq) == REQ_ABORTED)
238       throw("error accessing cookie header");
239     return string(cookies ? cookies : "");
240   }
241   virtual void setCookie(const string &name, const string &value) {
242     string cookie = name + '=' + value;
243     pblock_nvinsert("Set-Cookie", cookie.c_str(), m_rq->srvhdrs);
244   }
245   virtual string getArgs(void) { 
246     const char *q = pblock_findval("query", m_rq->reqpb);
247     return string(q ? q : "");
248   }
249   virtual string getPostData(void) {
250     char* content_length=NULL;
251     if (request_header("content-length", &content_length, m_sn, m_rq)!=REQ_PROCEED ||
252          atoi(content_length) > 1024*1024) // 1MB?
253       throw FatalProfileException("Blocked too-large a submission to profile endpoint.");
254     else {
255       char ch=IO_EOF+1;
256       int cl=atoi(content_length);
257       string cgistr;
258       while (cl && ch != IO_EOF) {
259         ch=netbuf_getc(m_sn->inbuf);
260       
261         // Check for error.
262         if(ch==IO_ERROR)
263           break;
264         cgistr += ch;
265         cl--;
266       }
267       if (cl)
268         throw FatalProfileException("Error reading profile submission from browser.");
269       return cgistr;
270     }
271   }
272   virtual void clearHeader(const string &name) {
273     param_free(pblock_remove(name.c_str(), m_rq->headers));
274   }
275   virtual void setHeader(const string &name, const string &value) {
276     pblock_nvinsert(name.c_str(), value.c_str() ,m_rq->headers);
277   }
278   virtual string getHeader(const string &name) {
279     char *hdr = NULL;
280     if (request_header(const_cast<char*>(name.c_str()), &hdr, m_sn, m_rq) != REQ_PROCEED)
281       hdr = NULL;
282     return string(hdr ? hdr : "");
283   }
284   virtual void setRemoteUser(const string &user) {
285     pblock_nvinsert("remote-user", user.c_str(), m_rq->headers);
286     pblock_nvinsert("auth-user", user.c_str(), m_rq->vars);
287   }
288   virtual string getRemoteUser(void) {
289     return getHeader("remote-user");
290   }
291   // Override this function because we want to add the NSAPI Directory override
292   /*
293   virtual pair<bool,bool> getRequireSession(IRequestMapper::Settings &settings) {
294     pair<bool,bool> requireSession=settings.first->getBool("requireSession");
295     if (!requireSession.first || !requireSession.second) {
296       const char* param=pblock_findval("require-session",pb);
297       if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
298         requireSession.second=true;
299     }
300     return requireSession;
301   }
302   */
303
304   virtual void* sendPage(
305     const string& msg,
306     int code=200,
307     const string& content_type="text/html",
308     const saml::Iterator<header_t>& headers=EMPTY(header_t)
309     ) {
310     pblock_nvinsert("Content-Type", content_type.c_str(), m_rq->srvhdrs);
311     pblock_nninsert("Content-Length", msg.length(), m_rq->srvhdrs);
312     pblock_nvinsert("Connection","close",m_rq->srvhdrs);
313     while (headers.hasNext()) {
314         const header_t& h=headers.next();
315         pblock_nvinsert(h.first.c_str(), h.second.c_str(), m_rq->srvhdrs);
316     }
317     protocol_status(m_sn, m_rq, code, NULL);
318     net_write(m_sn->csd,const_cast<char*>(msg.c_str()),msg.length());
319     return (void*)REQ_EXIT;
320   }
321   virtual void* sendRedirect(const string& url) {
322     pblock_nvinsert("Content-Type", "text/html", m_rq->srvhdrs);
323     pblock_nninsert("Content-Length", 40, m_rq->srvhdrs);
324     pblock_nvinsert("Expires", "01-Jan-1997 12:00:00 GMT", m_rq->srvhdrs);
325     pblock_nvinsert("Cache-Control", "private,no-store,no-cache", m_rq->srvhdrs);
326     pblock_nvinsert("Location", url.c_str(), m_rq->srvhdrs);
327     protocol_status(m_sn, m_rq, PROTOCOL_REDIRECT, "302 Please wait");
328     protocol_start_response(m_sn, m_rq);
329     char* msg="<HTML><BODY>Redirecting...</BODY></HTML>";
330     net_write(m_sn->csd,msg,strlen(msg));
331     return (void*)REQ_EXIT;
332   }
333   virtual void* returnDecline(void) { return (void*)REQ_NOACTION; }
334   virtual void* returnOK(void) { return (void*)REQ_PROCEED; }
335
336   pblock* m_pb;
337   Session* m_sn;
338   Request* m_rq;
339 };
340
341 /********************************************************************************/
342
343 int WriteClientError(Session* sn, Request* rq, char* func, char* msg)
344 {
345     log_error(LOG_FAILURE,func,sn,rq,msg);
346     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,msg);
347     return REQ_ABORTED;
348 }
349
350 #undef FUNC
351 #define FUNC "shibboleth"
352 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
353 {
354   ostringstream threadid;
355   threadid << "[" << getpid() << "] nsapi_shib" << '\0';
356   saml::NDC ndc(threadid.str().c_str());
357
358 #ifndef _DEBUG
359   try {
360 #endif
361     ShibTargetNSAPI stn(pb, sn, rq);
362
363     // Check user authentication
364     pair<bool,void*> res = stn.doCheckAuthN();
365     if (res.first) return (int)res.second;
366
367     // user authN was okay -- export the assertions now
368     /*
369     const char* param=pblock_findval("export-assertion", pb);
370     bool doExportAssn = false;
371     if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
372       doExportAssn = true;
373     */
374     res = stn.doExportAssertions();
375     if (res.first) return (int)res.second;
376
377     // Check the Authorization
378     res = stn.doCheckAuthZ();
379     if (res.first) return (int)res.second;
380
381     // this user is ok.
382     return REQ_PROCEED;
383
384 #ifndef _DEBUG
385   }
386   catch (...) {
387     return WriteClientError(sn, rq, FUNC, "threw an uncaught exception.");
388   }
389 #endif
390 }
391
392
393 #undef FUNC
394 #define FUNC "shib_handler"
395 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
396 {
397   ostringstream threadid;
398   threadid << "[" << getpid() << "] shib_handler" << '\0';
399   saml::NDC ndc(threadid.str().c_str());
400
401 #ifndef _DEBUG
402   try {
403 #endif
404     ShibTargetNSAPI stn(pb, sn, rq);
405
406     pair<bool,void*> res = stn.doHandler();
407     if (res.first) return (int)res.second;
408
409     return WriteClientError(sn, rq, FUNC, "Shibboleth handler did not do anything.");
410
411 #ifndef _DEBUG
412   }
413   catch (...) {
414     return WriteClientError(sn, rq, FUNC, "Filter threw an unknown exception.");
415   }
416 #endif
417 }
418
419
420 class SunRequestMapper : public virtual IRequestMapper, public virtual IPropertySet
421 {
422 public:
423     SunRequestMapper(const DOMElement* e);
424     ~SunRequestMapper() { delete m_mapper; delete m_stKey; delete m_propsKey; }
425     void lock() { m_mapper->lock(); }
426     void unlock() { m_stKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
427     Settings getSettings(ShibTarget* st) const;
428     
429     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
430     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
431     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
432     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
433     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
434     const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
435     const DOMElement* getElement() const;
436
437 private:
438     IRequestMapper* m_mapper;
439     ThreadKey* m_stKey;
440     ThreadKey* m_propsKey;
441 };
442
443 IPlugIn* SunRequestMapFactory(const DOMElement* e)
444 {
445     return new SunRequestMapper(e);
446 }
447
448 SunRequestMapper::SunRequestMapper(const DOMElement* e) : m_mapper(NULL), m_stKey(NULL), m_propsKey(NULL)
449 {
450     IPlugIn* p=SAMLConfig::getConfig().getPlugMgr().newPlugin(shibtarget::XML::XMLRequestMapType,e);
451     m_mapper=dynamic_cast<IRequestMapper*>(p);
452     if (!m_mapper) {
453         delete p;
454         throw UnsupportedExtensionException("Embedded request mapper plugin was not of correct type.");
455     }
456     m_stKey=ThreadKey::create(NULL);
457     m_propsKey=ThreadKey::create(NULL);
458 }
459
460 IRequestMapper::Settings SunRequestMapper::getSettings(ShibTarget* st) const
461 {
462     Settings s=m_mapper->getSettings(st);
463     m_stKey->setData(dynamic_cast<ShibTargetNSAPI*>(st));
464     m_propsKey->setData((void*)s.first);
465     return pair<const IPropertySet*,IAccessControl*>(this,s.second);
466 }
467
468 pair<bool,bool> SunRequestMapper::getBool(const char* name, const char* ns) const
469 {
470     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
471     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
472     if (stn && !ns && name) {
473         // Override boolean properties.
474         const char* param=pblock_findval(name,stn->m_pb);
475         if (param && (!strcmp(param,"1") || !util_strcasecmp(param,"true")))
476             return make_pair(true,true);
477     }
478     return s ? s->getBool(name,ns) : make_pair(false,false);
479 }
480
481 pair<bool,const char*> SunRequestMapper::getString(const char* name, const char* ns) const
482 {
483     ShibTargetNSAPI* stn=reinterpret_cast<ShibTargetNSAPI*>(m_stKey->getData());
484     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
485     if (stn && !ns && name) {
486         // Override string properties.
487         if (!strcmp(name,"authType"))
488             return pair<bool,const char*>(true,"shibboleth");
489         else {
490             const char* param=pblock_findval(name,stn->m_pb);
491             if (param)
492                 return make_pair(true,param);
493         }
494     }
495     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
496 }
497
498 pair<bool,const XMLCh*> SunRequestMapper::getXMLString(const char* name, const char* ns) const
499 {
500     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
501     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
502 }
503
504 pair<bool,unsigned int> SunRequestMapper::getUnsignedInt(const char* name, const char* ns) const
505 {
506     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
507     return s ? s->getUnsignedInt(name,ns) : make_pair(false,0);
508 }
509
510 pair<bool,int> SunRequestMapper::getInt(const char* name, const char* ns) const
511 {
512     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
513     return s ? s->getInt(name,ns) : make_pair(false,0);
514 }
515
516 const IPropertySet* SunRequestMapper::getPropertySet(const char* name, const char* ns) const
517 {
518     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
519     return s ? s->getPropertySet(name,ns) : NULL;
520 }
521
522 const DOMElement* SunRequestMapper::getElement() const
523 {
524     const IPropertySet* s=reinterpret_cast<const IPropertySet*>(m_propsKey->getData());
525     return s ? s->getElement() : NULL;
526 }
527
528
529 #if 0
530
531 IRequestMapper::Settings map_request(pblock* pb, Session* sn, Request* rq, IRequestMapper* mapper, string& target)
532 {
533     // Get everything but hostname...
534     const char* uri=pblock_findval("uri",rq->reqpb);
535     const char* qstr=pblock_findval("query",rq->reqpb);
536     int port=server_portnum;
537     const char* scheme=security_active ? "https" : "http";
538     const char* host=NULL;
539
540     string url;
541     if (uri)
542         url=uri;
543     if (qstr)
544         url=url + '?' + qstr;
545     
546 #ifdef vs_is_default_vs
547     // This is 6.0 or later, so we can distinguish requests to name-based vhosts.
548     if (!vs_is_default_vs)
549         // The beauty here is, a non-default vhost can *only* be accessed if the client
550         // specified the exact name in the Host header. So we can trust the Host header.
551         host=pblock_findval("host", rq->headers);
552     else
553 #endif
554     // In other cases, we're going to rely on the initialization process...
555     host=g_ServerName.c_str();
556         
557     target=(g_ServerScheme.empty() ? string(scheme) : g_ServerScheme) + "://" + host;
558     
559     // If port is non-default, append it.
560     if ((!security_active && port!=80) || (security_active && port!=443)) {
561         char portbuf[10];
562         util_snprintf(portbuf,9,"%d",port);
563         target = target + ':' + portbuf;
564     }
565
566     target+=url;
567         
568     return mapper->getSettingsFromParsedURL(scheme,host,port,url.c_str());
569 }
570
571 int WriteClientError(Session* sn, Request* rq, const IApplication* app, const char* page, ShibMLP& mlp)
572 {
573     const IPropertySet* props=app->getPropertySet("Errors");
574     if (props) {
575         pair<bool,const char*> p=props->getString(page);
576         if (p.first) {
577             ifstream infile(p.second);
578             if (!infile.fail()) {
579                 const char* res = mlp.run(infile,props);
580                 if (res) {
581                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
582                     pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
583                     pblock_nvinsert("Connection","close",rq->srvhdrs);
584                     protocol_status(sn,rq,PROTOCOL_OK,NULL);
585                     NET_WRITE(const_cast<char*>(res));
586                     return REQ_EXIT;
587                 }
588             }
589         }
590     }
591
592     log_error(LOG_FAILURE,"WriteClientError",sn,rq,"Unable to open error template, check settings.");
593     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open error template, check settings.");
594     return REQ_ABORTED;
595 }
596
597 int WriteRedirectPage(Session* sn, Request* rq, const IApplication* app, const char* file, ShibMLP& mlp)
598 {
599     ifstream infile(file);
600     if (!infile.fail()) {
601         const char* res = mlp.run(infile,app->getPropertySet("Errors"));
602         if (res) {
603             pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
604             pblock_nninsert("Content-Length",strlen(res),rq->srvhdrs);
605             protocol_status(sn,rq,PROTOCOL_OK,NULL);
606             NET_WRITE(const_cast<char*>(res));
607             return REQ_EXIT;
608         }
609     }
610     log_error(LOG_FAILURE,"WriteRedirectPage",sn,rq,"Unable to open redirect template, check settings.");
611     protocol_status(sn,rq,PROTOCOL_SERVER_ERROR,"Unable to open redirect template, check settings.");
612     return REQ_ABORTED;
613 }
614
615 #undef FUNC
616 #define FUNC "shibboleth"
617 extern "C" NSAPI_PUBLIC int nsapi_shib(pblock* pb, Session* sn, Request* rq)
618 {
619     try
620     {
621         ostringstream threadid;
622         threadid << "[" << getpid() << "] nsapi_shib" << '\0';
623         saml::NDC ndc(threadid.str().c_str());
624         
625         // We lock the configuration system for the duration.
626         IConfig* conf=g_Config->getINI();
627         Locker locker(conf);
628         
629         // Map request to application and content settings.
630         string targeturl;
631         IRequestMapper* mapper=conf->getRequestMapper();
632         Locker locker2(mapper);
633         IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
634         pair<bool,const char*> application_id=settings.first->getString("applicationId");
635         const IApplication* application=conf->getApplication(application_id.second);
636         if (!application)
637             return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
638         
639         // Declare SHIRE object for this request.
640         SHIRE shire(application);
641         
642         const char* shireURL=shire.getShireURL(targeturl.c_str());
643         if (!shireURL)
644             return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
645
646         // If the user is accessing the SHIRE acceptance point, pass it on.
647         if (targeturl.find(shireURL)!=string::npos)
648             return REQ_PROCEED;
649
650         // Now check the policy for this request.
651         pair<bool,bool> requireSession=settings.first->getBool("requireSession");
652         if (!requireSession.first || !requireSession.second) {
653             const char* param=pblock_findval("require-session",pb);
654             if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
655                 requireSession.second=true;
656         }
657         pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
658         pair<bool,bool> httpRedirects=application->getPropertySet("Sessions")->getBool("httpRedirects");
659         pair<bool,const char*> redirectPage=application->getPropertySet("Sessions")->getString("redirectPage");
660         if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
661             return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
662
663         // Check for session cookie.
664         const char* session_id=NULL;
665         string cookie;
666         if (request_header("cookie",(char**)&session_id,sn,rq)==REQ_ABORTED)
667             return WriteClientError(sn,rq,FUNC,"error accessing cookie header");
668
669         Category::getInstance("nsapi_shib."FUNC).debug("cookie header is {%s}",session_id ? session_id : "NULL");
670         if (session_id && (session_id=strstr(session_id,shib_cookie.first))) {
671             session_id+=strlen(shib_cookie.first) + 1;   /* Skip over the '=' */
672             char* cookieend=strchr(session_id,';');
673             if (cookieend) {
674                 // Chop out just the value portion.
675                 cookie.assign(session_id,cookieend-session_id-1);
676                 session_id=cookie.c_str();
677             }
678         }
679         
680         if (!session_id || !*session_id) {
681             // If no session required, bail now.
682             if (!requireSession.second)
683                 return REQ_PROCEED;
684     
685             // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
686             const char* areq = shire.getAuthnRequest(targeturl.c_str());
687             if (!httpRedirects.first || httpRedirects.second) {
688                 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
689                 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
690                 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
691                 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
692                 pblock_nvinsert("Location",areq,rq->srvhdrs);
693                 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
694                 protocol_start_response(sn,rq);
695                 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
696                 return REQ_EXIT;
697             }
698             else {
699                 ShibMLP markupProcessor;
700                 markupProcessor.insert("requestURL",areq);
701                 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
702             }
703         }
704
705         // Make sure this session is still valid.
706         RPCError* status = NULL;
707         ShibMLP markupProcessor;
708         markupProcessor.insert("requestURL", targeturl);
709     
710         try {
711             status = shire.sessionIsValid(session_id, pblock_findval("ip",sn->client));
712         }
713         catch (ShibTargetException &e) {
714             markupProcessor.insert("errorType", "Session Processing Error");
715             markupProcessor.insert("errorText", e.what());
716             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
717             return WriteClientError(sn, rq, application, "shire", markupProcessor);
718         }
719 #ifndef _DEBUG
720         catch (...) {
721             markupProcessor.insert("errorType", "Session Processing Error");
722             markupProcessor.insert("errorText", "Unexpected Exception");
723             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
724             return WriteClientError(sn, rq, application, "shire", markupProcessor);
725         }
726 #endif
727
728         // Check the status
729         if (status->isError()) {
730             if (!requireSession.second)
731                 return REQ_PROCEED;
732             else if (status->isRetryable()) {
733                 // Oops, session is invalid. Generate AuthnRequest.
734                 delete status;
735                 const char* areq = shire.getAuthnRequest(targeturl.c_str());
736                 if (!httpRedirects.first || httpRedirects.second) {
737                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
738                     pblock_nvinsert("Content-Length","40",rq->srvhdrs);
739                     pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
740                     pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
741                     pblock_nvinsert("Location",areq,rq->srvhdrs);
742                     protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
743                     protocol_start_response(sn,rq);
744                     NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
745                     return REQ_EXIT;
746                 }
747                 else {
748                     markupProcessor.insert("requestURL",areq);
749                     return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
750                 }
751             }
752             else {
753                 // return the error page to the user
754                 markupProcessor.insert(*status);
755                 delete status;
756                 return WriteClientError(sn, rq, application, "shire", markupProcessor);
757             }
758         }
759         delete status;
760     
761         // Move to RM phase.
762         RM rm(application);
763         vector<SAMLAssertion*> assertions;
764         SAMLAuthenticationStatement* sso_statement=NULL;
765
766         try {
767             status = rm.getAssertions(session_id, pblock_findval("ip",sn->client), assertions, &sso_statement);
768         }
769         catch (ShibTargetException &e) {
770             markupProcessor.insert("errorType", "Attribute Processing Error");
771             markupProcessor.insert("errorText", e.what());
772             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
773             return WriteClientError(sn, rq, application, "rm", markupProcessor);
774         }
775     #ifndef _DEBUG
776         catch (...) {
777             markupProcessor.insert("errorType", "Attribute Processing Error");
778             markupProcessor.insert("errorText", "Unexpected Exception");
779             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
780             return WriteClientError(sn, rq, application, "rm", markupProcessor);
781         }
782     #endif
783     
784         if (status->isError()) {
785             markupProcessor.insert(*status);
786             delete status;
787             return WriteClientError(sn, rq, application, "rm", markupProcessor);
788         }
789         delete status;
790
791         // Do we have an access control plugin?
792         if (settings.second) {
793             Locker acllock(settings.second);
794             if (!settings.second->authorized(*sso_statement,assertions)) {
795                 for (int k = 0; k < assertions.size(); k++)
796                     delete assertions[k];
797                 delete sso_statement;
798                 return WriteClientError(sn, rq, application, "access", markupProcessor);
799             }
800         }
801
802         // Get the AAP providers, which contain the attribute policy info.
803         Iterator<IAAP*> provs=application->getAAPProviders();
804     
805         // Clear out the list of mapped attributes
806         while (provs.hasNext()) {
807             IAAP* aap=provs.next();
808             aap->lock();
809             try {
810                 Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
811                 while (rules.hasNext()) {
812                     const char* header=rules.next()->getHeader();
813                     if (header)
814                         param_free(pblock_remove(header,rq->headers));
815                 }
816             }
817             catch(...) {
818                 aap->unlock();
819                 for (int k = 0; k < assertions.size(); k++)
820                   delete assertions[k];
821                 delete sso_statement;
822                 markupProcessor.insert("errorType", "Attribute Processing Error");
823                 markupProcessor.insert("errorText", "Unexpected Exception");
824                 markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
825                 return WriteClientError(sn, rq, application, "rm", markupProcessor);
826             }
827             aap->unlock();
828         }
829         provs.reset();
830
831         // Maybe export the first assertion.
832         param_free(pblock_remove("remote-user",rq->headers));
833         param_free(pblock_remove("auth-user",rq->vars));
834         param_free(pblock_remove("Shib-Attributes",rq->headers));
835         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
836         if (!exp.first || !exp.second) {
837             const char* param=pblock_findval("export-assertion",pb);
838             if (param && (!strcmp(param,"1") || !strcasecmp(param,"true")))
839                 exp.second=true;
840         }
841         if (exp.second && assertions.size()) {
842             string assertion;
843             RM::serialize(*(assertions[0]), assertion);
844             string::size_type lfeed;
845             while ((lfeed=assertion.find('\n'))!=string::npos)
846                 assertion.erase(lfeed,1);
847             pblock_nvinsert("Shib-Attributes",assertion.c_str(),rq->headers);
848         }
849         
850         pblock_nvinsert("auth-type","shibboleth",rq->vars);
851         param_free(pblock_remove("Shib-Origin-Site",rq->headers));
852         param_free(pblock_remove("Shib-Authentication-Method",rq->headers));
853         param_free(pblock_remove("Shib-NameIdentifier-Format",rq->headers));
854
855         // Export the SAML AuthnMethod and the origin site name.
856         auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
857         auto_ptr_char am(sso_statement->getAuthMethod());
858         pblock_nvinsert("Shib-Origin-Site",os.get(),rq->headers);
859         pblock_nvinsert("Shib-Authentication-Method",am.get(),rq->headers);
860
861         // Export NameID?
862         AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
863         if (!wrapper.fail() && wrapper->getHeader()) {
864             auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
865             auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
866             pblock_nvinsert("Shib-NameIdentifier-Format",form.get(),pb);
867             if (!strcmp(wrapper->getHeader(),"REMOTE_USER")) {
868                 pblock_nvinsert("remote-user",nameid.get(),rq->headers);
869                 pblock_nvinsert("auth-user",nameid.get(),rq->vars);
870             }
871             else {
872                 pblock_nvinsert(wrapper->getHeader(),nameid.get(),rq->headers);
873             }
874         }
875
876         param_free(pblock_remove("Shib-Application-ID",rq->headers));
877         pblock_nvinsert("Shib-Application-ID",application_id.second,rq->headers);
878
879         // Export the attributes.
880         Iterator<SAMLAssertion*> a_iter(assertions);
881         while (a_iter.hasNext()) {
882             SAMLAssertion* assert=a_iter.next();
883             Iterator<SAMLStatement*> statements=assert->getStatements();
884             while (statements.hasNext()) {
885                 SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
886                 if (!astate)
887                     continue;
888                 Iterator<SAMLAttribute*> attrs=astate->getAttributes();
889                 while (attrs.hasNext()) {
890                     SAMLAttribute* attr=attrs.next();
891         
892                     // Are we supposed to export it?
893                     AAP wrapper(provs,attr->getName(),attr->getNamespace());
894                     if (wrapper.fail() || !wrapper->getHeader())
895                         continue;
896                 
897                     Iterator<string> vals=attr->getSingleByteValues();
898                     if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext()) {
899                         char* principal=const_cast<char*>(vals.next().c_str());
900                         pblock_nvinsert("remote-user",principal,rq->headers);
901                         pblock_nvinsert("auth-user",principal,rq->vars);
902                     }
903                     else {
904                         int it=0;
905                         string header;
906                         const char* h=pblock_findval(wrapper->getHeader(),rq->headers);
907                         if (h) {
908                             header=h;
909                             param_free(pblock_remove(wrapper->getHeader(),rq->headers));
910                             it++;
911                         }
912                         for (; vals.hasNext(); it++) {
913                             string value = vals.next();
914                             for (string::size_type pos = value.find_first_of(";", string::size_type(0));
915                                     pos != string::npos;
916                                     pos = value.find_first_of(";", pos)) {
917                                 value.insert(pos, "\\");
918                                 pos += 2;
919                             }
920                             if (it == 0)
921                                 header=value;
922                             else
923                                 header=header + ';' + value;
924                         }
925                         pblock_nvinsert(wrapper->getHeader(),header.c_str(),rq->headers);
926                         }
927                 }
928             }
929         }
930     
931         // clean up memory
932         for (int k = 0; k < assertions.size(); k++)
933           delete assertions[k];
934         delete sso_statement;
935
936         return REQ_PROCEED;
937     }
938     catch(bad_alloc) {
939         return WriteClientError(sn, rq, FUNC,"Out of Memory");
940     }
941 #ifndef _DEBUG
942     catch(...) {
943         return WriteClientError(sn, rq, FUNC,"Server caught an unknown exception.");
944     }
945 #endif
946
947     return WriteClientError(sn, rq, FUNC,"Server reached unreachable code, save my walrus!");
948 }
949
950 #undef FUNC
951 #define FUNC "shib_handler"
952 extern "C" NSAPI_PUBLIC int shib_handler(pblock* pb, Session* sn, Request* rq)
953 {
954     string targeturl;
955     const IApplication* application=NULL;
956     try
957     {
958         ostringstream threadid;
959         threadid << "[" << getpid() << "] shib_handler" << '\0';
960         saml::NDC ndc(threadid.str().c_str());
961
962         // We lock the configuration system for the duration.
963         IConfig* conf=g_Config->getINI();
964         Locker locker(conf);
965         
966         // Map request to application and content settings.
967         IRequestMapper* mapper=conf->getRequestMapper();
968         Locker locker2(mapper);
969         IRequestMapper::Settings settings=map_request(pb,sn,rq,mapper,targeturl);
970         pair<bool,const char*> application_id=settings.first->getString("applicationId");
971         application=conf->getApplication(application_id.second);
972         const IPropertySet* sessionProps=application ? application->getPropertySet("Sessions") : NULL;
973         if (!application || !sessionProps)
974             return WriteClientError(sn,rq,FUNC,"Unable to map request to application settings, check configuration.");
975
976         SHIRE shire(application);
977         
978         const char* shireURL=shire.getShireURL(targeturl.c_str());
979         if (!shireURL)
980             return WriteClientError(sn,rq,FUNC,"Unable to map request to proper shireURL setting, check configuration.");
981
982         // Make sure we only process the SHIRE requests.
983         if (!strstr(targeturl.c_str(),shireURL))
984             return WriteClientError(sn,rq,FUNC,"NSAPI service function can only be invoked to process incoming sessions."
985                 "Make sure the mapped file extension or URL doesn't match actual content.");
986
987         pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();
988
989         // Make sure this is SSL, if it should be
990         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
991         if (!shireSSL.first || shireSSL.second) {
992             if (!security_active)
993                 throw ShibTargetException(SHIBRPC_OK,"blocked non-SSL access to Shibboleth session processor");
994         }
995         
996         pair<bool,bool> httpRedirects=sessionProps->getBool("httpRedirects");
997         pair<bool,const char*> redirectPage=sessionProps->getString("redirectPage");
998         if (httpRedirects.first && !httpRedirects.second && !redirectPage.first)
999             return WriteClientError(sn,rq,FUNC,"HTML-based redirection requires a redirectPage property.");
1000                 
1001         // If this is a GET, we manufacture an AuthnRequest.
1002         if (!strcasecmp(pblock_findval("method",rq->reqpb),"GET")) {
1003             const char* areq=pblock_findval("query",rq->reqpb) ? shire.getLazyAuthnRequest(pblock_findval("query",rq->reqpb)) : NULL;
1004             if (!areq)
1005                 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
1006             if (!httpRedirects.first || httpRedirects.second) {
1007                 pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1008                 pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1009                 pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1010                 pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1011                 pblock_nvinsert("Location",areq,rq->srvhdrs);
1012                 protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1013                 protocol_start_response(sn,rq);
1014                 NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1015                 return REQ_EXIT;
1016             }
1017             else {
1018                 ShibMLP markupProcessor;
1019                 markupProcessor.insert("requestURL",areq);
1020                 return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1021             }
1022         }
1023         else if (strcasecmp(pblock_findval("method",rq->reqpb),"POST"))
1024             throw ShibTargetException(SHIBRPC_OK,"blocked non-POST to Shibboleth session processor");
1025
1026         // Make sure this POST is an appropriate content type
1027         char* content_type=NULL;
1028         if (request_header("content-type",&content_type,sn,rq)!=REQ_PROCEED ||
1029                 !content_type || strcasecmp(content_type,"application/x-www-form-urlencoded"))
1030             throw ShibTargetException(SHIBRPC_OK,"blocked bad content-type to Shibboleth session processor");
1031     
1032         // Read the data.
1033         pair<const char*,const char*> elements=pair<const char*,const char*>(NULL,NULL);
1034         char* content_length=NULL;
1035         if (request_header("content-length",&content_length,sn,rq)!=REQ_PROCEED ||
1036                 atoi(content_length) > 1024*1024) // 1MB?
1037             throw ShibTargetException(SHIBRPC_OK,"blocked too-large a post to Shibboleth session processor");
1038         else {
1039             char ch=IO_EOF+1;
1040             int cl=atoi(content_length);
1041             string cgistr;
1042             while (cl && ch!=IO_EOF) {
1043                 ch=netbuf_getc(sn->inbuf);
1044         
1045                 // Check for error.
1046                 if(ch==IO_ERROR)
1047                     break;
1048                 cgistr+=ch;
1049                 cl--;
1050             }
1051             if (cl)
1052                 throw ShibTargetException(SHIBRPC_OK,"error reading POST data from browser");
1053             elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
1054         }
1055     
1056         // Make sure the SAML Response parameter exists
1057         if (!elements.first || !*elements.first)
1058             throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find SAMLResponse form element");
1059     
1060         // Make sure the target parameter exists
1061         if (!elements.second || !*elements.second)
1062             throw ShibTargetException(SHIBRPC_OK, "Shibboleth POST failed to find TARGET form element");
1063             
1064         // Process the post.
1065         string cookie;
1066         RPCError* status=NULL;
1067         ShibMLP markupProcessor;
1068         markupProcessor.insert("requestURL", targeturl.c_str());
1069         try {
1070             status = shire.sessionCreate(elements.first,pblock_findval("ip",sn->client),cookie);
1071         }
1072         catch (ShibTargetException &e) {
1073             markupProcessor.insert("errorType", "Session Creation Service Error");
1074             markupProcessor.insert("errorText", e.what());
1075             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1076             return WriteClientError(sn, rq, application, "shire", markupProcessor);
1077         }
1078 #ifndef _DEBUG
1079         catch (...) {
1080             markupProcessor.insert("errorType", "Session Creation Service Error");
1081             markupProcessor.insert("errorText", "Unexpected Exception");
1082             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1083             return WriteClientError(sn, rq, application, "shire", markupProcessor);
1084         }
1085 #endif
1086
1087         if (status->isError()) {
1088             if (status->isRetryable()) {
1089                 delete status;
1090                 const char* loc=shire.getAuthnRequest(elements.second);
1091                 if (!httpRedirects.first || httpRedirects.second) {
1092                     pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1093                     pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1094                     pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1095                     pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1096                     pblock_nvinsert("Location",loc,rq->srvhdrs);
1097                     protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1098                     protocol_start_response(sn,rq);
1099                     NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1100                     return REQ_EXIT;
1101                 }
1102                 else {
1103                     markupProcessor.insert("requestURL",loc);
1104                     return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1105                 }
1106             }
1107     
1108             // Return this error to the user.
1109             markupProcessor.insert(*status);
1110             delete status;
1111             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1112         }
1113         delete status;
1114     
1115         // We've got a good session, set the cookie and redirect to target.
1116         cookie = string(shib_cookie.first) + '=' + cookie + shib_cookie.second;
1117         pblock_nvinsert("Set-Cookie",cookie.c_str(),rq->srvhdrs);
1118         if (!httpRedirects.first || httpRedirects.second) {
1119             pblock_nvinsert("Content-Type","text/html",rq->srvhdrs);
1120             pblock_nvinsert("Content-Length","40",rq->srvhdrs);
1121             pblock_nvinsert("Expires","01-Jan-1997 12:00:00 GMT",rq->srvhdrs);
1122             pblock_nvinsert("Cache-Control","private,no-store,no-cache",rq->srvhdrs);
1123             pblock_nvinsert("Location",elements.second,rq->srvhdrs);
1124             protocol_status(sn,rq,PROTOCOL_REDIRECT,"302 Please wait");
1125             protocol_start_response(sn,rq);
1126             NET_WRITE("<HTML><BODY>Redirecting...</BODY></HTML>");
1127             return REQ_EXIT;
1128         }
1129         else {
1130             markupProcessor.insert("requestURL",elements.second);
1131             return WriteRedirectPage(sn, rq, application, redirectPage.second, markupProcessor);
1132         }
1133     }
1134     catch (ShibTargetException &e) {
1135         if (application) {
1136             ShibMLP markupProcessor;
1137             markupProcessor.insert("requestURL", targeturl.c_str());
1138             markupProcessor.insert("errorType", "Session Creation Service Error");
1139             markupProcessor.insert("errorText", e.what());
1140             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1141             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1142         }
1143     }
1144 #ifndef _DEBUG
1145     catch (...) {
1146         if (application) {
1147             ShibMLP markupProcessor;
1148             markupProcessor.insert("requestURL", targeturl.c_str());
1149             markupProcessor.insert("errorType", "Session Creation Service Error");
1150             markupProcessor.insert("errorText", "Unexpected Exception");
1151             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
1152             return WriteClientError(sn,rq,application,"shire",markupProcessor);
1153         }
1154     }
1155 #endif    
1156     return REQ_EXIT;
1157 }
1158
1159 #endif