VS10 solution files, convert from NULL macro to nullptr.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / StatusHandler.cpp
1 /*
2  *  Copyright 2001-2010 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 /**
18  * StatusHandler.cpp
19  *
20  * Handler for exposing information about the internals of the SP.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "util/CGIParser.h"
31
32 using namespace shibsp;
33 #ifndef SHIBSP_LITE
34 # include "SessionCache.h"
35 # include "metadata/MetadataProviderCriteria.h"
36 # include <saml/version.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <xmltooling/security/Credential.h>
39 # include <xmltooling/security/CredentialCriteria.h>
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 #endif
44 using namespace xmltooling;
45 using namespace std;
46
47 namespace shibsp {
48
49 #if defined (_MSC_VER)
50     #pragma warning( push )
51     #pragma warning( disable : 4250 )
52 #endif
53
54     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
55     {
56     public:
57 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
58         short
59 #else
60         FilterAction
61 #endif
62         acceptNode(const DOMNode* node) const {
63             return FILTER_REJECT;
64         }
65     };
66
67     static SHIBSP_DLLLOCAL Blocker g_Blocker;
68
69     class SHIBSP_API StatusHandler : public AbstractHandler, public RemotedHandler
70     {
71     public:
72         StatusHandler(const DOMElement* e, const char* appId);
73         virtual ~StatusHandler() {}
74
75         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
76         void receive(DDF& in, ostream& out);
77
78     private:
79         pair<bool,long> processMessage(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
80
81         set<string> m_acl;
82     };
83
84 #if defined (_MSC_VER)
85     #pragma warning( pop )
86 #endif
87
88     Handler* SHIBSP_DLLLOCAL StatusHandlerFactory(const pair<const DOMElement*,const char*>& p)
89     {
90         return new StatusHandler(p.first, p.second);
91     }
92
93 #ifndef XMLTOOLING_NO_XMLSEC
94     vector<XSECCryptoX509*> g_NoCerts;
95 #else
96     vector<string> g_NoCerts;
97 #endif
98
99     static char _x2c(const char *what)
100     {
101         register char digit;
102
103         digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
104         digit *= 16;
105         digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
106         return(digit);
107     }
108
109     class DummyRequest : public HTTPRequest
110     {
111     public:
112         DummyRequest(const char* url) : m_parser(nullptr), m_url(url), m_scheme(nullptr), m_query(nullptr), m_port(0) {
113 #ifdef HAVE_STRCASECMP
114             if (url && !strncasecmp(url,"http://",7)) {
115                 m_scheme="http";
116                 url+=7;
117             }
118             else if (url && !strncasecmp(url,"https://",8)) {
119                 m_scheme="https";
120                 url+=8;
121             }
122             else
123 #else
124             if (url && !strnicmp(url,"http://",7)) {
125                 m_scheme="http";
126                 m_port = 80;
127                 url+=7;
128             }
129             else if (url && !strnicmp(url,"https://",8)) {
130                 m_scheme="https";
131                 m_port = 443;
132                 url+=8;
133             }
134             else
135 #endif
136                 throw invalid_argument("Target parameter was not an absolute URL.");
137
138             m_query = strchr(url,'?');
139             if (m_query)
140                 m_query++;
141
142             const char* slash = strchr(url, '/');
143             const char* colon = strchr(url, ':');
144             if (colon && colon < slash) {
145                 m_hostname.assign(url, colon-url);
146                 string port(colon + 1, slash - colon);
147                 m_port = atoi(port.c_str());
148             }
149             else {
150                 m_hostname.assign(url, slash - url);
151             }
152
153             while (*slash) {
154                 if (*slash == '?') {
155                     m_uri += slash;
156                     break;
157                 }
158                 else if (*slash != '%') {
159                     m_uri += *slash;
160                 }
161                 else {
162                     ++slash;
163                     if (!isxdigit(*slash) || !isxdigit(*(slash+1)))
164                         throw invalid_argument("Bad request, contained unsupported encoded characters.");
165                     m_uri += _x2c(slash);
166                     ++slash;
167                 }
168                 ++slash;
169             }
170         }
171
172         ~DummyRequest() {
173             delete m_parser;
174         }
175
176         const char* getRequestURL() const {
177             return m_url;
178         }
179         const char* getScheme() const {
180             return m_scheme;
181         }
182         const char* getHostname() const {
183             return m_hostname.c_str();
184         }
185         int getPort() const {
186             return m_port;
187         }
188         const char* getRequestURI() const {
189             return m_uri.c_str();
190         }
191         const char* getMethod() const {
192             return "GET";
193         }
194         string getContentType() const {
195             return "";
196         }
197         long getContentLength() const {
198             return 0;
199         }
200         string getRemoteAddr() const {
201             return "";
202         }
203         string getRemoteUser() const {
204             return "";
205         }
206         const char* getRequestBody() const {
207             return nullptr;
208         }
209         const char* getQueryString() const {
210             return m_query;
211         }
212         const char* getParameter(const char* name) const
213         {
214             if (!m_parser)
215                 m_parser=new CGIParser(*this);
216
217             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
218             return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
219         }
220         vector<const char*>::size_type getParameters(const char* name, vector<const char*>& values) const
221         {
222             if (!m_parser)
223                 m_parser=new CGIParser(*this);
224
225             pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
226             while (bounds.first!=bounds.second) {
227                 values.push_back(bounds.first->second);
228                 ++bounds.first;
229             }
230             return values.size();
231         }
232         string getHeader(const char* name) const {
233             return "";
234         }
235         virtual const
236 #ifndef XMLTOOLING_NO_XMLSEC
237             std::vector<XSECCryptoX509*>&
238 #else
239             std::vector<std::string>&
240 #endif
241             getClientCertificates() const {
242                 return g_NoCerts;
243         }
244
245     private:
246         mutable CGIParser* m_parser;
247         const char* m_url;
248         const char* m_scheme;
249         const char* m_query;
250         int m_port;
251         string m_hostname,m_uri;
252     };
253 };
254
255 StatusHandler::StatusHandler(const DOMElement* e, const char* appId)
256     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".StatusHandler"), &g_Blocker)
257 {
258     string address(appId);
259     address += getString("Location").second;
260     setAddress(address.c_str());
261     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
262         pair<bool,const char*> acl = getString("acl");
263         if (acl.first) {
264             string aclbuf=acl.second;
265             int j = 0;
266             for (unsigned int i=0;  i < aclbuf.length();  i++) {
267                 if (aclbuf.at(i)==' ') {
268                     m_acl.insert(aclbuf.substr(j, i-j));
269                     j = i+1;
270                 }
271             }
272             m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
273         }
274     }
275 }
276
277 pair<bool,long> StatusHandler::run(SPRequest& request, bool isHandler) const
278 {
279     SPConfig& conf = SPConfig::getConfig();
280     if (conf.isEnabled(SPConfig::InProcess)) {
281         if (!m_acl.empty() && m_acl.count(request.getRemoteAddr()) == 0) {
282             m_log.error("status handler request blocked from invalid address (%s)", request.getRemoteAddr().c_str());
283             istringstream msg("Status Handler Blocked");
284             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN));
285         }
286     }
287
288     const char* target = request.getParameter("target");
289     if (target) {
290         // RequestMap query, so handle it inproc.
291         DummyRequest dummy(target);
292         RequestMapper::Settings settings = request.getApplication().getServiceProvider().getRequestMapper()->getSettings(dummy);
293         map<string,const char*> props;
294         settings.first->getAll(props);
295
296         request.setContentType("text/xml");
297         stringstream msg;
298         msg << "<StatusHandler>";
299             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
300 #ifndef SHIBSP_LITE
301                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
302                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
303 #endif
304                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
305             msg << "<RequestSettings";
306             for (map<string,const char*>::const_iterator p = props.begin(); p != props.end(); ++p)
307                 msg << ' ' << p->first << "='" << p->second << "'";
308             msg << '>' << target << "</RequestSettings>";
309             msg << "<Status><OK/></Status>";
310         msg << "</StatusHandler>";
311         return make_pair(true,request.sendResponse(msg));
312     }
313
314     try {
315         if (conf.isEnabled(SPConfig::OutOfProcess)) {
316             // When out of process, we run natively and directly process the message.
317             return processMessage(request.getApplication(), request, request);
318         }
319         else {
320             // When not out of process, we remote all the message processing.
321             DDF out,in = wrap(request);
322             DDFJanitor jin(in), jout(out);
323             out=request.getServiceProvider().getListenerService()->send(in);
324             return unwrap(request, out);
325         }
326     }
327     catch (XMLToolingException& ex) {
328         m_log.error("error while processing request: %s", ex.what());
329         request.setContentType("text/xml");
330         stringstream msg;
331         msg << "<StatusHandler>";
332             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
333 #ifndef SHIBSP_LITE
334                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
335                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
336 #endif
337                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
338             msg << "<Status><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></Status>";
339         msg << "</StatusHandler>";
340         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
341     }
342     catch (exception& ex) {
343         m_log.error("error while processing request: %s", ex.what());
344         request.setContentType("text/xml");
345         stringstream msg;
346         msg << "<StatusHandler>";
347             msg << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
348 #ifndef SHIBSP_LITE
349                 << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
350                 << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
351 #endif
352                 << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
353             msg << "<Status><Exception type='std::exception'>" << ex.what() << "</Exception></Status>";
354         msg << "</StatusHandler>";
355         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
356     }
357 }
358
359 void StatusHandler::receive(DDF& in, ostream& out)
360 {
361     // Find application.
362     const char* aid=in["application_id"].string();
363     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
364     if (!app) {
365         // Something's horribly wrong.
366         m_log.error("couldn't find application (%s) for status request", aid ? aid : "(missing)");
367         throw ConfigurationException("Unable to locate application for status request, deleted?");
368     }
369
370     // Wrap a response shim.
371     DDF ret(nullptr);
372     DDFJanitor jout(ret);
373     auto_ptr<HTTPRequest> req(getRequest(in));
374     auto_ptr<HTTPResponse> resp(getResponse(ret));
375
376     // Since we're remoted, the result should either be a throw, a false/0 return,
377     // which we just return as an empty structure, or a response/redirect,
378     // which we capture in the facade and send back.
379     processMessage(*app, *req.get(), *resp.get());
380     out << ret;
381 }
382
383 pair<bool,long> StatusHandler::processMessage(
384     const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
385     ) const
386 {
387 #ifndef SHIBSP_LITE
388     m_log.debug("processing status request");
389
390     stringstream s;
391     s << "<StatusHandler>";
392     const char* status = "<OK/>";
393
394     s << "<Version Xerces-C='" << XERCES_FULLVERSIONDOT
395         << "' XML-Security-C='" << XSEC_FULLVERSIONDOT
396         << "' OpenSAML-C='" << OPENSAML_FULLVERSIONDOT
397         << "' Shibboleth='" << PACKAGE_VERSION << "'/>";
398
399     const char* param = nullptr;
400     if (param) {
401     }
402     else {
403         // General configuration and status report.
404         try {
405             SessionCache* sc = application.getServiceProvider().getSessionCache(false);
406             if (sc) {
407                 sc->test();
408                 s << "<SessionCache><OK/></SessionCache>";
409             }
410             else {
411                 s << "<SessionCache><None/></SessionCache>";
412             }
413         }
414         catch (XMLToolingException& ex) {
415             s << "<SessionCache><Exception type='" << ex.getClassName() << "'>" << ex.what() << "</Exception></SessionCache>";
416             status = "<Partial/>";
417         }
418         catch (exception& ex) {
419             s << "<SessionCache><Exception type='std::exception'>" << ex.what() << "</Exception></SessionCache>";
420             status = "<Partial/>";
421         }
422
423         const PropertySet* relyingParty=nullptr;
424         param=httpRequest.getParameter("entityID");
425         if (param) {
426             MetadataProvider* m = application.getMetadataProvider();
427             Locker mlock(m);
428             relyingParty = application.getRelyingParty(m->getEntityDescriptor(MetadataProviderCriteria(application, param)).first);
429         }
430         else {
431             relyingParty = &application;
432         }
433
434         s << "<Application id='" << application.getId() << "' entityID='" << relyingParty->getString("entityID").second << "'/>";
435
436         s << "<Handlers>";
437         vector<const Handler*> handlers;
438         application.getHandlers(handlers);
439         for (vector<const Handler*>::const_iterator h = handlers.begin(); h != handlers.end(); ++h) {
440             s << "<Handler type='" << (*h)->getType() << "' Location='" << (*h)->getString("Location").second << "'";
441             if ((*h)->getString("Binding").first)
442                 s << " Binding='" << (*h)->getString("Binding").second << "'";
443             s << "/>";
444         }
445         s << "</Handlers>";
446
447         CredentialResolver* credResolver=application.getCredentialResolver();
448         if (credResolver) {
449             Locker credLocker(credResolver);
450             CredentialCriteria cc;
451             cc.setUsage(Credential::SIGNING_CREDENTIAL);
452             pair<bool,const char*> keyName = relyingParty->getString("keyName");
453             if (keyName.first)
454                 cc.getKeyNames().insert(keyName.second);
455             vector<const Credential*> creds;
456             credResolver->resolve(creds,&cc);
457             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
458                 KeyInfo* kinfo = (*c)->getKeyInfo();
459                 if (kinfo) {
460                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
461                     kd->setUse(KeyDescriptor::KEYTYPE_SIGNING);
462                     kd->setKeyInfo(kinfo);
463                     s << *(kd.get());
464                 }
465             }
466
467             cc.setUsage(Credential::ENCRYPTION_CREDENTIAL);
468             creds.clear();
469             cc.getKeyNames().clear();
470             credResolver->resolve(creds,&cc);
471             for (vector<const Credential*>::const_iterator c = creds.begin(); c != creds.end(); ++c) {
472                 KeyInfo* kinfo = (*c)->getKeyInfo();
473                 if (kinfo) {
474                     auto_ptr<KeyDescriptor> kd(KeyDescriptorBuilder::buildKeyDescriptor());
475                     kd->setUse(KeyDescriptor::KEYTYPE_ENCRYPTION);
476                     kd->setKeyInfo(kinfo);
477                     s << *(kd.get());
478                 }
479             }
480         }
481     }
482
483     s << "<Status>" << status << "</Status></StatusHandler>";
484
485     httpResponse.setContentType("text/xml");
486     return make_pair(true, httpResponse.sendResponse(s));
487 #else
488     return make_pair(false,0L);
489 #endif
490 }