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