icinga2/lib/remote/httpserverconnection.cpp

270 lines
8.6 KiB
C++
Raw Normal View History

2015-06-22 11:11:21 +02:00
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) *
2015-06-22 11:11:21 +02:00
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#include "remote/httpserverconnection.hpp"
2015-06-22 11:11:21 +02:00
#include "remote/httphandler.hpp"
#include "remote/httputility.hpp"
2015-06-22 11:11:21 +02:00
#include "remote/apilistener.hpp"
#include "remote/apifunction.hpp"
#include "remote/jsonrpc.hpp"
#include "base/base64.hpp"
#include "base/configtype.hpp"
2015-06-22 11:11:21 +02:00
#include "base/objectlock.hpp"
#include "base/utility.hpp"
#include "base/logger.hpp"
#include "base/exception.hpp"
#include "base/convert.hpp"
#include <boost/thread/once.hpp>
using namespace icinga;
static boost::once_flag l_HttpServerConnectionOnceFlag = BOOST_ONCE_INIT;
static Timer::Ptr l_HttpServerConnectionTimeoutTimer;
2015-06-22 11:11:21 +02:00
HttpServerConnection::HttpServerConnection(const String& identity, bool authenticated, const TlsStream::Ptr& stream)
2016-08-24 19:59:13 +02:00
: m_Stream(stream), m_Seen(Utility::GetTime()), m_CurrentRequest(stream), m_PendingRequests(0)
2015-06-22 11:11:21 +02:00
{
boost::call_once(l_HttpServerConnectionOnceFlag, &HttpServerConnection::StaticInitialize);
2015-06-22 11:11:21 +02:00
m_RequestQueue.SetName("HttpServerConnection");
2015-06-22 11:11:21 +02:00
if (authenticated)
m_ApiUser = ApiUser::GetByClientCN(identity);
2015-06-22 11:11:21 +02:00
}
void HttpServerConnection::StaticInitialize(void)
2015-06-22 11:11:21 +02:00
{
l_HttpServerConnectionTimeoutTimer = new Timer();
l_HttpServerConnectionTimeoutTimer->OnTimerExpired.connect(boost::bind(&HttpServerConnection::TimeoutTimerHandler));
l_HttpServerConnectionTimeoutTimer->SetInterval(15);
l_HttpServerConnectionTimeoutTimer->Start();
2015-06-22 11:11:21 +02:00
}
void HttpServerConnection::Start(void)
2015-06-22 11:11:21 +02:00
{
/* the stream holds an owning reference to this object through the callback we're registering here */
m_Stream->RegisterDataHandler(boost::bind(&HttpServerConnection::DataAvailableHandler, HttpServerConnection::Ptr(this)));
2015-06-22 11:11:21 +02:00
if (m_Stream->IsDataAvailable())
DataAvailableHandler();
}
ApiUser::Ptr HttpServerConnection::GetApiUser(void) const
2015-06-22 11:11:21 +02:00
{
return m_ApiUser;
}
TlsStream::Ptr HttpServerConnection::GetStream(void) const
2015-06-22 11:11:21 +02:00
{
return m_Stream;
}
void HttpServerConnection::Disconnect(void)
2015-06-22 11:11:21 +02:00
{
Log(LogDebug, "HttpServerConnection", "Http client disconnected");
2015-06-22 11:11:21 +02:00
ApiListener::Ptr listener = ApiListener::GetInstance();
listener->RemoveHttpClient(this);
m_CurrentRequest.~HttpRequest();
new (&m_CurrentRequest) HttpRequest(Stream::Ptr());
m_Stream->Close();
2015-06-22 11:11:21 +02:00
}
bool HttpServerConnection::ProcessMessage(void)
2015-06-22 11:11:21 +02:00
{
bool res;
try {
res = m_CurrentRequest.Parse(m_Context, false);
} catch (const std::invalid_argument& ex) {
HttpResponse response(m_Stream, m_CurrentRequest);
response.SetStatus(400, "Bad request");
String msg = String("<h1>Bad request</h1><p><pre>") + ex.what() + "</pre></p>";
response.WriteBody(msg.CStr(), msg.GetLength());
response.Finish();
m_Stream->Shutdown();
return false;
2015-06-22 11:11:21 +02:00
} catch (const std::exception& ex) {
HttpResponse response(m_Stream, m_CurrentRequest);
response.SetStatus(400, "Bad request");
String msg = "<h1>Bad request</h1><p><pre>" + DiagnosticInformation(ex) + "</pre></p>";
2015-06-22 11:11:21 +02:00
response.WriteBody(msg.CStr(), msg.GetLength());
2015-07-09 12:28:15 +02:00
response.Finish();
2015-06-22 11:11:21 +02:00
m_Stream->Shutdown();
return false;
}
if (m_CurrentRequest.Complete) {
m_RequestQueue.Enqueue(boost::bind(&HttpServerConnection::ProcessMessageAsync,
HttpServerConnection::Ptr(this), m_CurrentRequest));
2015-06-22 11:11:21 +02:00
m_Seen = Utility::GetTime();
m_PendingRequests++;
m_CurrentRequest.~HttpRequest();
new (&m_CurrentRequest) HttpRequest(m_Stream);
2015-06-22 11:11:21 +02:00
return true;
}
return res;
}
void HttpServerConnection::ProcessMessageAsync(HttpRequest& request)
2015-06-22 11:11:21 +02:00
{
String auth_header = request.Headers->Get("authorization");
String::SizeType pos = auth_header.FindFirstOf(" ");
String username, password;
if (pos != String::NPos && auth_header.SubStr(0, pos) == "Basic") {
String credentials_base64 = auth_header.SubStr(pos + 1);
String credentials = Base64::Decode(credentials_base64);
String::SizeType cpos = credentials.FindFirstOf(":");
if (cpos != String::NPos) {
username = credentials.SubStr(0, cpos);
password = credentials.SubStr(cpos + 1);
}
}
ApiUser::Ptr user;
/* client_cn matched. */
if (m_ApiUser)
user = m_ApiUser;
else {
user = ApiUser::GetByName(username);
/* Deny authentication if 1) given password is empty 2) configured password does not match. */
if (password.IsEmpty())
user.reset();
else if (user && user->GetPassword() != password)
user.reset();
}
String requestUrl = request.RequestUrl->Format();
Log(LogInformation, "HttpServerConnection")
<< "Request: " << request.RequestMethod << " " << requestUrl
<< " (from " << m_Stream->GetSocket()->GetPeerAddress() << ", user: " << (user ? user->GetName() : "<unauthenticated>") << ")";
2015-06-22 11:11:21 +02:00
HttpResponse response(m_Stream, request);
String accept_header = request.Headers->Get("accept");
if (request.RequestMethod != "GET" && accept_header != "application/json") {
response.SetStatus(400, "Wrong Accept header");
response.AddHeader("Content-Type", "text/html");
String msg = "<h1>Accept header is missing or not set to 'application/json'.</h1>";
response.WriteBody(msg.CStr(), msg.GetLength());
} else if (!user) {
Log(LogWarning, "HttpServerConnection")
<< "Unauthorized request: " << request.RequestMethod << " " << requestUrl;
response.SetStatus(401, "Unauthorized");
response.AddHeader("WWW-Authenticate", "Basic realm=\"Icinga 2\"");
if (request.Headers->Get("accept") == "application/json") {
Dictionary::Ptr result = new Dictionary();
result->Set("error", 401);
result->Set("status", "Unauthorized. Please check your user credentials.");
HttpUtility::SendJsonBody(response, result);
} else {
response.AddHeader("Content-Type", "text/html");
String msg = "<h1>Unauthorized. Please check your user credentials.</h1>";
response.WriteBody(msg.CStr(), msg.GetLength());
}
} else {
try {
HttpHandler::ProcessRequest(user, request, response);
} catch (const std::exception& ex) {
Log(LogCritical, "HttpServerConnection")
<< "Unhandled exception while processing Http request: " << DiagnosticInformation(ex);
response.SetStatus(503, "Unhandled exception");
String errorInfo = DiagnosticInformation(ex);
if (request.Headers->Get("accept") == "application/json") {
Dictionary::Ptr result = new Dictionary();
result->Set("error", 503);
result->Set("status", errorInfo);
HttpUtility::SendJsonBody(response, result);
} else {
response.AddHeader("Content-Type", "text/plain");
response.WriteBody(errorInfo.CStr(), errorInfo.GetLength());
}
}
}
2015-06-22 11:11:21 +02:00
response.Finish();
m_PendingRequests--;
}
void HttpServerConnection::DataAvailableHandler(void)
2015-06-22 11:11:21 +02:00
{
bool close = false;
2015-06-22 11:11:21 +02:00
if (!m_Stream->IsEof()) {
boost::mutex::scoped_lock lock(m_DataHandlerMutex);
2015-06-22 11:11:21 +02:00
try {
while (ProcessMessage())
; /* empty loop body */
} catch (const std::exception& ex) {
Log(LogWarning, "HttpServerConnection")
<< "Error while reading Http request: " << DiagnosticInformation(ex);
close = true;
}
} else
close = true;
if (close)
Disconnect();
2015-06-22 11:11:21 +02:00
}
void HttpServerConnection::CheckLiveness(void)
2015-06-22 11:11:21 +02:00
{
if (m_Seen < Utility::GetTime() - 10 && m_PendingRequests == 0) {
Log(LogInformation, "HttpServerConnection")
2015-06-22 11:11:21 +02:00
<< "No messages for Http connection have been received in the last 10 seconds.";
Disconnect();
}
}
void HttpServerConnection::TimeoutTimerHandler(void)
2015-06-22 11:11:21 +02:00
{
ApiListener::Ptr listener = ApiListener::GetInstance();
for (const HttpServerConnection::Ptr& client : listener->GetHttpClients()) {
2015-06-22 11:11:21 +02:00
client->CheckLiveness();
}
}