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