blob: d5f4481700b561cd7a02b4d5c5dd8028c9aad1e9 [file] [log] [blame]
Ed Tanousfca2cbe2021-01-28 14:49:59 -08001#pragma once
2#include "bmcweb_config.h"
3
4#include "async_resp.hpp"
5#include "authentication.hpp"
6#include "complete_response_fields.hpp"
Ed Tanous325310d2024-03-15 09:05:04 -07007#include "http_body.hpp"
Ed Tanousfca2cbe2021-01-28 14:49:59 -08008#include "http_response.hpp"
9#include "http_utility.hpp"
10#include "logging.hpp"
11#include "mutual_tls.hpp"
12#include "nghttp2_adapters.hpp"
13#include "ssl_key_handler.hpp"
14#include "utility.hpp"
15
Ed Tanousfca2cbe2021-01-28 14:49:59 -080016#include <boost/asio/io_context.hpp>
17#include <boost/asio/ip/tcp.hpp>
18#include <boost/asio/ssl/stream.hpp>
19#include <boost/asio/steady_timer.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080020#include <boost/beast/http/error.hpp>
21#include <boost/beast/http/parser.hpp>
22#include <boost/beast/http/read.hpp>
23#include <boost/beast/http/serializer.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080024#include <boost/beast/http/write.hpp>
25#include <boost/beast/ssl/ssl_stream.hpp>
26#include <boost/beast/websocket.hpp>
Ed Tanousd0882182024-01-26 23:45:25 -080027#include <boost/system/error_code.hpp>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080028
Ed Tanousd0882182024-01-26 23:45:25 -080029#include <array>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080030#include <atomic>
31#include <chrono>
Ed Tanousd0882182024-01-26 23:45:25 -080032#include <functional>
33#include <memory>
Ed Tanousfca2cbe2021-01-28 14:49:59 -080034#include <vector>
35
36namespace crow
37{
38
39struct Http2StreamData
40{
Ed Tanous47f29342024-03-19 12:18:06 -070041 Request req;
Ed Tanous325310d2024-03-15 09:05:04 -070042 std::optional<bmcweb::HttpBody::reader> reqReader;
Ed Tanous47f29342024-03-19 12:18:06 -070043 Response res;
Ed Tanousb2896142024-01-31 15:25:47 -080044 std::optional<bmcweb::HttpBody::writer> writer;
Ed Tanousfca2cbe2021-01-28 14:49:59 -080045};
46
47template <typename Adaptor, typename Handler>
48class HTTP2Connection :
49 public std::enable_shared_from_this<HTTP2Connection<Adaptor, Handler>>
50{
51 using self_type = HTTP2Connection<Adaptor, Handler>;
52
53 public:
54 HTTP2Connection(Adaptor&& adaptorIn, Handler* handlerIn,
Ed Tanous52e31622024-01-23 16:31:11 -080055 std::function<std::string()>& getCachedDateStrF) :
Ed Tanousfca2cbe2021-01-28 14:49:59 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous52e31622024-01-23 16:31:11 -080057 ngSession(initializeNghttp2Session()), handler(handlerIn),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanousfca2cbe2021-01-28 14:49:59 -080059 {}
60
61 void start()
62 {
63 // Create the control stream
Ed Tanousf42e8592023-08-25 10:47:44 -070064 streams[0];
Ed Tanousfca2cbe2021-01-28 14:49:59 -080065
66 if (sendServerConnectionHeader() != 0)
67 {
Ed Tanous62598e32023-07-17 17:06:25 -070068 BMCWEB_LOG_ERROR("send_server_connection_header failed");
Ed Tanousfca2cbe2021-01-28 14:49:59 -080069 return;
70 }
71 doRead();
72 }
73
74 int sendServerConnectionHeader()
75 {
Ed Tanous62598e32023-07-17 17:06:25 -070076 BMCWEB_LOG_DEBUG("send_server_connection_header()");
Ed Tanousfca2cbe2021-01-28 14:49:59 -080077
78 uint32_t maxStreams = 4;
79 std::array<nghttp2_settings_entry, 2> iv = {
80 {{NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, maxStreams},
81 {NGHTTP2_SETTINGS_ENABLE_PUSH, 0}}};
82 int rv = ngSession.submitSettings(iv);
83 if (rv != 0)
84 {
Ed Tanous62598e32023-07-17 17:06:25 -070085 BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
Ed Tanousfca2cbe2021-01-28 14:49:59 -080086 return -1;
87 }
Ed Tanousd0882182024-01-26 23:45:25 -080088 writeBuffer();
Ed Tanousfca2cbe2021-01-28 14:49:59 -080089 return 0;
90 }
91
92 static ssize_t fileReadCallback(nghttp2_session* /* session */,
Ed Tanousf42e8592023-08-25 10:47:44 -070093 int32_t streamId, uint8_t* buf,
Ed Tanousfca2cbe2021-01-28 14:49:59 -080094 size_t length, uint32_t* dataFlags,
Ed Tanousf42e8592023-08-25 10:47:44 -070095 nghttp2_data_source* /*source*/,
96 void* userPtr)
Ed Tanousfca2cbe2021-01-28 14:49:59 -080097 {
Ed Tanousf42e8592023-08-25 10:47:44 -070098 self_type& self = userPtrToSelf(userPtr);
99
100 auto streamIt = self.streams.find(streamId);
101 if (streamIt == self.streams.end())
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800102 {
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800103 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
104 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700105 Http2StreamData& stream = streamIt->second;
Ed Tanous62598e32023-07-17 17:06:25 -0700106 BMCWEB_LOG_DEBUG("File read callback length: {}", length);
Ed Tanousd547d8d2024-03-16 18:04:41 -0700107 if (!stream.writer)
108 {
109 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
110 }
Ed Tanous52e31622024-01-23 16:31:11 -0800111 boost::beast::error_code ec;
112 boost::optional<std::pair<boost::asio::const_buffer, bool>> out =
113 stream.writer->getWithMaxSize(ec, length);
114 if (ec)
Ed Tanous27b0cf92023-08-07 12:02:40 -0700115 {
Ed Tanous325310d2024-03-15 09:05:04 -0700116 BMCWEB_LOG_CRITICAL("Failed to get buffer");
Ed Tanous27b0cf92023-08-07 12:02:40 -0700117 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
118 }
Ed Tanous52e31622024-01-23 16:31:11 -0800119 if (!out)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800120 {
Ed Tanous325310d2024-03-15 09:05:04 -0700121 BMCWEB_LOG_ERROR("Empty file, setting EOF");
Ed Tanous52e31622024-01-23 16:31:11 -0800122 *dataFlags |= NGHTTP2_DATA_FLAG_EOF;
123 return 0;
124 }
125
126 BMCWEB_LOG_DEBUG("Send chunk of size: {}", out->first.size());
127 if (length < out->first.size())
128 {
Ed Tanous325310d2024-03-15 09:05:04 -0700129 BMCWEB_LOG_CRITICAL(
130 "Buffer overflow that should never happen happened");
Ed Tanous52e31622024-01-23 16:31:11 -0800131 // Should never happen because of length limit on get() above
132 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
133 }
Ed Tanous325310d2024-03-15 09:05:04 -0700134 boost::asio::mutable_buffer writeableBuf(buf, length);
Ed Tanous52e31622024-01-23 16:31:11 -0800135 BMCWEB_LOG_DEBUG("Copying {} bytes to buf", out->first.size());
Ed Tanous325310d2024-03-15 09:05:04 -0700136 size_t copied = boost::asio::buffer_copy(writeableBuf, out->first);
137 if (copied != out->first.size())
138 {
139 BMCWEB_LOG_ERROR(
140 "Couldn't copy all {} bytes into buffer, only copied {}",
141 out->first.size(), copied);
142 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
143 }
Ed Tanous52e31622024-01-23 16:31:11 -0800144
145 if (!out->second)
146 {
Ed Tanous325310d2024-03-15 09:05:04 -0700147 BMCWEB_LOG_DEBUG("Setting EOF flag");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800148 *dataFlags |= NGHTTP2_DATA_FLAG_EOF;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800149 }
Ed Tanous325310d2024-03-15 09:05:04 -0700150 return static_cast<ssize_t>(copied);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800151 }
152
153 nghttp2_nv headerFromStringViews(std::string_view name,
Ed Tanous52e31622024-01-23 16:31:11 -0800154 std::string_view value, uint8_t flags)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800155 {
156 uint8_t* nameData = std::bit_cast<uint8_t*>(name.data());
157 uint8_t* valueData = std::bit_cast<uint8_t*>(value.data());
Ed Tanous52e31622024-01-23 16:31:11 -0800158 return {nameData, valueData, name.size(), value.size(), flags};
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800159 }
160
161 int sendResponse(Response& completedRes, int32_t streamId)
162 {
Ed Tanous62598e32023-07-17 17:06:25 -0700163 BMCWEB_LOG_DEBUG("send_response stream_id:{}", streamId);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800164
165 auto it = streams.find(streamId);
166 if (it == streams.end())
167 {
168 close();
169 return -1;
170 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700171 Response& thisRes = it->second.res;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800172 thisRes = std::move(completedRes);
Ed Tanousf42e8592023-08-25 10:47:44 -0700173 crow::Request& thisReq = it->second.req;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800174 std::vector<nghttp2_nv> hdr;
175
176 completeResponseFields(thisReq, thisRes);
177 thisRes.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous325310d2024-03-15 09:05:04 -0700178 thisRes.preparePayload();
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800179
Ed Tanous27b0cf92023-08-07 12:02:40 -0700180 boost::beast::http::fields& fields = thisRes.fields();
181 std::string code = std::to_string(thisRes.resultInt());
Ed Tanous52e31622024-01-23 16:31:11 -0800182 hdr.emplace_back(
183 headerFromStringViews(":status", code, NGHTTP2_NV_FLAG_NONE));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800184 for (const boost::beast::http::fields::value_type& header : fields)
185 {
Ed Tanous52e31622024-01-23 16:31:11 -0800186 hdr.emplace_back(headerFromStringViews(
Ed Tanousd0882182024-01-26 23:45:25 -0800187 header.name_string(), header.value(), NGHTTP2_NV_FLAG_NONE));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800188 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700189 Http2StreamData& stream = it->second;
Ed Tanous52e31622024-01-23 16:31:11 -0800190 crow::Response& res = stream.res;
Ed Tanousb2896142024-01-31 15:25:47 -0800191 http::response<bmcweb::HttpBody>& fbody = res.response;
Ed Tanous52e31622024-01-23 16:31:11 -0800192 stream.writer.emplace(fbody.base(), fbody.body());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800193
194 nghttp2_data_provider dataPrd{
Ed Tanousf42e8592023-08-25 10:47:44 -0700195 .source = {.fd = 0},
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800196 .read_callback = fileReadCallback,
197 };
198
199 int rv = ngSession.submitResponse(streamId, hdr, &dataPrd);
200 if (rv != 0)
201 {
Ed Tanous62598e32023-07-17 17:06:25 -0700202 BMCWEB_LOG_ERROR("Fatal error: {}", nghttp2_strerror(rv));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800203 close();
204 return -1;
205 }
Ed Tanousd0882182024-01-26 23:45:25 -0800206 writeBuffer();
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800207
208 return 0;
209 }
210
211 nghttp2_session initializeNghttp2Session()
212 {
213 nghttp2_session_callbacks callbacks;
214 callbacks.setOnFrameRecvCallback(onFrameRecvCallbackStatic);
215 callbacks.setOnStreamCloseCallback(onStreamCloseCallbackStatic);
216 callbacks.setOnHeaderCallback(onHeaderCallbackStatic);
217 callbacks.setOnBeginHeadersCallback(onBeginHeadersCallbackStatic);
Ed Tanous325310d2024-03-15 09:05:04 -0700218 callbacks.setOnDataChunkRecvCallback(onDataChunkRecvStatic);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800219
220 nghttp2_session session(callbacks);
221 session.setUserData(this);
222
223 return session;
224 }
225
226 int onRequestRecv(int32_t streamId)
227 {
Ed Tanous62598e32023-07-17 17:06:25 -0700228 BMCWEB_LOG_DEBUG("on_request_recv");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800229
230 auto it = streams.find(streamId);
231 if (it == streams.end())
232 {
233 close();
234 return -1;
235 }
Ed Tanousd547d8d2024-03-16 18:04:41 -0700236 auto& reqReader = it->second.reqReader;
237 if (reqReader)
Ed Tanous325310d2024-03-15 09:05:04 -0700238 {
239 boost::beast::error_code ec;
Ed Tanousd547d8d2024-03-16 18:04:41 -0700240 reqReader->finish(ec);
Ed Tanous325310d2024-03-15 09:05:04 -0700241 if (ec)
242 {
243 BMCWEB_LOG_CRITICAL("Failed to finalize payload");
244 close();
245 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
246 }
247 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700248 crow::Request& thisReq = it->second.req;
Ed Tanous62598e32023-07-17 17:06:25 -0700249 BMCWEB_LOG_DEBUG("Handling {} \"{}\"", logPtr(&thisReq),
250 thisReq.url().encoded_path());
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800251
Ed Tanousf42e8592023-08-25 10:47:44 -0700252 crow::Response& thisRes = it->second.res;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800253
254 thisRes.setCompleteRequestHandler(
255 [this, streamId](Response& completeRes) {
Ed Tanous62598e32023-07-17 17:06:25 -0700256 BMCWEB_LOG_DEBUG("res.completeRequestHandler called");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800257 if (sendResponse(completeRes, streamId) != 0)
258 {
259 close();
260 return;
261 }
262 });
263 auto asyncResp =
Ed Tanousf42e8592023-08-25 10:47:44 -0700264 std::make_shared<bmcweb::AsyncResp>(std::move(it->second.res));
Ed Tanous325310d2024-03-15 09:05:04 -0700265#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
266 thisReq.session = crow::authentication::authenticate(
267 {}, thisRes, thisReq.method(), thisReq.req, nullptr);
268 if (!crow::authentication::isOnAllowlist(thisReq.url().path(),
269 thisReq.method()) &&
270 thisReq.session == nullptr)
271 {
272 BMCWEB_LOG_WARNING("Authentication failed");
273 forward_unauthorized::sendUnauthorized(
274 thisReq.url().encoded_path(),
275 thisReq.getHeaderValue("X-Requested-With"),
276 thisReq.getHeaderValue("Accept"), thisRes);
277 }
278 else
279#endif // BMCWEB_INSECURE_DISABLE_AUTHX
280 {
281 handler->handle(thisReq, asyncResp);
282 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800283 return 0;
284 }
285
Ed Tanous325310d2024-03-15 09:05:04 -0700286 int onDataChunkRecvCallback(uint8_t /*flags*/, int32_t streamId,
287 const uint8_t* data, size_t len)
288 {
289 auto thisStream = streams.find(streamId);
290 if (thisStream == streams.end())
291 {
292 BMCWEB_LOG_ERROR("Unknown stream{}", streamId);
293 close();
294 return -1;
295 }
Ed Tanousd547d8d2024-03-16 18:04:41 -0700296
297 std::optional<bmcweb::HttpBody::reader>& reqReader =
298 thisStream->second.reqReader;
299 if (!reqReader)
Ed Tanous325310d2024-03-15 09:05:04 -0700300 {
Ed Tanous8e5cc7b2024-04-02 11:00:54 -0700301 reqReader.emplace(
302 bmcweb::HttpBody::reader(thisStream->second.req.req.base(),
303 thisStream->second.req.req.body()));
Ed Tanous325310d2024-03-15 09:05:04 -0700304 }
305 boost::beast::error_code ec;
Ed Tanousd547d8d2024-03-16 18:04:41 -0700306 reqReader->put(boost::asio::const_buffer(data, len), ec);
Ed Tanous325310d2024-03-15 09:05:04 -0700307 if (ec)
308 {
309 BMCWEB_LOG_CRITICAL("Failed to write payload");
310 return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
311 }
312 return 0;
313 }
314
315 static int onDataChunkRecvStatic(nghttp2_session* /* session */,
316 uint8_t flags, int32_t streamId,
317 const uint8_t* data, size_t len,
318 void* userData)
319 {
320 BMCWEB_LOG_DEBUG("on_frame_recv_callback");
321 if (userData == nullptr)
322 {
323 BMCWEB_LOG_CRITICAL("user data was null?");
324 return NGHTTP2_ERR_CALLBACK_FAILURE;
325 }
326 return userPtrToSelf(userData).onDataChunkRecvCallback(flags, streamId,
327 data, len);
328 }
329
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800330 int onFrameRecvCallback(const nghttp2_frame& frame)
331 {
Ed Tanous62598e32023-07-17 17:06:25 -0700332 BMCWEB_LOG_DEBUG("frame type {}", static_cast<int>(frame.hd.type));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800333 switch (frame.hd.type)
334 {
335 case NGHTTP2_DATA:
336 case NGHTTP2_HEADERS:
337 // Check that the client request has finished
338 if ((frame.hd.flags & NGHTTP2_FLAG_END_STREAM) != 0)
339 {
340 return onRequestRecv(frame.hd.stream_id);
341 }
342 break;
343 default:
344 break;
345 }
346 return 0;
347 }
348
349 static int onFrameRecvCallbackStatic(nghttp2_session* /* session */,
350 const nghttp2_frame* frame,
351 void* userData)
352 {
Ed Tanous62598e32023-07-17 17:06:25 -0700353 BMCWEB_LOG_DEBUG("on_frame_recv_callback");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800354 if (userData == nullptr)
355 {
Ed Tanous62598e32023-07-17 17:06:25 -0700356 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800357 return NGHTTP2_ERR_CALLBACK_FAILURE;
358 }
359 if (frame == nullptr)
360 {
Ed Tanous62598e32023-07-17 17:06:25 -0700361 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800362 return NGHTTP2_ERR_CALLBACK_FAILURE;
363 }
364 return userPtrToSelf(userData).onFrameRecvCallback(*frame);
365 }
366
367 static self_type& userPtrToSelf(void* userData)
368 {
369 // This method exists to keep the unsafe reinterpret cast in one
370 // place.
371 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
372 return *reinterpret_cast<self_type*>(userData);
373 }
374
375 static int onStreamCloseCallbackStatic(nghttp2_session* /* session */,
376 int32_t streamId,
377 uint32_t /*unused*/, void* userData)
378 {
Ed Tanous62598e32023-07-17 17:06:25 -0700379 BMCWEB_LOG_DEBUG("on_stream_close_callback stream {}", streamId);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800380 if (userData == nullptr)
381 {
Ed Tanous62598e32023-07-17 17:06:25 -0700382 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800383 return NGHTTP2_ERR_CALLBACK_FAILURE;
384 }
Ed Tanousf42e8592023-08-25 10:47:44 -0700385 if (userPtrToSelf(userData).streams.erase(streamId) <= 0)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800386 {
387 return -1;
388 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800389 return 0;
390 }
391
392 int onHeaderCallback(const nghttp2_frame& frame,
393 std::span<const uint8_t> name,
394 std::span<const uint8_t> value)
395 {
396 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
397 std::string_view nameSv(reinterpret_cast<const char*>(name.data()),
398 name.size());
399 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
400 std::string_view valueSv(reinterpret_cast<const char*>(value.data()),
401 value.size());
402
Ed Tanous62598e32023-07-17 17:06:25 -0700403 BMCWEB_LOG_DEBUG("on_header_callback name: {} value {}", nameSv,
404 valueSv);
Ed Tanousa07e9812024-03-19 10:31:13 -0700405 if (frame.hd.type != NGHTTP2_HEADERS)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800406 {
Ed Tanousa07e9812024-03-19 10:31:13 -0700407 return 0;
408 }
409 if (frame.headers.cat != NGHTTP2_HCAT_REQUEST)
410 {
411 return 0;
412 }
413 auto thisStream = streams.find(frame.hd.stream_id);
414 if (thisStream == streams.end())
415 {
416 BMCWEB_LOG_ERROR("Unknown stream{}", frame.hd.stream_id);
417 close();
418 return -1;
419 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800420
Ed Tanousa07e9812024-03-19 10:31:13 -0700421 crow::Request& thisReq = thisStream->second.req;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800422
Ed Tanousa07e9812024-03-19 10:31:13 -0700423 if (nameSv == ":path")
424 {
425 thisReq.target(valueSv);
426 }
427 else if (nameSv == ":method")
428 {
429 boost::beast::http::verb verb =
430 boost::beast::http::string_to_verb(valueSv);
431 if (verb == boost::beast::http::verb::unknown)
432 {
433 BMCWEB_LOG_ERROR("Unknown http verb {}", valueSv);
434 close();
435 return -1;
436 }
Myung Bae1873a042024-04-01 09:27:39 -0500437 thisReq.method(verb);
Ed Tanousa07e9812024-03-19 10:31:13 -0700438 }
439 else if (nameSv == ":scheme")
440 {
441 // Nothing to check on scheme
442 }
443 else
444 {
Myung Bae1873a042024-04-01 09:27:39 -0500445 thisReq.addHeader(nameSv, valueSv);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800446 }
447 return 0;
448 }
449
450 static int onHeaderCallbackStatic(nghttp2_session* /* session */,
451 const nghttp2_frame* frame,
452 const uint8_t* name, size_t namelen,
453 const uint8_t* value, size_t vallen,
454 uint8_t /* flags */, void* userData)
455 {
456 if (userData == nullptr)
457 {
Ed Tanous62598e32023-07-17 17:06:25 -0700458 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800459 return NGHTTP2_ERR_CALLBACK_FAILURE;
460 }
461 if (frame == nullptr)
462 {
Ed Tanous62598e32023-07-17 17:06:25 -0700463 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800464 return NGHTTP2_ERR_CALLBACK_FAILURE;
465 }
466 if (name == nullptr)
467 {
Ed Tanous62598e32023-07-17 17:06:25 -0700468 BMCWEB_LOG_CRITICAL("name was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800469 return NGHTTP2_ERR_CALLBACK_FAILURE;
470 }
471 if (value == nullptr)
472 {
Ed Tanous62598e32023-07-17 17:06:25 -0700473 BMCWEB_LOG_CRITICAL("value was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800474 return NGHTTP2_ERR_CALLBACK_FAILURE;
475 }
476 return userPtrToSelf(userData).onHeaderCallback(*frame, {name, namelen},
477 {value, vallen});
478 }
479
480 int onBeginHeadersCallback(const nghttp2_frame& frame)
481 {
482 if (frame.hd.type == NGHTTP2_HEADERS &&
483 frame.headers.cat == NGHTTP2_HCAT_REQUEST)
484 {
Ed Tanous62598e32023-07-17 17:06:25 -0700485 BMCWEB_LOG_DEBUG("create stream for id {}", frame.hd.stream_id);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800486
Ed Tanousf42e8592023-08-25 10:47:44 -0700487 Http2StreamData& stream = streams[frame.hd.stream_id];
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800488 // http2 is by definition always tls
Ed Tanousf42e8592023-08-25 10:47:44 -0700489 stream.req.isSecure = true;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800490 }
491 return 0;
492 }
493
494 static int onBeginHeadersCallbackStatic(nghttp2_session* /* session */,
495 const nghttp2_frame* frame,
496 void* userData)
497 {
Ed Tanous62598e32023-07-17 17:06:25 -0700498 BMCWEB_LOG_DEBUG("on_begin_headers_callback");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800499 if (userData == nullptr)
500 {
Ed Tanous62598e32023-07-17 17:06:25 -0700501 BMCWEB_LOG_CRITICAL("user data was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800502 return NGHTTP2_ERR_CALLBACK_FAILURE;
503 }
504 if (frame == nullptr)
505 {
Ed Tanous62598e32023-07-17 17:06:25 -0700506 BMCWEB_LOG_CRITICAL("frame was null?");
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800507 return NGHTTP2_ERR_CALLBACK_FAILURE;
508 }
509 return userPtrToSelf(userData).onBeginHeadersCallback(*frame);
510 }
511
512 static void afterWriteBuffer(const std::shared_ptr<self_type>& self,
513 const boost::system::error_code& ec,
514 size_t sendLength)
515 {
516 self->isWriting = false;
Ed Tanous62598e32023-07-17 17:06:25 -0700517 BMCWEB_LOG_DEBUG("Sent {}", sendLength);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800518 if (ec)
519 {
520 self->close();
521 return;
522 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800523 self->writeBuffer();
524 }
525
526 void writeBuffer()
527 {
528 if (isWriting)
529 {
530 return;
531 }
Ed Tanousd0882182024-01-26 23:45:25 -0800532 std::span<const uint8_t> data = ngSession.memSend();
533 if (data.empty())
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800534 {
535 return;
536 }
537 isWriting = true;
Ed Tanous325310d2024-03-15 09:05:04 -0700538 boost::asio::async_write(
539 adaptor, boost::asio::const_buffer(data.data(), data.size()),
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800540 std::bind_front(afterWriteBuffer, shared_from_this()));
541 }
542
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800543 void close()
544 {
545 if constexpr (std::is_same_v<Adaptor,
546 boost::beast::ssl_stream<
547 boost::asio::ip::tcp::socket>>)
548 {
549 adaptor.next_layer().close();
550 }
551 else
552 {
553 adaptor.close();
554 }
555 }
556
Ed Tanousd0882182024-01-26 23:45:25 -0800557 void afterDoRead(const std::shared_ptr<self_type>& /*self*/,
558 const boost::system::error_code& ec,
559 size_t bytesTransferred)
560 {
561 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
562 bytesTransferred);
563
564 if (ec)
565 {
566 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
567 ec.message());
568 close();
569 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
570 return;
571 }
572 std::span<uint8_t> bufferSpan{inBuffer.data(), bytesTransferred};
573
574 ssize_t readLen = ngSession.memRecv(bufferSpan);
575 if (readLen < 0)
576 {
577 BMCWEB_LOG_ERROR("nghttp2_session_mem_recv returned {}", readLen);
578 close();
579 return;
580 }
581 writeBuffer();
582
583 doRead();
584 }
585
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800586 void doRead()
587 {
Ed Tanous62598e32023-07-17 17:06:25 -0700588 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800589 adaptor.async_read_some(
Ed Tanousd0882182024-01-26 23:45:25 -0800590 boost::asio::buffer(inBuffer),
591 std::bind_front(&self_type::afterDoRead, this, shared_from_this()));
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800592 }
593
594 // A mapping from http2 stream ID to Stream Data
Ed Tanous52e31622024-01-23 16:31:11 -0800595 std::map<int32_t, Http2StreamData> streams;
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800596
Ed Tanousd0882182024-01-26 23:45:25 -0800597 std::array<uint8_t, 8192> inBuffer{};
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800598
599 Adaptor adaptor;
600 bool isWriting = false;
601
602 nghttp2_session ngSession;
603
604 Handler* handler;
605 std::function<std::string()>& getCachedDateStr;
606
607 using std::enable_shared_from_this<
608 HTTP2Connection<Adaptor, Handler>>::shared_from_this;
609
610 using std::enable_shared_from_this<
611 HTTP2Connection<Adaptor, Handler>>::weak_from_this;
612};
613} // namespace crow