304cb9f28a3a6f2243759e5172e8933e63574c23
[shibboleth/cpp-sp.git] / shibsp / impl / XMLRequestMapper.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /** XMLRequestMapper.cpp
18  *
19  * XML-based RequestMapper implementation.
20  */
21
22 #include "internal.h"
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"
29
30 #include <algorithm>
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>
36
37 using namespace shibsp;
38 using namespace xmltooling;
39 using namespace std;
40
41 namespace shibsp {
42
43     // Blocks access when an ACL plugin fails to load.
44     class AccessControlDummy : public AccessControl
45     {
46     public:
47         Lockable* lock() {
48             return this;
49         }
50
51         void unlock() {}
52
53         aclresult_t authorized(const SPRequest& request, const Session* session) const {
54             return shib_acl_false;
55         }
56     };
57
58     class Override : public DOMPropertySet, public DOMNodeFilter
59     {
60     public:
61         Override() : m_acl(NULL) {}
62         Override(const DOMElement* e, Category& log, const Override* base=NULL);
63         ~Override();
64
65         // Provides filter to exclude special config elements.
66 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
67         short
68 #else
69         FilterAction
70 #endif
71         acceptNode(const DOMNode* node) const {
72             return FILTER_REJECT;
73         }
74
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)); }
77
78     protected:
79         void loadACL(const DOMElement* e, Category& log);
80
81         map<string,Override*> m_map;
82         vector< pair<RegularExpression*,Override*> > m_regexps;
83         vector< pair< pair<string,RegularExpression*>,Override*> > m_queries;
84
85     private:
86         AccessControl* m_acl;
87     };
88
89     class XMLRequestMapperImpl : public Override
90     {
91     public:
92         XMLRequestMapperImpl(const DOMElement* e, Category& log);
93
94         ~XMLRequestMapperImpl() {
95             if (m_document)
96                 m_document->release();
97         }
98
99         void setDocument(DOMDocument* doc) {
100             m_document = doc;
101         }
102
103         const Override* findOverride(const char* vhost, const HTTPRequest& request) const;
104
105     private:
106         map<string,Override*> m_extras;
107         DOMDocument* m_document;
108     };
109
110 #if defined (_MSC_VER)
111     #pragma warning( push )
112     #pragma warning( disable : 4250 )
113 #endif
114
115     class XMLRequestMapper : public RequestMapper, public ReloadableXMLFile
116     {
117     public:
118         XMLRequestMapper(const DOMElement* e) : ReloadableXMLFile(e,Category::getInstance(SHIBSP_LOGCAT".RequestMapper")), m_impl(NULL) {
119             load();
120         }
121
122         ~XMLRequestMapper() {
123             delete m_impl;
124         }
125
126         Settings getSettings(const HTTPRequest& request) const;
127
128     protected:
129         pair<bool,DOMElement*> load();
130
131     private:
132         XMLRequestMapperImpl* m_impl;
133     };
134
135 #if defined (_MSC_VER)
136     #pragma warning( pop )
137 #endif
138
139     RequestMapper* SHIBSP_DLLLOCAL XMLRequestMapperFactory(const DOMElement* const & e)
140     {
141         return new XMLRequestMapper(e);
142     }
143
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);
157 }
158
159 void SHIBSP_API shibsp::registerRequestMappers()
160 {
161     SPConfig& conf=SPConfig::getConfig();
162     conf.RequestMapperManager.registerFactory(XML_REQUEST_MAPPER, XMLRequestMapperFactory);
163     conf.RequestMapperManager.registerFactory(NATIVE_REQUEST_MAPPER, XMLRequestMapperFactory);
164 }
165
166 void Override::loadACL(const DOMElement* e, Category& log)
167 {
168     try {
169         const DOMElement* acl=XMLHelper::getFirstChildElement(e,htaccess);
170         if (acl) {
171             log.info("building Apache htaccess AccessControl provider...");
172             m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(HT_ACCESS_CONTROL,acl);
173         }
174         else {
175             acl=XMLHelper::getFirstChildElement(e,_AccessControl);
176             if (acl) {
177                 log.info("building XML-based AccessControl provider...");
178                 m_acl=SPConfig::getConfig().AccessControlManager.newPlugin(XML_ACCESS_CONTROL,acl);
179             }
180             else {
181                 acl=XMLHelper::getFirstChildElement(e,AccessControlProvider);
182                 if (acl) {
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);
186                 }
187             }
188         }
189     }
190     catch (exception& ex) {
191         log.crit("exception building AccessControl provider: %s", ex.what());
192         m_acl = new AccessControlDummy();
193     }
194 }
195
196 Override::Override(const DOMElement* e, Category& log, const Override* base) : m_acl(NULL)
197 {
198     try {
199         // Load the property set.
200         load(e,NULL,this);
201         setParent(base);
202
203         // Load any AccessControl provider.
204         loadACL(e,log);
205
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);
210
211             // Skip any leading slashes.
212             while (n && *n==chForwardSlash)
213                 n++;
214
215             // Check for empty name.
216             if (!n || !*n) {
217                 log.warn("skipping Path element (%d) with empty name attribute", i);
218                 continue;
219             }
220
221             // Check for an embedded slash.
222             int slash=XMLString::indexOf(n,chForwardSlash);
223             if (slash>0) {
224                 // Copy the first path segment.
225                 XMLCh* namebuf=new XMLCh[slash + 1];
226                 for (int pos=0; pos < slash; pos++)
227                     namebuf[pos]=n[pos];
228                 namebuf[slash]=chNull;
229
230                 // Move past the slash in the original pathname.
231                 n=n+slash+1;
232
233                 // Skip any leading slashes again.
234                 while (*n==chForwardSlash)
235                     n++;
236
237                 if (*n) {
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);
244
245                     // Repoint our locals at the new parent.
246                     path=newpath;
247                     n=path->getAttributeNS(NULL,name);
248                 }
249                 else {
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);
253                 }
254                 delete[] namebuf;
255             }
256
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++)
261                 *pch=tolower(*pch);
262             if (m_map.count(dup)) {
263                 log.warn("skipping duplicate Path element (%s)",dup);
264                 free(dup);
265                 delete o;
266                 continue;
267             }
268             m_map[dup]=o;
269             log.debug("added Path mapping (%s)", dup);
270             free(dup);
271         }
272
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);
278                 if (!n || !*n) {
279                     log.warn("skipping PathRegex element (%d) with empty regex attribute",i);
280                     continue;
281                 }
282
283                 auto_ptr<Override> o(new Override(path,log,this));
284
285                 const XMLCh* flag=path->getAttributeNS(NULL,ignoreCase);
286                 try {
287                     auto_ptr<RegularExpression> re(
288                         new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
289                         );
290                     m_regexps.push_back(make_pair(re.release(), o.release()));
291                 }
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.");
296                 }
297
298                 if (log.isDebugEnabled())
299                     log.debug("added <PathRegex> mapping (%s)", m_regexps.back().second->getString("regex").second);
300             }
301         }
302
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);
307             if (!n || !*n) {
308                 log.warn("skipping Query element (%d) with empty name attribute",i);
309                 continue;
310             }
311             auto_ptr_char ntemp(n);
312             const XMLCh* v=path->getAttributeNS(NULL,regex);
313
314             auto_ptr<Override> o(new Override(path,log,this));
315             try {
316                 RegularExpression* re = NULL;
317                 if (v && *v)
318                     re = new RegularExpression(v);
319                 m_queries.push_back(make_pair(make_pair(string(ntemp.get()),re), o.release()));
320             }
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.");
325             }
326
327             log.debug("added <Query> mapping (%s)", ntemp.get());
328         }
329     }
330     catch (exception&) {
331         delete m_acl;
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) {
334             delete i->first;
335             delete i->second;
336         }
337         for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
338             delete j->first.second;
339             delete j->second;
340         }
341         throw;
342     }
343 }
344
345 Override::~Override()
346 {
347     delete m_acl;
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) {
350         delete i->first;
351         delete i->second;
352     }
353     for (vector< pair< pair<string,RegularExpression*>,Override*> >::iterator j = m_queries.begin(); j != m_queries.end(); ++j) {
354         delete j->first.second;
355         delete j->second;
356     }
357 }
358
359 const Override* Override::locate(const HTTPRequest& request) const
360 {
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();
366     if (*path == '/')
367         path++;
368
369     // Now we copy the path, chop the query string, and lower case it.
370     char* dup=strdup(path);
371     char* sep=strchr(dup,'?');
372     if (sep)
373         *sep=0;
374     for (char* pch=dup; *pch; pch++)
375         *pch=tolower(*pch);
376
377     // Default is for the current object to provide settings.
378     const Override* o=this;
379
380     // Tokenize the path by segment and try and map each segment.
381 #ifdef HAVE_STRTOK_R
382     char* pos=NULL;
383     const char* token=strtok_r(dup,"/",&pos);
384 #else
385     const char* token=strtok(dup,"/");
386 #endif
387     while (token) {
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.
392         o=i->second;
393
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);
397         if (*path == '/')
398             path++;
399
400         // Get the next segment, if any.
401 #ifdef HAVE_STRTOK_R
402         token=strtok_r(NULL,"/",&pos);
403 #else
404         token=strtok(NULL,"/");
405 #endif
406     }
407
408     free(dup);
409
410     // If there's anything left, we try for a regex match on the rest of the path minus the query string.
411     if (*path) {
412         string path2(path);
413         path2 = path2.substr(0,path2.find('?'));
414
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())) {
417                 o = re->second;
418                 break;
419             }
420         }
421     }
422
423     // Finally, check for query string matches. This is another "unrolled" recursive descent in a loop.
424     bool descended;
425     do {
426         descended = false;
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)) {
434                             o = q->second;
435                             descended = true;
436                             break;
437                         }
438                     }
439                 }
440                 else {
441                     // The simple presence of the parameter is sufficient to match.
442                     o = q->second;
443                     descended = true;
444                 }
445             }
446         }
447     } while (descended);
448
449     return o;
450 }
451
452 XMLRequestMapperImpl::XMLRequestMapperImpl(const DOMElement* e, Category& log) : m_document(NULL)
453 {
454 #ifdef _DEBUG
455     xmltooling::NDC ndc("XMLRequestMapperImpl");
456 #endif
457
458     // Load the property set.
459     load(e,NULL,this);
460
461     // Load any AccessControl provider.
462     loadACL(e,log);
463
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);
468         if (!n || !*n) {
469             log.warn("Skipping HostRegex element (%d) with empty regex attribute",i);
470             continue;
471         }
472
473         auto_ptr<Override> o(new Override(host,log,this));
474
475         const XMLCh* flag=host->getAttributeNS(NULL,ignoreCase);
476         try {
477             auto_ptr<RegularExpression> re(
478                 new RegularExpression(n, (flag && (*flag==chLatin_f || *flag==chDigit_0)) ? &chNull : ignoreOption)
479                 );
480             m_regexps.push_back(make_pair(re.release(), o.release()));
481         }
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());
485         }
486
487         log.debug("Added <HostRegex> mapping for %s", m_regexps.back().second->getString("regex").second);
488     }
489
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);
494         if (!n || !*n) {
495             log.warn("Skipping Host element (%d) with empty name attribute",i);
496             continue;
497         }
498
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");
503
504         char* dup=strdup(name.second);
505         for (char* pch=dup; *pch; pch++)
506             *pch=tolower(*pch);
507         auto_ptr<char> dupwrap(dup);
508
509         if (!scheme.first && port.first) {
510             // No scheme, but a port, so assume http.
511             scheme = pair<bool,const char*>(true,"http");
512         }
513         else if (scheme.first && !port.first) {
514             // Scheme, no port, so default it.
515             // XXX Use getservbyname instead?
516             port.first = true;
517             if (!strcmp(scheme.second,"http"))
518                 port.second = "80";
519             else if (!strcmp(scheme.second,"https"))
520                 port.second = "443";
521             else if (!strcmp(scheme.second,"ftp"))
522                 port.second = "21";
523             else if (!strcmp(scheme.second,"ldap"))
524                 port.second = "389";
525             else if (!strcmp(scheme.second,"ldaps"))
526                 port.second = "636";
527         }
528
529         if (scheme.first) {
530             string url(scheme.second);
531             url=url + "://" + dup;
532
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());
542                     delete o;
543                     continue;
544                 }
545                 m_map[url]=o;
546                 log.debug("Added <Host> mapping for %s",url.c_str());
547
548                 // Now append the port. We use the extras vector, to avoid double freeing the object later.
549                 url=url + ':' + port.second;
550                 m_extras[url]=o;
551                 log.debug("Added <Host> mapping for %s",url.c_str());
552             }
553             else {
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());
557                     delete o;
558                     continue;
559                 }
560                 m_map[url]=o;
561                 log.debug("Added <Host> mapping for %s",url.c_str());
562             }
563         }
564         else {
565             // No scheme or port, so we enter dual hosts on http:80 and https:443
566             string url("http://");
567             url = url + dup;
568             if (m_map.count(url) || m_extras.count(url)) {
569                 log.warn("Skipping duplicate Host element (%s)",url.c_str());
570                 delete o;
571                 continue;
572             }
573             m_map[url]=o;
574             log.debug("Added <Host> mapping for %s",url.c_str());
575
576             url = url + ":80";
577             if (m_map.count(url) || m_extras.count(url)) {
578                 log.warn("Skipping duplicate Host element (%s)",url.c_str());
579                 continue;
580             }
581             m_extras[url]=o;
582             log.debug("Added <Host> mapping for %s",url.c_str());
583
584             url = "https://";
585             url = url + dup;
586             if (m_map.count(url) || m_extras.count(url)) {
587                 log.warn("Skipping duplicate Host element (%s)",url.c_str());
588                 continue;
589             }
590             m_extras[url]=o;
591             log.debug("Added <Host> mapping for %s",url.c_str());
592
593             url = url + ":443";
594             if (m_map.count(url) || m_extras.count(url)) {
595                 log.warn("Skipping duplicate Host element (%s)",url.c_str());
596                 continue;
597             }
598             m_extras[url]=o;
599             log.debug("Added <Host> mapping for %s",url.c_str());
600         }
601     }
602 }
603
604 const Override* XMLRequestMapperImpl::findOverride(const char* vhost, const HTTPRequest& request) const
605 {
606     const Override* o=NULL;
607     map<string,Override*>::const_iterator i=m_map.find(vhost);
608     if (i!=m_map.end())
609         o=i->second;
610     else {
611         i=m_extras.find(vhost);
612         if (i!=m_extras.end())
613             o=i->second;
614         else {
615             for (vector< pair<RegularExpression*,Override*> >::const_iterator re = m_regexps.begin(); !o && re != m_regexps.end(); ++re) {
616                 if (re->first->matches(vhost))
617                     o=re->second;
618             }
619         }
620     }
621
622     return o ? o->locate(request) : this;
623 }
624
625 pair<bool,DOMElement*> XMLRequestMapper::load()
626 {
627     // Load from source using base class.
628     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
629
630     // If we own it, wrap it.
631     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
632
633     XMLRequestMapperImpl* impl = new XMLRequestMapperImpl(raw.second,m_log);
634
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());
637
638     delete m_impl;
639     m_impl = impl;
640
641     return make_pair(false,(DOMElement*)NULL);
642 }
643
644 RequestMapper::Settings XMLRequestMapper::getSettings(const HTTPRequest& request) const
645 {
646     ostringstream vhost;
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());
650 }