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