2 * Copyright 2001-2010 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/Threads.h>
34 #include <xmltooling/util/XMLHelper.h>
35 #include <xercesc/util/XMLUniDefs.hpp>
36 #include <xercesc/util/regx/RegularExpression.hpp>
38 using namespace shibsp;
39 using namespace xmltooling;
44 // Blocks access when an ACL plugin fails to load.
45 class AccessControlDummy : public AccessControl
54 aclresult_t authorized(const SPRequest& request, const Session* session) const {
55 return shib_acl_false;
59 class Override : public DOMPropertySet, public DOMNodeFilter
62 Override() : m_acl(NULL) {}
63 Override(const DOMElement* e, Category& log, const Override* base=NULL);
66 // Provides filter to exclude special config elements.
67 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
72 acceptNode(const DOMNode* node) const {
76 const Override* locate(const HTTPRequest& request) const;
77 AccessControl* getAC() const { return (m_acl ? m_acl : (getParent() ? dynamic_cast<const Override*>(getParent())->getAC() : NULL)); }
80 void loadACL(const DOMElement* e, Category& log);
82 map<string,Override*> m_map;
83 vector< pair<RegularExpression*,Override*> > m_regexps;
84 vector< pair< pair<string,RegularExpression*>,Override*> > m_queries;
90 class XMLRequestMapperImpl : public Override
93 XMLRequestMapperImpl(const DOMElement* e, Category& log);
95 ~XMLRequestMapperImpl() {
97 m_document->release();
100 void setDocument(DOMDocument* doc) {
104 const Override* findOverride(const char* vhost, const HTTPRequest& request) const;
107 map<string,Override*> m_extras;
108 DOMDocument* m_document;
111 #if defined (_MSC_VER)
112 #pragma warning( push )
113 #pragma warning( disable : 4250 )
116 class XMLRequestMapper : public RequestMapper, public ReloadableXMLFile
119 XMLRequestMapper(const DOMElement* e) : ReloadableXMLFile(e,Category::getInstance(SHIBSP_LOGCAT".RequestMapper")), m_impl(NULL) {
123 ~XMLRequestMapper() {
127 Settings getSettings(const HTTPRequest& request) const;
130 pair<bool,DOMElement*> background_load();
133 XMLRequestMapperImpl* m_impl;
136 #if defined (_MSC_VER)
137 #pragma warning( pop )
140 RequestMapper* SHIBSP_DLLLOCAL XMLRequestMapperFactory(const DOMElement* const & e)
142 return new XMLRequestMapper(e);
145 static const XMLCh _AccessControl[] = UNICODE_LITERAL_13(A,c,c,e,s,s,C,o,n,t,r,o,l);
146 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);
147 static const XMLCh Host[] = UNICODE_LITERAL_4(H,o,s,t);
148 static const XMLCh HostRegex[] = UNICODE_LITERAL_9(H,o,s,t,R,e,g,e,x);
149 static const XMLCh htaccess[] = UNICODE_LITERAL_8(h,t,a,c,c,e,s,s);
150 static const XMLCh ignoreCase[] = UNICODE_LITERAL_10(i,g,n,o,r,e,C,a,s,e);
151 static const XMLCh ignoreOption[] = UNICODE_LITERAL_1(i);
152 static const XMLCh Path[] = UNICODE_LITERAL_4(P,a,t,h);
153 static const XMLCh PathRegex[] = UNICODE_LITERAL_9(P,a,t,h,R,e,g,e,x);
154 static const XMLCh Query[] = UNICODE_LITERAL_5(Q,u,e,r,y);
155 static const XMLCh name[] = UNICODE_LITERAL_4(n,a,m,e);
156 static const XMLCh regex[] = UNICODE_LITERAL_5(r,e,g,e,x);
157 static const XMLCh _type[] = UNICODE_LITERAL_4(t,y,p,e);
160 void SHIBSP_API shibsp::registerRequestMappers()
162 SPConfig& conf=SPConfig::getConfig();
163 conf.RequestMapperManager.registerFactory(XML_REQUEST_MAPPER, XMLRequestMapperFactory);
164 conf.RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, XMLRequestMapperFactory);
167 RequestMapper::RequestMapper()
171 RequestMapper::~RequestMapper()
175 void Override::loadACL(const DOMElement* e, Category& log)
178 const DOMElement* acl=XMLHelper::getFirstChildElement(e,htaccess);
180 log.info("building Apache htaccess AccessControl provider...");
181 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(HT_ACCESS_CONTROL,acl);
184 acl=XMLHelper::getFirstChildElement(e,_AccessControl);
186 log.info("building XML-based AccessControl provider...");
187 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(XML_ACCESS_CONTROL,acl);
190 acl=XMLHelper::getFirstChildElement(e,AccessControlProvider);
192 auto_ptr_char type(acl->getAttributeNS(NULL,_type));
193 log.info("building AccessControl provider of type %s...",type.get());
194 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(type.get(),acl);
199 catch (exception& ex) {
200 log.crit("exception building AccessControl provider: %s", ex.what());
201 m_acl = new AccessControlDummy();
205 Override::Override(const DOMElement* e, Category& log, const Override* base) : m_acl(NULL)
208 // Load the property set.
212 // Load any AccessControl provider.
215 // Handle nested Paths.
216 DOMElement* path = XMLHelper::getFirstChildElement(e,Path);
217 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,Path)) {
218 const XMLCh* n=path->getAttributeNS(NULL,name);
220 // Skip any leading slashes.
221 while (n && *n==chForwardSlash)
224 // Check for empty name.
226 log.warn("skipping Path element (%d) with empty name attribute", i);
230 // Check for an embedded slash.
231 int slash=XMLString::indexOf(n,chForwardSlash);
233 // Copy the first path segment.
234 XMLCh* namebuf=new XMLCh[slash + 1];
235 for (int pos=0; pos < slash; pos++)
237 namebuf[slash]=chNull;
239 // Move past the slash in the original pathname.
242 // Skip any leading slashes again.
243 while (*n==chForwardSlash)
247 // Create a placeholder Path element for the first path segment and replant under it.
248 DOMElement* newpath=path->getOwnerDocument()->createElementNS(shibspconstants::SHIB2SPCONFIG_NS,Path);
249 newpath->setAttributeNS(NULL,name,namebuf);
250 path->setAttributeNS(NULL,name,n);
251 path->getParentNode()->replaceChild(newpath,path);
252 newpath->appendChild(path);
254 // Repoint our locals at the new parent.
256 n=path->getAttributeNS(NULL,name);
259 // All we had was a pathname with trailing slash(es), so just reset it without them.
260 path->setAttributeNS(NULL,name,namebuf);
261 n=path->getAttributeNS(NULL,name);
266 Override* o=new Override(path,log,this);
267 pair<bool,const char*> name=o->getString("name");
268 char* dup=strdup(name.second);
269 for (char* pch=dup; *pch; pch++)
271 if (m_map.count(dup)) {
272 log.warn("skipping duplicate Path element (%s)",dup);
278 log.debug("added Path mapping (%s)", dup);
282 if (!XMLString::equals(e->getLocalName(), PathRegex)) {
283 // Handle nested PathRegexs.
284 path = XMLHelper::getFirstChildElement(e,PathRegex);
285 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,PathRegex)) {
286 const XMLCh* n=path->getAttributeNS(NULL,regex);
288 log.warn("skipping PathRegex element (%d) with empty regex attribute",i);
292 auto_ptr<Override> o(new Override(path,log,this));
294 const XMLCh* flag=path->getAttributeNS(NULL,ignoreCase);
296 auto_ptr<RegularExpression> re(
297 new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
299 m_regexps.push_back(make_pair(re.release(), o.release()));
301 catch (XMLException& ex) {
302 auto_ptr_char tmp(ex.getMessage());
303 log.error("caught exception while parsing PathRegex regular expression (%d): %s", i, tmp.get());
304 throw ConfigurationException("Invalid regular expression in PathRegex element.");
307 if (log.isDebugEnabled())
308 log.debug("added <PathRegex> mapping (%s)", m_regexps.back().second->getString("regex").second);
312 // Handle nested Querys.
313 path = XMLHelper::getFirstChildElement(e,Query);
314 for (int i=1; path; ++i, path=XMLHelper::getNextSiblingElement(path,Query)) {
315 const XMLCh* n=path->getAttributeNS(NULL,name);
317 log.warn("skipping Query element (%d) with empty name attribute",i);
320 auto_ptr_char ntemp(n);
321 const XMLCh* v=path->getAttributeNS(NULL,regex);
323 auto_ptr<Override> o(new Override(path,log,this));
325 RegularExpression* re = NULL;
327 re = new RegularExpression(v);
328 m_queries.push_back(make_pair(make_pair(string(ntemp.get()),re), o.release()));
330 catch (XMLException& ex) {
331 auto_ptr_char tmp(ex.getMessage());
332 log.error("caught exception while parsing Query regular expression (%d): %s", i, tmp.get());
333 throw ConfigurationException("Invalid regular expression in Query element.");
336 log.debug("added <Query> mapping (%s)", ntemp.get());
341 for_each(m_map.begin(),m_map.end(),xmltooling::cleanup_pair<string,Override>());
342 for (vector< pair<RegularExpression*,Override*> >::iterator i = m_regexps.begin(); i != m_regexps.end(); ++i) {
346 for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
347 delete j->first.second;
354 Override::~Override()
357 for_each(m_map.begin(),m_map.end(),xmltooling::cleanup_pair<string,Override>());
358 for (vector< pair<RegularExpression*,Override*> >::iterator i = m_regexps.begin(); i != m_regexps.end(); ++i) {
362 for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
363 delete j->first.second;
368 const Override* Override::locate(const HTTPRequest& request) const
370 // This function is confusing because it's *not* recursive.
371 // The whole path is tokenized and mapped in a loop, so the
372 // path parameter starts with the entire request path and
373 // we can skip the leading slash as irrelevant.
374 const char* path = request.getRequestURI();
378 // Now we copy the path, chop the query string, and lower case it.
379 char* dup=strdup(path);
380 char* sep=strchr(dup,'?');
383 for (char* pch=dup; *pch; pch++)
386 // Default is for the current object to provide settings.
387 const Override* o=this;
389 // Tokenize the path by segment and try and map each segment.
392 const char* token=strtok_r(dup,"/",&pos);
394 const char* token=strtok(dup,"/");
397 map<string,Override*>::const_iterator i=o->m_map.find(token);
398 if (i==o->m_map.end())
399 break; // Once there's no match, we've consumed as much of the path as possible here.
400 // We found a match, so reset the settings pointer.
403 // We descended a step down the path, so we need to advance the original
404 // parameter for the regex step later.
405 path += strlen(token);
409 // Get the next segment, if any.
411 token=strtok_r(NULL,"/",&pos);
413 token=strtok(NULL,"/");
419 // If there's anything left, we try for a regex match on the rest of the path minus the query string.
422 path2 = path2.substr(0,path2.find('?'));
424 for (vector< pair<RegularExpression*,Override*> >::const_iterator re = o->m_regexps.begin(); re != o->m_regexps.end(); ++re) {
425 if (re->first->matches(path2.c_str())) {
432 // Finally, check for query string matches. This is another "unrolled" recursive descent in a loop.
436 for (vector< pair< pair<string,RegularExpression*>,Override*> >::const_iterator q = o->m_queries.begin(); !descended && q != o->m_queries.end(); ++q) {
437 vector<const char*> vals;
438 if (request.getParameters(q->first.first.c_str(), vals)) {
439 if (q->first.second) {
440 // We have to match one of the values.
441 for (vector<const char*>::const_iterator v = vals.begin(); v != vals.end(); ++v) {
442 if (q->first.second->matches(*v)) {
450 // The simple presence of the parameter is sufficient to match.
461 XMLRequestMapperImpl::XMLRequestMapperImpl(const DOMElement* e, Category& log) : m_document(NULL)
464 xmltooling::NDC ndc("XMLRequestMapperImpl");
467 // Load the property set.
470 // Load any AccessControl provider.
473 // Loop over the HostRegex elements.
474 const DOMElement* host = XMLHelper::getFirstChildElement(e,HostRegex);
475 for (int i=1; host; ++i, host=XMLHelper::getNextSiblingElement(host,HostRegex)) {
476 const XMLCh* n=host->getAttributeNS(NULL,regex);
478 log.warn("Skipping HostRegex element (%d) with empty regex attribute",i);
482 auto_ptr<Override> o(new Override(host,log,this));
484 const XMLCh* flag=host->getAttributeNS(NULL,ignoreCase);
486 auto_ptr<RegularExpression> re(
487 new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
489 m_regexps.push_back(make_pair(re.release(), o.release()));
491 catch (XMLException& ex) {
492 auto_ptr_char tmp(ex.getMessage());
493 log.error("caught exception while parsing HostRegex regular expression (%d): %s", i, tmp.get());
496 log.debug("Added <HostRegex> mapping for %s", m_regexps.back().second->getString("regex").second);
499 // Loop over the Host elements.
500 host = XMLHelper::getFirstChildElement(e,Host);
501 for (int i=1; host; ++i, host=XMLHelper::getNextSiblingElement(host,Host)) {
502 const XMLCh* n=host->getAttributeNS(NULL,name);
504 log.warn("Skipping Host element (%d) with empty name attribute",i);
508 Override* o=new Override(host,log,this);
509 pair<bool,const char*> name=o->getString("name");
510 pair<bool,const char*> scheme=o->getString("scheme");
511 pair<bool,const char*> port=o->getString("port");
513 char* dup=strdup(name.second);
514 for (char* pch=dup; *pch; pch++)
516 auto_ptr<char> dupwrap(dup);
518 if (!scheme.first && port.first) {
519 // No scheme, but a port, so assume http.
520 scheme = pair<bool,const char*>(true,"http");
522 else if (scheme.first && !port.first) {
523 // Scheme, no port, so default it.
524 // XXX Use getservbyname instead?
526 if (!strcmp(scheme.second,"http"))
528 else if (!strcmp(scheme.second,"https"))
530 else if (!strcmp(scheme.second,"ftp"))
532 else if (!strcmp(scheme.second,"ldap"))
534 else if (!strcmp(scheme.second,"ldaps"))
539 string url(scheme.second);
540 url=url + "://" + dup;
542 // Is this the default port?
543 if ((!strcmp(scheme.second,"http") && !strcmp(port.second,"80")) ||
544 (!strcmp(scheme.second,"https") && !strcmp(port.second,"443")) ||
545 (!strcmp(scheme.second,"ftp") && !strcmp(port.second,"21")) ||
546 (!strcmp(scheme.second,"ldap") && !strcmp(port.second,"389")) ||
547 (!strcmp(scheme.second,"ldaps") && !strcmp(port.second,"636"))) {
548 // First store a port-less version.
549 if (m_map.count(url) || m_extras.count(url)) {
550 log.warn("Skipping duplicate Host element (%s)",url.c_str());
555 log.debug("Added <Host> mapping for %s",url.c_str());
557 // Now append the port. We use the extras vector, to avoid double freeing the object later.
558 url=url + ':' + port.second;
560 log.debug("Added <Host> mapping for %s",url.c_str());
563 url=url + ':' + port.second;
564 if (m_map.count(url) || m_extras.count(url)) {
565 log.warn("Skipping duplicate Host element (%s)",url.c_str());
570 log.debug("Added <Host> mapping for %s",url.c_str());
574 // No scheme or port, so we enter dual hosts on http:80 and https:443
575 string url("http://");
577 if (m_map.count(url) || m_extras.count(url)) {
578 log.warn("Skipping duplicate Host element (%s)",url.c_str());
583 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());
595 if (m_map.count(url) || m_extras.count(url)) {
596 log.warn("Skipping duplicate Host element (%s)",url.c_str());
600 log.debug("Added <Host> mapping for %s",url.c_str());
603 if (m_map.count(url) || m_extras.count(url)) {
604 log.warn("Skipping duplicate Host element (%s)",url.c_str());
608 log.debug("Added <Host> mapping for %s",url.c_str());
613 const Override* XMLRequestMapperImpl::findOverride(const char* vhost, const HTTPRequest& request) const
615 const Override* o=NULL;
616 map<string,Override*>::const_iterator i=m_map.find(vhost);
620 i=m_extras.find(vhost);
621 if (i!=m_extras.end())
624 for (vector< pair<RegularExpression*,Override*> >::const_iterator re = m_regexps.begin(); !o && re != m_regexps.end(); ++re) {
625 if (re->first->matches(vhost))
631 return o ? o->locate(request) : this;
634 pair<bool,DOMElement*> XMLRequestMapper::background_load()
636 // Load from source using base class.
637 pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
639 // If we own it, wrap it.
640 XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
642 XMLRequestMapperImpl* impl = new XMLRequestMapperImpl(raw.second, m_log);
644 // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
645 impl->setDocument(docjanitor.release());
647 // Perform the swap inside a lock.
650 SharedLock locker(m_lock, false);
654 return make_pair(false,(DOMElement*)NULL);
657 RequestMapper::Settings XMLRequestMapper::getSettings(const HTTPRequest& request) const
661 vhost << request.getScheme() << "://" << request.getHostname() << ':' << request.getPort();
662 const Override* o=m_impl->findOverride(vhost.str().c_str(), request);
663 return Settings(o,o->getAC());
665 catch (XMLException& ex) {
666 auto_ptr_char tmp(ex.getMessage());
667 m_log.error("caught exception while locating content settings: %s", tmp.get());
668 throw ConfigurationException("XML-based RequestMapper failed to retrieve content settings.");