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