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