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