1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "remote/httpserverconnection.hpp"
4 #include "remote/httphandler.hpp"
5 #include "remote/httputility.hpp"
6 #include "remote/apilistener.hpp"
7 #include "remote/apifunction.hpp"
8 #include "remote/jsonrpc.hpp"
9 #include "base/application.hpp"
10 #include "base/base64.hpp"
11 #include "base/convert.hpp"
12 #include "base/configtype.hpp"
13 #include "base/defer.hpp"
14 #include "base/exception.hpp"
15 #include "base/io-engine.hpp"
16 #include "base/logger.hpp"
17 #include "base/objectlock.hpp"
18 #include "base/timer.hpp"
19 #include "base/tlsstream.hpp"
20 #include "base/utility.hpp"
24 #include <boost/asio/error.hpp>
25 #include <boost/asio/io_context.hpp>
26 #include <boost/asio/spawn.hpp>
27 #include <boost/beast/core.hpp>
28 #include <boost/beast/http.hpp>
29 #include <boost/system/error_code.hpp>
30 #include <boost/system/system_error.hpp>
31 #include <boost/thread/once.hpp>
33 using namespace icinga;
35 auto const l_ServerHeader ("Icinga/" + Application::GetAppVersion());
37 HttpServerConnection::HttpServerConnection(const String& identity, bool authenticated, const std::shared_ptr<AsioTlsStream>& stream)
38 : HttpServerConnection(identity, authenticated, stream, IoEngine::Get().GetIoContext())
42 HttpServerConnection::HttpServerConnection(const String& identity, bool authenticated, const std::shared_ptr<AsioTlsStream>& stream, boost::asio::io_context& io)
43 : m_Stream(stream), m_Seen(Utility::GetTime()), m_IoStrand(io), m_ShuttingDown(false), m_HasStartedStreaming(false),
44 m_CheckLivenessTimer(io)
47 m_ApiUser = ApiUser::GetByClientCN(identity);
51 std::ostringstream address;
52 auto endpoint (stream->lowest_layer().remote_endpoint());
54 address << '[' << endpoint.address() << "]:" << endpoint.port();
56 m_PeerAddress = address.str();
60 void HttpServerConnection::Start()
62 namespace asio = boost::asio;
64 HttpServerConnection::Ptr keepAlive (this);
66 IoEngine::SpawnCoroutine(m_IoStrand, [this, keepAlive](asio::yield_context yc) { ProcessMessages(yc); });
67 IoEngine::SpawnCoroutine(m_IoStrand, [this, keepAlive](asio::yield_context yc) { CheckLiveness(yc); });
70 void HttpServerConnection::Disconnect()
72 namespace asio = boost::asio;
74 HttpServerConnection::Ptr keepAlive (this);
76 IoEngine::SpawnCoroutine(m_IoStrand, [this, keepAlive](asio::yield_context yc) {
77 if (!m_ShuttingDown) {
78 m_ShuttingDown = true;
80 Log(LogInformation, "HttpServerConnection")
81 << "HTTP client disconnected (from " << m_PeerAddress << ")";
84 * Do not swallow exceptions in a coroutine.
85 * https://github.com/Icinga/icinga2/issues/7351
86 * We must not catch `detail::forced_unwind exception` as
87 * this is used for unwinding the stack.
89 * Just use the error_code dummy here.
91 boost::system::error_code ec;
93 m_CheckLivenessTimer.cancel();
95 m_Stream->lowest_layer().cancel(ec);
97 m_Stream->next_layer().async_shutdown(yc[ec]);
99 m_Stream->lowest_layer().shutdown(m_Stream->lowest_layer().shutdown_both, ec);
101 auto listener (ApiListener::GetInstance());
104 CpuBoundWork removeHttpClient (yc);
106 listener->RemoveHttpClient(this);
112 void HttpServerConnection::StartStreaming()
114 namespace asio = boost::asio;
116 m_HasStartedStreaming = true;
118 HttpServerConnection::Ptr keepAlive (this);
120 IoEngine::SpawnCoroutine(m_IoStrand, [this, keepAlive](asio::yield_context yc) {
121 if (!m_ShuttingDown) {
123 asio::mutable_buffer readBuf (buf, 128);
124 boost::system::error_code ec;
127 m_Stream->async_read_some(readBuf, yc[ec]);
135 bool HttpServerConnection::Disconnected()
137 return m_ShuttingDown;
141 bool EnsureValidHeaders(
142 AsioTlsStream& stream,
143 boost::beast::flat_buffer& buf,
144 boost::beast::http::parser<true, boost::beast::http::string_body>& parser,
145 boost::beast::http::response<boost::beast::http::string_body>& response,
147 boost::asio::yield_context& yc
150 namespace http = boost::beast::http;
155 bool httpError = false;
158 boost::system::error_code ec;
160 http::async_read_header(stream, buf, parser, yc[ec]);
163 if (ec == boost::asio::error::operation_aborted)
166 errorMsg = ec.message();
169 switch (parser.get().version()) {
174 errorMsg = "Unsupported HTTP version";
178 if (!errorMsg.IsEmpty() || httpError) {
179 response.result(http::status::bad_request);
181 if (!httpError && parser.get()[http::field::accept] == "application/json") {
182 HttpUtility::SendJsonBody(response, nullptr, new Dictionary({
184 { "status", String("Bad Request: ") + errorMsg }
187 response.set(http::field::content_type, "text/html");
188 response.body() = String("<h1>Bad Request</h1><p><pre>") + errorMsg + "</pre></p>";
189 response.set(http::field::content_length, response.body().size());
192 response.set(http::field::connection, "close");
194 boost::system::error_code ec;
196 http::async_write(stream, response, yc[ec]);
197 stream.async_flush(yc[ec]);
206 void HandleExpect100(
207 AsioTlsStream& stream,
208 boost::beast::http::request<boost::beast::http::string_body>& request,
209 boost::asio::yield_context& yc
212 namespace http = boost::beast::http;
214 if (request[http::field::expect] == "100-continue") {
215 http::response<http::string_body> response;
217 response.result(http::status::continue_);
219 boost::system::error_code ec;
221 http::async_write(stream, response, yc[ec]);
222 stream.async_flush(yc[ec]);
227 bool HandleAccessControl(
228 AsioTlsStream& stream,
229 boost::beast::http::request<boost::beast::http::string_body>& request,
230 boost::beast::http::response<boost::beast::http::string_body>& response,
231 boost::asio::yield_context& yc
234 namespace http = boost::beast::http;
236 auto listener (ApiListener::GetInstance());
239 auto headerAllowOrigin (listener->GetAccessControlAllowOrigin());
241 if (headerAllowOrigin) {
242 CpuBoundWork allowOriginHeader (yc);
244 auto allowedOrigins (headerAllowOrigin->ToSet<String>());
246 if (!allowedOrigins.empty()) {
247 auto& origin (request[http::field::origin]);
249 if (allowedOrigins.find(origin.to_string()) != allowedOrigins.end()) {
250 response.set(http::field::access_control_allow_origin, origin);
253 allowOriginHeader.Done();
255 response.set(http::field::access_control_allow_credentials, "true");
257 if (request.method() == http::verb::options && !request[http::field::access_control_request_method].empty()) {
258 response.result(http::status::ok);
259 response.set(http::field::access_control_allow_methods, "GET, POST, PUT, DELETE");
260 response.set(http::field::access_control_allow_headers, "Authorization, X-HTTP-Method-Override");
261 response.body() = "Preflight OK";
262 response.set(http::field::content_length, response.body().size());
263 response.set(http::field::connection, "close");
265 boost::system::error_code ec;
267 http::async_write(stream, response, yc[ec]);
268 stream.async_flush(yc[ec]);
280 bool EnsureAcceptHeader(
281 AsioTlsStream& stream,
282 boost::beast::http::request<boost::beast::http::string_body>& request,
283 boost::beast::http::response<boost::beast::http::string_body>& response,
284 boost::asio::yield_context& yc
287 namespace http = boost::beast::http;
289 if (request.method() != http::verb::get && request[http::field::accept] != "application/json") {
290 response.result(http::status::bad_request);
291 response.set(http::field::content_type, "text/html");
292 response.body() = "<h1>Accept header is missing or not set to 'application/json'.</h1>";
293 response.set(http::field::content_length, response.body().size());
294 response.set(http::field::connection, "close");
296 boost::system::error_code ec;
298 http::async_write(stream, response, yc[ec]);
299 stream.async_flush(yc[ec]);
308 bool EnsureAuthenticatedUser(
309 AsioTlsStream& stream,
310 boost::beast::http::request<boost::beast::http::string_body>& request,
311 ApiUser::Ptr& authenticatedUser,
312 boost::beast::http::response<boost::beast::http::string_body>& response,
313 boost::asio::yield_context& yc
316 namespace http = boost::beast::http;
318 if (!authenticatedUser) {
319 Log(LogWarning, "HttpServerConnection")
320 << "Unauthorized request: " << request.method_string() << ' ' << request.target();
322 response.result(http::status::unauthorized);
323 response.set(http::field::www_authenticate, "Basic realm=\"Icinga 2\"");
324 response.set(http::field::connection, "close");
326 if (request[http::field::accept] == "application/json") {
327 HttpUtility::SendJsonBody(response, nullptr, new Dictionary({
329 { "status", "Unauthorized. Please check your user credentials." }
332 response.set(http::field::content_type, "text/html");
333 response.body() = "<h1>Unauthorized. Please check your user credentials.</h1>";
334 response.set(http::field::content_length, response.body().size());
337 boost::system::error_code ec;
339 http::async_write(stream, response, yc[ec]);
340 stream.async_flush(yc[ec]);
349 bool EnsureValidBody(
350 AsioTlsStream& stream,
351 boost::beast::flat_buffer& buf,
352 boost::beast::http::parser<true, boost::beast::http::string_body>& parser,
353 ApiUser::Ptr& authenticatedUser,
354 boost::beast::http::response<boost::beast::http::string_body>& response,
356 boost::asio::yield_context& yc
359 namespace http = boost::beast::http;
362 size_t maxSize = 1024 * 1024;
363 Array::Ptr permissions = authenticatedUser->GetPermissions();
366 CpuBoundWork evalPermissions (yc);
368 ObjectLock olock(permissions);
370 for (const Value& permissionInfo : permissions) {
373 if (permissionInfo.IsObjectType<Dictionary>()) {
374 permission = static_cast<Dictionary::Ptr>(permissionInfo)->Get("permission");
376 permission = permissionInfo;
379 static std::vector<std::pair<String, size_t>> specialContentLengthLimits {
380 { "config/modify", 512 * 1024 * 1024 }
383 for (const auto& limitInfo : specialContentLengthLimits) {
384 if (limitInfo.second <= maxSize) {
388 if (Utility::Match(permission, limitInfo.first)) {
389 maxSize = limitInfo.second;
395 parser.body_limit(maxSize);
401 boost::system::error_code ec;
403 http::async_read(stream, buf, parser, yc[ec]);
406 if (ec == boost::asio::error::operation_aborted)
410 * Unfortunately there's no way to tell an HTTP protocol error
411 * from an error on a lower layer:
413 * <https://github.com/boostorg/beast/issues/643>
416 response.result(http::status::bad_request);
418 if (parser.get()[http::field::accept] == "application/json") {
419 HttpUtility::SendJsonBody(response, nullptr, new Dictionary({
421 { "status", String("Bad Request: ") + ec.message() }
424 response.set(http::field::content_type, "text/html");
425 response.body() = String("<h1>Bad Request</h1><p><pre>") + ec.message() + "</pre></p>";
426 response.set(http::field::content_length, response.body().size());
429 response.set(http::field::connection, "close");
431 http::async_write(stream, response, yc[ec]);
432 stream.async_flush(yc[ec]);
442 AsioTlsStream& stream,
443 boost::beast::http::request<boost::beast::http::string_body>& request,
444 ApiUser::Ptr& authenticatedUser,
445 boost::beast::http::response<boost::beast::http::string_body>& response,
446 HttpServerConnection& server,
447 bool& hasStartedStreaming,
448 boost::asio::yield_context& yc
451 namespace http = boost::beast::http;
454 CpuBoundWork handlingRequest (yc);
456 HttpHandler::ProcessRequest(stream, authenticatedUser, request, response, yc, server);
457 } catch (const std::exception& ex) {
458 if (hasStartedStreaming) {
462 auto sysErr (dynamic_cast<const boost::system::system_error*>(&ex));
464 if (sysErr && sysErr->code() == boost::asio::error::operation_aborted) {
468 http::response<http::string_body> response;
470 HttpUtility::SendJsonError(response, nullptr, 500, "Unhandled exception" , DiagnosticInformation(ex));
472 boost::system::error_code ec;
474 http::async_write(stream, response, yc[ec]);
475 stream.async_flush(yc[ec]);
480 if (hasStartedStreaming) {
484 boost::system::error_code ec;
486 http::async_write(stream, response, yc[ec]);
487 stream.async_flush(yc[ec]);
492 void HttpServerConnection::ProcessMessages(boost::asio::yield_context yc)
494 namespace beast = boost::beast;
495 namespace http = beast::http;
498 beast::flat_buffer buf;
501 m_Seen = Utility::GetTime();
503 http::parser<true, http::string_body> parser;
504 http::response<http::string_body> response;
506 parser.header_limit(1024 * 1024);
507 parser.body_limit(-1);
509 response.set(http::field::server, l_ServerHeader);
511 // Best practice is to always reset the buffer.
513 if (!EnsureValidHeaders(*m_Stream, buf, parser, response, m_ShuttingDown, yc)) {
517 m_Seen = Utility::GetTime();
519 auto& request (parser.get());
522 auto method (http::string_to_verb(request["X-Http-Method-Override"]));
524 if (method != http::verb::unknown) {
525 request.method(method);
529 HandleExpect100(*m_Stream, request, yc);
531 auto authenticatedUser (m_ApiUser);
533 if (!authenticatedUser) {
534 CpuBoundWork fetchingAuthenticatedUser (yc);
536 authenticatedUser = ApiUser::GetByAuthHeader(request[http::field::authorization].to_string());
539 Log(LogInformation, "HttpServerConnection")
540 << "Request: " << request.method_string() << ' ' << request.target()
541 << " (from " << m_PeerAddress
542 << "), user: " << (authenticatedUser ? authenticatedUser->GetName() : "<unauthenticated>")
543 << ", agent: " << request[http::field::user_agent] << ")."; //operator[] - Returns the value for a field, or "" if it does not exist.
546 if (!HandleAccessControl(*m_Stream, request, response, yc)) {
550 if (!EnsureAcceptHeader(*m_Stream, request, response, yc)) {
554 if (!EnsureAuthenticatedUser(*m_Stream, request, authenticatedUser, response, yc)) {
558 // Best practice is to always reset the buffer.
560 if (!EnsureValidBody(*m_Stream, buf, parser, authenticatedUser, response, m_ShuttingDown, yc)) {
564 m_Seen = std::numeric_limits<decltype(m_Seen)>::max();
566 if (!ProcessRequest(*m_Stream, request, authenticatedUser, response, *this, m_HasStartedStreaming, yc)) {
570 if (request.version() != 11 || request[http::field::connection] == "close") {
574 } catch (const std::exception& ex) {
575 if (!m_ShuttingDown) {
576 Log(LogCritical, "HttpServerConnection")
577 << "Unhandled exception while processing HTTP request: " << ex.what();
584 void HttpServerConnection::CheckLiveness(boost::asio::yield_context yc)
586 boost::system::error_code ec;
589 m_CheckLivenessTimer.expires_from_now(boost::posix_time::seconds(5));
590 m_CheckLivenessTimer.async_wait(yc[ec]);
592 if (m_ShuttingDown) {
596 if (m_Seen < Utility::GetTime() - 10) {
597 Log(LogInformation, "HttpServerConnection")
598 << "No messages for HTTP connection have been received in the last 10 seconds.";