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