Apache header conflict on Solaris 9
[shibboleth/cpp-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     // Get location of this application's assertion consumer service and see if this is it.
225     if (strstr(targeturl,shire.getShireURL(targeturl))) {
226         return shib_handler(r,application,shire);
227     }
228
229     // We can short circuit the handler if we run this...
230     apr_pool_userdata_setn((const void*)42,g_UserDataKey,NULL,r->pool);
231
232     // Regular access to arbitrary resource...check AuthType
233     const char *auth_type=ap_auth_type(r);
234     if (!auth_type)
235         return DECLINED;
236
237     if (strcasecmp(auth_type,"shibboleth")) {
238         if (!strcasecmp(auth_type,"basic") && dc->bBasicHijack==1) {
239             core_dir_config* conf=
240                 (core_dir_config*)ap_get_module_config(r->per_dir_config,
241                     ap_find_linked_module("http_core.c"));
242             conf->ap_auth_type="shibboleth";
243         }
244         else
245             return DECLINED;
246     }
247
248     pair<bool,bool> requireSession = settings.first->getBool("requireSession");
249     if (!requireSession.first || !requireSession.second)
250         if (dc->bRequireSession==1)
251             requireSession.second=true;
252
253     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session check for %s",targeturl);
254
255     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns *something*
256
257     // We're in charge, so check for cookie.
258     const char* session_id=NULL;
259     const char* cookies=ap_table_get(r->headers_in,"Cookie");
260
261     if (cookies) {
262         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: cookies found: %s",cookies);
263         if (session_id=strstr(cookies,shib_cookie.first)) {
264             // Yep, we found a cookie -- pull it out (our session_id)
265             session_id+=strlen(shib_cookie.first) + 1; /* Skip over the '=' */
266             char* cookiebuf = ap_pstrdup(r->pool,session_id);
267             char* cookieend = strchr(cookiebuf,';');
268             if (cookieend)
269                 *cookieend = '\0';    /* Ignore anyting after a ; */
270             session_id=cookiebuf;
271         }
272     }
273
274     if (!session_id || !*session_id) {
275         // If no session required, bail now.
276         if (!requireSession.second)
277             return OK;
278
279         // No acceptable cookie, and we require a session.  Generate an AuthnRequest.
280         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: no cookie found -- redirecting to WAYF");
281         ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
282         return REDIRECT;
283     }
284
285     // Make sure this session is still valid.
286     RPCError* status = NULL;
287     ShibMLP markupProcessor;
288     markupProcessor.insert("requestURL", targeturl);
289
290     try {
291         status = shire.sessionIsValid(session_id, r->connection->remote_ip);
292     }
293     catch (ShibTargetException &e) {
294         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
295         markupProcessor.insert("errorType", "Session Processing Error");
296         markupProcessor.insert("errorText", e.what());
297         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
298         return shib_error_page(r, application, "shire", markupProcessor);
299     }
300 #ifndef _DEBUG
301     catch (...) {
302         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
303         markupProcessor.insert("errorType", "Session Processing Error");
304         markupProcessor.insert("errorText", "Unexpected Exception");
305         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
306         return shib_error_page(r, application, "shire", markupProcessor);
307     }
308 #endif
309
310     // Check the status
311     if (status->isError()) {
312         ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
313                       "shib_check_user() session invalid: %s", status->getText());
314
315         // If no session required, bail now.
316         if (!requireSession.second)
317             return OK;  // XXX: Or should this be DECLINED?
318                         // Has to be OK because DECLINED will just cause Apache to fail when it can't locate
319                         // anything to process the AuthType. No session plus requireSession false means 
320                         // do not authenticate the user.
321         else if (status->isRetryable()) {
322             // Oops, session is invalid. Generate AuthnRequest.
323             ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(targeturl)));
324             delete status;
325             return REDIRECT;
326         }
327         else {
328             // return the error page to the user
329             markupProcessor.insert(*status);
330             delete status;
331             return shib_error_page(r, application, "shire", markupProcessor);
332         }
333     }
334
335     delete status;
336     // set the authtype
337 #ifdef SHIB_APACHE_13
338     if (r->connection)
339         r->connection->ap_auth_type = "shibboleth";
340 #else
341     r->ap_auth_type = "shibboleth";
342 #endif
343     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user: session successfully verified");
344
345     // This is code transferred in from the auth check to export the attributes.
346     // We could even combine the isSessionValid/getAssertions API...?
347
348     RM rm(application);
349     vector<SAMLAssertion*> assertions;
350     SAMLAuthenticationStatement* sso_statement=NULL;
351
352     try {
353         status = rm.getAssertions(session_id, r->connection->remote_ip, assertions, &sso_statement);
354     }
355     catch (ShibTargetException &e) {
356         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): %s", e.what());
357         markupProcessor.insert("errorType", "Attribute Processing Error");
358         markupProcessor.insert("errorText", e.what());
359         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
360         return shib_error_page(r, application, "rm", markupProcessor);
361     }
362 #ifndef _DEBUG
363     catch (...) {
364         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): caught unexpected error");
365         markupProcessor.insert("errorType", "Attribute Processing Error");
366         markupProcessor.insert("errorText", "Unexpected Exception");
367         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
368         return shib_error_page(r, application, "rm", markupProcessor);
369     }
370 #endif
371
372     if (status->isError()) {
373         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
374             "shib_check_user() getAssertions failed: %s", status->getText());
375
376         markupProcessor.insert(*status);
377         delete status;
378         return shib_error_page(r, application, "rm", markupProcessor);
379     }
380     delete status;
381
382     // Do we have an access control plugin?
383     if (settings.second) {
384         Locker acllock(settings.second);
385         if (!settings.second->authorized(*sso_statement,assertions)) {
386             for (int k = 0; k < assertions.size(); k++)
387                 delete assertions[k];
388             delete sso_statement;
389             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_check_user(): access control provider denied access");
390             return shib_error_page(r, application, "access", markupProcessor);
391         }
392     }
393
394     // Get the AAP providers, which contain the attribute policy info.
395     Iterator<IAAP*> provs=application->getAAPProviders();
396
397     // Clear out the list of mapped attributes
398     while (provs.hasNext()) {
399         IAAP* aap=provs.next();
400         aap->lock();
401         try {
402             Iterator<const IAttributeRule*> rules=aap->getAttributeRules();
403             while (rules.hasNext()) {
404                 const char* header=rules.next()->getHeader();
405                 if (header)
406                     ap_table_unset(r->headers_in,header);
407             }
408         }
409         catch(...) {
410             aap->unlock();
411             for (int k = 0; k < assertions.size(); k++)
412                 delete assertions[k];
413             delete sso_statement;
414             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
415                 "shib_check_user(): caught unexpected error while clearing headers");
416             markupProcessor.insert("errorType", "Attribute Processing Error");
417             markupProcessor.insert("errorText", "Unexpected Exception");
418             markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
419             return shib_error_page(r, application, "rm", markupProcessor);
420         }
421         aap->unlock();
422     }
423     provs.reset();
424     
425     // Maybe export the first assertion.
426     ap_table_unset(r->headers_in,"Shib-Attributes");
427     pair<bool,bool> exp=settings.first->getBool("exportAssertion");
428     if (!exp.first || !exp.second)
429         if (dc->bExportAssertion==1)
430             exp.second=true;
431     if (exp.second && assertions.size()) {
432         string assertion;
433         RM::serialize(*(assertions[0]), assertion);
434         ap_table_set(r->headers_in,"Shib-Attributes", assertion.c_str());
435     }
436
437     // Export the SAML AuthnMethod and the origin site name, and possibly the NameIdentifier.
438     ap_table_unset(r->headers_in,"Shib-Origin-Site");
439     ap_table_unset(r->headers_in,"Shib-Authentication-Method");
440     ap_table_unset(r->headers_in,"Shib-NameIdentifier-Format");
441     auto_ptr_char os(sso_statement->getSubject()->getNameIdentifier()->getNameQualifier());
442     auto_ptr_char am(sso_statement->getAuthMethod());
443     ap_table_set(r->headers_in,"Shib-Origin-Site", os.get());
444     ap_table_set(r->headers_in,"Shib-Authentication-Method", am.get());
445     
446     // Export NameID?
447     AAP wrapper(provs,sso_statement->getSubject()->getNameIdentifier()->getFormat(),Constants::SHIB_ATTRIBUTE_NAMESPACE_URI);
448     if (!wrapper.fail() && wrapper->getHeader()) {
449         auto_ptr_char form(sso_statement->getSubject()->getNameIdentifier()->getFormat());
450         auto_ptr_char nameid(sso_statement->getSubject()->getNameIdentifier()->getName());
451         ap_table_set(r->headers_in,"Shib-NameIdentifier-Format",form.get());
452         if (!strcmp(wrapper->getHeader(),"REMOTE_USER"))
453             SH_AP_USER(r)=ap_pstrdup(r->pool,nameid.get());
454         else
455             ap_table_set(r->headers_in,wrapper->getHeader(),nameid.get());
456     }
457     
458     ap_table_unset(r->headers_in,"Shib-Application-ID");
459     ap_table_set(r->headers_in,"Shib-Application-ID",application_id.second);
460
461     // Export the attributes.
462     Iterator<SAMLAssertion*> a_iter(assertions);
463     while (a_iter.hasNext()) {
464         SAMLAssertion* assert=a_iter.next();
465         Iterator<SAMLStatement*> statements=assert->getStatements();
466         while (statements.hasNext()) {
467             SAMLAttributeStatement* astate=dynamic_cast<SAMLAttributeStatement*>(statements.next());
468             if (!astate)
469                 continue;
470             Iterator<SAMLAttribute*> attrs=astate->getAttributes();
471             while (attrs.hasNext()) {
472                 SAMLAttribute* attr=attrs.next();
473         
474                 // Are we supposed to export it?
475                 AAP wrapper(provs,attr->getName(),attr->getNamespace());
476                 if (wrapper.fail() || !wrapper->getHeader())
477                     continue;
478                 
479                 Iterator<string> vals=attr->getSingleByteValues();
480                 if (!strcmp(wrapper->getHeader(),"REMOTE_USER") && vals.hasNext())
481                     SH_AP_USER(r)=ap_pstrdup(r->pool,vals.next().c_str());
482                 else {
483                     int it=0;
484                     char* header = (char*)ap_table_get(r->headers_in, wrapper->getHeader());
485                     if (header) {
486                         header=ap_pstrdup(r->pool, header);
487                         it++;
488                     }
489                     else
490                         header = ap_pstrdup(r->pool, "");
491                     for (; vals.hasNext(); it++) {
492                         string value = vals.next();
493                         for (string::size_type pos = value.find_first_of(";", string::size_type(0));
494                                 pos != string::npos;
495                                 pos = value.find_first_of(";", pos)) {
496                             value.insert(pos, "\\");
497                             pos += 2;
498                         }
499                         header=ap_pstrcat(r->pool, header, (it ? ";" : ""), value.c_str(), NULL);
500                     }
501                     ap_table_setn(r->headers_in, wrapper->getHeader(), header);
502                }
503             }
504         }
505     }
506
507     // clean up memory
508     for (int k = 0; k < assertions.size(); k++)
509         delete assertions[k];
510     delete sso_statement;
511
512     return OK;
513 }
514
515 extern "C" int shib_post_handler(request_rec* r)
516 {
517     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
518                 "shib_post_handler(%d): ENTER", (int)getpid());
519     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
520
521 #ifndef SHIB_APACHE_13
522     // With 2.x, this handler always runs, though last.
523     // We check if shib_check_user ran, because it will detect a SHIRE request
524     // and dispatch it directly.
525     void* data;
526     apr_pool_userdata_get(&data,g_UserDataKey,r->pool);
527     if (data==(const void*)42) {
528         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_post_handler skipped since check_user ran");
529         return DECLINED;
530     }
531 #endif
532     
533     ostringstream threadid;
534     threadid << "[" << getpid() << "] shib_post_handler" << '\0';
535     saml::NDC ndc(threadid.str().c_str());
536
537     // We lock the configuration system for the duration.
538     IConfig* conf=g_Config->getINI();
539     Locker locker(conf);
540     
541     // Map request to application and content settings.
542     IRequestMapper* mapper=conf->getRequestMapper();
543     Locker locker2(mapper);
544     IRequestMapper::Settings settings=mapper->getSettingsFromParsedURL(
545         (sc->szScheme ? sc->szScheme : ap_http_method(r)), ap_get_server_name(r), ap_get_server_port(r), r->unparsed_uri
546         );
547     pair<bool,const char*> application_id=settings.first->getString("applicationId");
548     const IApplication* application=conf->getApplication(application_id.second);
549     if (!application) {
550         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
551            "shib_post_handler: unable to map request to application settings, check configuration");
552         return SERVER_ERROR;
553     }
554     
555     // Declare SHIRE object for this request.
556     SHIRE shire(application);
557     
558     return shib_handler(r, application, shire);
559 }
560
561 int shib_handler(request_rec* r, const IApplication* application, SHIRE& shire)
562 {
563     shib_server_config* sc=(shib_server_config*)ap_get_module_config(r->server->module_config,&mod_shib);
564
565     const char* targeturl=shib_get_targeturl(r,sc->szScheme);
566
567     // Make sure we only process the SHIRE requests.
568     if (!strstr(targeturl,shire.getShireURL(targeturl)))
569         return DECLINED;
570
571     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() running");
572
573     const IPropertySet* sessionProps=application->getPropertySet("Sessions");
574     if (!sessionProps) {
575         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
576            "shib_post_handler: unable to map request to application session settings, check configuration");
577         return SERVER_ERROR;
578     }
579
580     pair<const char*,const char*> shib_cookie=shire.getCookieNameProps();   // always returns something
581
582     ShibMLP markupProcessor;
583     markupProcessor.insert("requestURL", targeturl);
584
585     // Process SHIRE request
586     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() Beginning SHIRE processing");
587       
588     try {
589         pair<bool,bool> shireSSL=sessionProps->getBool("shireSSL");
590       
591         // Make sure this is SSL, if it should be
592         if ((!shireSSL.first || shireSSL.second) && strcmp(ap_http_method(r),"https"))
593             throw ShibTargetException(SHIBRPC_OK, "blocked non-SSL access to session creation service");
594
595         // If this is a GET, we manufacture an AuthnRequest.
596         if (!strcasecmp(r->method,"GET")) {
597             const char* areq=r->args ? shire.getLazyAuthnRequest(r->args) : NULL;
598             if (!areq)
599                 throw ShibTargetException(SHIBRPC_OK, "malformed arguments to request a new session");
600             ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,areq));
601             return REDIRECT;
602         }
603         else if (strcasecmp(r->method,"POST")) {
604             throw ShibTargetException(SHIBRPC_OK, "blocked non-POST to SHIRE POST processor");
605         }
606
607         // Sure sure this POST is an appropriate content type
608         const char *ct = ap_table_get(r->headers_in, "Content-type");
609         if (!ct || strcasecmp(ct, "application/x-www-form-urlencoded"))
610             throw ShibTargetException(SHIBRPC_OK,
611                                       ap_psprintf(r->pool, "blocked bad content-type to SHIRE POST processor: %s", (ct ? ct : "")));
612
613         // Read the posted data
614         if (ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))
615             throw ShibTargetException(SHIBRPC_OK, "CGI setup_client_block failed");
616         if (!ap_should_client_block(r))
617             throw ShibTargetException(SHIBRPC_OK, "CGI should_client_block failed");
618         if (r->remaining > 1024*1024)
619             throw ShibTargetException (SHIBRPC_OK, "CGI length too long...");
620
621         string cgistr;
622         char buff[HUGE_STRING_LEN];
623         ap_hard_timeout("[mod_shib] CGI Parser", r);
624         memset(buff, 0, sizeof(buff));
625         while (ap_get_client_block(r, buff, sizeof(buff)-1) > 0) {
626             cgistr += buff;
627             memset(buff, 0, sizeof(buff));
628         }
629         ap_kill_timeout(r);
630
631         // Parse the submission.
632         pair<const char*,const char*> elements=shire.getFormSubmission(cgistr.c_str(),cgistr.length());
633     
634         // Make sure the SAML Response parameter exists
635         if (!elements.first || !*elements.first)
636             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find SAMLResponse form element");
637     
638         // Make sure the target parameter exists
639         if (!elements.second || !*elements.second)
640             throw ShibTargetException(SHIBRPC_OK, "SHIRE POST failed to find TARGET form element");
641     
642         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
643             "shib_handler() Processing POST for target: %s", elements.second);
644
645         // process the post
646         string cookie;
647         RPCError* status = shire.sessionCreate(elements.first, r->connection->remote_ip, cookie);
648
649         if (status->isError()) {
650             ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
651                     "shib_handler() POST process failed (%d): %s", status->getCode(), status->getText());
652
653             if (status->isRetryable()) {
654                 delete status;
655                 ap_log_rerror(APLOG_MARK,APLOG_INFO|APLOG_NOERRNO,SH_AP_R(r),
656                         "shib_handler() retryable error, generating new AuthnRequest");
657                 ap_table_setn(r->headers_out,"Location",ap_pstrdup(r->pool,shire.getAuthnRequest(elements.second)));
658                 return REDIRECT;
659             }
660
661             // return this error to the user.
662             markupProcessor.insert(*status);
663             delete status;
664             return shib_error_page(r, application, "shire", markupProcessor);
665         }
666         delete status;
667
668         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
669                   "shib_handler() POST process succeeded.  New session: %s", cookie.c_str());
670
671         // We've got a good session, set the cookie...
672         char* val = ap_psprintf(r->pool,"%s=%s%s",shib_cookie.first,cookie.c_str(),shib_cookie.second);
673         ap_table_setn(r->err_headers_out, "Set-Cookie", val);
674         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() setting cookie: %s", val);
675
676         // ... and redirect to the target
677         ap_table_setn(r->headers_out, "Location", ap_pstrdup(r->pool,elements.second));
678         return REDIRECT;
679     }
680     catch (ShibTargetException &e) {
681         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r), "shib_handler() caught exception: %s", e.what());
682         markupProcessor.insert("errorType", "Session Creation Service Error");
683         markupProcessor.insert("errorText", e.what());
684         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
685         return shib_error_page(r, application, "shire", markupProcessor);
686     }
687 #ifndef _DEBUG
688     catch (...) {
689         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_handler(): unexpected exception");
690         markupProcessor.insert("errorType", "Session Creation Service Error");
691         markupProcessor.insert("errorText", "Unknown Exception");
692         markupProcessor.insert("errorDesc", "An error occurred while processing your request.");
693         return shib_error_page(r, application, "shire", markupProcessor);
694     }
695 #endif
696
697     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),"shib_handler() server error");
698     return SERVER_ERROR;
699 }
700
701 static SH_AP_TABLE* groups_for_user(request_rec* r, const char* user, char* grpfile)
702 {
703     SH_AP_CONFIGFILE* f;
704     SH_AP_TABLE* grps=ap_make_table(r->pool,15);
705     char l[MAX_STRING_LEN];
706     const char *group_name, *ll, *w;
707
708 #ifdef SHIB_APACHE_13
709     if (!(f=ap_pcfg_openfile(r->pool,grpfile))) {
710 #else
711     if (ap_pcfg_openfile(&f,r->pool,grpfile) != APR_SUCCESS) {
712 #endif
713         ap_log_rerror(APLOG_MARK,APLOG_DEBUG,SH_AP_R(r),"groups_for_user() could not open group file: %s\n",grpfile);
714         return NULL;
715     }
716
717     SH_AP_POOL* sp;
718 #ifdef SHIB_APACHE_13
719     sp=ap_make_sub_pool(r->pool);
720 #else
721     if (apr_pool_create(&sp,r->pool) != APR_SUCCESS) {
722         ap_log_rerror(APLOG_MARK,APLOG_ERR,0,r,
723             "groups_for_user() could not create a subpool");
724         return NULL;
725     }
726 #endif
727
728     while (!(ap_cfg_getline(l,MAX_STRING_LEN,f))) {
729         if ((*l=='#') || (!*l))
730             continue;
731         ll = l;
732         ap_clear_pool(sp);
733
734         group_name=ap_getword(sp,&ll,':');
735
736         while (*ll) {
737             w=ap_getword_conf(sp,&ll);
738             if (!strcmp(w,user)) {
739                 ap_table_setn(grps,ap_pstrdup(r->pool,group_name),"in");
740                 break;
741             }
742         }
743     }
744     ap_cfg_closefile(f);
745     ap_destroy_pool(sp);
746     return grps;
747 }
748
749 /*
750  * shib_auth_checker() -- a simple resource manager to
751  * process the .htaccess settings and copy attributes
752  * into the HTTP headers.
753  */
754 extern "C" int shib_auth_checker(request_rec* r)
755 {
756     shib_dir_config* dc=
757         (shib_dir_config*)ap_get_module_config(r->per_dir_config,&mod_shib);
758
759     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() executing");
760
761     // Regular access to arbitrary resource...check AuthType
762     const char* auth_type=ap_auth_type(r);
763     if (!auth_type || strcasecmp(auth_type,"shibboleth"))
764         return DECLINED;
765
766     ostringstream threadid;
767     threadid << "[" << getpid() << "] shibrm" << '\0';
768     saml::NDC ndc(threadid.str().c_str());
769
770     // We lock the configuration system for the duration.
771     IConfig* conf=g_Config->getINI();
772     Locker locker(conf);
773     
774     const char* application_id=ap_table_get(r->headers_in,"Shib-Application-ID");
775     const IApplication* application=NULL;
776     if (application_id)
777         application = conf->getApplication(application_id);
778
779     // mod_auth clone
780
781     int m=r->method_number;
782     bool method_restricted=false;
783     const char *t, *w;
784     
785     const array_header* reqs_arr=ap_requires(r);
786     if (!reqs_arr)
787         return OK;
788
789     require_line* reqs=(require_line*)reqs_arr->elts;
790
791     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE nelts: %d", reqs_arr->nelts);
792     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"REQUIRE all: %d", dc->bRequireAll);
793
794     vector<bool> auth_OK(reqs_arr->nelts,false);
795
796 #define SHIB_AP_CHECK_IS_OK {       \
797      if (dc->bRequireAll < 1)    \
798          return OK;      \
799      auth_OK[x] = true;      \
800      continue;           \
801 }
802
803     for (int x=0; x<reqs_arr->nelts; x++) {
804         auth_OK[x] = false;
805         if (!(reqs[x].method_mask & (1 << m)))
806             continue;
807         method_restricted=true;
808
809         t = reqs[x].requirement;
810         w = ap_getword_white(r->pool, &t);
811
812         if (!strcasecmp(w,"Shibboleth")) {
813             // This is a dummy rule needed because Apache conflates authn and authz.
814             // Without some require rule, AuthType is ignored and no check_user hooks run.
815             SHIB_AP_CHECK_IS_OK;
816         }
817         else if (!strcmp(w,"valid-user") && application_id) {
818             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting valid-user");
819             SHIB_AP_CHECK_IS_OK;
820         }
821         else if (!strcmp(w,"user") && SH_AP_USER(r)) {
822             bool regexp=false;
823             while (*t) {
824                 w=ap_getword_conf(r->pool,&t);
825                 if (*w=='~') {
826                     regexp=true;
827                     continue;
828                 }
829                 
830                 if (regexp) {
831                     try {
832                         // To do regex matching, we have to convert from UTF-8.
833                         auto_ptr<XMLCh> trans(fromUTF8(w));
834                         RegularExpression re(trans.get());
835                         auto_ptr<XMLCh> trans2(fromUTF8(SH_AP_USER(r)));
836                         if (re.matches(trans2.get())) {
837                             ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
838                             SHIB_AP_CHECK_IS_OK;
839                         }
840                     }
841                     catch (XMLException& ex) {
842                         auto_ptr_char tmp(ex.getMessage());
843                         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
844                                         "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
845                     }
846                 }
847                 else if (!strcmp(SH_AP_USER(r),w)) {
848                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting user: %s",w);
849                     SHIB_AP_CHECK_IS_OK;
850                 }
851             }
852         }
853         else if (!strcmp(w,"group")) {
854             SH_AP_TABLE* grpstatus=NULL;
855             if (dc->szAuthGrpFile && SH_AP_USER(r)) {
856                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() using groups file: %s\n",dc->szAuthGrpFile);
857                 grpstatus=groups_for_user(r,SH_AP_USER(r),dc->szAuthGrpFile);
858             }
859             if (!grpstatus)
860                 return DECLINED;
861     
862             while (*t) {
863                 w=ap_getword_conf(r->pool,&t);
864                 if (ap_table_get(grpstatus,w)) {
865                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),"shib_auth_checker() accepting group: %s",w);
866                     SHIB_AP_CHECK_IS_OK;
867                 }
868             }
869         }
870         else {
871             Iterator<IAAP*> provs=application ? application->getAAPProviders() : EMPTY(IAAP*);
872             AAP wrapper(provs,w);
873             if (wrapper.fail()) {
874                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
875                     "shib_auth_checker() didn't recognize require rule: %s\n",w);
876                 continue;
877             }
878
879             bool regexp=false;
880             const char* vals=ap_table_get(r->headers_in,wrapper->getHeader());
881             while (*t && vals) {
882                 w=ap_getword_conf(r->pool,&t);
883                 if (*w=='~') {
884                     regexp=true;
885                     continue;
886                 }
887
888                 try {
889                     auto_ptr<RegularExpression> re;
890                     if (regexp) {
891                         delete re.release();
892                         auto_ptr<XMLCh> trans(fromUTF8(w));
893                         auto_ptr<RegularExpression> temp(new RegularExpression(trans.get()));
894                         re=temp;
895                     }
896                     
897                     string vals_str(vals);
898                     int j = 0;
899                     for (int i = 0;  i < vals_str.length();  i++) {
900                         if (vals_str.at(i) == ';') {
901                             if (i == 0) {
902                                 ap_log_rerror(APLOG_MARK,APLOG_WARNING|APLOG_NOERRNO,SH_AP_R(r),
903                                                 "shib_auth_checker() invalid header encoding %s: starts with semicolon", vals);
904                                 return SERVER_ERROR;
905                             }
906
907                             if (vals_str.at(i-1) == '\\') {
908                                 vals_str.erase(i-1, 1);
909                                 i--;
910                                 continue;
911                             }
912
913                             string val = vals_str.substr(j, i-j);
914                             j = i+1;
915                             if (regexp) {
916                                 auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
917                                 if (re->matches(trans.get())) {
918                                     ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
919                                                     "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
920                                     SHIB_AP_CHECK_IS_OK;
921                                 }
922                             }
923                             else if (val==w) {
924                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
925                                                 "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
926                                 SHIB_AP_CHECK_IS_OK;
927                             }
928                             else {
929                                 ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
930                                                 "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
931                             }
932                         }
933                     }
934     
935                     string val = vals_str.substr(j, vals_str.length()-j);
936                     if (regexp) {
937                         auto_ptr<XMLCh> trans(fromUTF8(val.c_str()));
938                         if (re->matches(trans.get())) {
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                     }
944                     else if (val==w) {
945                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
946                                         "shib_auth_checker() expecting %s, got %s: authorization granted", w, val.c_str());
947                         SHIB_AP_CHECK_IS_OK;
948                     }
949                     else {
950                         ap_log_rerror(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(r),
951                                         "shib_auth_checker() expecting %s, got %s: authorization not granted", w, val.c_str());
952                     }
953                 }
954                 catch (XMLException& ex) {
955                     auto_ptr_char tmp(ex.getMessage());
956                     ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
957                                     "shib_auth_checker caught exception while parsing regular expression (%s): %s",w,tmp.get());
958                 }
959             }
960         }
961     }
962
963     // check if all require directives are true
964     bool auth_all_OK = true;
965     for (int i= 0; i<reqs_arr->nelts; i++) {
966         auth_all_OK &= auth_OK[i];
967     }
968     if (auth_all_OK)
969         return OK;
970
971     if (!method_restricted)
972         return OK;
973
974     if (!application_id) {
975         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
976            "shib_auth_checker: Shib-Application-ID header not found in request");
977         return HTTP_FORBIDDEN;
978     }
979     else if (!application) {
980         ap_log_rerror(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(r),
981            "shib_auth_checker: unable to map request to application settings, check configuration");
982         return HTTP_FORBIDDEN;
983     }
984
985     ShibMLP markupProcessor;
986     markupProcessor.insert("requestURL", ap_construct_url(r->pool,r->unparsed_uri,r));
987     return shib_error_page(r, application, "access", markupProcessor);
988 }
989
990 /*
991  * shib_exit()
992  *  Cleanup the (per-process) pool info.
993  */
994 #ifdef SHIB_APACHE_13
995 extern "C" void shib_exit(server_rec* s, SH_AP_POOL* p)
996 {
997 #else
998 extern "C" apr_status_t shib_exit(void* data)
999 {
1000     server_rec* s = NULL;
1001 #endif
1002
1003     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit(%d) dealing with g_Config..", (int)getpid());
1004
1005     g_Config->shutdown();
1006     g_Config = NULL;
1007
1008     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_exit() done\n");
1009 #ifndef SHIB_APACHE_13
1010     return OK;
1011 #endif
1012 }
1013
1014
1015 #ifdef SHIB_APACHE_13
1016 extern "C" void shib_child_exit(server_rec* s, SH_AP_POOL* p)
1017 {
1018 #else
1019 extern "C" apr_status_t shib_child_exit(void* data)
1020 {
1021   server_rec* s = NULL;
1022 #endif
1023
1024   ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_exit(%d)",
1025                (int)getpid());
1026
1027 #ifndef SHIB_APACHE_13
1028     return OK;
1029 #endif
1030 }
1031
1032 /* 
1033  * shire_child_init()
1034  *  Things to do when the child process is initialized.
1035  *  (or after the configs are read in apache-2)
1036  */
1037 #ifdef SHIB_APACHE_13
1038 extern "C" void shib_child_init(server_rec* s, SH_AP_POOL* p)
1039 #else
1040 extern "C" int shib_post_config(apr_pool_t* pconf, apr_pool_t* plog,
1041                                 apr_pool_t* ptemp, server_rec* s)
1042 #endif
1043 {
1044     // Initialize runtime components.
1045
1046     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init(%d) starting", (int)getpid());
1047
1048     if (g_Config) {
1049         ap_log_error(APLOG_MARK,APLOG_ERR|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() already initialized!");
1050 #ifdef SHIB_APACHE_13
1051         exit(1);
1052 #else
1053         return OK;
1054 #endif
1055     }
1056
1057     try {
1058         g_Config=&ShibTargetConfig::getConfig();
1059         g_Config->setFeatures(
1060             ShibTargetConfig::Listener |
1061             ShibTargetConfig::Metadata |
1062             ShibTargetConfig::AAP |
1063             ShibTargetConfig::RequestMapper |
1064             ShibTargetConfig::SHIREExtensions |
1065             ShibTargetConfig::Logging
1066             );
1067         if (!g_Config->init(g_szSchemaDir,g_szSHIBConfig)) {
1068             ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1069             exit(1);
1070         }
1071     }
1072     catch (...) {
1073         ap_log_error(APLOG_MARK,APLOG_CRIT|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() failed to initialize SHIB Target");
1074         exit (1);
1075     }
1076
1077     // Set the cleanup handler
1078     apr_pool_cleanup_register(pconf, NULL, &shib_exit, &shib_child_exit);
1079
1080     ap_log_error(APLOG_MARK,APLOG_DEBUG|APLOG_NOERRNO,SH_AP_R(s),"shib_child_init() done");
1081
1082 #ifndef SHIB_APACHE_13
1083     return OK;
1084 #endif
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_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_post_config(shib_post_config, 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 }