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