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