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