2 * Copyright 2001-2009 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /** XMLRequestMapper.cpp
19 * XML-based RequestMapper implementation.
23 #include "exceptions.h"
24 #include "AccessControl.h"
25 #include "RequestMapper.h"
26 #include "SPRequest.h"
27 #include "util/DOMPropertySet.h"
28 #include "util/SPConstants.h"
31 #include <xmltooling/util/NDC.h>
32 #include <xmltooling/util/ReloadableXMLFile.h>
33 #include <xmltooling/util/XMLHelper.h>
34 #include <xercesc/util/XMLUniDefs.hpp>
35 #include <xercesc/util/regx/RegularExpression.hpp>
37 using namespace shibsp;
38 using namespace xmltooling;
43 // Blocks access when an ACL plugin fails to load.
44 class AccessControlDummy : public AccessControl
53 aclresult_t authorized(const SPRequest& request, const Session* session) const {
54 return shib_acl_false;
58 class Override : public DOMPropertySet, public DOMNodeFilter
61 Override() : m_acl(NULL) {}
62 Override(const DOMElement* e, Category& log, const Override* base=NULL);
65 // Provides filter to exclude special config elements.
66 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
71 acceptNode(const DOMNode* node) const {
75 const Override* locate(const HTTPRequest& request) const;
76 AccessControl* getAC() const { return (m_acl ? m_acl : (getParent() ? dynamic_cast<const Override*>(getParent())->getAC() : NULL)); }
79 void loadACL(const DOMElement* e, Category& log);
81 map<string,Override*> m_map;
82 vector< pair<RegularExpression*,Override*> > m_regexps;
83 vector< pair< pair<string,RegularExpression*>,Override*> > m_queries;
89 class XMLRequestMapperImpl : public Override
92 XMLRequestMapperImpl(const DOMElement* e, Category& log);
94 ~XMLRequestMapperImpl() {
96 m_document->release();
99 void setDocument(DOMDocument* doc) {
103 const Override* findOverride(const char* vhost, const HTTPRequest& request) const;
106 map<string,Override*> m_extras;
107 DOMDocument* m_document;
110 #if defined (_MSC_VER)
111 #pragma warning( push )
112 #pragma warning( disable : 4250 )
115 class XMLRequestMapper : public RequestMapper, public ReloadableXMLFile
118 XMLRequestMapper(const DOMElement* e) : ReloadableXMLFile(e,Category::getInstance(SHIBSP_LOGCAT".RequestMapper")), m_impl(NULL) {
122 ~XMLRequestMapper() {
126 Settings getSettings(const HTTPRequest& request) const;
129 pair<bool,DOMElement*> load();
132 XMLRequestMapperImpl* m_impl;
135 #if defined (_MSC_VER)
136 #pragma warning( pop )
139 RequestMapper* SHIBSP_DLLLOCAL XMLRequestMapperFactory(const DOMElement* const & e)
141 return new XMLRequestMapper(e);
144 static const XMLCh _AccessControl[] = UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);
145 static const XMLCh AccessControlProvider[] = UNICODE_LITERAL_21(A,c,c,e,s,s,C,o,n,t,r,o,l,P,r,o,v,i,d,e,r);
146 static const XMLCh Host[] = UNICODE_LITERAL_4(H,o,s,t);
147 static const XMLCh HostRegex[] = UNICODE_LITERAL_9(H,o,s,t,R,e,g,e,x);
148 static const XMLCh htaccess[] = UNICODE_LITERAL_8(h,t,a,c,c,e,s,s);
149 static const XMLCh ignoreCase[] = UNICODE_LITERAL_10(i,g,n,o,r,e,C,a,s,e);
150 static const XMLCh ignoreOption[] = UNICODE_LITERAL_1(i);
151 static const XMLCh Path[] = UNICODE_LITERAL_4(P,a,t,h);
152 static const XMLCh PathRegex[] = UNICODE_LITERAL_9(P,a,t,h,R,e,g,e,x);
153 static const XMLCh Query[] = UNICODE_LITERAL_5(Q,u,e,r,y);
154 static const XMLCh name[] = UNICODE_LITERAL_4(n,a,m,e);
155 static const XMLCh regex[] = UNICODE_LITERAL_5(r,e,g,e,x);
156 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
159 void SHIBSP_API shibsp::registerRequestMappers()
161 SPConfig& conf=SPConfig::getConfig();
162 conf.RequestMapperManager.registerFactory(XML_REQUEST_MAPPER, XMLRequestMapperFactory);
163 conf.RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, XMLRequestMapperFactory);
166 void Override::loadACL(const DOMElement* e, Category& log)
169 const DOMElement* acl=XMLHelper::getFirstChildElement(e,htaccess);
171 log.info("building Apache htaccess AccessControl provider...");
172 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(HT_ACCESS_CONTROL,acl);
175 acl=XMLHelper::getFirstChildElement(e,_AccessControl);
177 log.info("building XML-based AccessControl provider...");
178 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(XML_ACCESS_CONTROL,acl);
181 acl=XMLHelper::getFirstChildElement(e,AccessControlProvider);
183 auto_ptr_char type(acl->getAttributeNS(NULL,_type));
184 log.info("building AccessControl provider of type %s...",type.get());
185 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(type.get(),acl);
190 catch (exception& ex) {
191 log.crit("exception building AccessControl provider: %s", ex.what());
192 m_acl = new AccessControlDummy();
196 Override::Override(const DOMElement* e, Category& log, const Override* base) : m_acl(NULL)
199 // Load the property set.
203 // Load any AccessControl provider.
206 // Handle nested Paths.
207 DOMElement* path = XMLHelper::getFirstChildElement(e,Path);
208 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,Path)) {
209 const XMLCh* n=path->getAttributeNS(NULL,name);
211 // Skip any leading slashes.
212 while (n && *n==chForwardSlash)
215 // Check for empty name.
217 log.warn("skipping Path element (%d) with empty name attribute", i);
221 // Check for an embedded slash.
222 int slash=XMLString::indexOf(n,chForwardSlash);
224 // Copy the first path segment.
225 XMLCh* namebuf=new XMLCh[slash + 1];
226 for (int pos=0; pos < slash; pos++)
228 namebuf[slash]=chNull;
230 // Move past the slash in the original pathname.
233 // Skip any leading slashes again.
234 while (*n==chForwardSlash)
238 // Create a placeholder Path element for the first path segment and replant under it.
239 DOMElement* newpath=path->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,Path);
240 newpath->setAttributeNS(NULL,name,namebuf);
241 path->setAttributeNS(NULL,name,n);
242 path->getParentNode()->replaceChild(newpath,path);
243 newpath->appendChild(path);
245 // Repoint our locals at the new parent.
247 n=path->getAttributeNS(NULL,name);
250 // All we had was a pathname with trailing slash(es), so just reset it without them.
251 path->setAttributeNS(NULL,name,namebuf);
252 n=path->getAttributeNS(NULL,name);
257 Override* o=new Override(path,log,this);
258 pair<bool,const char*> name=o->getString("name");
259 char* dup=strdup(name.second);
260 for (char* pch=dup; *pch; pch++)
262 if (m_map.count(dup)) {
263 log.warn("skipping duplicate Path element (%s)",dup);
269 log.debug("added Path mapping (%s)", dup);
273 if (!XMLString::equals(e->getLocalName(), PathRegex)) {
274 // Handle nested PathRegexs.
275 path = XMLHelper::getFirstChildElement(e,PathRegex);
276 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,PathRegex)) {
277 const XMLCh* n=path->getAttributeNS(NULL,regex);
279 log.warn("skipping PathRegex element (%d) with empty regex attribute",i);
283 auto_ptr<Override> o(new Override(path,log,this));
285 const XMLCh* flag=path->getAttributeNS(NULL,ignoreCase);
287 auto_ptr<RegularExpression> re(
288 new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
290 m_regexps.push_back(make_pair(re.release(), o.release()));
292 catch (XMLException& ex) {
293 auto_ptr_char tmp(ex.getMessage());
294 log.error("caught exception while parsing PathRegex regular expression (%d): %s", i, tmp.get());
295 throw ConfigurationException("Invalid regular expression in PathRegex element.");
298 if (log.isDebugEnabled())
299 log.debug("added <PathRegex> mapping (%s)", m_regexps.back().second->getString("regex").second);
303 // Handle nested Querys.
304 path = XMLHelper::getFirstChildElement(e,Query);
305 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,Query)) {
306 const XMLCh* n=path->getAttributeNS(NULL,name);
308 log.warn("skipping Query element (%d) with empty name attribute",i);
311 auto_ptr_char ntemp(n);
312 const XMLCh* v=path->getAttributeNS(NULL,regex);
314 auto_ptr<Override> o(new Override(path,log,this));
316 RegularExpression* re = NULL;
318 re = new RegularExpression(v);
319 m_queries.push_back(make_pair(make_pair(string(ntemp.get()),re), o.release()));
321 catch (XMLException& ex) {
322 auto_ptr_char tmp(ex.getMessage());
323 log.error("caught exception while parsing Query regular expression (%d): %s", i, tmp.get());
324 throw ConfigurationException("Invalid regular expression in Query element.");
327 log.debug("added <Query> mapping (%s)", ntemp.get());
332 for_each(m_map.begin(),m_map.end(),xmltooling::cleanup_pair<string,Override>());
333 for (vector< pair<RegularExpression*,Override*> >::iterator i = m_regexps.begin(); i != m_regexps.end(); ++i) {
337 for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
338 delete j->first.second;
345 Override::~Override()
348 for_each(m_map.begin(),m_map.end(),xmltooling::cleanup_pair<string,Override>());
349 for (vector< pair<RegularExpression*,Override*> >::iterator i = m_regexps.begin(); i != m_regexps.end(); ++i) {
353 for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
354 delete j->first.second;
359 const Override* Override::locate(const HTTPRequest& request) const
361 // This function is confusing because it's *not* recursive.
362 // The whole path is tokenized and mapped in a loop, so the
363 // path parameter starts with the entire request path and
364 // we can skip the leading slash as irrelevant.
365 const char* path = request.getRequestURI();
369 // Now we copy the path, chop the query string, and lower case it.
370 char* dup=strdup(path);
371 char* sep=strchr(dup,'?');
374 for (char* pch=dup; *pch; pch++)
377 // Default is for the current object to provide settings.
378 const Override* o=this;
380 // Tokenize the path by segment and try and map each segment.
383 const char* token=strtok_r(dup,"/",&pos);
385 const char* token=strtok(dup,"/");
388 map<string,Override*>::const_iterator i=o->m_map.find(token);
389 if (i==o->m_map.end())
390 break; // Once there's no match, we've consumed as much of the path as possible here.
391 // We found a match, so reset the settings pointer.
394 // We descended a step down the path, so we need to advance the original
395 // parameter for the regex step later.
396 path += strlen(token);
400 // Get the next segment, if any.
402 token=strtok_r(NULL,"/",&pos);
404 token=strtok(NULL,"/");
410 // If there's anything left, we try for a regex match on the rest of the path minus the query string.
413 path2 = path2.substr(0,path2.find('?'));
415 for (vector< pair<RegularExpression*,Override*> >::const_iterator re = o->m_regexps.begin(); re != o->m_regexps.end(); ++re) {
416 if (re->first->matches(path2.c_str())) {
423 // Finally, check for query string matches. This is another "unrolled" recursive descent in a loop.
427 for (vector< pair< pair<string,RegularExpression*>,Override*> >::const_iterator q = o->m_queries.begin(); !descended && q != o->m_queries.end(); ++q) {
428 vector<const char*> vals;
429 if (request.getParameters(q->first.first.c_str(), vals)) {
430 if (q->first.second) {
431 // We have to match one of the values.
432 for (vector<const char*>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
433 if (q->first.second->matches(*v)) {
441 // The simple presence of the parameter is sufficient to match.
452 XMLRequestMapperImpl::XMLRequestMapperImpl(const DOMElement* e, Category& log) : m_document(NULL)
455 xmltooling::NDC ndc("XMLRequestMapperImpl");
458 // Load the property set.
461 // Load any AccessControl provider.
464 // Loop over the HostRegex elements.
465 const DOMElement* host = XMLHelper::getFirstChildElement(e,HostRegex);
466 for (int i=1; host; ++i, host=XMLHelper::getNextSiblingElement(host,HostRegex)) {
467 const XMLCh* n=host->getAttributeNS(NULL,regex);
469 log.warn("Skipping HostRegex element (%d) with empty regex attribute",i);
473 auto_ptr<Override> o(new Override(host,log,this));
475 const XMLCh* flag=host->getAttributeNS(NULL,ignoreCase);
477 auto_ptr<RegularExpression> re(
478 new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
480 m_regexps.push_back(make_pair(re.release(), o.release()));
482 catch (XMLException& ex) {
483 auto_ptr_char tmp(ex.getMessage());
484 log.error("caught exception while parsing HostRegex regular expression (%d): %s", i, tmp.get());
487 log.debug("Added <HostRegex> mapping for %s", m_regexps.back().second->getString("regex").second);
490 // Loop over the Host elements.
491 host = XMLHelper::getFirstChildElement(e,Host);
492 for (int i=1; host; ++i, host=XMLHelper::getNextSiblingElement(host,Host)) {
493 const XMLCh* n=host->getAttributeNS(NULL,name);
495 log.warn("Skipping Host element (%d) with empty name attribute",i);
499 Override* o=new Override(host,log,this);
500 pair<bool,const char*> name=o->getString("name");
501 pair<bool,const char*> scheme=o->getString("scheme");
502 pair<bool,const char*> port=o->getString("port");
504 char* dup=strdup(name.second);
505 for (char* pch=dup; *pch; pch++)
507 auto_ptr<char> dupwrap(dup);
509 if (!scheme.first && port.first) {
510 // No scheme, but a port, so assume http.
511 scheme = pair<bool,const char*>(true,"http");
513 else if (scheme.first && !port.first) {
514 // Scheme, no port, so default it.
515 // XXX Use getservbyname instead?
517 if (!strcmp(scheme.second,"http"))
519 else if (!strcmp(scheme.second,"https"))
521 else if (!strcmp(scheme.second,"ftp"))
523 else if (!strcmp(scheme.second,"ldap"))
525 else if (!strcmp(scheme.second,"ldaps"))
530 string url(scheme.second);
531 url=url + "://" + dup;
533 // Is this the default port?
534 if ((!strcmp(scheme.second,"http") && !strcmp(port.second,"80")) ||
535 (!strcmp(scheme.second,"https") && !strcmp(port.second,"443")) ||
536 (!strcmp(scheme.second,"ftp") && !strcmp(port.second,"21")) ||
537 (!strcmp(scheme.second,"ldap") && !strcmp(port.second,"389")) ||
538 (!strcmp(scheme.second,"ldaps") && !strcmp(port.second,"636"))) {
539 // First store a port-less version.
540 if (m_map.count(url) || m_extras.count(url)) {
541 log.warn("Skipping duplicate Host element (%s)",url.c_str());
546 log.debug("Added <Host> mapping for %s",url.c_str());
548 // Now append the port. We use the extras vector, to avoid double freeing the object later.
549 url=url + ':' + port.second;
551 log.debug("Added <Host> mapping for %s",url.c_str());
554 url=url + ':' + port.second;
555 if (m_map.count(url) || m_extras.count(url)) {
556 log.warn("Skipping duplicate Host element (%s)",url.c_str());
561 log.debug("Added <Host> mapping for %s",url.c_str());
565 // No scheme or port, so we enter dual hosts on http:80 and https:443
566 string url("http://");
568 if (m_map.count(url) || m_extras.count(url)) {
569 log.warn("Skipping duplicate Host element (%s)",url.c_str());
574 log.debug("Added <Host> mapping for %s",url.c_str());
577 if (m_map.count(url) || m_extras.count(url)) {
578 log.warn("Skipping duplicate Host element (%s)",url.c_str());
582 log.debug("Added <Host> mapping for %s",url.c_str());
586 if (m_map.count(url) || m_extras.count(url)) {
587 log.warn("Skipping duplicate Host element (%s)",url.c_str());
591 log.debug("Added <Host> mapping for %s",url.c_str());
594 if (m_map.count(url) || m_extras.count(url)) {
595 log.warn("Skipping duplicate Host element (%s)",url.c_str());
599 log.debug("Added <Host> mapping for %s",url.c_str());
604 const Override* XMLRequestMapperImpl::findOverride(const char* vhost, const HTTPRequest& request) const
606 const Override* o=NULL;
607 map<string,Override*>::const_iterator i=m_map.find(vhost);
611 i=m_extras.find(vhost);
612 if (i!=m_extras.end())
615 for (vector< pair<RegularExpression*,Override*> >::const_iterator re = m_regexps.begin(); !o && re != m_regexps.end(); ++re) {
616 if (re->first->matches(vhost))
622 return o ? o->locate(request) : this;
625 pair<bool,DOMElement*> XMLRequestMapper::load()
627 // Load from source using base class.
628 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
630 // If we own it, wrap it.
631 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
633 XMLRequestMapperImpl* impl = new XMLRequestMapperImpl(raw.second,m_log);
635 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
636 impl->setDocument(docjanitor.release());
641 return make_pair(false,(DOMElement*)NULL);
644 RequestMapper::Settings XMLRequestMapper::getSettings(const HTTPRequest& request) const
647 vhost << request.getScheme() << "://" << request.getHostname() << ':' << request.getPort();
648 const Override* o=m_impl->findOverride(vhost.str().c_str(), request);
649 return Settings(o,o->getAC());