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