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