Add a timeout reset to 1.3 module, emulating other examples.
[shibboleth/sp.git] / apache / mod_apache.cpp
1 /*
2  * mod_apache.cpp -- the core Apache Module code
3  *
4  * Created by:  Derek Atkins <derek@ihtfp.com>
5  *
6  * $Id$
7  */
8
9 #ifdef SOLARIS2
10 #undef _XOPEN_SOURCE    // causes gethostname conflict in unistd.h
11 #endif
12
13 // SAML Runtime
14 #include <saml/saml.h>
15 #include <shib/shib.h>
16 #include <shib/shib-threads.h>
17 #include <shib-target/shib-target.h>
18 #include <xercesc/util/regx/RegularExpression.hpp>
19
20 #undef _XPG4_2
21
22 // Apache specific header files
23 #include <httpd.h>
24 #include <http_config.h>
25 #include <http_protocol.h>
26 #include <http_main.h>
27 #define CORE_PRIVATE
28 #include <http_core.h>
29 #include <http_log.h>
30
31 #ifndef SHIB_APACHE_13
32 #include <http_request.h>
33 #include <apr_strings.h>
34 #include <apr_pools.h>
35 #endif
36
37 #include <fstream>
38 #include <sstream>
39
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>             // for getpid()
42 #endif
43
44 using namespace std;
45 using namespace saml;
46 using namespace shibboleth;
47 using namespace shibtarget;
48
49 extern "C" module MODULE_VAR_EXPORT mod_shib;
50 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire);
51
52 namespace {
53     char* g_szSHIBConfig = NULL;
54     char* g_szSchemaDir = NULL;
55     ShibTargetConfig* g_Config = NULL;
56     static const char* g_UserDataKey = "_shib_check_user_";
57 }
58
59 // per-server module configuration structure
60 struct shib_server_config
61 {
62     char* szScheme;
63 };
64
65 // creates the per-server configuration
66 extern "C" void* create_shib_server_config(SH_AP_POOL* p, server_rec* s)
67 {
68     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
69     sc->szScheme = NULL;
70     return sc;
71 }
72
73 // overrides server configuration in virtual servers
74 extern "C" void* merge_shib_server_config (SH_AP_POOL* p, void* base, void* sub)
75 {
76     shib_server_config* sc=(shib_server_config*)ap_pcalloc(p,sizeof(shib_server_config));
77     shib_server_config* parent=(shib_server_config*)base;
78     shib_server_config* child=(shib_server_config*)sub;
79
80     if (child->szScheme)
81         sc->szScheme=ap_pstrdup(p,child->szScheme);
82     else if (parent->szScheme)
83         sc->szScheme=ap_pstrdup(p,parent->szScheme);
84     else
85         sc->szScheme=NULL;
86
87     return sc;
88 }
89
90 // per-dir module configuration structure
91 struct shib_dir_config
92 {
93     // RM Configuration
94     char* szAuthGrpFile;    // Auth GroupFile name
95     int bRequireAll;        // all require directives must match, otherwise OR logic
96
97     // SHIRE Configuration
98     int bBasicHijack;       // activate for AuthType Basic?
99     int bRequireSession;    // require a session?
100     int bExportAssertion;   // export SAML assertion to the environment?
101 };
102
103 // creates per-directory config structure
104 extern "C" void* create_shib_dir_config (SH_AP_POOL* p, char* d)
105 {
106     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
107     dc->bBasicHijack = -1;
108     dc->bRequireSession = -1;
109     dc->bExportAssertion = -1;
110     dc->bRequireAll = -1;
111     dc->szAuthGrpFile = NULL;
112     return dc;
113 }
114
115 // overrides server configuration in directories
116 extern "C" void* merge_shib_dir_config (SH_AP_POOL* p, void* base, void* sub)
117 {
118     shib_dir_config* dc=(shib_dir_config*)ap_pcalloc(p,sizeof(shib_dir_config));
119     shib_dir_config* parent=(shib_dir_config*)base;
120     shib_dir_config* child=(shib_dir_config*)sub;
121
122     if (child->szAuthGrpFile)
123         dc->szAuthGrpFile=ap_pstrdup(p,child->szAuthGrpFile);
124     else if (parent->szAuthGrpFile)
125         dc->szAuthGrpFile=ap_pstrdup(p,parent->szAuthGrpFile);
126     else
127         dc->szAuthGrpFile=NULL;
128
129     dc->bBasicHijack=((child->bBasicHijack==-1) ? parent->bBasicHijack : child->bBasicHijack);
130     dc->bRequireSession=((child->bRequireSession==-1) ? parent->bRequireSession : child->bRequireSession);
131     dc->bExportAssertion=((child->bExportAssertion==-1) ? parent->bExportAssertion : child->bExportAssertion);
132     dc->bRequireAll=((child->bRequireAll==-1) ? parent->bRequireAll : child->bRequireAll);
133     return dc;
134 }
135
136 // generic global slot handlers
137 extern "C" const char* ap_set_global_string_slot(cmd_parms* parms, void*, const char* arg)
138 {
139     *((char**)(parms->info))=ap_pstrdup(parms->pool,arg);
140     return NULL;
141 }
142
143 extern "C" const char* shib_set_server_string_slot(cmd_parms* parms, void*, const char* arg)
144 {
145     char* base=(char*)ap_get_module_config(parms->server->module_config,&mod_shib);
146     int offset=(int)parms->info;
147     *((char**)(base + offset))=ap_pstrdup(parms->pool,arg);
148     return NULL;
149 }
150
151 typedef const char* (*config_fn_t)(void);
152
153 static int shib_error_page(request_rec* r, const IApplication* app, const char* page, ShibMLP& mlp)
154 {
155     const IPropertySet* props=app->getPropertySet("Errors");
156     if (props) {
157         pair<bool,const char*> p=props->getString(page);
158         if (p.first) {
159             ifstream infile(p.second);
160             if (!infile.fail()) {
161                 const char* res = mlp.run(infile,props);
162                 if (res) {
163                     r->content_type = ap_psprintf(r->pool, "text/html");
164                     ap_send_http_header(r);
165                     ap_rprintf(r, res);
166                     return DONE;
167                 }
168             }
169         }
170     }
171
172     ap_log_rerror(APLOG_MARK,APLOG_ERR,SH_AP_R(r),
173         "shib_error_page() could not process shire error template for application %s",app->getId());
174     return SERVER_ERROR;
175 }
176
177 static char* shib_get_targeturl(request_rec* r, const char* scheme=NULL)
178 {
179     // On 1.3, this is always canonical, but on 2.0, UseCanonicalName comes into play.
180     // However, we also have a setting to forcibly replace the scheme for esoteric cases.
181     if (scheme) {
182         unsigned port = ap_get_server_port(r);
183         if ((!strcmp(scheme,"http") && port==80) || (!strcmp(scheme,"https") && port==443)) {
184             return ap_pstrcat(r->pool, scheme, "://", ap_get_server_name(r), r->unparsed_uri, NULL);
185         }
186         return ap_psprintf(r->pool, "%s://%s:%u%s", scheme, ap_get_server_name(r), port, r->unparsed_uri);
187     }
188     return ap_construct_url(r->pool,r->unparsed_uri,r);
189 }
190
191 extern "C" int shib_check_user(request_rec* r)
192 {
193     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: ENTER");
194     shib_dir_config* dc=(shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
195     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
196
197     ostringstream threadid;
198     threadid << "[" << getpid() << "] shib_check_user" << '\0';
199     saml::NDC ndc(threadid.str().c_str());
200
201     const char* targeturl=shib_get_targeturl(r,sc->szScheme);
202
203     // We lock the configuration system for the duration.
204     IConfig* conf=g_Config->getINI();
205     Locker locker(conf);
206     
207     // Map request to application and content settings.
208     IRequestMapper* mapper=conf->getRequestMapper();
209     Locker locker2(mapper);
210     IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
211         (sc-> szScheme ? sc-> szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
212         );
213     pair<bool,const char*> application_id=settings.first->getString("applicationId");
214     const IApplication* application=conf->getApplication(application_id.second);
215     if (!application) {
216         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
217            "shib_check_user: unable to map request to application settings, check configuration");
218         return SERVER_ERROR;
219     }
220     
221     // Declare SHIRE object for this request.
222     SHIRE shire(application);
223     
224     const char* shireURL=shire.getShireURL(targeturl);
225     if (!shireURL) {
226         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
227            "shib_check_user: unable to map request to proper shireURL setting, check configuration");
228         return SERVER_ERROR;
229     }
230     
231     // Get location of this application's assertion consumer service and see if this is it.
232     if (strstr(targeturl,shireURL)) {
233         return shib_handler(r,application,shire);
234     }
235
236     // We can short circuit the handler if we run this...
237     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
238
239     // Regular access to arbitrary resource...check AuthType
240     const char *auth_type=ap_auth_type(r);
241     if (!auth_type)
242         return DECLINED;
243
244     if (strcasecmp(auth_type,"shibboleth")) {
245         if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
246             core_dir_config* conf=
247                 (core_dir_config*)ap_get_module_config(r->per_dir_config,
248                     ap_find_linked_module("http_core.c"));
249             conf->ap_auth_type="shibboleth";
250         }
251         else
252             return DECLINED;
253     }
254
255     pair<bool,bool> requireSession = settings.first->getBool("requireSession");
256     if (!requireSession.first || !requireSession.second)
257         if (dc->bRequireSession==1)
258             requireSession.second=true;
259
260     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
261
262     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns *something*
263
264     // We're in charge, so check for cookie.
265     const char* session_id=NULL;
266     const char* cookies=ap_table_get(r->headers_in,"Cookie");
267
268     if (cookies) {
269         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
270         if (session_id=strstr(cookies,shib_cookie.first)) {
271             // Yep, we found a cookie -- pull it out (our session_id)
272             session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
273             char* cookiebuf = ap_pstrdup(r->pool,session_id);
274             char* cookieend = strchr(cookiebuf,';');
275             if (cookieend)
276                 *cookieend = '\0';    /* Ignore anyting after a ; */
277             session_id=cookiebuf;
278         }
279     }
280
281     if (!session_id || !*session_id) {
282         // If no session required, bail now.
283         if (!requireSession.second)
284             return OK;
285
286         // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
287         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
288         ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
289         return REDIRECT;
290     }
291
292     // Make sure this session is still valid.
293     RPCError* status = NULL;
294     ShibMLP markupProcessor;
295     markupProcessor.insert("requestURL", targeturl);
296
297     try {
298         status = shire.sessionIsValid(session_id, r->connection->remote_ip);
299     }
300     catch (ShibTargetException &e) {
301         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
302         markupProcessor.insert("errorType", "Session Processing Error");
303         markupProcessor.insert("errorText", e.what());
304         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
305         return shib_error_page(r, application, "shire", markupProcessor);
306     }
307 #ifndef _DEBUG
308     catch (...) {
309         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
310         markupProcessor.insert("errorType", "Session Processing Error");
311         markupProcessor.insert("errorText", "Unexpected Exception");
312         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
313         return shib_error_page(r, application, "shire", markupProcessor);
314     }
315 #endif
316
317     // Check the status
318     if (status->isError()) {
319         ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
320                       "shib_check_user() session invalid: %s", status->getText());
321
322         // If no session required, bail now.
323         if (!requireSession.second)
324             return OK;  // XXX: Or should this be DECLINED?
325                         // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
326                         // anything to process the AuthType. No session plus requireSession false means 
327                         // do not authenticate the user.
328         else if (status->isRetryable()) {
329             // Oops, session is invalid. Generate AuthnRequest.
330             ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
331             delete status;
332             return REDIRECT;
333         }
334         else {
335             // return the error page to the user
336             markupProcessor.insert(*status);
337             delete status;
338             return shib_error_page(r, application, "shire", markupProcessor);
339         }
340     }
341
342     delete status;
343     // set the authtype
344 #ifdef SHIB_APACHE_13
345     if (r->connection)
346         r->connection->ap_auth_type = "shibboleth";
347 #else
348     r->ap_auth_type = "shibboleth";
349 #endif
350     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
351
352     // This is code transferred in from the auth check to export the attributes.
353     // We could even combine the isSessionValid/getAssertions API...?
354
355     RM rm(application);
356     vector<SAMLAssertion*> assertions;
357     SAMLAuthenticationStatement* sso_statement=NULL;
358
359     try {
360         status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
361     }
362     catch (ShibTargetException &e) {
363         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
364         markupProcessor.insert("errorType", "Attribute Processing Error");
365         markupProcessor.insert("errorText", e.what());
366         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
367         return shib_error_page(r, application, "rm", markupProcessor);
368     }
369 #ifndef _DEBUG
370     catch (...) {
371         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
372         markupProcessor.insert("errorType", "Attribute Processing Error");
373         markupProcessor.insert("errorText", "Unexpected Exception");
374         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
375         return shib_error_page(r, application, "rm", markupProcessor);
376     }
377 #endif
378
379     if (status->isError()) {
380         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
381             "shib_check_user() getAssertions failed: %s", status->getText());
382
383         markupProcessor.insert(*status);
384         delete status;
385         return shib_error_page(r, application, "rm", markupProcessor);
386     }
387     delete status;
388
389     // Do we have an access control plugin?
390     if (settings.second) {
391         Locker acllock(settings.second);
392         if (!settings.second->authorized(*sso_statement,assertions)) {
393             for (int k = 0; k < assertions.size(); k++)
394                 delete assertions[k];
395             delete sso_statement;
396             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
397             return shib_error_page(r, application, "access", markupProcessor);
398         }
399     }
400
401     // Get the AAP providers, which contain the attribute policy info.
402     Iterator<IAAP*> provs=application->getAAPProviders();
403
404     // Clear out the list of mapped attributes
405     while (provs.hasNext()) {
406         IAAP* aap=provs.next();
407         aap->lock();
408         try {
409             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
410             while (rules.hasNext()) {
411                 const char* header=rules.next()->getHeader();
412                 if (header)
413                     ap_table_unset(r->headers_in,header);
414             }
415         }
416         catch(...) {
417             aap->unlock();
418             for (int k = 0; k < assertions.size(); k++)
419                 delete assertions[k];
420             delete sso_statement;
421             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
422                 "shib_check_user(): caught unexpected error while clearing headers");
423             markupProcessor.insert("errorType", "Attribute Processing Error");
424             markupProcessor.insert("errorText", "Unexpected Exception");
425             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
426             return shib_error_page(r, application, "rm", markupProcessor);
427         }
428         aap->unlock();
429     }
430     provs.reset();
431     
432     // Maybe export the first assertion.
433     ap_table_unset(r->headers_in,"Shib-Attributes");
434     pair<bool,bool> exp=settings.first->getBool("exportAssertion");
435     if (!exp.first || !exp.second)
436         if (dc->bExportAssertion==1)
437             exp.second=true;
438     if (exp.second && assertions.size()) {
439         string assertion;
440         RM::serialize(*(assertions[0]), assertion);
441         ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
442     }
443
444     // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
445     ap_table_unset(r->headers_in,"Shib-Origin-Site");
446     ap_table_unset(r->headers_in,"Shib-Authentication-Method");
447     ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
448     auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
449     auto_ptr_char am(sso_statement->getAuthMethod());
450     ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
451     ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
452     
453     // Export NameID?
454     AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
455     if (!wrapper.fail() && wrapper->getHeader()) {
456         auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
457         auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
458         ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
459         if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
460             SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
461         else
462             ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
463     }
464     
465     ap_table_unset(r->headers_in,"Shib-Application-ID");
466     ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
467
468     // Export the attributes.
469     Iterator<SAMLAssertion*> a_iter(assertions);
470     while (a_iter.hasNext()) {
471         SAMLAssertion* assert=a_iter.next();
472         Iterator<SAMLStatement*> statements=assert->getStatements();
473         while (statements.hasNext()) {
474             SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
475             if (!astate)
476                 continue;
477             Iterator<SAMLAttribute*> attrs=astate->getAttributes();
478             while (attrs.hasNext()) {
479                 SAMLAttribute* attr=attrs.next();
480         
481                 // Are we supposed to export it?
482                 AAP wrapper(provs,attr->getName(),attr->getNamespace());
483                 if (wrapper.fail() || !wrapper->getHeader())
484                     continue;
485                 
486                 Iterator<string> vals=attr->getSingleByteValues();
487                 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
488                     SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
489                 else {
490                     int it=0;
491                     char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
492                     if (header) {
493                         header=ap_pstrdup(r->pool, header);
494                         it++;
495                     }
496                     else
497                         header = ap_pstrdup(r->pool, "");
498                     for (; vals.hasNext(); it++) {
499                         string value = vals.next();
500                         for (string::size_type pos = value.find_first_of(";", string::size_type(0));
501                                 pos != string::npos;
502                                 pos = value.find_first_of(";", pos)) {
503                             value.insert(pos, "\\");
504                             pos += 2;
505                         }
506                         header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
507                     }
508                     ap_table_setn(r->headers_in, wrapper->getHeader(), header);
509                }
510             }
511         }
512     }
513
514     // clean up memory
515     for (int k = 0; k < assertions.size(); k++)
516         delete assertions[k];
517     delete sso_statement;
518
519     return OK;
520 }
521
522 extern "C" int shib_post_handler(request_rec* r)
523 {
524     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
525                 "shib_post_handler(%d): ENTER", (int)getpid());
526     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
527
528 #ifndef SHIB_APACHE_13
529     // With 2.x, this handler always runs, though last.
530     // We check if shib_check_user ran, because it will detect a SHIRE request
531     // and dispatch it directly.
532     void* data;
533     apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
534     if (data==(const void*)42) {
535         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
536         return DECLINED;
537     }
538 #endif
539     
540     ostringstream threadid;
541     threadid << "[" << getpid() << "] shib_post_handler" << '\0';
542     saml::NDC ndc(threadid.str().c_str());
543
544     // We lock the configuration system for the duration.
545     IConfig* conf=g_Config->getINI();
546     Locker locker(conf);
547     
548     // Map request to application and content settings.
549     IRequestMapper* mapper=conf->getRequestMapper();
550     Locker locker2(mapper);
551     IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
552         (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
553         );
554     pair<bool,const char*> application_id=settings.first->getString("applicationId");
555     const IApplication* application=conf->getApplication(application_id.second);
556     if (!application) {
557         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
558            "shib_post_handler: unable to map request to application settings, check configuration");
559         return SERVER_ERROR;
560     }
561     
562     // Declare SHIRE object for this request.
563     SHIRE shire(application);
564     
565     return shib_handler(r, application, shire);
566 }
567
568 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
569 {
570     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
571
572     const char* targeturl=shib_get_targeturl(r,sc->szScheme);
573
574     const char* shireURL=shire.getShireURL(targeturl);
575     if (!shireURL) {
576         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
577            "shib_post_handler: unable to map request to proper shireURL setting, check configuration");
578         return SERVER_ERROR;
579     }
580
581     // Make sure we only process the SHIRE requests.
582     if (!strstr(targeturl,shireURL))
583         return DECLINED;
584
585     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
586
587     const IPropertySet* sessionProps=application->getPropertySet("Sessions");
588     if (!sessionProps) {
589         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
590            "shib_post_handler: unable to map request to application session settings, check configuration");
591         return SERVER_ERROR;
592     }
593
594     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns something
595
596     ShibMLP markupProcessor;
597     markupProcessor.insert("requestURL", targeturl);
598
599     // Process SHIRE request
600     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
601       
602     try {
603         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
604       
605         // Make sure this is SSL, if it should be
606         if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
607             throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
608
609         // If this is a GET, we manufacture an AuthnRequest.
610         if (!strcasecmp(r->method,"GET")) {
611             const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
612             if (!areq)
613                 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
614             ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
615             return REDIRECT;
616         }
617         else if (strcasecmp(r->method,"POST")) {
618             throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
619         }
620
621         // Sure sure this POST is an appropriate content type
622         const char *ct = ap_table_get(r->headers_in, "Content-type");
623         if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
624             throw ShibTargetException(SHIBRPC_OK,
625                                       ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
626
627         // Read the posted data
628         if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
629             throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
630         if (!ap_should_client_block(r))
631             throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
632         if (r->remaining > 1024*1024)
633             throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
634
635         string cgistr;
636         char buff[HUGE_STRING_LEN];
637         ap_hard_timeout("[mod_shib] CGI Parser", r);
638         memset(buff, 0, sizeof(buff));
639         while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
640             ap_reset_timeout(r);
641             cgistr += buff;
642             memset(buff, 0, sizeof(buff));
643         }
644         ap_kill_timeout(r);
645
646         // Parse the submission.
647         pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
648     
649         // Make sure the SAML Response parameter exists
650         if (!elements.first || !*elements.first)
651             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
652     
653         // Make sure the target parameter exists
654         if (!elements.second || !*elements.second)
655             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
656     
657         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
658             "shib_handler() Processing POST for target: %s", elements.second);
659
660         // process the post
661         string cookie;
662         RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
663
664         if (status->isError()) {
665             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
666                     "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
667
668             if (status->isRetryable()) {
669                 delete status;
670                 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
671                         "shib_handler() retryable error, generating new AuthnRequest");
672                 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
673                 return REDIRECT;
674             }
675
676             // return this error to the user.
677             markupProcessor.insert(*status);
678             delete status;
679             return shib_error_page(r, application, "shire", markupProcessor);
680         }
681         delete status;
682
683         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
684                   "shib_handler() POST process succeeded.  New session: %s", cookie.c_str());
685
686         // We've got a good session, set the cookie...
687         char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
688         ap_table_setn(r->err_headers_out, "Set-Cookie", val);
689         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
690
691         // ... and redirect to the target
692         ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
693         return REDIRECT;
694     }
695     catch (ShibTargetException &e) {
696         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
697         markupProcessor.insert("errorType", "Session Creation Service Error");
698         markupProcessor.insert("errorText", e.what());
699         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
700         return shib_error_page(r, application, "shire", markupProcessor);
701     }
702 #ifndef _DEBUG
703     catch (...) {
704         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
705         markupProcessor.insert("errorType", "Session Creation Service Error");
706         markupProcessor.insert("errorText", "Unknown Exception");
707         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
708         return shib_error_page(r, application, "shire", markupProcessor);
709     }
710 #endif
711
712     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
713     return SERVER_ERROR;
714 }
715
716 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
717 {
718     SH_AP_CONFIGFILE* f;
719     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
720     char l[MAX_STRING_LEN];
721     const char *group_name, *ll, *w;
722
723 #ifdef SHIB_APACHE_13
724     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
725 #else
726     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
727 #endif
728         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
729         return NULL;
730     }
731
732     SH_AP_POOL* sp;
733 #ifdef SHIB_APACHE_13
734     sp=ap_make_sub_pool(r->pool);
735 #else
736     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
737         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
738             "groups_for_user() could not create a subpool");
739         return NULL;
740     }
741 #endif
742
743     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
744         if ((*l=='#') || (!*l))
745             continue;
746         ll = l;
747         ap_clear_pool(sp);
748
749         group_name=ap_getword(sp,&ll,':');
750
751         while (*ll) {
752             w=ap_getword_conf(sp,&ll);
753             if (!strcmp(w,user)) {
754                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
755                 break;
756             }
757         }
758     }
759     ap_cfg_closefile(f);
760     ap_destroy_pool(sp);
761     return grps;
762 }
763
764 /*
765  * shib_auth_checker() -- a simple resource manager to
766  * process the .htaccess settings and copy attributes
767  * into the HTTP headers.
768  */
769 extern "C" int shib_auth_checker(request_rec* r)
770 {
771     shib_dir_config* dc=
772         (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
773
774     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
775
776     // Regular access to arbitrary resource...check AuthType
777     const char* auth_type=ap_auth_type(r);
778     if (!auth_type || strcasecmp(auth_type,"shibboleth"))
779         return DECLINED;
780
781     ostringstream threadid;
782     threadid << "[" << getpid() << "] shibrm" << '\0';
783     saml::NDC ndc(threadid.str().c_str());
784
785     // We lock the configuration system for the duration.
786     IConfig* conf=g_Config->getINI();
787     Locker locker(conf);
788     
789     const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
790     const IApplication* application=NULL;
791     if (application_id)
792         application = conf->getApplication(application_id);
793
794     // mod_auth clone
795
796     int m=r->method_number;
797     bool method_restricted=false;
798     const char *t, *w;
799     
800     const array_header* reqs_arr=ap_requires(r);
801     if (!reqs_arr)
802         return OK;
803
804     require_line* reqs=(require_line*)reqs_arr->elts;
805
806     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
807     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
808
809     vector<bool> auth_OK(reqs_arr->nelts,false);
810
811 #define SHIB_AP_CHECK_IS_OK {       \
812      if (dc->bRequireAll < 1)    \
813          return OK;      \
814      auth_OK[x] = true;      \
815      continue;           \
816 }
817
818     for (int x=0; x<reqs_arr->nelts; x++) {
819         auth_OK[x] = false;
820         if (!(reqs[x].method_mask & (1 << m)))
821             continue;
822         method_restricted=true;
823
824         t = reqs[x].requirement;
825         w = ap_getword_white(r->pool, &t);
826
827         if (!strcasecmp(w,"Shibboleth")) {
828             // This is a dummy rule needed because Apache conflates authn and authz.
829             // Without some require rule, AuthType is ignored and no check_user hooks run.
830             SHIB_AP_CHECK_IS_OK;
831         }
832         else if (!strcmp(w,"valid-user") && application_id) {
833             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
834             SHIB_AP_CHECK_IS_OK;
835         }
836         else if (!strcmp(w,"user") && SH_AP_USER(r)) {
837             bool regexp=false;
838             while (*t) {
839                 w=ap_getword_conf(r->pool,&t);
840                 if (*w=='~') {
841                     regexp=true;
842                     continue;
843                 }
844                 
845                 if (regexp) {
846                     try {
847                         // To do regex matching, we have to convert from UTF-8.
848                         auto_ptr<XMLCh> trans(fromUTF8(w));
849                         RegularExpression re(trans.get());
850                         auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
851                         if (re.matches(trans2.get())) {
852                             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
853                             SHIB_AP_CHECK_IS_OK;
854                         }
855                     }
856                     catch (XMLException& ex) {
857                         auto_ptr_char tmp(ex.getMessage());
858                         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
859                                         "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
860                     }
861                 }
862                 else if (!strcmp(SH_AP_USER(r),w)) {
863                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
864                     SHIB_AP_CHECK_IS_OK;
865                 }
866             }
867         }
868         else if (!strcmp(w,"group")) {
869             SH_AP_TABLE* grpstatus=NULL;
870             if (dc->szAuthGrpFile && SH_AP_USER(r)) {
871                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
872                 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
873             }
874             if (!grpstatus)
875                 return DECLINED;
876     
877             while (*t) {
878                 w=ap_getword_conf(r->pool,&t);
879                 if (ap_table_get(grpstatus,w)) {
880                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
881                     SHIB_AP_CHECK_IS_OK;
882                 }
883             }
884         }
885         else {
886             Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
887             AAP wrapper(provs,w);
888             if (wrapper.fail()) {
889                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
890                     "shib_auth_checker() didn't recognize require rule: %s\n",w);
891                 continue;
892             }
893
894             bool regexp=false;
895             const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
896             while (*t && vals) {
897                 w=ap_getword_conf(r->pool,&t);
898                 if (*w=='~') {
899                     regexp=true;
900                     continue;
901                 }
902
903                 try {
904                     auto_ptr<RegularExpression> re;
905                     if (regexp) {
906                         delete re.release();
907                         auto_ptr<XMLCh> trans(fromUTF8(w));
908                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
909                         re=temp;
910                     }
911                     
912                     string vals_str(vals);
913                     int j = 0;
914                     for (int i = 0;  i < vals_str.length();  i++) {
915                         if (vals_str.at(i) == ';') {
916                             if (i == 0) {
917                                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
918                                                 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
919                                 return SERVER_ERROR;
920                             }
921
922                             if (vals_str.at(i-1) == '\\') {
923                                 vals_str.erase(i-1, 1);
924                                 i--;
925                                 continue;
926                             }
927
928                             string val = vals_str.substr(j, i-j);
929                             j = i+1;
930                             if (regexp) {
931                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
932                                 if (re->matches(trans.get())) {
933                                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
934                                                     "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
935                                     SHIB_AP_CHECK_IS_OK;
936                                 }
937                             }
938                             else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
939                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
940                                                 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
941                                 SHIB_AP_CHECK_IS_OK;
942                             }
943                             else {
944                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
945                                                 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
946                             }
947                         }
948                     }
949     
950                     string val = vals_str.substr(j, vals_str.length()-j);
951                     if (regexp) {
952                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
953                         if (re->matches(trans.get())) {
954                             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
955                                             "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
956                             SHIB_AP_CHECK_IS_OK;
957                         }
958                     }
959                     else if ((wrapper->getCaseSensitive() && val==w) || (!wrapper->getCaseSensitive() && !strcasecmp(val.c_str(),w))) {
960                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
961                                         "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
962                         SHIB_AP_CHECK_IS_OK;
963                     }
964                     else {
965                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
966                                         "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
967                     }
968                 }
969                 catch (XMLException& ex) {
970                     auto_ptr_char tmp(ex.getMessage());
971                     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
972                                     "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
973                 }
974             }
975         }
976     }
977
978     // check if all require directives are true
979     bool auth_all_OK = true;
980     for (int i= 0; i<reqs_arr->nelts; i++) {
981         auth_all_OK &= auth_OK[i];
982     }
983     if (auth_all_OK)
984         return OK;
985
986     if (!method_restricted)
987         return OK;
988
989     if (!application_id) {
990         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
991            "shib_auth_checker: Shib-Application-ID header not found in request");
992         return HTTP_FORBIDDEN;
993     }
994     else if (!application) {
995         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
996            "shib_auth_checker: unable to map request to application settings, check configuration");
997         return HTTP_FORBIDDEN;
998     }
999
1000     ShibMLP markupProcessor;
1001     markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
1002     return shib_error_page(r, application, "access", markupProcessor);
1003 }
1004
1005 #ifndef SHIB_APACHE_13
1006 /*
1007  * shib_exit()
1008  *  Empty cleanup hook, Apache 2.x doesn't check NULL very well...
1009  */
1010 extern "C" apr_status_t shib_exit(void* data)
1011 {
1012     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,0,NULL,"shib_exit() done\n");
1013     return OK;
1014 }
1015 #endif
1016
1017
1018 /*
1019  * shib_child_exit()
1020  *  Cleanup the (per-process) pool info.
1021  */
1022 #ifdef SHIB_APACHE_13
1023 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1024 {
1025 #else
1026 extern "C" apr_status_t shib_child_exit(void* data)
1027 {
1028   server_rec* s = NULL;
1029 #endif
1030
1031     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d) dealing with g_Config..", (int)getpid());
1032     g_Config->shutdown();
1033     g_Config = NULL;
1034     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit() done\n");
1035
1036 #ifndef SHIB_APACHE_13
1037     return OK;
1038 #endif
1039 }
1040
1041 /* 
1042  * shire_child_init()
1043  *  Things to do when the child process is initialized.
1044  *  (or after the configs are read in apache-2)
1045  */
1046 #ifdef SHIB_APACHE_13
1047 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1048 #else
1049 extern "C" void shib_child_init(apr_pool_t* p, server_rec* s)
1050 #endif
1051 {
1052     // Initialize runtime components.
1053
1054     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1055
1056     if (g_Config) {
1057         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1058         exit(1);
1059     }
1060
1061     try {
1062         g_Config=&ShibTargetConfig::getConfig();
1063         g_Config->setFeatures(
1064             ShibTargetConfig::Listener |
1065             ShibTargetConfig::Metadata |
1066             ShibTargetConfig::AAP |
1067             ShibTargetConfig::RequestMapper |
1068             ShibTargetConfig::SHIREExtensions |
1069             ShibTargetConfig::Logging
1070             );
1071         if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1072             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1073             exit(1);
1074         }
1075     }
1076     catch (...) {
1077         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1078         exit (1);
1079     }
1080
1081     // Set the cleanup handler
1082     apr_pool_cleanup_register(p, NULL, &shib_exit, &shib_child_exit);
1083
1084     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1085 }
1086
1087 #ifdef SHIB_APACHE_13
1088
1089 // SHIB Module commands
1090
1091 static command_rec shire_cmds[] = {
1092   {"SHIREConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1093    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1094   {"ShibConfig", (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1095    RSRC_CONF, TAKE1, "Path to shibboleth.xml config file."},
1096   {"ShibSchemaDir", (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1097    RSRC_CONF, TAKE1, "Path to Shibboleth XML schema directory."},
1098
1099   {"ShibURLScheme", (config_fn_t)shib_set_server_string_slot,
1100    (void *) XtOffsetOf (shib_server_config, szScheme),
1101    RSRC_CONF, TAKE1, "URL scheme to force into generated URLs for a vhost."},
1102    
1103   {"ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1104    (void *) XtOffsetOf (shib_dir_config, bBasicHijack),
1105    OR_AUTHCFG, FLAG, "Respond to AuthType Basic and convert to shib?"},
1106   {"ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1107    (void *) XtOffsetOf (shib_dir_config, bRequireSession),
1108    OR_AUTHCFG, FLAG, "Initiates a new session if one does not exist."},
1109   {"ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1110    (void *) XtOffsetOf (shib_dir_config, bExportAssertion),
1111    OR_AUTHCFG, FLAG, "Export SAML assertion to Shibboleth-defined header?"},
1112   {"AuthGroupFile", (config_fn_t)ap_set_file_slot,
1113    (void *) XtOffsetOf (shib_dir_config, szAuthGrpFile),
1114    OR_AUTHCFG, TAKE1, "text file containing group names and member user IDs"},
1115   {"ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1116    (void *) XtOffsetOf (shib_dir_config, bRequireAll),
1117    OR_AUTHCFG, FLAG, "All require directives must match!"},
1118
1119   {NULL}
1120 };
1121
1122 extern "C"{
1123 handler_rec shib_handlers[] = {
1124   { "shib-shire-post", shib_post_handler },
1125   { NULL }
1126 };
1127
1128 module MODULE_VAR_EXPORT mod_shib = {
1129     STANDARD_MODULE_STUFF,
1130     NULL,                        /* initializer */
1131     create_shib_dir_config,     /* dir config creater */
1132     merge_shib_dir_config,      /* dir merger --- default is to override */
1133     create_shib_server_config, /* server config */
1134     merge_shib_server_config,   /* merge server config */
1135     shire_cmds,                 /* command table */
1136     shib_handlers,              /* handlers */
1137     NULL,                       /* filename translation */
1138     shib_check_user,            /* check_user_id */
1139     shib_auth_checker,          /* check auth */
1140     NULL,                       /* check access */
1141     NULL,                       /* type_checker */
1142     NULL,                       /* fixups */
1143     NULL,                       /* logger */
1144     NULL,                       /* header parser */
1145     shib_child_init,            /* child_init */
1146     shib_child_exit,            /* child_exit */
1147     NULL                        /* post read-request */
1148 };
1149
1150 #elif defined(SHIB_APACHE_20)
1151
1152 extern "C" void shib_register_hooks (apr_pool_t *p)
1153 {
1154   ap_hook_child_init(shib_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1155   ap_hook_check_user_id(shib_check_user, NULL, NULL, APR_HOOK_MIDDLE);
1156   ap_hook_auth_checker(shib_auth_checker, NULL, NULL, APR_HOOK_FIRST);
1157   ap_hook_handler(shib_post_handler, NULL, NULL, APR_HOOK_LAST);
1158 }
1159
1160 // SHIB Module commands
1161
1162 extern "C" {
1163 static command_rec shib_cmds[] = {
1164   AP_INIT_TAKE1("ShibConfig",
1165                 (config_fn_t)ap_set_global_string_slot, &g_szSHIBConfig,
1166                 RSRC_CONF, "Path to shibboleth.xml config file."),
1167   AP_INIT_TAKE1("ShibSchemaDir",
1168      (config_fn_t)ap_set_global_string_slot, &g_szSchemaDir,
1169       RSRC_CONF, "Path to Shibboleth XML schema directory."),
1170
1171   AP_INIT_TAKE1("ShibURLScheme",
1172      (config_fn_t)shib_set_server_string_slot,
1173      (void *) offsetof (shib_server_config, szScheme),
1174       RSRC_CONF, "URL scheme to force into generated URLs for a vhost."),
1175
1176   AP_INIT_FLAG("ShibBasicHijack", (config_fn_t)ap_set_flag_slot,
1177                (void *) offsetof (shib_dir_config, bBasicHijack),
1178                OR_AUTHCFG, "Respond to AuthType Basic and convert to shib?"),
1179   AP_INIT_FLAG("ShibRequireSession", (config_fn_t)ap_set_flag_slot,
1180          (void *) offsetof (shib_dir_config, bRequireSession),
1181         OR_AUTHCFG, "Initiates a new session if one does not exist."),
1182   AP_INIT_FLAG("ShibExportAssertion", (config_fn_t)ap_set_flag_slot,
1183          (void *) offsetof (shib_dir_config, bExportAssertion),
1184         OR_AUTHCFG, "Export SAML assertion to Shibboleth-defined header?"),
1185   AP_INIT_TAKE1("AuthGroupFile", (config_fn_t)ap_set_file_slot,
1186                 (void *) offsetof (shib_dir_config, szAuthGrpFile),
1187                 OR_AUTHCFG, "text file containing group names and member user IDs"),
1188   AP_INIT_FLAG("ShibRequireAll", (config_fn_t)ap_set_flag_slot,
1189                (void *) offsetof (shib_dir_config, bRequireAll),
1190                OR_AUTHCFG, "All require directives must match!"),
1191
1192   {NULL}
1193 };
1194
1195 module AP_MODULE_DECLARE_DATA mod_shib = {
1196     STANDARD20_MODULE_STUFF,
1197     create_shib_dir_config,     /* create dir config */
1198     merge_shib_dir_config,      /* merge dir config --- default is to override */
1199     create_shib_server_config,  /* create server config */
1200     merge_shib_server_config,   /* merge server config */
1201     shib_cmds,                  /* command table */
1202     shib_register_hooks         /* register hooks */
1203 };
1204
1205 #else
1206 #error "undefined APACHE version"
1207 #endif
1208
1209 }