Update copyright.
[shibboleth/sp.git] / apache / mod_apache.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * mod_apache.cpp -- the core Apache Module code
19  *
20  * Created by:  Derek Atkins <derek@ihtfp.com>
21  *
22  * $Id$
23  */
24
25 #ifdef SOLARIS2
26 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
27 #endif
28
29 #ifdef WIN32
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 #endif
33
34 #include <shibsp/AbstractSPRequest.h>
35 #include <shibsp/AccessControl.h>
36 #include <shibsp/exceptions.h>
37 #include <shibsp/RequestMapper.h>
38 #include <shibsp/SPConfig.h>
39
40 // SAML Runtime
41 #include <saml/saml.h>
42 #include <shib/shib.h>
43 #include <shib-target/shib-target.h>
44 #include <xercesc/util/regx/RegularExpression.hpp>
45 #include <xmltooling/util/NDC.h>
46 #include <xmltooling/util/Threads.h>
47
48 #ifdef WIN32
49 # include <winsock.h>
50 #endif
51
52 #undef _XPG4_2
53
54 // Apache specific header files
55 #include <httpd.h>
56 #include <http_config.h>
57 #include <http_protocol.h>
58 #include <http_main.h>
59 #define CORE_PRIVATE
60 #include <http_core.h>
61 #include <http_log.h>
62
63 #ifndef SHIB_APACHE_13
64 #include <http_request.h>
65 #include <apr_strings.h>
66 #include <apr_pools.h>
67 #endif
68
69 #include <fstream>
70 #include <sstream>
71
72 #ifdef HAVE_UNISTD_H
73 #include <unistd.h>             // for getpid()
74 #endif
75
76 using namespace shibsp;
77 using namespace xmltooling;
78 using namespace std;
79
80 extern "C" module MODULE_VAR_EXPORT mod_shib;
81
82 namespace {
83     char* g_szSHIBConfig = NULL;
84     char* g_szSchemaDir = NULL;
85     shibtarget::ShibTargetConfig* g_Config = NULL;
86     string g_unsetHeaderValue;
87     static const char* g_UserDataKey = "_shib_check_user_";
88 }
89
90 /* Apache 2.2.x headers must be accumulated and set in the output filter.
91    Apache 2.0.49+ supports the filter method.
92    Apache 1.3.x and lesser 2.0.x must write the headers directly. */
93
94 #if (defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)) && AP_MODULE_MAGIC_AT_LEAST(20020903,6)
95 #define SHIB_DEFERRED_HEADERS
96 #endif
97
98 /********************************************************************************/
99 // Basic Apache Configuration code.
100 //
101
102 // per-server module configuration structure
103 struct shib_server_config
104 {
105     char* szScheme;
106 };
107
108 // creates the per-server configuration
109 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
110 {
111     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
112     sc->szScheme = NULL;
113     return sc;
114 }
115
116 // overrides server configuration in virtual servers
117 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
118 {
119     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
120     shib_server_config* parent=(shib_server_config*)base;
121     shib_server_config* child=(shib_server_config*)sub;
122
123     if (child->szScheme)
124         sc->szScheme=ap_pstrdup(p,child->szScheme);
125     else if (parent->szScheme)
126         sc->szScheme=ap_pstrdup(p,parent->szScheme);
127     else
128         sc->szScheme=NULL;
129
130     return sc;
131 }
132
133 // per-dir module configuration structure
134 struct shib_dir_config
135 {
136     // RM Configuration
137     char* szAuthGrpFile;    // Auth GroupFile name
138     int bRequireAll;        // all require directives must match, otherwise OR logic
139
140     // Content Configuration
141     char* szApplicationId;  // Shib applicationId value
142     char* szRequireWith;    // require a session using a specific initiator?
143     char* szRedirectToSSL;  // redirect non-SSL requests to SSL port
144     int bOff;               // flat-out disable all Shib processing
145     int bBasicHijack;       // activate for AuthType Basic?
146     int bRequireSession;    // require a session?
147     int bExportAssertion;   // export SAML assertion to the environment?
148     int bUseEnvVars;        // use environment instead of headers?
149 };
150
151 // creates per-directory config structure
152 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
153 {
154     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
155     dc->bOff = -1;
156     dc->bBasicHijack = -1;
157     dc->bRequireSession = -1;
158     dc->bExportAssertion = -1;
159     dc->bRequireAll = -1;
160     dc->szRedirectToSSL = NULL;
161     dc->szAuthGrpFile = NULL;
162     dc->szApplicationId = NULL;
163     dc->szRequireWith = NULL;
164     dc->bUseEnvVars = -1;
165     return dc;
166 }
167
168 // overrides server configuration in directories
169 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
170 {
171     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
172     shib_dir_config* parent=(shib_dir_config*)base;
173     shib_dir_config* child=(shib_dir_config*)sub;
174
175     if (child->szAuthGrpFile)
176         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
177     else if (parent->szAuthGrpFile)
178         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
179     else
180         dc->szAuthGrpFile=NULL;
181
182     if (child->szApplicationId)
183         dc->szApplicationId=ap_pstrdup(p,child->szApplicationId);
184     else if (parent->szApplicationId)
185         dc->szApplicationId=ap_pstrdup(p,parent->szApplicationId);
186     else
187         dc->szApplicationId=NULL;
188
189     if (child->szRequireWith)
190         dc->szRequireWith=ap_pstrdup(p,child->szRequireWith);
191     else if (parent->szRequireWith)
192         dc->szRequireWith=ap_pstrdup(p,parent->szRequireWith);
193     else
194         dc->szRequireWith=NULL;
195
196     if (child->szRedirectToSSL)
197         dc->szRedirectToSSL=ap_pstrdup(p,child->szRedirectToSSL);
198     else if (parent->szRedirectToSSL)
199         dc->szRedirectToSSL=ap_pstrdup(p,parent->szRedirectToSSL);
200     else
201         dc->szRedirectToSSL=NULL;
202
203     dc->bOff=((child->bOff==-1) ? parent->bOff : child->bOff);
204     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
205     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
206     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
207     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
208     dc->bUseEnvVars=((child->bUseEnvVars==-1) ? parent->bUseEnvVars : child->bUseEnvVars);
209     return dc;
210 }
211
212 // per-request module structure
213 struct shib_request_config
214 {
215     SH_AP_TABLE *env;        // environment vars
216 #ifdef SHIB_DEFERRED_HEADERS
217     SH_AP_TABLE *hdr_out;    // headers to browser
218     SH_AP_TABLE *hdr_err;    // err headers to browser
219 #endif
220 };
221
222 // create a request record
223 static shib_request_config *init_request_config(request_rec *r)
224 {
225     shib_request_config* rc=(shib_request_config*)ap_pcalloc(r->pool,sizeof(shib_request_config));
226     ap_set_module_config (r->request_config, &mod_shib, rc);
227     memset(rc, 0, sizeof(shib_request_config));
228     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_init_rc");
229     return rc;
230 }
231
232 // generic global slot handlers
233 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
234 {
235     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
236     return NULL;
237 }
238
239 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
240 {
241     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
242     size_t offset=(size_t)parms->info;
243     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
244     return NULL;
245 }
246
247 extern "C" const char* shib_ap_set_file_slot(cmd_parms* parms,
248 #ifdef SHIB_APACHE_13
249                                              char* arg1, char* arg2
250 #else
251                                              void* arg1, const char* arg2
252 #endif
253                                              )
254 {
255   ap_set_file_slot(parms, arg1, arg2);
256   return DECLINE_CMD;
257 }
258
259 /********************************************************************************/
260 // Apache ShibTarget subclass(es) here.
261
262 class ShibTargetApache : public AbstractSPRequest
263 {
264   mutable string m_body;
265   mutable bool m_gotBody;
266   vector<XSECCryptoX509*> m_certs;
267
268 public:
269   request_rec* m_req;
270   shib_dir_config* m_dc;
271   shib_server_config* m_sc;
272   shib_request_config* m_rc;
273
274   ShibTargetApache(request_rec* req) : m_gotBody(false) {
275     m_sc = (shib_server_config*)ap_get_module_config(req->server->module_config, &mod_shib);
276     m_dc = (shib_dir_config*)ap_get_module_config(req->per_dir_config, &mod_shib);
277     m_rc = (shib_request_config*)ap_get_module_config(req->request_config, &mod_shib);
278     m_req = req;
279   }
280   virtual ~ShibTargetApache() {}
281
282   const char* getScheme() const {
283     return m_sc->szScheme ? m_sc->szScheme : ap_http_method(m_req);
284   }
285   const char* getHostname() const {
286     return ap_get_server_name(m_req);
287   }
288   int getPort() const {
289     return ap_get_server_port(m_req);
290   }
291   const char* getRequestURI() const {
292     return m_req->unparsed_uri;
293   }
294   const char* getMethod() const {
295     return m_req->method;
296   }
297   string getContentType() const {
298     const char* type = ap_table_get(m_req->headers_in, "Content-Type");
299     return type ? type : "";
300   }
301   long getContentLength() const {
302       return m_gotBody ? m_body.length() : m_req->remaining;
303   }
304   string getRemoteAddr() const {
305     return m_req->connection->remote_ip;
306   }
307   void log(SPLogLevel level, const string& msg) const {
308     AbstractSPRequest::log(level,msg);
309     ap_log_rerror(
310         APLOG_MARK,
311         (level == SPDebug ? APLOG_DEBUG :
312         (level == SPInfo ? APLOG_INFO :
313         (level == SPWarn ? APLOG_WARNING :
314         (level == SPError ? APLOG_ERR : APLOG_CRIT))))|APLOG_NOERRNO,
315         SH_AP_R(m_req),
316         msg.c_str()
317         );
318   }
319   const char* getQueryString() const { return m_req->args; }
320   const char* getRequestBody() const {
321     if (m_gotBody)
322         return m_body.c_str();
323     // Read the posted data
324     if (ap_setup_client_block(m_req, REQUEST_CHUNKED_ERROR))
325         throw opensaml::BindingException("Apache function (setup_client_block) failed while reading POST request body.");
326     if (!ap_should_client_block(m_req))
327         throw opensaml::BindingException("Apache function (should_client_block) failed while reading POST request body.");
328     if (m_req->remaining > 1024*1024)
329         throw opensaml::BindingException("Blocked POST request body larger than size limit.");
330     m_gotBody=true;
331     char buff[HUGE_STRING_LEN];
332     ap_hard_timeout("[mod_shib] getRequestBody", m_req);
333     memset(buff, 0, sizeof(buff));
334     while (ap_get_client_block(m_req, buff, sizeof(buff)-1) > 0) {
335       ap_reset_timeout(m_req);
336       m_body += buff;
337       memset(buff, 0, sizeof(buff));
338     }
339     ap_kill_timeout(m_req);
340     return m_body.c_str();
341   }
342   void clearHeader(const char* name) {
343     if (m_dc->bUseEnvVars!=0) {
344        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: env\n");
345        if (m_rc && m_rc->env) ap_table_unset(m_rc->env, name);
346     } else {
347        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_clear_header: hdr\n");
348        ap_table_unset(m_req->headers_in, name);
349        ap_table_set(m_req->headers_in, name, g_unsetHeaderValue.c_str());
350     }
351   }
352   void setHeader(const char* name, const char* value) {
353     if (m_dc->bUseEnvVars!=0) {
354        if (!m_rc) {
355           // this happens on subrequests
356           // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_setheader: no_m_rc\n");
357           m_rc = init_request_config(m_req);
358        }
359        if (!m_rc->env) m_rc->env = ap_make_table(m_req->pool, 10);
360        // ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(m_req), "shib_set_env: %s=%s\n", name, value?value:"Null");
361        ap_table_set(m_rc->env, name, value?value:"");
362     }
363     else {
364        ap_table_set(m_req->headers_in, name, value);
365     }
366   }
367   string getHeader(const char* name) const {
368     const char* hdr = ap_table_get(m_req->headers_in, name);
369     return string(hdr ? hdr : "");
370   }
371   string getSecureHeader(const char* name) const {
372     if (m_dc->bUseEnvVars!=0) {
373        const char *hdr;
374        if (m_rc && m_rc->env)
375            hdr = ap_table_get(m_rc->env, name);
376        else
377            hdr = NULL;
378        return string(hdr ? hdr : "");
379     }
380     return getHeader(name);
381   }
382   void setRemoteUser(const char* user) {
383       SH_AP_USER(m_req) = user ? ap_pstrdup(m_req->pool, user) : NULL;
384   }
385   string getRemoteUser() const {
386     return string(SH_AP_USER(m_req) ? SH_AP_USER(m_req) : "");
387   }
388   void setContentType(const char* type) {
389       m_req->content_type = ap_psprintf(m_req->pool, type);
390   }
391   void setResponseHeader(const char* name, const char* value) {
392 #ifdef SHIB_DEFERRED_HEADERS
393    if (!m_rc)
394       // this happens on subrequests
395       m_rc = init_request_config(m_req);
396     ap_table_add(m_rc->hdr_err, name, value);
397     ap_table_add(m_rc->hdr_out, name, value);
398 #else
399     ap_table_add(m_req->err_headers_out, name, value);
400 #endif
401   }
402   long sendResponse(istream& in, long status) {
403     ap_send_http_header(m_req);
404     char buf[1024];
405     while (in) {
406         in.read(buf,1024);
407         ap_rwrite(buf,in.gcount(),m_req);
408     }
409     return ((status==SAML_HTTP_STATUS_OK) ? DONE : status);
410   }
411   long sendRedirect(const char* url) {
412     ap_table_set(m_req->headers_out, "Location", url);
413     return REDIRECT;
414   }
415   const vector<XSECCryptoX509*>& getClientCertificates() const {
416       return m_certs;
417   }
418   long returnDecline(void) { return DECLINED; }
419   long returnOK(void) { return OK; }
420 };
421
422 /********************************************************************************/
423 // Apache handlers
424
425 extern "C" int shib_check_user(request_rec* r)
426 {
427   // Short-circuit entirely?
428   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
429     return DECLINED;
430     
431   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_check_user(%d): ENTER\n", (int)getpid());
432
433   ostringstream threadid;
434   threadid << "[" << getpid() << "] shib_check_user" << '\0';
435   xmltooling::NDC ndc(threadid.str().c_str());
436
437   try {
438     ShibTargetApache sta(r);
439
440     // Check user authentication and export information, then set the handler bypass
441     pair<bool,long> res = sta.getServiceProvider().doAuthentication(sta,true);
442     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
443     if (res.first) return res.second;
444
445     // user auth was okay -- export the assertions now
446     res = sta.getServiceProvider().doExport(sta);
447     if (res.first) return res.second;
448
449     // export happened successfully..  this user is ok.
450     return OK;
451   }
452   catch (exception& e) {
453     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an exception: %s", e.what());
454     return SERVER_ERROR;
455   }
456 #ifndef _DEBUG
457   catch (...) {
458     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_check_user threw an uncaught exception!");
459     return SERVER_ERROR;
460   }
461 #endif
462 }
463
464 extern "C" int shib_handler(request_rec* r)
465 {
466   // Short-circuit entirely?
467   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
468     return DECLINED;
469
470   ostringstream threadid;
471   threadid << "[" << getpid() << "] shib_handler" << '\0';
472   xmltooling::NDC ndc(threadid.str().c_str());
473
474 #ifndef SHIB_APACHE_13
475   // With 2.x, this handler always runs, though last.
476   // We check if shib_check_user ran, because it will detect a handler request
477   // and dispatch it directly.
478   void* data;
479   apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
480   if (data==(const void*)42) {
481     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler skipped since check_user ran");
482     return DECLINED;
483   }
484 #endif
485
486   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(%d): ENTER: %s", (int)getpid(), r->handler);
487
488   try {
489     ShibTargetApache sta(r);
490
491     pair<bool,long> res = sta.getServiceProvider().doHandler(sta);
492     if (res.first) return res.second;
493
494     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "doHandler() did not do anything.");
495     return SERVER_ERROR;
496   }
497   catch (exception& e) {
498     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an exception: %s", e.what());
499     return SERVER_ERROR;
500   }
501 #ifndef _DEBUG
502   catch (...) {
503     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_handler threw an uncaught exception!");
504     return SERVER_ERROR;
505   }
506 #endif
507 }
508
509 /*
510  * shib_auth_checker() -- a simple resource manager to
511  * process the .htaccess settings
512  */
513 extern "C" int shib_auth_checker(request_rec* r)
514 {
515   // Short-circuit entirely?
516   if (((shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib))->bOff==1)
517     return DECLINED;
518
519   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_auth_checker(%d): ENTER", (int)getpid());
520
521   ostringstream threadid;
522   threadid << "[" << getpid() << "] shib_auth_checker" << '\0';
523   xmltooling::NDC ndc(threadid.str().c_str());
524
525   try {
526     ShibTargetApache sta(r);
527
528     pair<bool,long> res = sta.getServiceProvider().doAuthorization(sta);
529     if (res.first) return res.second;
530
531     // We're all okay.
532     return OK;
533   }
534   catch (exception& e) {
535     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an exception: %s", e.what());
536     return SERVER_ERROR;
537   }
538 #ifndef _DEBUG
539   catch (...) {
540     ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, SH_AP_R(r), "shib_auth_checker threw an uncaught exception!");
541     return SERVER_ERROR;
542   }
543 #endif
544 }
545
546 // Access control plugin that enforces htaccess rules
547 class htAccessControl : virtual public AccessControl
548 {
549 public:
550     htAccessControl() {}
551     ~htAccessControl() {}
552     Lockable* lock() {return this;}
553     void unlock() {}
554     bool authorized(const SPRequest& request, const Session* session) const;
555 };
556
557 AccessControl* htAccessFactory(const DOMElement* const & e)
558 {
559     return new htAccessControl();
560 }
561
562 class ApacheRequestMapper : public virtual RequestMapper, public virtual PropertySet
563 {
564 public:
565     ApacheRequestMapper(const DOMElement* e);
566     ~ApacheRequestMapper() { delete m_mapper; delete m_htaccess; delete m_staKey; delete m_propsKey; }
567     Lockable* lock() { return m_mapper->lock(); }
568     void unlock() { m_staKey->setData(NULL); m_propsKey->setData(NULL); m_mapper->unlock(); }
569     Settings getSettings(const SPRequest& request) const;
570     
571     pair<bool,bool> getBool(const char* name, const char* ns=NULL) const;
572     pair<bool,const char*> getString(const char* name, const char* ns=NULL) const;
573     pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const;
574     pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const;
575     pair<bool,int> getInt(const char* name, const char* ns=NULL) const;
576     const PropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const;
577     const DOMElement* getElement() const;
578
579 private:
580     RequestMapper* m_mapper;
581     ThreadKey* m_staKey;
582     ThreadKey* m_propsKey;
583     AccessControl* m_htaccess;
584 };
585
586 RequestMapper* ApacheRequestMapFactory(const DOMElement* const & e)
587 {
588     return new ApacheRequestMapper(e);
589 }
590
591 ApacheRequestMapper::ApacheRequestMapper(const DOMElement* e) : m_mapper(NULL), m_staKey(NULL), m_propsKey(NULL), m_htaccess(NULL)
592 {
593     m_mapper=SPConfig::getConfig().RequestMapperManager.newPlugin(XML_REQUEST_MAPPER,e);
594     m_htaccess=new htAccessControl();
595     m_staKey=ThreadKey::create(NULL);
596     m_propsKey=ThreadKey::create(NULL);
597 }
598
599 RequestMapper::Settings ApacheRequestMapper::getSettings(const SPRequest& request) const
600 {
601     Settings s=m_mapper->getSettings(request);
602     m_staKey->setData((void*)dynamic_cast<const ShibTargetApache*>(&request));
603     m_propsKey->setData((void*)s.first);
604     return pair<const PropertySet*,AccessControl*>(this,s.second ? s.second : m_htaccess);
605 }
606
607 pair<bool,bool> ApacheRequestMapper::getBool(const char* name, const char* ns) const
608 {
609     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
610     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
611     if (sta && !ns) {
612         // Override Apache-settable boolean properties.
613         if (name && !strcmp(name,"requireSession") && sta->m_dc->bRequireSession==1)
614             return make_pair(true,true);
615         else if (name && !strcmp(name,"exportAssertion") && sta->m_dc->bExportAssertion==1)
616             return make_pair(true,true);
617     }
618     return s ? s->getBool(name,ns) : make_pair(false,false);
619 }
620
621 pair<bool,const char*> ApacheRequestMapper::getString(const char* name, const char* ns) const
622 {
623     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
624     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
625     if (sta && !ns) {
626         // Override Apache-settable string properties.
627         if (name && !strcmp(name,"authType")) {
628             const char *auth_type=ap_auth_type(sta->m_req);
629             if (auth_type) {
630                 // Check for Basic Hijack
631                 if (!strcasecmp(auth_type, "basic") && sta->m_dc->bBasicHijack == 1)
632                     auth_type = "shibboleth";
633                 return make_pair(true,auth_type);
634             }
635         }
636         else if (name && !strcmp(name,"applicationId") && sta->m_dc->szApplicationId)
637             return pair<bool,const char*>(true,sta->m_dc->szApplicationId);
638         else if (name && !strcmp(name,"requireSessionWith") && sta->m_dc->szRequireWith)
639             return pair<bool,const char*>(true,sta->m_dc->szRequireWith);
640         else if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
641             return pair<bool,const char*>(true,sta->m_dc->szRedirectToSSL);
642     }
643     return s ? s->getString(name,ns) : pair<bool,const char*>(false,NULL);
644 }
645
646 pair<bool,const XMLCh*> ApacheRequestMapper::getXMLString(const char* name, const char* ns) const
647 {
648     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
649     return s ? s->getXMLString(name,ns) : pair<bool,const XMLCh*>(false,NULL);
650 }
651
652 pair<bool,unsigned int> ApacheRequestMapper::getUnsignedInt(const char* name, const char* ns) const
653 {
654     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
655     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
656     if (sta && !ns) {
657         // Override Apache-settable int properties.
658         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
659             return pair<bool,unsigned int>(true,strtol(sta->m_dc->szRedirectToSSL,NULL,10));
660     }
661     return s ? s->getUnsignedInt(name,ns) : pair<bool,unsigned int>(false,0);
662 }
663
664 pair<bool,int> ApacheRequestMapper::getInt(const char* name, const char* ns) const
665 {
666     const ShibTargetApache* sta=reinterpret_cast<const ShibTargetApache*>(m_staKey->getData());
667     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
668     if (sta && !ns) {
669         // Override Apache-settable int properties.
670         if (name && !strcmp(name,"redirectToSSL") && sta->m_dc->szRedirectToSSL)
671             return pair<bool,int>(true,atoi(sta->m_dc->szRedirectToSSL));
672     }
673     return s ? s->getInt(name,ns) : pair<bool,int>(false,0);
674 }
675
676 const PropertySet* ApacheRequestMapper::getPropertySet(const char* name, const char* ns) const
677 {
678     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
679     return s ? s->getPropertySet(name,ns) : NULL;
680 }
681
682 const DOMElement* ApacheRequestMapper::getElement() const
683 {
684     const PropertySet* s=reinterpret_cast<const PropertySet*>(m_propsKey->getData());
685     return s ? s->getElement() : NULL;
686 }
687
688 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
689 {
690     SH_AP_CONFIGFILE* f;
691     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
692     char l[MAX_STRING_LEN];
693     const char *group_name, *ll, *w;
694
695 #ifdef SHIB_APACHE_13
696     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
697 #else
698     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
699 #endif
700         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
701         return NULL;
702     }
703
704     SH_AP_POOL* sp;
705 #ifdef SHIB_APACHE_13
706     sp=ap_make_sub_pool(r->pool);
707 #else
708     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
709         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
710             "groups_for_user() could not create a subpool");
711         return NULL;
712     }
713 #endif
714
715     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
716         if ((*l=='#') || (!*l))
717             continue;
718         ll = l;
719         ap_clear_pool(sp);
720
721         group_name=ap_getword(sp,&ll,':');
722
723         while (*ll) {
724             w=ap_getword_conf(sp,&ll);
725             if (!strcmp(w,user)) {
726                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
727                 break;
728             }
729         }
730     }
731     ap_cfg_closefile(f);
732     ap_destroy_pool(sp);
733     return grps;
734 }
735
736 bool htAccessControl::authorized(const SPRequest& request, const Session* session) const
737 {
738     // Make sure the object is our type.
739     const ShibTargetApache* sta=dynamic_cast<const ShibTargetApache*>(&request);
740     if (!sta)
741         throw ConfigurationException("Request wrapper object was not of correct type.");
742
743     // mod_auth clone
744
745     int m=sta->m_req->method_number;
746     bool method_restricted=false;
747     const char *t, *w;
748     
749     const array_header* reqs_arr=ap_requires(sta->m_req);
750     if (!reqs_arr)
751         return true;
752
753     require_line* reqs=(require_line*)reqs_arr->elts;
754     
755     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE nelts: %d", reqs_arr->nelts);
756     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(sta->m_req),"REQUIRE all: %d", sta->m_dc->bRequireAll);
757
758     vector<bool> auth_OK(reqs_arr->nelts,false);
759
760 #define SHIB_AP_CHECK_IS_OK {           \
761      if (sta->m_dc->bRequireAll < 1)    \
762          return true;                   \
763      auth_OK[x] = true;                 \
764      continue;                          \
765 }
766
767     for (int x=0; x<reqs_arr->nelts; x++) {
768         auth_OK[x] = false;
769         if (!(reqs[x].method_mask & (1 << m)))
770             continue;
771         method_restricted=true;
772         string remote_user = request.getRemoteUser();
773
774         t = reqs[x].requirement;
775         w = ap_getword_white(sta->m_req->pool, &t);
776
777         if (!strcasecmp(w,"shibboleth")) {
778             // This is a dummy rule needed because Apache conflates authn and authz.
779             // Without some require rule, AuthType is ignored and no check_user hooks run.
780             SHIB_AP_CHECK_IS_OK;
781         }
782         else if (!strcmp(w,"valid-user")) {
783             if (session) {
784                 request.log(SPRequest::SPDebug,"htAccessControl plugin accepting valid-user based on active session");
785                 SHIB_AP_CHECK_IS_OK;
786             }
787             else
788                 request.log(SPRequest::SPError,"htAccessControl plugin rejecting access for valid-user rule, no session is active");
789         }
790         else if (!strcmp(w,"user") && !remote_user.empty()) {
791             bool regexp=false;
792             while (*t) {
793                 w=ap_getword_conf(sta->m_req->pool,&t);
794                 if (*w=='~') {
795                     regexp=true;
796                     continue;
797                 }
798                 
799                 if (regexp) {
800                     try {
801                         // To do regex matching, we have to convert from UTF-8.
802                         auto_ptr<XMLCh> trans(fromUTF8(w));
803                         RegularExpression re(trans.get());
804                         auto_ptr<XMLCh> trans2(fromUTF8(remote_user.c_str()));
805                         if (re.matches(trans2.get())) {
806                             request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
807                             SHIB_AP_CHECK_IS_OK;
808                         }
809                     }
810                     catch (XMLException& ex) {
811                         auto_ptr_char tmp(ex.getMessage());
812                         request.log(SPRequest::SPError,
813                             string("htAccessControl plugin caught exception while parsing regular expression (") + w + "): " + tmp.get());
814                     }
815                 }
816                 else if (remote_user==w) {
817                     request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting user (") + w + ")");
818                     SHIB_AP_CHECK_IS_OK;
819                 }
820             }
821         }
822         else if (!strcmp(w,"group")) {
823             SH_AP_TABLE* grpstatus=NULL;
824             if (sta->m_dc->szAuthGrpFile && !remote_user.empty()) {
825                 request.log(SPRequest::SPDebug,string("htAccessControl plugin using groups file: ") + sta->m_dc->szAuthGrpFile);
826                 grpstatus=groups_for_user(sta->m_req,remote_user.c_str(),sta->m_dc->szAuthGrpFile);
827             }
828             if (!grpstatus)
829                 return false;
830     
831             while (*t) {
832                 w=ap_getword_conf(sta->m_req->pool,&t);
833                 if (ap_table_get(grpstatus,w)) {
834                     request.log(SPRequest::SPDebug, string("htAccessControl plugin accepting group (") + w + ")");
835                     SHIB_AP_CHECK_IS_OK;
836                 }
837             }
838         }
839         else {
840             saml::Iterator<shibboleth::IAAP*> provs=dynamic_cast<const shibtarget::IApplication&>(request.getApplication()).getAAPProviders();
841             shibboleth::AAP wrapper(provs,w);
842             if (wrapper.fail()) {
843                 request.log(SPRequest::SPWarn, string("htAccessControl plugin didn't recognize require rule: ") + w);
844                 continue;
845             }
846
847             bool regexp=false;
848             const char* vals;
849             if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
850                 vals=remote_user.c_str();
851             else
852                 if (sta->m_dc->bUseEnvVars!=0) {
853                    if (sta->m_rc && sta->m_rc->env) vals=ap_table_get(sta->m_rc->env,wrapper->getHeader());
854                    else vals = NULL;
855                 } else {
856                    vals=ap_table_get(sta->m_req->headers_in,wrapper->getHeader());
857                 }
858
859             while (*t && vals && *vals) {
860                 w=ap_getword_conf(sta->m_req->pool,&t);
861                 if (*w=='~') {
862                     regexp=true;
863                     continue;
864                 }
865
866                 try {
867                     auto_ptr<RegularExpression> re;
868                     if (regexp) {
869                         delete re.release();
870                         auto_ptr<XMLCh> trans(fromUTF8(w));
871                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
872                         re=temp;
873                     }
874                     
875                     string vals_str(vals);
876                     int j = 0;
877                     for (unsigned int i = 0;  i < vals_str.length();  i++) {
878                         if (vals_str.at(i) == ';') {
879                             if (i == 0) {
880                                 request.log(SPRequest::SPError, string("htAccessControl plugin found invalid header encoding (") +
881                                     vals + "): starts with a semicolon");
882                                 throw saml::SAMLException("Invalid information supplied to authorization plugin.");
883                             }
884
885                             if (vals_str.at(i-1) == '\\') {
886                                 vals_str.erase(i-1, 1);
887                                 i--;
888                                 continue;
889                             }
890
891                             string val = vals_str.substr(j, i-j);
892                             j = i+1;
893                             if (regexp) {
894                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
895                                 if (re->matches(trans.get())) {
896                                     request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
897                                        ", got " + val + ": authorization granted");
898                                     SHIB_AP_CHECK_IS_OK;
899                                 }
900                             }
901                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
902                                 request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
903                                     ", got " + val + ": authorization granted.");
904                                 SHIB_AP_CHECK_IS_OK;
905                             }
906                             else {
907                                 request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
908                                     ", got " + val + ": authoritzation not granted.");
909                             }
910                         }
911                     }
912     
913                     string val = vals_str.substr(j, vals_str.length()-j);
914                     if (regexp) {
915                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
916                         if (re->matches(trans.get())) {
917                             request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
918                                 ", got " + val + ": authorization granted.");
919                             SHIB_AP_CHECK_IS_OK;
920                         }
921                     }
922                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
923                         request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
924                             ", got " + val + ": authorization granted");
925                         SHIB_AP_CHECK_IS_OK;
926                     }
927                     else {
928                             request.log(SPRequest::SPDebug, string("htAccessControl plugin expecting ") + w +
929                                 ", got " + val + ": authorization not granted");
930                     }
931                 }
932                 catch (XMLException& ex) {
933                     auto_ptr_char tmp(ex.getMessage());
934                     request.log(SPRequest::SPError, string("htAccessControl plugin caught exception while parsing regular expression (")
935                         + w + "): " + tmp.get());
936                 }
937             }
938         }
939     }
940
941     // check if all require directives are true
942     bool auth_all_OK = true;
943     for (int i= 0; i<reqs_arr->nelts; i++) {
944         auth_all_OK &= auth_OK[i];
945     }
946     if (auth_all_OK || !method_restricted)
947         return true;
948
949     return false;
950 }
951
952 #ifndef SHIB_APACHE_13
953 /*
954  * shib_exit()
955  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
956  */
957 extern "C" apr_status_t shib_exit(void* data)
958 {
959     if (g_Config) {
960         g_Config->shutdown();
961         g_Config = NULL;
962     }
963     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done");
964     return OK;
965 }
966 #endif
967
968
969 // Initial look at a request - create the per-request structure
970 static int shib_post_read(request_rec *r)
971 {
972     shib_request_config* rc = init_request_config(r);
973
974     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_post_read: E=%s", rc->env?"env":"hdr");
975
976 #ifdef SHIB_DEFERRED_HEADERS
977     rc->hdr_out = ap_make_table(r->pool, 5);
978     rc->hdr_err = ap_make_table(r->pool, 5);
979 #endif
980     return DECLINED;
981 }
982
983 // fixups: set environment vars
984
985 extern "C" int shib_fixups(request_rec* r)
986 {
987   shib_request_config *rc = (shib_request_config*)ap_get_module_config(r->request_config, &mod_shib);
988   shib_dir_config *dc = (shib_dir_config*)ap_get_module_config(r->per_dir_config, &mod_shib);
989   if (dc->bOff==1 || dc->bUseEnvVars==0)
990     return DECLINED;
991
992   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup(%d): ENTER", (int)getpid());
993
994   if (rc==NULL || rc->env==NULL || ap_is_empty_table(rc->env))
995         return DECLINED;
996
997   ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_fixup adding %d vars", ap_table_elts(rc->env)->nelts);
998   r->subprocess_env = ap_overlay_tables(r->pool, r->subprocess_env, rc->env);
999
1000   return OK;
1001 }
1002
1003 /*
1004  * shib_child_exit()
1005  *  Cleanup the (per-process) pool info.
1006  */
1007 #ifdef SHIB_APACHE_13
1008 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1009 {
1010 #else
1011 extern "C" apr_status_t shib_child_exit(void* data)
1012 {
1013   server_rec* s = NULL;
1014 #endif
1015
1016     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1017     g_Config->shutdown();
1018     g_Config = NULL;
1019     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done");
1020
1021 #ifndef SHIB_APACHE_13
1022     return OK;
1023 #endif
1024 }
1025
1026 /* 
1027  * shire_child_init()
1028  *  Things to do when the child process is initialized.
1029  *  (or after the configs are read in apache-2)
1030  */
1031 #ifdef SHIB_APACHE_13
1032 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1033 #else
1034 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1035 #endif
1036 {
1037     // Initialize runtime components.
1038
1039     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1040
1041     if (g_Config) {
1042         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1043         exit(1);
1044     }
1045
1046     try {
1047         g_Config=&shibtarget::ShibTargetConfig::getConfig();
1048         SPConfig::getConfig().setFeatures(
1049             SPConfig::Caching |
1050             SPConfig::Listener |
1051             SPConfig::Metadata |
1052             SPConfig::AAP |
1053             SPConfig::RequestMapping |
1054             SPConfig::InProcess |
1055             SPConfig::Logging
1056             );
1057         if (!g_Config->init(g_szSchemaDir)) {
1058             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize libraries");
1059             exit(1);
1060         }
1061         SPConfig::getConfig().AccessControlManager.registerFactory(HT_ACCESS_CONTROL,&htAccessFactory);
1062         SPConfig::getConfig().RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER,&ApacheRequestMapFactory);
1063         
1064         if (!g_Config->load(g_szSHIBConfig)) {
1065             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to load configuration");
1066             exit(1);
1067         }
1068
1069         ServiceProvider* conf=SPConfig::getConfig().getServiceProvider();
1070         xmltooling::Locker locker(conf);
1071         const PropertySet* props=conf->getPropertySet("Local");
1072         if (props) {
1073             pair<bool,const char*> unsetValue=props->getString("unsetHeaderValue");
1074             if (unsetValue.first)
1075                 g_unsetHeaderValue = unsetValue.second;
1076         }
1077     }
1078     catch (...) {
1079         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize system");
1080         exit(1);
1081     }
1082
1083     // Set the cleanup handler
1084     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1085
1086     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1087 }
1088
1089 // Output filters
1090 #ifdef SHIB_DEFERRED_HEADERS
1091 static void set_output_filter(request_rec *r)
1092 {
1093    ap_add_output_filter("SHIB_HEADERS_OUT", NULL, r, r->connection);
1094 }
1095
1096 static void set_error_filter(request_rec *r)
1097 {
1098    ap_add_output_filter("SHIB_HEADERS_ERR", NULL, r, r->connection);
1099 }
1100
1101 static apr_status_t do_output_filter(ap_filter_t *f, apr_bucket_brigade *in)
1102 {
1103     request_rec *r = f->r;
1104     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1105
1106     if (rc) {
1107         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_out_filter: merging %d headers", apr_table_elts(rc->hdr_out)->nelts);
1108         apr_table_overlap(r->headers_out, rc->hdr_out, APR_OVERLAP_TABLES_MERGE);
1109     }
1110
1111     /* remove ourselves from the filter chain */
1112     ap_remove_output_filter(f);
1113
1114     /* send the data up the stack */
1115     return ap_pass_brigade(f->next,in);
1116 }
1117
1118 static apr_status_t do_error_filter(ap_filter_t *f, apr_bucket_brigade *in)
1119 {
1120     request_rec *r = f->r;
1121     shib_request_config *rc = (shib_request_config*) ap_get_module_config(r->request_config, &mod_shib);
1122
1123     if (rc) {
1124         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_err_filter: merging %d headers", apr_table_elts(rc->hdr_err)->nelts);
1125         apr_table_overlap(r->err_headers_out, rc->hdr_err, APR_OVERLAP_TABLES_MERGE);
1126     }
1127
1128     /* remove ourselves from the filter chain */
1129     ap_remove_output_filter(f);
1130
1131     /* send the data up the stack */
1132     return ap_pass_brigade(f->next,in);
1133 }
1134 #endif // SHIB_DEFERRED_HEADERS
1135
1136 typedef const char* (*config_fn_t)(void);
1137
1138 #ifdef SHIB_APACHE_13
1139
1140 // SHIB Module commands
1141
1142 static command_rec shire_cmds[] = {
1143   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1144    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file"},
1145   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1146    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory"},
1147
1148   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1149    (void *) XtOffsetOf (shib_server_config, szScheme),
1150    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost"},
1151    
1152   {"ShibDisable", (config_fn_t)ap_set_flag_slot,
1153    (void *) XtOffsetOf (shib_dir_config, bOff),
1154    OR_AUTHCFG, FLAG, "Disable all Shib module activity here to save processing effort"},
1155   {"ShibApplicationId", (config_fn_t)ap_set_string_slot,
1156    (void *) XtOffsetOf (shib_dir_config, szApplicationId),
1157    OR_AUTHCFG, TAKE1, "Set Shibboleth applicationId property for content"},
1158   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1159    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1160    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shibboleth"},
1161   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1162    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1163    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist"},
1164   {"ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1165    (void *) XtOffsetOf (shib_dir_config, szRequireWith),
1166    OR_AUTHCFG, TAKE1, "Initiates a new session if one does not exist using a specific SessionInitiator"},
1167   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1168    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1169    OR_AUTHCFG, FLAG, "Export SAML attribute assertion(s) to Shib-Attributes header"},
1170   {"ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1171    (void *) XtOffsetOf (shib_dir_config, szRedirectToSSL),
1172    OR_AUTHCFG, TAKE1, "Redirect non-SSL requests to designated port" },
1173   {"AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1174    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1175    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1176   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1177    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1178    OR_AUTHCFG, FLAG, "All require directives must match"},
1179   {"ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1180    (void *) XtOffsetOf (shib_dir_config, bUseEnvVars),
1181    OR_AUTHCFG, FLAG, "Export data in environment instead of headers (default)"},
1182
1183   {NULL}
1184 };
1185
1186 extern "C"{
1187 handler_rec shib_handlers[] = {
1188   { "shib-handler", shib_handler },
1189   { NULL }
1190 };
1191
1192 module MODULE_VAR_EXPORT mod_shib = {
1193     STANDARD_MODULE_STUFF,
1194     NULL,                        /* initializer */
1195     create_shib_dir_config,     /* dir config creater */
1196     merge_shib_dir_config,      /* dir merger --- default is to override */
1197     create_shib_server_config, /* server config */
1198     merge_shib_server_config,   /* merge server config */
1199     shire_cmds,                 /* command table */
1200     shib_handlers,              /* handlers */
1201     NULL,                       /* filename translation */
1202     shib_check_user,            /* check_user_id */
1203     shib_auth_checker,          /* check auth */
1204     NULL,                       /* check access */
1205     NULL,                       /* type_checker */
1206     shib_fixups,                /* fixups */
1207     NULL,                       /* logger */
1208     NULL,                       /* header parser */
1209     shib_child_init,            /* child_init */
1210     shib_child_exit,            /* child_exit */
1211     shib_post_read              /* post read-request */
1212 };
1213
1214 #elif defined(SHIB_APACHE_20) || defined(SHIB_APACHE_22)
1215
1216 extern "C" void shib_register_hooks (apr_pool_t *p)
1217 {
1218 #ifdef SHIB_DEFERRED_HEADERS
1219   ap_register_output_filter("SHIB_HEADERS_OUT", do_output_filter, NULL, AP_FTYPE_CONTENT_SET);
1220   ap_hook_insert_filter(set_output_filter, NULL, NULL, APR_HOOK_LAST);
1221   ap_register_output_filter("SHIB_HEADERS_ERR", do_error_filter, NULL, AP_FTYPE_CONTENT_SET);
1222   ap_hook_insert_error_filter(set_error_filter, NULL, NULL, APR_HOOK_LAST);
1223   ap_hook_post_read_request(shib_post_read, NULL, NULL, APR_HOOK_MIDDLE);
1224 #endif
1225   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1226   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1227   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1228   ap_hook_handler(shib_handler, NULL, NULL, APR_HOOK_LAST);
1229   ap_hook_fixups(shib_fixups, NULL, NULL, APR_HOOK_MIDDLE);
1230 }
1231
1232 // SHIB Module commands
1233
1234 extern "C" {
1235 static command_rec shib_cmds[] = {
1236   AP_INIT_TAKE1("ShibConfig",
1237                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1238                 RSRC_CONF, "Path to shibboleth.xml config file"),
1239   AP_INIT_TAKE1("ShibSchemaDir",
1240      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1241       RSRC_CONF, "Path to Shibboleth XML schema directory"),
1242
1243   AP_INIT_TAKE1("ShibURLScheme",
1244      (config_fn_t)shib_set_server_string_slot,
1245      (void *) offsetof (shib_server_config, szScheme),
1246       RSRC_CONF, "URL scheme to force into generated URLs for a vhost"),
1247
1248   AP_INIT_FLAG("ShibDisable", (config_fn_t)ap_set_flag_slot,
1249         (void *) offsetof (shib_dir_config, bOff),
1250         OR_AUTHCFG, "Disable all Shib module activity here to save processing effort"),
1251   AP_INIT_TAKE1("ShibApplicationId", (config_fn_t)ap_set_string_slot,
1252         (void *) offsetof (shib_dir_config, szApplicationId),
1253         OR_AUTHCFG, "Set Shibboleth applicationId property for content"),
1254   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1255         (void *) offsetof (shib_dir_config, bBasicHijack),
1256         OR_AUTHCFG, "Respond to AuthType Basic and convert to shibboleth"),
1257   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1258         (void *) offsetof (shib_dir_config, bRequireSession),
1259         OR_AUTHCFG, "Initiates a new session if one does not exist"),
1260   AP_INIT_TAKE1("ShibRequireSessionWith", (config_fn_t)ap_set_string_slot,
1261         (void *) offsetof (shib_dir_config, szRequireWith),
1262         OR_AUTHCFG, "Initiates a new session if one does not exist using a specific SessionInitiator"),
1263   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1264         (void *) offsetof (shib_dir_config, bExportAssertion),
1265         OR_AUTHCFG, "Export SAML attribute assertion(s) to Shib-Attributes header"),
1266   AP_INIT_TAKE1("ShibRedirectToSSL", (config_fn_t)ap_set_string_slot,
1267         (void *) offsetof (shib_dir_config, szRedirectToSSL),
1268         OR_AUTHCFG, "Redirect non-SSL requests to designated port"),
1269   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)shib_ap_set_file_slot,
1270                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1271                 OR_AUTHCFG, "Text file containing group names and member user IDs"),
1272   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1273         (void *) offsetof (shib_dir_config, bRequireAll),
1274         OR_AUTHCFG, "All require directives must match"),
1275   AP_INIT_FLAG("ShibUseEnvironment", (config_fn_t)ap_set_flag_slot,
1276         (void *) offsetof (shib_dir_config, bUseEnvVars),
1277         OR_AUTHCFG, "Export data in environment instead of headers (default)"),
1278
1279   {NULL}
1280 };
1281
1282 module AP_MODULE_DECLARE_DATA mod_shib = {
1283     STANDARD20_MODULE_STUFF,
1284     create_shib_dir_config,     /* create dir config */
1285     merge_shib_dir_config,      /* merge dir config --- default is to override */
1286     create_shib_server_config,  /* create server config */
1287     merge_shib_server_config,   /* merge server config */
1288     shib_cmds,                  /* command table */
1289     shib_register_hooks         /* register hooks */
1290 };
1291
1292 #else
1293 #error "undefined APACHE version"
1294 #endif
1295
1296 }