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